Overview
APE Balance
APE Value
$0.00Multichain Info
Latest 25 from a total of 3,053 transactions
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| Set Manager | 17005955 | 241 days ago | IN | 0 APE | 0.00070572 | ||||
| Sell Gold | 17000288 | 241 days ago | IN | 0 APE | 0.00152732 | ||||
| Sell Gold | 17000158 | 241 days ago | IN | 0 APE | 0.00152732 | ||||
| Sell Gold | 17000069 | 241 days ago | IN | 0 APE | 0.00152732 | ||||
| Sell Gold | 16285609 | 246 days ago | IN | 0 APE | 0.00143718 | ||||
| Sell Gold | 16285606 | 246 days ago | IN | 0 APE | 0.00143718 | ||||
| Deposit Ores | 16116445 | 250 days ago | IN | 0 APE | 0.03709031 | ||||
| Deposit Ores | 16110219 | 250 days ago | IN | 0 APE | 0.12231986 | ||||
| Sell Gold | 15974408 | 253 days ago | IN | 0 APE | 0.00143654 | ||||
| Emergency Withdr... | 15915177 | 255 days ago | IN | 0 APE | 0.00080517 | ||||
| Emergency Withdr... | 15915155 | 255 days ago | IN | 0 APE | 0.00102717 | ||||
| Set Manager | 15915134 | 255 days ago | IN | 0 APE | 0.00070572 | ||||
| Exchange Gold Fo... | 15914752 | 255 days ago | IN | 0 APE | 0.0029507 | ||||
| Exchange Gold Fo... | 15914726 | 255 days ago | IN | 0 APE | 0.0033854 | ||||
| Transfer | 15907998 | 255 days ago | IN | 464.7793016 APE | 0.00067463 | ||||
| Deposit Ores | 15903367 | 255 days ago | IN | 0 APE | 0.00687006 | ||||
| Deposit Ores | 15903361 | 255 days ago | IN | 0 APE | 0.01790376 | ||||
| Deposit Ores | 15891704 | 255 days ago | IN | 0 APE | 0.00458675 | ||||
| Deposit Ores | 15891691 | 255 days ago | IN | 0 APE | 0.03012928 | ||||
| Deposit Ores | 15891552 | 255 days ago | IN | 0 APE | 0.01185476 | ||||
| Deposit Ores | 15884069 | 255 days ago | IN | 0 APE | 0.06084589 | ||||
| Deposit Ores | 15884058 | 255 days ago | IN | 0 APE | 0.11335017 | ||||
| Deposit Ores | 15884043 | 255 days ago | IN | 0 APE | 0.10668761 | ||||
| Deposit Ores | 15880387 | 256 days ago | IN | 0 APE | 0.04819902 | ||||
| Deposit Ores | 15880312 | 256 days ago | IN | 0 APE | 0.10181543 |
Latest 25 internal transactions (View All)
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 15915177 | 255 days ago | 46,123.24671582 APE | ||||
| 15878034 | 256 days ago | 1.3357 APE | ||||
| 15872639 | 256 days ago | 1 wei | ||||
| 15872639 | 256 days ago | 0.00000088 APE | ||||
| 15865695 | 256 days ago | 1 wei | ||||
| 15865695 | 256 days ago | 0.00015001 APE | ||||
| 15863029 | 256 days ago | 1 wei | ||||
| 15863029 | 256 days ago | 0.00102952 APE | ||||
| 15863026 | 256 days ago | 1 wei | ||||
| 15863026 | 256 days ago | 0.01956091 APE | ||||
| 15863024 | 256 days ago | 2.07413394 APE | ||||
| 15860967 | 256 days ago | 2.966 APE | ||||
| 15851419 | 256 days ago | 1.3358 APE | ||||
| 15849329 | 256 days ago | 1.3327 APE | ||||
| 15819670 | 257 days ago | 1.2 APE | ||||
| 15819611 | 257 days ago | 3.3 APE | ||||
| 15809155 | 257 days ago | 1.3535 APE | ||||
| 15809155 | 257 days ago | 1.3535 APE | ||||
| 15809155 | 257 days ago | 1.3535 APE | ||||
| 15809139 | 257 days ago | 0.975 APE | ||||
| 15808979 | 257 days ago | 1.3535 APE | ||||
| 15808972 | 257 days ago | 1.3524 APE | ||||
| 15808960 | 257 days ago | 0.9843 APE | ||||
| 15808947 | 257 days ago | 1.3535 APE | ||||
| 15808936 | 257 days ago | 0.9843 APE |
Cross-Chain Transactions
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IOreMine} from "./OreMine.sol";
import {IOreChunks} from "./OreChunks.sol";
import {IPickaxes} from "./Pickaxes.sol";
interface IGoldMerchant {
function goldCap() external view returns (uint256);
function goldValue() external view returns (uint256);
function averageAcquisitionPrice() external view returns (uint256);
function calculateWeiForGold(
uint256 goldAmount
) external view returns (uint256);
function depositOres(uint256[] calldata oreIds) external;
function exchangeGoldForOre(uint256 oreId) external;
function sellGold(uint256 goldWeiAmount) external;
function buyGold() external payable;
function setManager(address newManager) external;
function setMerchantEnabled() external;
}
/**
* @title Not a Gold Merchant
* @dev The Gold Merchant serves as the central hub of TheMine's economy. It:
* - Allows miners to convert their ore chunks into gold tokens
* - Provides a marketplace where users can buy gold tokens for APE
* - Buys back gold tokens from users at the current gold value
* - Enables users to exchange gold tokens back for specific ore chunks
*
* The contract implements dynamic pricing through the goldCap mechanism, which:
* - Determines the value of gold tokens (goldCap / GOLD_SUPPLY)
* - Increases when users buy gold (through premiums)
* - Increases when the contract sells gold at a profit
*
* This creates a sustainable economy where gold tokens gradually appreciate
* in value as they circulate through the ecosystem.
*/
contract NotaGoldMerchant is ReentrancyGuard, IERC721Receiver, IGoldMerchant {
// Constants
address internal constant DEAD_ADDRESS =
0x000000000000000000000000000000000000dEaD;
uint256 internal constant GOLD_SUPPLY = 21_000_000; // All that glitters has its limits
uint256 internal constant WEI_MULTIPLIER = 10 ** 18;
// External contracts
address internal immutable goldOre; // The Ores NFT contract
address internal immutable picks; // The Picks NFT contract
address internal immutable theMine; // The Mine contract
address internal immutable goldToken; // The Gold Token contract
// Internal state
bool internal _oreDepositsEnabled; // Is the ore deposits enabled?
bool internal _merchantEnabled; // Is the gold merchant open for business?
bool internal _emergencyWithdrawDisabled; // Is the emergency withdraw disabled?
address public manager; // Address that receives management fees
uint256 public goldCap; // Controls the value of gold (in wei) - goldCap/GOLD_SUPPLY = price per token
// Gold buying/selling tracking
uint256 public goldForSale; // Total gold tokens contract has for sale
uint256 public totalWeiSpent; // Total wei spent buying gold tokens the contract has for sale
// Chunk tracking
mapping(uint256 => bool) public depositedOres; // Tracks which ores have been deposited
mapping(uint256 => bool) public orePreviouslyDeposited; // Tracks which ores have been deposited more than once
// Events
event OreDeposited(address indexed depositor, uint256 indexed oreId);
event GoldBought(
address indexed buyer,
uint256 indexed goldAmount,
uint256 indexed totalGoldValue,
uint256 totalPremium
);
event GoldSold(
address indexed seller,
uint256 indexed goldAmount,
uint256 indexed totalGoldValue
);
event ManagerPaymentFailed(address indexed manager, uint256 weiAmount);
event GoldExchangedForOre(address indexed sender, uint256 oreId);
modifier onlyManager() {
require(msg.sender == manager, "Only manager can call this function");
_;
}
modifier onlyMerchantEnabled() {
require(
_merchantEnabled || msg.sender == manager,
"Merchant is not enabled"
);
_;
}
/**
* @notice Creates a new Gold Merchant for TheMine ecosystem
* @param goldOre_ Address of the OreChunks contract
* @param picks_ Address of the Pickaxes contract
* @param theMine_ Address of the TheMine contract
* @param goldToken_ Address of the GoldToken contract
* @dev Sets up the initial contract state without activating the merchant
*/
constructor(
address goldOre_,
address picks_,
address theMine_,
address goldToken_
) ReentrancyGuard() {
require(goldOre_ != address(0), "Invalid OreChunks address");
require(picks_ != address(0), "Invalid Pickaxes address");
require(theMine_ != address(0), "Invalid TheMine address");
require(goldToken_ != address(0), "Invalid GoldToken address");
goldOre = goldOre_;
picks = picks_;
theMine = theMine_;
goldToken = goldToken_;
manager = msg.sender;
}
/**
* @notice Allows contract to receive APE, which increases goldCap
* @dev When users send APE directly to the contract, it increases the goldCap
* This effectively increases the value of gold tokens for everyone
*/
receive() external payable {
goldCap += msg.value; // All that glitters increases in value
}
// ** MANAGER ONLY ** //
/**
* @notice Updates the manager address for fee collection
* @param newManager The address of the new manager
* @dev Only callable by the current manager
*/
function setManager(address newManager) external onlyManager {
manager = newManager;
}
/**
* @notice Disable emergency withdraw
* @dev This function is used to disable emergency withdraw
*/
function disableEmergencyWithdraw() external onlyManager {
_emergencyWithdrawDisabled = true;
}
/**
* @notice Emergency withdraw contract value
* @dev This function is used to withdraw contract value
*/
function emergencyWithdraw() external onlyManager {
require(!_emergencyWithdrawDisabled, "Emergency withdraw is disabled");
(bool success, ) = manager.call{value: address(this).balance}("");
require(success, "Failed to send to manager");
}
/**
* @notice Emergency withdraw tokens
* @dev This function is used to withdraw tokens from the contract
*/
function emergencyWithdrawToken() external onlyManager {
require(!_emergencyWithdrawDisabled, "Emergency withdraw is disabled");
IERC20(goldToken).transfer(
manager,
IERC20(goldToken).balanceOf(address(this))
);
}
/**
* @notice Emergency withdraw ore
* @dev This function is used to withdraw ore from the contract
*/
function emergencyWithdrawOre(uint256 oreId) external onlyManager {
require(!_emergencyWithdrawDisabled, "Emergency withdraw is disabled");
IOreChunks(goldOre).safeTransferFrom(address(this), manager, oreId);
}
/**
* @notice Opens the gold merchant for business
* @dev Once enabled, users buy and sell gold
*/
function setMerchantEnabled() external onlyManager {
_merchantEnabled = true; // The merchant is ready to receive gold!
}
/**
* @notice Opens the ore deposits for the gold merchant
* @dev Once enabled, users can deposit ores
*/
function setOreDepositsEnabled() external onlyManager {
_oreDepositsEnabled = true; // The merchant is ready to receive ores!
}
// ** PUBLIC ** //
function balanceOf(address account) public view returns (uint256) {
return IERC20(goldToken).balanceOf(account);
}
/**
* @notice Returns the value of one gold token in wei
* @return The current value of one gold token in wei
* @dev This is the core pricing mechanism: goldCap / GOLD_SUPPLY
*/
function goldValue() public view returns (uint256) {
return goldCap / GOLD_SUPPLY; // How much is your shiny worth today?
}
/**
* @notice Returns the average price the contract paid for gold in wei
* @return The average acquisition price per token in wei
* @dev Used to calculate profit when selling gold
* totalWeiSpent is multiplied by WEI_MULTIPLIER to avoid precision loss
*/
function averageAcquisitionPrice() public view returns (uint256) {
if (goldForSale == 0) return 0;
return (totalWeiSpent * WEI_MULTIPLIER) / goldForSale;
}
/**
* @notice Calculate how much wei needs to be sent to purchase a specific amount of gold
* @param goldAmount The amount of gold tokens to purchase (with 18 decimals)
* @return weiRequired The total amount of wei needed to buy the specified gold
* @dev This is the reverse calculation of buyGold:
* - Calculates the base cost of the gold
* - Applies the same premium and management fee percentages
* - Useful for users to know how much to send before transaction
*/
function calculateWeiForGold(
uint256 goldAmount
) public view returns (uint256) {
// Calculate base cost of gold
uint256 currentGoldValue = goldValue();
uint256 baseGoldCost = (goldAmount * currentGoldValue) / WEI_MULTIPLIER;
// Get the same premium and management fee percentages
uint256 managementFeePct = 100; // 1% - consistent with _calculateValueToConvertToGold
uint256 goldCapPremiumPct = 100; // Default 1%
// Calculate premium percentage based on goldCap (same logic as _calculateValueToConvertToGold)
if (goldCap <= 21_000 ether) {
goldCapPremiumPct = 1000; // 10% when goldCap is low
} else if (goldCap < 210_000 ether) {
goldCapPremiumPct = (100 * 210_000 ether) / goldCap; // Dynamic scaling
}
// Calculate total required wei
// If valueToConvertToGold = (value * 10000) / (10000 + fees),
// Then value = valueToConvertToGold * (10000 + fees) / 10000
uint256 weiRequired = (baseGoldCost *
(10000 + goldCapPremiumPct + managementFeePct)) / 10000;
return weiRequired; // Strike gold without guessing how much to send!
}
/**
* @notice Deposit multiple ore chunks to mint gold tokens
* @param oreIds Array of ore chunk IDs to deposit
* @dev The motherlode - convert multiple ores to gold in one transaction
* Batches rewards efficiently by accumulating royalties per pickaxe owner
* Limited to 50 ores per transaction to prevent gas limit issues
*/
function depositOres(uint256[] calldata oreIds) external nonReentrant {
address sender = msg.sender;
if (!_oreDepositsEnabled) {
require(sender == manager, "Ore deposits not enabled");
}
require(oreIds.length > 0, "Must deposit at least one ore");
require(oreIds.length <= 50, "Too many ores at once");
// Transfer ores to this contract, which also verifies ownership since it will revert if any ore is not owned by the caller
IOreChunks(goldOre).batchSafeTransferFrom(
sender,
address(this),
oreIds
);
// Track rewards per pickaxe owner to batch mint operations
address[] memory pickaxeOwners = new address[](oreIds.length);
uint256[] memory rewards = new uint256[](oreIds.length);
uint256 uniqueOwnersCount = 0;
uint256 depositorTotalReward = 0;
// Process each ore now that ownership is verified
for (uint256 i = 0; i < oreIds.length; i++) {
uint256 oreId = oreIds[i];
// Calculate rewards and accumulate them
(
uint256 pickaxeReward,
uint256 depositorReward,
address pickaxeOwner
) = _calculateOreRewards(oreId, sender);
// Track depositor's reward
depositorTotalReward += depositorReward;
// Add pickaxe owner reward if applicable
if (pickaxeReward > 0) {
_accumulatePickaxeReward(
pickaxeOwner,
pickaxeReward,
pickaxeOwners,
rewards,
uniqueOwnersCount
);
uniqueOwnersCount = _getUniqueOwnersCount(pickaxeOwners);
}
// Mark ore as deposited and track repeated deposits
depositedOres[oreId] = true;
orePreviouslyDeposited[oreId] = true;
emit OreDeposited(sender, oreId);
}
// Distribute the accumulated rewards
_distributeRewards(
sender,
depositorTotalReward,
pickaxeOwners,
rewards,
uniqueOwnersCount
);
}
/**
* @notice Sell gold tokens to the contract
* @param goldWeiAmount Amount of gold tokens to sell (with 18 decimals)
* @dev Users can cash out their gold tokens for APE at the current gold value
* The contract buys gold at exactly goldValue() with no fees or premium
* This increases goldForSale and totalWeiSpent for tracking
*/
function sellGold(
uint256 goldWeiAmount
) external nonReentrant onlyMerchantEnabled {
address seller = msg.sender;
require(goldWeiAmount > 0, "Amount cannot be zero");
require(
IERC20(goldToken).balanceOf(seller) >= goldWeiAmount,
"Insufficient balance"
);
uint256 currentGoldValue = goldValue();
// Calculate APE to send to seller
// divide by WEI_MULTIPLIER because currentGoldValue is for 1 gold with 18 decimals
uint256 totalGoldValue = (goldWeiAmount * currentGoldValue) /
WEI_MULTIPLIER;
// Make sure contract has enough APE, otherwise adjust the amount
// This should never happen, the contract should always have enough APE,
// but just in case, we'll adjust the amount to sell
if (totalGoldValue > address(this).balance) {
totalGoldValue = address(this).balance;
goldWeiAmount =
(totalGoldValue * WEI_MULTIPLIER) /
currentGoldValue;
}
// Transfer gold from seller to contract
IERC20(goldToken).transferFrom(seller, address(this), goldWeiAmount);
// Update contract's tracking
totalWeiSpent += totalGoldValue;
goldForSale += goldWeiAmount;
// Send APE to seller
(bool success, ) = msg.sender.call{value: totalGoldValue}("");
require(success, "Payment failed");
emit GoldSold(seller, goldWeiAmount, totalGoldValue);
}
/**
* @notice Buy gold tokens from the contract
* @dev The Midas touch - convert your APE to shiny gold tokens
* Users send APE and get gold tokens at the current value plus premiums:
* - A base 1% management fee
* - A dynamic premium that decreases as goldCap increases (10% below 21000 APE, 1% above 210000 APE)
* - Premiums and profits increase goldCap, raising gold value for everyone
*/
function buyGold() external payable nonReentrant {
uint256 value = msg.value;
require(value > 0, "No value sent");
uint256 contractOwnedGold = goldForSale;
require(contractOwnedGold > 0, "No gold available for purchase");
// Calculate how much gold the user gets for their APE
// value is multiplied by WEI_MULTIPLIER because currentGoldValue is for 1 gold with 18 decimals
uint256 currentGoldValue = goldValue();
(
uint256 valueToConvertToGold,
uint256 premiumPct,
uint256 managementFeePct
) = _calculateValueToConvertToGold(value);
uint256 goldAmount = (valueToConvertToGold * WEI_MULTIPLIER) /
currentGoldValue;
uint256 refund = 0;
// Make sure we don't sell more than the contract owns
if (goldAmount > contractOwnedGold) {
goldAmount = contractOwnedGold;
}
uint256 saleAmount18 = (goldAmount * currentGoldValue);
// Calculate profit
// e.g. previously bought 1 gold for 1 eth => averageAcquisitionPrice = 1 * 10^18
uint256 acquisitionCost18 = (goldAmount * averageAcquisitionPrice());
// If we made a profit, add it to goldCap (increases gold value for everyone)
uint256 profit = saleAmount18 - acquisitionCost18;
// Adjust tracking variables to maintain accurate acquisition price
goldForSale -= goldAmount;
totalWeiSpent -= acquisitionCost18 / WEI_MULTIPLIER;
// Recalculate actual fees based on the final gold amount
uint256 actualCost = saleAmount18 / WEI_MULTIPLIER;
uint256 actualPremium = (actualCost * premiumPct) / 10000;
uint256 actualManagementFee = (actualCost * managementFeePct) / 10000;
uint256 actualTotalCost = actualCost +
actualPremium +
actualManagementFee;
if (actualTotalCost > value) {
revert("Actual total cost is greater than value");
}
// Add premium and profit to goldCap - the rising tide lifts all boats
goldCap += actualPremium + (profit / WEI_MULTIPLIER);
// Send management fee to manager or add to goldCap if it fails
if (manager != address(0)) {
(bool managerSuccess, ) = manager.call{value: actualManagementFee}(
""
);
if (!managerSuccess) {
emit ManagerPaymentFailed(manager, actualManagementFee);
goldCap += actualManagementFee;
}
} else {
goldCap += actualManagementFee;
}
// Refund excess value
refund = value - actualTotalCost;
if (refund > 0) {
(bool success, ) = msg.sender.call{value: refund}("");
require(success, "Refund failed");
}
// Transfer gold to buyer
IERC20(goldToken).transfer(msg.sender, goldAmount);
emit GoldBought(
msg.sender,
goldAmount,
actualCost,
actualPremium + actualManagementFee
);
}
/**
* @notice Exchange gold tokens back for a specific ore chunk
* @param oreId The ID of the ore chunk to retrieve
* @dev Allows users to return to their mining roots by trading gold for original ore
* The ore must have been previously deposited, and caller must have sufficient gold
* Gold tokens are burned in exchange for the ore NFT
*/
function exchangeGoldForOre(uint256 oreId) external nonReentrant {
require(depositedOres[oreId], "Ore not deposited");
// Get chunk data
(, uint256 goldQuantity) = IOreMine(theMine).getOrePickAndGoldQuantity(
oreId
);
// Calculate gold amount with 18 decimals
uint256 goldWeiQuantity = goldQuantity * WEI_MULTIPLIER;
// Mark ore as not deposited, burn gold, and transfer ore
depositedOres[oreId] = false;
IERC20(goldToken).transfer(msg.sender, goldWeiQuantity);
IERC721(goldOre).safeTransferFrom(address(this), msg.sender, oreId);
emit GoldExchangedForOre(msg.sender, oreId);
}
// ** INTERNAL ** //
/**
* @notice Calculates rewards for a single ore
* @dev Handles reward calculation and pickaxe owner determination
*
* @param oreId ID of the ore chunk
* @param depositor Address of the ore depositor
*
* @return pickaxeReward Reward for the pickaxe owner
* @return depositorReward Reward for the depositor
* @return pickaxeOwner Address of the pickaxe owner
*/
function _calculateOreRewards(
uint256 oreId,
address depositor
)
internal
view
returns (
uint256 pickaxeReward,
uint256 depositorReward,
address pickaxeOwner
)
{
// Get chunk data
(uint256 pickaxeId, uint256 goldQuantity) = IOreMine(theMine)
.getOrePickAndGoldQuantity(oreId);
// Calculate gold amount with 18 decimals
uint256 goldWeiQuantity = goldQuantity * WEI_MULTIPLIER;
// Default values
pickaxeReward = 0;
pickaxeOwner = address(0);
try IERC721(picks).ownerOf(pickaxeId) returns (address owner) {
pickaxeOwner = owner;
} catch {}
// If pickaxe owner is different from ore depositor, give them 5%
if (
pickaxeOwner != depositor &&
pickaxeOwner != address(0) &&
pickaxeOwner != DEAD_ADDRESS
) {
// Every good miner shares with their tool provider
pickaxeReward = (goldWeiQuantity * 5) / 100;
}
// Calculate manager's reward
uint256 managerReward = orePreviouslyDeposited[oreId]
? 0
: (goldWeiQuantity * 5) / 100;
// Calculate depositor's reward
depositorReward = goldWeiQuantity - pickaxeReward - managerReward;
return (pickaxeReward, depositorReward, pickaxeOwner);
}
/**
* @notice Accumulates pickaxe rewards for unique owners
* @param pickaxeOwner Address of the pickaxe owner
* @param pickaxeReward Amount of reward for this pickaxe owner
* @param pickaxeOwners Array of unique pickaxe owner addresses
* @param rewards Array of rewards corresponding to pickaxeOwners
* @param uniqueOwnersCount Current count of unique owners
* @dev Updates the pickaxeOwners and rewards arrays
*/
function _accumulatePickaxeReward(
address pickaxeOwner,
uint256 pickaxeReward,
address[] memory pickaxeOwners,
uint256[] memory rewards,
uint256 uniqueOwnersCount
) internal pure {
// Add to pickaxe owner's rewards or create new entry
bool ownerFound = false;
for (uint256 j = 0; j < uniqueOwnersCount; j++) {
if (pickaxeOwners[j] == pickaxeOwner) {
rewards[j] += pickaxeReward;
ownerFound = true;
break;
}
}
if (!ownerFound) {
pickaxeOwners[uniqueOwnersCount] = pickaxeOwner;
rewards[uniqueOwnersCount] = pickaxeReward;
}
}
/**
* @notice Gets the count of unique pickaxe owners
* @param pickaxeOwners Array of pickaxe owner addresses
* @return count Number of unique non-zero addresses
*/
function _getUniqueOwnersCount(
address[] memory pickaxeOwners
) internal pure returns (uint256 count) {
for (uint256 i = 0; i < pickaxeOwners.length; i++) {
if (pickaxeOwners[i] != address(0)) {
count++;
} else {
break;
}
}
return count;
}
/**
* @notice Distributes all accumulated rewards
* @param depositor Address of the depositor
* @param depositorReward Total reward for the depositor
* @param pickaxeOwners Array of pickaxe owner addresses
* @param rewards Array of rewards corresponding to pickaxeOwners
* @param uniqueOwnersCount Count of unique pickaxe owners
* @dev Mints tokens to each recipient - one golden payday for everyone!
*/
function _distributeRewards(
address depositor,
uint256 depositorReward,
address[] memory pickaxeOwners,
uint256[] memory rewards,
uint256 uniqueOwnersCount
) internal {
// Mint total rewards to depositor
IERC20(goldToken).transfer(depositor, depositorReward);
// Mint tokens to pickaxe owners (one mint per unique owner)
for (uint256 i = 0; i < uniqueOwnersCount; i++) {
IERC20(goldToken).transfer(pickaxeOwners[i], rewards[i]);
}
}
/**
* @notice Calculate the value conversion and fees for gold purchases
* @param value The amount of APE sent to the contract
* @return valueToConvertToGold The base amount of APE used to buy gold
* @return goldCapPremiumPct The premium percentage based on goldCap
* @return managementFeePct The management fee percentage
* @dev This implements the dynamic premium system:
* - 1% management fee (flat)
* - Premium scales from 10% when goldCap is low to 1% when goldCap is high
* - The formula ensures that all APE is accounted for with no rounding issues
*/
function _calculateValueToConvertToGold(
uint256 value
) internal view returns (uint256, uint256, uint256) {
uint256 managementFeePct = 100; // 1% - every merchant needs their cut
uint256 goldCapPremiumPct = 100; // Default 1% - the treasure chest premium
// Higher premium when goldCap is low, lower premium when goldCap is high
if (goldCap <= 21_000 ether) {
goldCapPremiumPct = 1000; // 10%
} else if (goldCap < 210_000 ether) {
// Dynamic scaling - the more valuable gold is, the lower the premium
goldCapPremiumPct = (100 * 210_000 ether) / goldCap;
}
// Calculate how much of the sent value goes to buying gold vs fees
uint256 valueToConvertToGold = (value * 10000) /
(10000 + managementFeePct + goldCapPremiumPct);
uint256 premium = (valueToConvertToGold * goldCapPremiumPct) / 10000;
uint256 managementFee = (valueToConvertToGold * managementFeePct) /
10000;
// Recalculate to ensure exact accounting (handles rounding)
valueToConvertToGold = value - premium - managementFee;
return (valueToConvertToGold, goldCapPremiumPct, managementFeePct);
}
// ** ERC721 Receiver ** //
/**
* @notice Required for IERC721Receiver interface
* @dev Ensures the contract can receive only Gold Ore NFTs from those properly using safeTransferFrom
*/
function onERC721Received(
address operator,
address,
uint256,
bytes calldata
) external view override returns (bytes4) {
if (operator != address(this)) {
revert("Not gold merchant");
}
return this.onERC721Received.selector;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ICreatorToken {
event TransferValidatorUpdated(address oldValidator, address newValidator);
function getTransferValidator() external view returns (address validator);
function setTransferValidator(address validator) external;
function getTransferValidationFunction() external view returns (bytes4 functionSignature, bool isViewFunction);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ICreatorTokenLegacy {
event TransferValidatorUpdated(address oldValidator, address newValidator);
function getTransferValidator() external view returns (address validator);
function setTransferValidator(address validator) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ITransferValidator {
function applyCollectionTransferPolicy(address caller, address from, address to) external view;
function validateTransfer(address caller, address from, address to) external view;
function validateTransfer(address caller, address from, address to, uint256 tokenId) external view;
function validateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount) external;
function beforeAuthorizedTransfer(address operator, address token, uint256 tokenId) external;
function afterAuthorizedTransfer(address token, uint256 tokenId) external;
function beforeAuthorizedTransfer(address operator, address token) external;
function afterAuthorizedTransfer(address token) external;
function beforeAuthorizedTransfer(address token, uint256 tokenId) external;
function beforeAuthorizedTransferWithAmount(address token, uint256 tokenId, uint256 amount) external;
function afterAuthorizedTransferWithAmount(address token, uint256 tokenId) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ITransferValidatorSetTokenType {
function setTokenTypeOfCollection(address collection, uint16 tokenType) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../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 anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing 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;
}// 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 IERC1822ProxiableUpgradeable {
/**
* @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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.3) (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.9._
*/
interface IERC1967Upgradeable {
/**
* @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);
}// 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 IBeaconUpgradeable {
/**
* @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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.3) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/IERC1967Upgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.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._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// 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 StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.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) {
_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 (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(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 StorageSlotUpgradeable.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");
StorageSlotUpgradeable.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 StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.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) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @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;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (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]
* ```
* 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;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.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 Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @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.
*/
function upgradeTo(address newImplementation) external 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.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external 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;
/**
* @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;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @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);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @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;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../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 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;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.2) (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 "../../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;
}// 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);
}// 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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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
* ====
*
* [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://diligence.consensys.net/posts/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.5.11/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 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);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../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;
}
/**
* @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;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../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;
}// 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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 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 10, 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 * 8) < value ? 1 : 0);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
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:
* ```
* 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`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 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
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.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 `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);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) pragma solidity ^0.8.0; import "../token/ERC721/IERC721.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @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 ReentrancyGuard {
// 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;
constructor() {
_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;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* 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].
*
* 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 ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these 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 override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override 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 value {ERC20} uses, unless this function is
* 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 override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override 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 `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` 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 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* 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 `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `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.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` 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.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount
) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 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 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);
}// 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 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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*
* _Available since v4.5._
*/
library Base64 {
/**
* @dev Base64 Encoding/Decoding Table
*/
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/
function encode(bytes memory data) internal pure returns (string memory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/
if (data.length == 0) return "";
// Loads the table into memory
string memory table = _TABLE;
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
// and split into 4 numbers of 6 bits.
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
// - `data.length + 2` -> Round up
// - `/ 3` -> Number of 3-bytes chunks
// - `4 *` -> 4 characters for each chunk
string memory result = new string(4 * ((data.length + 2) / 3));
/// @solidity memory-safe-assembly
assembly {
// Prepare the lookup table (skip the first "length" byte)
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 32)
// Run over the input, 3 bytes at a time
for {
let dataPtr := data
let endPtr := add(data, mload(data))
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// To write each character, shift the 3 bytes (18 bits) chunk
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
// and apply logical AND with 0x3F which is the number of
// the previous character in the ASCII table prior to the Base64 Table
// The result is then added to the table to get the character to write,
// and finally write it in the result pointer but with a left shift
// of 256 (1 byte) - 8 (1 ASCII char) = 248 bits
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
}
// When data `bytes` is not exactly 3 bytes long
// it is padded with `=` characters at the end
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
return result;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}// 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 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[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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
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) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 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 10, 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 * 8) < value ? 1 : 0);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
/**
* @dev String operations.
*/
library Strings {
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 = Math.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 `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.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);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@limitbreak/creator-token-standards/src/interfaces/ICreatorToken.sol";
import "@limitbreak/creator-token-standards/src/interfaces/ITransferValidator.sol";
import "@limitbreak/creator-token-standards/src/interfaces/ITransferValidatorSetTokenType.sol";
/**
* @title CreatorTokenBase
* @author Limit Break, Inc.
* @notice CreatorTokenBaseV3 is an abstract contract that provides basic functionality for managing token
* transfer policies through an implementation of ICreatorTokenTransferValidator/ICreatorTokenTransferValidatorV2/ICreatorTokenTransferValidatorV3.
* This contract is intended to be used as a base for creator-specific token contracts, enabling customizable transfer
* restrictions and security policies.
*
* <h4>Features:</h4>
* <ul>Ownable: This contract can have an owner who can set and update the transfer validator.</ul>
* <ul>TransferValidation: Implements the basic token transfer validation interface.</ul>
*
* <h4>Benefits:</h4>
* <ul>Provides a flexible and modular way to implement custom token transfer restrictions and security policies.</ul>
* <ul>Allows creators to enforce policies such as account and codehash blacklists, whitelists, and graylists.</ul>
* <ul>Can be easily integrated into other token contracts as a base contract.</ul>
*
* <h4>Intended Usage:</h4>
* <ul>Use as a base contract for creator token implementations that require advanced transfer restrictions and
* security policies.</ul>
* <ul>Set and update the ICreatorTokenTransferValidator implementation contract to enforce desired policies for the
* creator token.</ul>
*
* <h4>Compatibility:</h4>
* <ul>Backward and Forward Compatible - V1/V2/V3 Creator Token Base will work with V1/V2/V3 Transfer Validators.</ul>
*/
abstract contract CreatorTokenBaseUpgradeable is Initializable, ICreatorToken {
/// @dev Thrown when setting a transfer validator address that has no deployed code.
error CreatorTokenBase__InvalidTransferValidatorContract();
/// @dev The default transfer validator that will be used if no transfer validator has been set by the creator.
address public constant DEFAULT_TRANSFER_VALIDATOR =
address(0x721C002B0059009a671D00aD1700c9748146cd1B);
/// @dev Used to determine if the default transfer validator is applied.
/// @dev Set to true when the creator sets a transfer validator address.
bool private isValidatorInitialized;
/// @dev Address of the transfer validator to apply to transactions.
address private transferValidator;
function __CreatorTokenBaseUpgradeable_init() internal onlyInitializing {
_emitDefaultTransferValidator();
_registerTokenType(DEFAULT_TRANSFER_VALIDATOR);
}
/**
* @notice Sets the transfer validator for the token contract.
*
* @dev Throws when provided validator contract is not the zero address and does not have code.
* @dev Throws when the caller is not the contract owner.
*
* @dev <h4>Postconditions:</h4>
* 1. The transferValidator address is updated.
* 2. The `TransferValidatorUpdated` event is emitted.
*
* @param transferValidator_ The address of the transfer validator contract.
*/
function setTransferValidator(address transferValidator_) public {
_requireCallerIsContractOwner();
bool isValidTransferValidator = transferValidator_.code.length > 0;
if (transferValidator_ != address(0) && !isValidTransferValidator) {
revert CreatorTokenBase__InvalidTransferValidatorContract();
}
emit TransferValidatorUpdated(
address(getTransferValidator()),
transferValidator_
);
isValidatorInitialized = true;
transferValidator = transferValidator_;
if (transferValidator_ != address(0)) {
_registerTokenType(transferValidator_);
}
}
/**
* @notice Returns the transfer validator contract address for this token contract.
*/
function getTransferValidator()
public
view
override
returns (address validator)
{
validator = transferValidator;
if (validator == address(0)) {
if (!isValidatorInitialized) {
validator = DEFAULT_TRANSFER_VALIDATOR;
}
}
if (validator != address(0)) {
uint256 validatorCodeSize;
assembly {
validatorCodeSize := extcodesize(validator)
}
if (validatorCodeSize == 0) {
validator = address(0);
}
}
}
/**
* @dev Pre-validates a token transfer, reverting if the transfer is not allowed by this token's security policy.
* Inheriting contracts are responsible for overriding the _beforeTokenTransfer function, or its equivalent
* and calling _validateBeforeTransfer so that checks can be properly applied during token transfers.
*
* @dev Be aware that if the msg.sender is the transfer validator, the transfer is automatically permitted, as the
* transfer validator is expected to pre-validate the transfer.
*
* @dev Throws when the transfer doesn't comply with the collection's transfer policy, if the transferValidator is
* set to a non-zero address.
*
* @param caller The address of the caller.
* @param from The address of the sender.
* @param to The address of the receiver.
* @param tokenId The token id being transferred.
*/
function _preValidateTransfer(
address caller,
address from,
address to,
uint256 tokenId
) internal virtual {
address validator = getTransferValidator();
if (validator != address(0)) {
if (msg.sender == validator) {
return;
}
ITransferValidator(validator).validateTransfer(
caller,
from,
to,
tokenId
);
}
}
/**
* @dev Pre-validates a token transfer, reverting if the transfer is not allowed by this token's security policy.
* Inheriting contracts are responsible for overriding the _beforeTokenTransfer function, or its equivalent
* and calling _validateBeforeTransfer so that checks can be properly applied during token transfers.
*
* @dev Be aware that if the msg.sender is the transfer validator, the transfer is automatically permitted, as the
* transfer validator is expected to pre-validate the transfer.
*
* @dev Used for ERC20 and ERC1155 token transfers which have an amount value to validate in the transfer validator.
* @dev The `tokenId` for ERC20 tokens should be set to `0`.
*
* @dev Throws when the transfer doesn't comply with the collection's transfer policy, if the transferValidator is
* set to a non-zero address.
*
* @param caller The address of the caller.
* @param from The address of the sender.
* @param to The address of the receiver.
* @param tokenId The token id being transferred.
* @param amount The amount of token being transferred.
*/
function _preValidateTransfer(
address caller,
address from,
address to,
uint256 tokenId,
uint256 amount
) internal virtual {
address validator = getTransferValidator();
if (validator != address(0)) {
if (msg.sender == validator) {
return;
}
ITransferValidator(validator).validateTransfer(
caller,
from,
to,
tokenId,
amount
);
}
}
function _registerTokenType(address validator) internal {
if (validator != address(0)) {
uint256 validatorCodeSize;
assembly {
validatorCodeSize := extcodesize(validator)
}
if (validatorCodeSize > 0) {
try
ITransferValidatorSetTokenType(validator)
.setTokenTypeOfCollection(address(this), _tokenType())
{} catch {}
}
}
}
/**
* @dev Used during contract deployment for constructable and cloneable creator tokens
* @dev to emit the `TransferValidatorUpdated` event signaling the validator for the contract
* @dev is the default transfer validator.
*/
function _emitDefaultTransferValidator() internal {
emit TransferValidatorUpdated(address(0), DEFAULT_TRANSFER_VALIDATOR);
}
function _tokenType() internal pure virtual returns (uint16);
function _requireCallerIsContractOwner() internal view virtual;
uint256[48] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {IOreMine} from "./OreMine.sol";
import {IOreChunks} from "./OreChunks.sol";
import {IPickaxes} from "./Pickaxes.sol";
interface IGoldMerchant {
function goldCap() external view returns (uint256);
function goldValue() external view returns (uint256);
function averageAcquisitionPrice() external view returns (uint256);
function calculateWeiForGold(
uint256 goldAmount
) external view returns (uint256);
function depositOres(uint256[] calldata oreIds) external;
function exchangeGoldForOre(uint256 oreId) external;
function sellGold(uint256 goldWeiAmount) external;
function buyGold() external payable;
function setManager(address newManager) external;
function setMerchantEnabled() external;
}
/**
* @title GoldToken
* @notice This is an ERC20 token contract for gold in TheMine ecosystem
* @dev The GoldMerchant serves as the central hub of TheMine's economy. It:
* - Allows miners to convert their ore chunks into gold tokens
* - Provides a marketplace where users can buy gold tokens for APE
* - Buys back gold tokens from users at the current gold value
* - Enables users to exchange gold tokens back for specific ore chunks
*
* The contract implements dynamic pricing through the goldCap mechanism, which:
* - Determines the value of gold tokens (goldCap / GOLD_SUPPLY)
* - Increases when users buy gold (through premiums)
* - Increases when the contract sells gold at a profit
*
* This creates a sustainable economy where gold tokens gradually appreciate
* in value as they circulate through the ecosystem.
*/
contract GoldMerchant is
ERC20,
ReentrancyGuard,
IERC721Receiver,
IGoldMerchant
{
// Constants
address private DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD;
uint256 internal constant GOLD_SUPPLY = 21_000_000; // All that glitters has its limits
uint256 internal constant WEI_MULTIPLIER = 10 ** 18;
// External contracts
address internal immutable goldOre; // The ore chunks NFT contract
address internal immutable picks; // The pickaxes NFT contract
address internal immutable theMine; // TheMine contract
address internal manager; // Address that receives management fees
bool internal _oreDepositsEnabled; // Is the ore deposits enabled?
bool internal _merchantEnabled; // Is the gold merchant open for business?
bool internal _emergencyWithdrawDisabled; // Is the emergency withdraw disabled?
// State variables
bool internal _tokenReceiptAllowed; // Controls when contract can receive tokens via _transfer
uint256 internal _goldCap; // Controls the value of gold (in wei) - goldCap/GOLD_SUPPLY = price per token
// Gold buying/selling tracking
uint256 public goldForSale; // Total gold tokens contract has for sale
uint256 internal totalWeiSpent; // Total wei spent buying gold tokens
// Chunk tracking
mapping(uint256 => bool) public depositedOreChunks; // Tracks which ores have been deposited
mapping(uint256 => bool) internal _orePreviouslyDeposited; // Tracks which ores have been deposited more than once
// Events
event OreDeposited(address indexed depositor, uint256 indexed oreId);
event GoldBought(
address indexed buyer,
uint256 indexed goldAmount,
uint256 indexed totalGoldValue,
uint256 totalPremium
);
event GoldSold(
address indexed seller,
uint256 indexed goldAmount,
uint256 indexed totalGoldValue
);
event ManagerPaymentFailed(address indexed manager, uint256 weiAmount);
event GoldExchangedForOre(address indexed sender, uint256 oreId);
modifier onlyManager() {
require(msg.sender == manager, "Only manager can call this function");
_;
}
modifier onlyMerchantEnabled() {
require(
_merchantEnabled || msg.sender == manager,
"Merchant is not enabled"
);
_;
}
modifier allowTokenReceipt() {
_tokenReceiptAllowed = true;
_;
_tokenReceiptAllowed = false;
}
/**
* @notice Creates a new Gold Merchant for TheMine ecosystem
* @param _goldOre Address of the OreChunks contract
* @param _picks Address of the Pickaxes contract
* @param _theMine Address of the TheMine contract
* @dev Sets up the initial contract state without activating the merchant
*/
constructor(
string memory name,
string memory symbol,
address _goldOre,
address _picks,
address _theMine
) ERC20(name, symbol) ReentrancyGuard() {
require(_goldOre != address(0), "Invalid OreChunks address");
require(_picks != address(0), "Invalid Pickaxes address");
require(_theMine != address(0), "Invalid TheMine address");
goldOre = _goldOre;
picks = _picks;
theMine = _theMine;
manager = msg.sender;
_init();
}
/**
* @notice Allows contract to receive APE, which increases goldCap
* @dev When users send APE directly to the contract, it increases the goldCap
* This effectively increases the value of gold tokens for everyone
*/
receive() external payable {
_goldCap += msg.value; // All that glitters increases in value
}
function goldCap() external view returns (uint256) {
return _goldCap;
}
/**
* @notice Returns the value of one gold token in wei
* @return The current value of one gold token in wei
* @dev This is the core pricing mechanism: goldCap / GOLD_SUPPLY
*/
function goldValue() public view returns (uint256) {
return _goldCap / GOLD_SUPPLY; // How much is your shiny worth today?
}
/**
* @notice Returns the average price the contract paid for gold in wei
* @return The average acquisition price per token in wei
* @dev Used to calculate profit when selling gold
* totalWeiSpent is multiplied by WEI_MULTIPLIER to avoid precision loss
*/
function averageAcquisitionPrice() public view returns (uint256) {
if (goldForSale == 0) return 0;
return (totalWeiSpent * WEI_MULTIPLIER) / goldForSale;
}
/**
* @notice Updates the manager address for fee collection
* @param newManager The address of the new manager
* @dev Only callable by the current manager
*/
function setManager(address newManager) external onlyManager {
manager = newManager;
}
/**
* @notice Disable emergency withdraw
* @dev This function is used to disable emergency withdraw
*/
function disableEmergencyWithdraw() external onlyManager {
_emergencyWithdrawDisabled = true;
}
/**
* @notice Emergency withdraw APE
* @dev This function is used to withdraw APE from the contract
*/
function emergencyWithdraw() external onlyManager {
require(!_emergencyWithdrawDisabled, "Emergency withdraw is disabled");
(bool success, ) = manager.call{value: address(this).balance}("");
require(success, "Failed to send APE to manager");
}
/**
* @notice Emergency withdraw tokens
* @dev This function is used to withdraw tokens from the contract
*/
function emergencyWithdrawToken() external onlyManager {
require(!_emergencyWithdrawDisabled, "Emergency withdraw is disabled");
_transfer(address(this), manager, balanceOf(address(this)));
}
/**
* @notice Emergency withdraw ore
* @dev This function is used to withdraw ore from the contract
*/
function emergencyWithdrawOre(uint256 oreId) external onlyManager {
require(!_emergencyWithdrawDisabled, "Emergency withdraw is disabled");
IOreChunks(goldOre).safeTransferFrom(address(this), manager, oreId);
}
/**
* @notice Deposit multiple ore chunks to mint gold tokens
* @param oreIds Array of ore chunk IDs to deposit
* @dev The motherlode - convert multiple ores to gold in one transaction
* Batches rewards efficiently by accumulating royalties per pickaxe owner
* Limited to 20 ores per transaction to prevent gas limit issues
*/
function depositOres(uint256[] calldata oreIds) external nonReentrant {
address sender = msg.sender;
if (!_oreDepositsEnabled) {
require(sender == manager, "Ore deposits not enabled");
}
require(oreIds.length > 0, "Must deposit at least one ore");
require(oreIds.length <= 50, "Too many ores at once");
// Transfer ores to this contract, which also verifies ownership since it will revert if any ore is not owned by the caller
IOreChunks(goldOre).batchSafeTransferFrom(
sender,
address(this),
oreIds
);
// Track rewards per pickaxe owner to batch mint operations
address[] memory pickaxeOwners = new address[](oreIds.length);
uint256[] memory rewards = new uint256[](oreIds.length);
uint256 uniqueOwnersCount = 0;
uint256 depositorTotalReward = 0;
// Process each ore now that ownership is verified
for (uint256 i = 0; i < oreIds.length; i++) {
uint256 oreId = oreIds[i];
// Calculate rewards and accumulate them
(
uint256 pickaxeReward,
uint256 depositorReward,
address pickaxeOwner
) = _calculateOreRewards(oreId, sender);
// Track depositor's reward
depositorTotalReward += depositorReward;
// Add pickaxe owner reward if applicable
if (pickaxeReward > 0) {
_accumulatePickaxeReward(
pickaxeOwner,
pickaxeReward,
pickaxeOwners,
rewards,
uniqueOwnersCount
);
uniqueOwnersCount = _getUniqueOwnersCount(pickaxeOwners);
}
// Mark ore as deposited and track repeated deposits
depositedOreChunks[oreId] = true;
_orePreviouslyDeposited[oreId] = true;
emit OreDeposited(sender, oreId);
}
// Distribute the accumulated rewards
_distributeRewards(
sender,
depositorTotalReward,
pickaxeOwners,
rewards,
uniqueOwnersCount
);
}
/**
* @notice Calculates rewards for a single ore
* @dev Handles reward calculation and pickaxe owner determination
*
* @param oreId ID of the ore chunk
* @param depositor Address of the ore depositor
*
* @return pickaxeReward Reward for the pickaxe owner
* @return depositorReward Reward for the depositor
* @return pickaxeOwner Address of the pickaxe owner
*/
function _calculateOreRewards(
uint256 oreId,
address depositor
)
internal
view
returns (
uint256 pickaxeReward,
uint256 depositorReward,
address pickaxeOwner
)
{
// Get chunk data
(uint256 pickaxeId, uint256 goldQuantity) = IOreMine(theMine)
.getOrePickAndGoldQuantity(oreId);
// Calculate gold amount with 18 decimals
uint256 goldWeiQuantity = goldQuantity * WEI_MULTIPLIER;
// Default values
pickaxeReward = 0;
pickaxeOwner = address(0);
try IERC721(picks).ownerOf(pickaxeId) returns (address owner) {
pickaxeOwner = owner;
} catch {}
// If pickaxe owner is different from ore depositor, give them 5%
if (
pickaxeOwner != depositor &&
pickaxeOwner != address(0) &&
pickaxeOwner != DEAD_ADDRESS
) {
// Every good miner shares with their tool provider
pickaxeReward = (goldWeiQuantity * 5) / 100;
}
// Calculate manager's reward
uint256 managerReward = _orePreviouslyDeposited[oreId]
? 0
: (goldWeiQuantity * 5);
// Calculate depositor's reward
depositorReward = goldWeiQuantity - pickaxeReward - managerReward;
return (pickaxeReward, depositorReward, pickaxeOwner);
}
/**
* @notice Accumulates pickaxe rewards for unique owners
* @param pickaxeOwner Address of the pickaxe owner
* @param pickaxeReward Amount of reward for this pickaxe owner
* @param pickaxeOwners Array of unique pickaxe owner addresses
* @param rewards Array of rewards corresponding to pickaxeOwners
* @param uniqueOwnersCount Current count of unique owners
* @dev Updates the pickaxeOwners and rewards arrays
*/
function _accumulatePickaxeReward(
address pickaxeOwner,
uint256 pickaxeReward,
address[] memory pickaxeOwners,
uint256[] memory rewards,
uint256 uniqueOwnersCount
) internal pure {
// Add to pickaxe owner's rewards or create new entry
bool ownerFound = false;
for (uint256 j = 0; j < uniqueOwnersCount; j++) {
if (pickaxeOwners[j] == pickaxeOwner) {
rewards[j] += pickaxeReward;
ownerFound = true;
break;
}
}
if (!ownerFound) {
pickaxeOwners[uniqueOwnersCount] = pickaxeOwner;
rewards[uniqueOwnersCount] = pickaxeReward;
}
}
/**
* @notice Gets the count of unique pickaxe owners
* @param pickaxeOwners Array of pickaxe owner addresses
* @return count Number of unique non-zero addresses
*/
function _getUniqueOwnersCount(
address[] memory pickaxeOwners
) internal pure returns (uint256 count) {
for (uint256 i = 0; i < pickaxeOwners.length; i++) {
if (pickaxeOwners[i] != address(0)) {
count++;
} else {
break;
}
}
return count;
}
/**
* @notice Distributes all accumulated rewards
* @param depositor Address of the depositor
* @param depositorReward Total reward for the depositor
* @param pickaxeOwners Array of pickaxe owner addresses
* @param rewards Array of rewards corresponding to pickaxeOwners
* @param uniqueOwnersCount Count of unique pickaxe owners
* @dev Mints tokens to each recipient - one golden payday for everyone!
*/
function _distributeRewards(
address depositor,
uint256 depositorReward,
address[] memory pickaxeOwners,
uint256[] memory rewards,
uint256 uniqueOwnersCount
) internal {
// Mint total rewards to depositor
_transfer(address(this), depositor, depositorReward);
// Mint tokens to pickaxe owners (one mint per unique owner)
for (uint256 i = 0; i < uniqueOwnersCount; i++) {
_transfer(address(this), pickaxeOwners[i], rewards[i]);
}
}
/**
* @notice Sell gold tokens to the contract
* @param goldWeiAmount Amount of gold tokens to sell (with 18 decimals)
* @dev Users can cash out their gold tokens for APE at the current gold value
* The contract buys gold at exactly goldValue() with no fees or premium
* This increases goldForSale and totalWeiSpent for tracking
*/
function sellGold(
uint256 goldWeiAmount
) external nonReentrant onlyMerchantEnabled allowTokenReceipt {
address seller = msg.sender;
require(goldWeiAmount > 0, "Amount cannot be zero");
require(balanceOf(seller) >= goldWeiAmount, "Insufficient balance");
uint256 currentGoldValue = goldValue();
// Calculate APE to send to seller
// divide by WEI_MULTIPLIER because currentGoldValue is for 1 gold with 18 decimals
uint256 totalGoldValue = (goldWeiAmount * currentGoldValue) /
WEI_MULTIPLIER;
// Make sure contract has enough APE, otherwise adjust the amount
// This should never happen, the contract should always have enough APE,
// but just in case, we'll adjust the amount to sell
if (totalGoldValue > address(this).balance) {
totalGoldValue = address(this).balance;
goldWeiAmount =
(totalGoldValue * WEI_MULTIPLIER) /
currentGoldValue;
}
// Transfer gold from seller to contract
_transfer(seller, address(this), goldWeiAmount);
// Update contract's tracking
totalWeiSpent += totalGoldValue;
goldForSale += goldWeiAmount;
// Send APE to seller
(bool success, ) = msg.sender.call{value: totalGoldValue}("");
require(success, "Payment failed");
emit GoldSold(seller, goldWeiAmount, totalGoldValue);
}
/**
* @notice Buy gold tokens from the contract
* @dev The Midas touch - convert your APE to shiny gold tokens
* Users send APE and get gold tokens at the current value plus premiums:
* - A base 1% management fee
* - A dynamic premium that decreases as goldCap increases (10% below 21000 APE, 1% above 210000 APE)
* - Premiums and profits increase goldCap, raising gold value for everyone
*/
function buyGold() external payable nonReentrant {
uint256 value = msg.value;
require(value > 0, "No value sent");
uint256 contractOwnedGold = goldForSale;
require(contractOwnedGold > 0, "No gold available for purchase");
// Calculate how much gold the user gets for their APE
// value is multiplied by WEI_MULTIPLIER because currentGoldValue is for 1 gold with 18 decimals
uint256 currentGoldValue = goldValue();
(
uint256 valueToConvertToGold,
uint256 premiumPct,
uint256 managementFeePct
) = _calculateValueToConvertToGold(value);
uint256 goldAmount = (valueToConvertToGold * WEI_MULTIPLIER) /
currentGoldValue;
uint256 refund = 0;
// Make sure we don't sell more than the contract owns
if (goldAmount > contractOwnedGold) {
goldAmount = contractOwnedGold;
}
uint256 saleAmount18 = (goldAmount * currentGoldValue);
// Calculate profit
// e.g. previously bought 1 gold for 1 eth => averageAcquisitionPrice = 1 * 10^18
uint256 acquisitionCost18 = (goldAmount * averageAcquisitionPrice());
// If we made a profit, add it to goldCap (increases gold value for everyone)
uint256 profit = saleAmount18 - acquisitionCost18;
// Adjust tracking variables to maintain accurate acquisition price
goldForSale -= goldAmount;
totalWeiSpent -= acquisitionCost18 / WEI_MULTIPLIER;
// Recalculate actual fees based on the final gold amount
uint256 actualCost = saleAmount18 / WEI_MULTIPLIER;
uint256 actualPremium = (actualCost * premiumPct) / 10000;
uint256 actualManagementFee = (actualCost * managementFeePct) / 10000;
uint256 actualTotalCost = actualCost +
actualPremium +
actualManagementFee;
if (actualTotalCost > value) {
revert("Actual total cost is greater than value");
}
// Add premium and profit to goldCap - the rising tide lifts all boats
_goldCap += actualPremium + (profit / WEI_MULTIPLIER);
// Send management fee to manager or add to goldCap if it fails
if (manager != address(0)) {
(bool managerSuccess, ) = manager.call{value: actualManagementFee}(
""
);
if (!managerSuccess) {
emit ManagerPaymentFailed(manager, actualManagementFee);
_goldCap += actualManagementFee;
}
} else {
_goldCap += actualManagementFee;
}
// Refund excess value
refund = value - actualTotalCost;
if (refund > 0) {
(bool success, ) = msg.sender.call{value: refund}("");
require(success, "Refund failed");
}
// Transfer gold to buyer
_transfer(address(this), msg.sender, goldAmount);
emit GoldBought(
msg.sender,
goldAmount,
actualCost,
actualPremium + actualManagementFee
);
}
/**
* @notice Exchange gold tokens back for a specific ore chunk
* @param oreId The ID of the ore chunk to retrieve
* @dev Allows users to return to their mining roots by trading gold for original ore
* The ore must have been previously deposited, and caller must have sufficient gold
* Gold tokens are burned in exchange for the ore NFT
*/
function exchangeGoldForOre(
uint256 oreId
) external nonReentrant allowTokenReceipt {
require(depositedOreChunks[oreId], "Ore not deposited");
// Get chunk data
(, uint256 goldQuantity) = IOreMine(theMine).getOrePickAndGoldQuantity(
oreId
);
// Calculate gold amount with 18 decimals
uint256 goldWeiQuantity = goldQuantity * WEI_MULTIPLIER;
// Mark ore as not deposited, burn gold, and transfer ore
depositedOreChunks[oreId] = false;
_transfer(msg.sender, address(this), goldWeiQuantity);
IERC721(goldOre).safeTransferFrom(address(this), msg.sender, oreId);
emit GoldExchangedForOre(msg.sender, oreId);
}
/**
* @notice Opens the gold merchant for business
* @dev Once enabled, users can deposit ores, buy and sell gold
*/
function setMerchantEnabled() external onlyManager {
_merchantEnabled = true; // The merchant is ready to receive gold!
}
/**
* @notice Opens the ore deposits for the gold merchant
* @dev Once enabled, users can deposit ores
*/
function setOreDepositsEnabled() external onlyManager {
_oreDepositsEnabled = true; // The merchant is ready to receive ores!
}
/**
* @notice Required for IERC721Receiver interface
* @dev Ensures the contract can receive only Gold Ore NFTs from those properly using safeTransferFrom
*/
function onERC721Received(
address operator,
address,
uint256,
bytes calldata
) external view override returns (bytes4) {
if (operator != address(this)) {
revert("Not gold merchant");
}
return this.onERC721Received.selector;
}
/**
* @notice Calculate how much wei needs to be sent to purchase a specific amount of gold
* @param goldAmount The amount of gold tokens to purchase (with 18 decimals)
* @return weiRequired The total amount of wei needed to buy the specified gold
* @dev This is the reverse calculation of buyGold:
* - Calculates the base cost of the gold
* - Applies the same premium and management fee percentages
* - Useful for users to know how much to send before transaction
*/
function calculateWeiForGold(
uint256 goldAmount
) public view returns (uint256) {
// Calculate base cost of gold
uint256 currentGoldValue = goldValue();
uint256 baseGoldCost = (goldAmount * currentGoldValue) / WEI_MULTIPLIER;
// Get the same premium and management fee percentages
uint256 managementFeePct = 100; // 1% - consistent with _calculateValueToConvertToGold
uint256 goldCapPremiumPct = 100; // Default 1%
// Calculate premium percentage based on goldCap (same logic as _calculateValueToConvertToGold)
if (_goldCap <= 21_000 ether) {
goldCapPremiumPct = 1000; // 10% when goldCap is low
} else if (_goldCap < 210_000 ether) {
goldCapPremiumPct = (100 * 210_000 ether) / _goldCap; // Dynamic scaling
}
// Calculate total required wei
// If valueToConvertToGold = (value * 10000) / (10000 + fees),
// Then value = valueToConvertToGold * (10000 + fees) / 10000
uint256 weiRequired = (baseGoldCost *
(10000 + goldCapPremiumPct + managementFeePct)) / 10000;
return weiRequired; // Strike gold without guessing how much to send!
}
/**
* @notice Calculate the value conversion and fees for gold purchases
* @param value The amount of APE sent to the contract
* @return valueToConvertToGold The base amount of APE used to buy gold
* @return goldCapPremiumPct The premium percentage based on goldCap
* @return managementFeePct The management fee percentage
* @dev This implements the dynamic premium system:
* - 1% management fee (flat)
* - Premium scales from 10% when goldCap is low to 1% when goldCap is high
* - The formula ensures that all APE is accounted for with no rounding issues
*/
function _calculateValueToConvertToGold(
uint256 value
) internal view returns (uint256, uint256, uint256) {
uint256 managementFeePct = 100; // 1% - every merchant needs their cut
uint256 goldCapPremiumPct = 100; // Default 1% - the treasure chest premium
// Higher premium when goldCap is low, lower premium when goldCap is high
if (_goldCap <= 21_000 ether) {
goldCapPremiumPct = 1000; // 10%
} else if (_goldCap < 210_000 ether) {
// Dynamic scaling - the more valuable gold is, the lower the premium
goldCapPremiumPct = (100 * 210_000 ether) / _goldCap;
}
// Calculate how much of the sent value goes to buying gold vs fees
uint256 valueToConvertToGold = (value * 10000) /
(10000 + managementFeePct + goldCapPremiumPct);
uint256 premium = (valueToConvertToGold * goldCapPremiumPct) / 10000;
uint256 managementFee = (valueToConvertToGold * managementFeePct) /
10000;
// Recalculate to ensure exact accounting (handles rounding)
valueToConvertToGold = value - premium - managementFee;
return (valueToConvertToGold, goldCapPremiumPct, managementFeePct);
}
/**
* @notice Initializes the contract
* @dev This function is called when the contract is deployed
* @dev Mints the full supply of tokens to this contract, then transfers 5% to the manager
*/
function _init() internal allowTokenReceipt {
uint256 supply = GOLD_SUPPLY * WEI_MULTIPLIER;
_mint(address(this), supply);
// Transfer 5% of the supply to the manager
_transfer(address(this), manager, (supply * 5) / 100);
}
function _beforeTokenTransfer(
address,
address to,
uint256
) internal override {
if (to == address(this)) {
require(
_tokenReceiptAllowed,
"Transfer to merchant only allowed during approved functions"
);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import {OreMine, GoldOreChunkData, MinerNFT} from "./OreMine.sol";
import {PickaxeMerchant, PickaxeTypeMetadata} from "./PickaxeMerchant.sol";
import {IPickaxes} from "./Pickaxes.sol";
import {IOreChunks} from "./OreChunks.sol";
import {IGoldMerchant} from "./GoldMerchant.sol";
interface ITheMine {
function getPickaxeMetadata(
uint256 pickaxeId
) external view returns (string memory);
}
interface IDelegateRegistry {
function checkDelegateForAll(
address to,
address from,
bytes32 rights
) external view returns (bool);
}
contract TheMine is
UUPSUpgradeable,
OwnableUpgradeable,
ReentrancyGuardUpgradeable,
PausableUpgradeable,
IERC721ReceiverUpgradeable,
PickaxeMerchant,
OreMine
{
using Strings for string;
address internal constant DEAD_ADDRESS =
0x000000000000000000000000000000000000dEaD;
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address internal immutable PICKAXES_CONTRACT;
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address internal immutable ORE_CHUNKS_CONTRACT;
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address internal immutable DELEGATE_REGISTRY;
uint256 internal PICKAXE_RENTAL_PRICE;
address internal management;
uint256 internal goldCap;
bool internal pickaxeMerchantEnabled;
bool internal oreMerchantEnabled;
// NFT contracts that can mine
mapping(address => bool) internal minerNFTContracts;
// Pickaxe state
mapping(uint256 => uint256) public pickaxeTotalOresMined;
mapping(uint256 => uint256) public pickaxeTotalGoldMined;
// Rented pickaxes
mapping(address => uint256) internal rentedPickaxes;
mapping(uint256 => bool) internal rentedPickaxeUsed;
uint256 internal nextRentedPickaxeId;
mapping(uint256 => uint256) internal chunkSoldPrice;
uint256 internal pickaxeRentalCount;
address public goldMerchant;
bool public goldMerchantEnabled;
// Events
event OrePurchased(
uint256 indexed oreId,
address indexed buyer,
uint256 price
);
event OreSold(uint256 indexed oreId, address indexed seller, uint256 price);
event MinerPaymentFailed(address indexed miner, uint256 amount);
modifier onlyManagement() {
require(
msg.sender == management,
"Only management can call this function"
);
_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(
address _pickaxesContract,
address _oreChunksContract,
address _delegateRegistry
) {
_disableInitializers();
require(_pickaxesContract != address(0), "Invalid pickaxes contract");
require(
_oreChunksContract != address(0),
"Invalid ore chunks contract"
);
PICKAXES_CONTRACT = _pickaxesContract;
ORE_CHUNKS_CONTRACT = _oreChunksContract;
DELEGATE_REGISTRY = _delegateRegistry;
}
function initialize(address _signer) public initializer {
__Ownable_init();
__ReentrancyGuard_init();
__Pausable_init();
__PickaxeMerchant_init(_signer);
__OreMine_init();
management = msg.sender;
nextRentedPickaxeId = 10000;
}
receive() external payable {
if (goldMerchantEnabled) {
(bool success, ) = goldMerchant.call{value: msg.value}("");
require(success, "Transfer to gold merchant failed");
} else {
goldCap += msg.value;
}
}
// ** ADMIN ** //
function pause() external onlyManagement {
_pause();
}
function unpause() external onlyManagement {
_unpause();
}
function setManagement(address newManagement) external onlyManagement {
require(newManagement != address(0), "Invalid management address");
management = newManagement;
}
function withdrawERC20(
address tokenContract,
uint256 amount
) external onlyManagement {
IERC20(tokenContract).transfer(management, amount);
}
function withdrawERC721Batch(
address tokenContract,
uint256[] calldata tokenIds
) external onlyManagement {
for (uint256 i = 0; i < tokenIds.length; i++) {
IERC721(tokenContract).safeTransferFrom(
address(this),
management,
tokenIds[i]
);
}
}
function setGoldMerchant(address _goldMerchant) external onlyOwner {
goldMerchant = _goldMerchant;
}
function transferToGoldMerchant() external onlyOwner {
(bool success, ) = goldMerchant.call{value: address(this).balance}("");
require(success, "Transfer to gold merchant failed");
goldMerchantEnabled = true;
}
// ** PUBLIC GETTERS ** //
function chunkValue(uint256 oreId) public view returns (uint256) {
GoldOreChunkData memory chunk = getOreChunk(oreId);
return goldValue() * chunk.goldQuantity;
}
function goldValue() public view returns (uint256) {
if (goldMerchantEnabled) {
return IGoldMerchant(goldMerchant).goldValue();
} else {
return goldCap / MAX_GOLD;
}
}
function getGoldCap() public view returns (uint256) {
if (goldMerchantEnabled) {
return IGoldMerchant(goldMerchant).goldCap();
} else {
return goldCap;
}
}
// ** METADATA ** //
function getPickaxeMetadata(
uint256 pickaxeId
) external view returns (string memory) {
string memory metadata = "";
PickaxeTypeMetadata memory pickaxeTypeMetadata = _pickaxeTypeMetadata[
pickaxeType(pickaxeId)
];
metadata = string.concat(
metadata,
'{"name": "Pick #',
Strings.toString(pickaxeId),
'", "description": "',
pickaxeTypeMetadata.description,
'", "image": "',
pickaxeTypeMetadata.image,
'", "attributes": [',
'{"trait_type": "Ores Mined", "display_type": "number", "value": ',
Strings.toString(pickaxeTotalOresMined[pickaxeId]),
"}, ",
'{"trait_type": "Gold Mined", "display_type": "number", "value": ',
Strings.toString(pickaxeTotalGoldMined[pickaxeId]),
'}, {"trait_type": "Type", "value": "',
pickaxeTypeMetadata.name,
'"}, {"trait_type": "Multiplier", "display_type": "boost_number", "value": ',
Strings.toString(pickaxeType(pickaxeId)),
"}]}"
);
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(bytes(metadata))
)
);
}
function getOreChunkMetadata(
uint256 oreId
) external view returns (string memory) {
string memory metadata = "";
GoldOreChunkData memory chunk = goldOreChunks[oreId];
MinerNFT memory minerNFT = oreMinedByNFT[oreId];
metadata = string.concat(
metadata,
'{"name": "Gold Ore #',
Strings.toString(oreId),
'", "image": "https://themine.io/api/gold?oreId=',
Strings.toString(oreId),
'", "description": "Gold Ore containing ',
Strings.toString(chunk.goldQuantity),
" gold.\\n\\nMined by NFT from contract ",
Strings.toHexString(uint160(minerNFT.nftContract)),
" with ID ",
Strings.toString(minerNFT.nftId),
".\\n\\nHash: ",
Strings.toHexString(uint256(chunk.miningHash)),
'", "attributes": [{"trait_type": "Gold Quantity", "value": ',
Strings.toString(chunk.goldQuantity),
'}, {"trait_type": "Pick ID", "value": "',
Strings.toString(chunk.pickaxeId),
'"}, {"trait_type": "Gold Ratio", "value": ',
Strings.toString(chunk.goldRatio),
'}, {"trait_type": "Pick Multiplier", "display_type": "boost_number", "value": ',
Strings.toString(pickaxeType(chunk.pickaxeId)),
'}, {"trait_type": "Purity", "display_type": "boost_percentage", "value": ',
Strings.toString(orePurity(oreId)),
'}, {"trait_type": "Difficulty", "display_type": "number", "value": ',
Strings.toString(chunk.miningDifficulty),
'}, {"trait_type": "Attempts", "display_type": "number", "value": ',
Strings.toString(chunk.miningAttempts),
"}]}"
);
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(bytes(metadata))
)
);
}
// OVERRIDES //
function _authorizeUpgrade(address) internal virtual override {
_requireCallerIsContractOwner();
}
function _requireCallerIsContractOwner() internal view virtual override {
require(
msg.sender == owner(),
"Only the contract owner can call this function"
);
}
function onERC721Received(
address operator,
address,
uint256,
bytes calldata
) external view override returns (bytes4) {
require(operator == address(this), "Invalid operator");
return this.onERC721Received.selector;
}
function pickaxesContract() internal view returns (address) {
return PICKAXES_CONTRACT;
}
function oreChunksContract() internal view returns (address) {
return ORE_CHUNKS_CONTRACT;
}
function pickaxeType(
uint256 pickaxeId
) public view returns (uint256 pickaxeType_) {
pickaxeType_ = _pickaxeType[pickaxeId];
if (pickaxeType_ == 0) {
revert("Invalid Pickaxe ID");
}
}
// ** Upgradeable Gap ** //
uint256[36] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../NPC721CUpgradeable.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {GoldOreChunkData, IOreMine} from "./OreMine.sol";
import {IPickaxes} from "./Pickaxes.sol";
interface IOreChunks is IERC721 {
function batchSafeTransferFrom(
address from,
address to,
uint256[] calldata tokenIds
) external;
}
contract OreChunks is UUPSUpgradeable, NPC721CUpgradeable {
address constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD;
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint256 immutable ROYALTY_FEE_NUMERATOR;
// State variables
IPickaxes public pickaxes;
IOreMine public oreMine;
uint256 public totalSupply;
address public goldMerchant;
event MetadataUpdate(uint256 tokenId);
event BatchMetadataUpdate(uint256 startTokenId, uint256 endTokenId);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(uint256 _royaltyFeeNumerator) {
require(
_royaltyFeeNumerator <= ROYALTY_FEE_DENOMINATOR,
"Invalid royalty fee"
);
ROYALTY_FEE_NUMERATOR = _royaltyFeeNumerator;
_disableInitializers();
}
function initialize(
string memory name_,
string memory symbol_,
address _pickaxes
) public initializer {
__NPC721CUpgradeable_init(name_, symbol_);
pickaxes = IPickaxes(_pickaxes);
}
function setGoldMerchant(address _goldMerchant) external onlyOwner {
require(_goldMerchant != address(0), "Invalid gold merchant");
goldMerchant = _goldMerchant;
}
function royaltyInfo(
uint256 tokenId,
uint256 salePrice
) external view override returns (address receiver, uint256 royaltyAmount) {
require(_exists(tokenId), "Token does not exist");
GoldOreChunkData memory chunk = oreMine.getOreChunk(tokenId);
try pickaxes.ownerOf(chunk.pickaxeId) returns (address owner) {
receiver = owner;
} catch {
receiver = address(oreMine);
}
if (receiver == address(0) || receiver == DEAD_ADDRESS) {
receiver = address(oreMine);
}
royaltyAmount =
(salePrice * ROYALTY_FEE_NUMERATOR) /
ROYALTY_FEE_DENOMINATOR;
}
function tokenURI(
uint256 tokenId
) public view virtual override returns (string memory) {
require(_exists(tokenId), "Token does not exist");
return oreMine.getOreChunkMetadata(tokenId);
}
function contractURI() public pure returns (string memory) {
string
memory json = '{"name": "Gold Ore (The Mine)", "description": "Gold Ore is the raw material mined by Picks", "image": "https://themine.io/images/gold-ore.png", "external_link": "https://themine.io"}';
return string.concat("data:application/json;utf8,", json);
}
function emitMetadataUpdate(uint256 tokenId) external {
emit MetadataUpdate(tokenId);
}
function emitMetadataUpdateAll() external {
emit BatchMetadataUpdate(1, totalSupply);
}
function batchSafeTransferFrom(
address from,
address to,
uint256[] calldata tokenIds
) external {
uint256 numTokens = tokenIds.length;
for (uint256 i = 0; i < numTokens; ++i) {
_safeTransfer(from, to, tokenIds[i], "");
}
}
// OVERRIDES //
function _authorizeUpgrade(address) internal view override onlyOwner {}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId,
uint256
) internal override {
address sender = _msgSender();
if (sender != goldMerchant) {
_preValidateTransfer(sender, from, to, tokenId);
}
super._beforeTokenTransfer(from, to, tokenId, 1);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
struct GoldOreChunkData {
address minedBy;
bytes32 miningHash;
uint256 minedAt;
uint256 miningAttempts;
uint256 miningDifficulty;
uint256 pickaxeId;
uint256 pickaxeType;
uint256 pickaxePreviousMined;
uint256 goldRatio;
uint256 goldQuantity;
}
struct MinerNFT {
address nftContract;
uint256 nftId;
}
interface IOreMine {
function getOreChunk(
uint256 tokenId
) external view returns (GoldOreChunkData memory);
function getOreChunkMetadata(
uint256 tokenId
) external view returns (string memory);
function getOrePickAndGoldQuantity(
uint256 tokenId
) external view returns (uint256, uint256);
}
abstract contract OreMine is Initializable, IOreMine {
uint256 internal constant MAX_GOLD = 21_000_000;
bool internal miningEnabled;
uint256 internal goldMined;
uint256 internal nftMiningCooldownHours;
uint256 internal lastOreChunkMined;
mapping(bytes32 => uint256) public miningHashToOreChunkId;
mapping(uint256 => uint256) internal pickaxeLastMinedOre; // pickaxeId => oreId
mapping(uint256 => uint256) internal pickaxeLastMiningTime; // pickaxeId => timestamp
mapping(address => mapping(uint256 => uint256))
internal _previousNftMiningTime; // nftContract => nftId => timestamp
mapping(uint256 => GoldOreChunkData) internal goldOreChunks;
mapping(uint256 => MinerNFT) public oreMinedByNFT; // oreId => MinerNFT
mapping(uint256 => uint256) internal _totalGoldMinedBeforeOreId;
mapping(uint256 => uint256) internal _orePurity;
event MiningEnabled(bool enabled);
function __OreMine_init() internal onlyInitializing {}
// ** PUBLIC ** //
function getOreChunk(
uint256 tokenId
) public view returns (GoldOreChunkData memory) {
return goldOreChunks[tokenId];
}
function getOrePickAndGoldQuantity(
uint256 tokenId
) public view returns (uint256, uint256) {
GoldOreChunkData memory chunk = goldOreChunks[tokenId];
return (chunk.pickaxeId, chunk.goldQuantity);
}
function nftLastMinedTime(
address nftContract,
uint256 nftId
) public view returns (uint256) {
return _previousNftMiningTime[nftContract][nftId];
}
function orePurity(uint256 oreId) public view returns (uint256 purity) {
purity = _orePurity[oreId];
if (purity == 0) {
purity = 100;
}
}
// ** Upgradeable Gap ** //
uint256[38] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {IPickaxes} from "./Pickaxes.sol";
interface IPickaxeMerchant {}
struct PickaxeTypeMetadata {
string name;
string description;
string image;
}
abstract contract PickaxeMerchant is Initializable {
using ECDSA for bytes32;
uint256 internal nonGtdMinted;
bool internal GTD_RESERVE_ENDED;
mapping(uint256 => uint256) internal _pickaxeType; // tokenId => pickaxe type
mapping(address => uint256) internal boughtPickaxes; // address => total pickaxes bought
mapping(uint256 => uint256) internal pickaxeTypeSupply; // pickaxe type => current supply
mapping(uint256 => uint256) internal pickaxeTypeMaxSupply; // pickaxe type => max supply
mapping(uint256 => PickaxeTypeMetadata) internal _pickaxeTypeMetadata; // pickaxe type => metadata
address internal signer; // signer of the allowance signature
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {}
function __PickaxeMerchant_init(address _signer) internal onlyInitializing {
signer = _signer;
}
function setPickaxeTypeMetadata(
uint256 pickaxeType_,
PickaxeTypeMetadata memory metadata
) external {
_requireCallerIsContractOwner();
_pickaxeTypeMetadata[pickaxeType_] = metadata;
}
function _requireCallerIsContractOwner() internal view virtual;
// upgradeable gap
uint256[42] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../NPC721CUpgradeable.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ITheMine} from "./Mine.sol";
interface IPickaxes is IERC721 {
function mint(
address to,
uint256 amount
) external returns (uint256 tokenId);
function tokenPickaxeType(uint256 tokenId) external view returns (uint256);
function emitMetadataUpdate(uint256 tokenId) external;
function emitMetadataUpdateAll() external;
}
contract Pickaxes is UUPSUpgradeable, NPC721CUpgradeable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint256 immutable ROYALTY_FEE_NUMERATOR;
// State variables
address public THE_MINE;
uint256 public totalSupply;
event RoyaltyFeeUpdated(uint256 oldFee, uint256 newFee);
event MetadataUpdate(uint256 tokenId);
event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
modifier onlyTheMine() {
require(
THE_MINE != address(0) && msg.sender == THE_MINE,
"Only The Mine can do this"
);
_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(uint256 _royaltyFeeNumerator) {
_disableInitializers();
require(
_royaltyFeeNumerator <= ROYALTY_FEE_DENOMINATOR,
"Invalid royalty fee"
);
ROYALTY_FEE_NUMERATOR = _royaltyFeeNumerator;
}
function initialize(
string memory name_,
string memory symbol_
) public initializer {
__NPC721CUpgradeable_init(name_, symbol_);
}
function setMineContract(address _theMine) external onlyOwner {
require(_theMine != address(0), "Invalid mine contract");
THE_MINE = _theMine;
}
function mint(
address to,
uint256 amount
) external onlyTheMine returns (uint256) {
uint256 tokenId = totalSupply + 1;
for (uint256 i = 0; i < amount; i++) {
_safeMint(to, tokenId + i);
}
totalSupply += amount;
return tokenId;
}
function royaltyInfo(
uint256 tokenId,
uint256 salePrice
) external view override returns (address receiver, uint256 royaltyAmount) {
require(_exists(tokenId), "Token does not exist");
receiver = address(THE_MINE);
royaltyAmount =
(salePrice * ROYALTY_FEE_NUMERATOR) /
ROYALTY_FEE_DENOMINATOR;
}
function tokenURI(
uint256 tokenId
) public view virtual override returns (string memory) {
require(_exists(tokenId), "Token does not exist");
return ITheMine(THE_MINE).getPickaxeMetadata(tokenId);
}
function emitMetadataUpdate(uint256 tokenId) external {
emit MetadataUpdate(tokenId);
}
function emitMetadataUpdateAll() external {
emit BatchMetadataUpdate(1, totalSupply);
}
function batchSafeTransferFrom(
address from,
address to,
uint256[] calldata tokenIds
) external {
uint256 numTokens = tokenIds.length;
for (uint256 i = 0; i < numTokens; ++i) {
_safeTransfer(from, to, tokenIds[i], "");
}
}
function _authorizeUpgrade(
address newImplementation
) internal view override onlyOwner {}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId,
uint256
) internal override {
address sender = _msgSender();
if (sender != THE_MINE) {
_preValidateTransfer(sender, from, to, tokenId);
}
super._beforeTokenTransfer(from, to, tokenId, 1);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./limitbreak-upgradeable/CreatorTokenBaseUpgradeable.sol";
import "@limitbreak/creator-token-standards/src/interfaces/ICreatorToken.sol";
import "@limitbreak/creator-token-standards/src/interfaces/ICreatorTokenLegacy.sol";
import "@openzeppelin/contracts/interfaces/IERC721.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
abstract contract NPC721CUpgradeable is
OwnableUpgradeable,
ReentrancyGuardUpgradeable,
ERC721Upgradeable,
CreatorTokenBaseUpgradeable
{
uint256 internal constant ROYALTY_FEE_DENOMINATOR = 10000;
function __NPC721CUpgradeable_init(
string memory name_,
string memory symbol_
) public initializer {
__Ownable_init();
__ReentrancyGuard_init();
__ERC721_init(name_, symbol_);
__CreatorTokenBaseUpgradeable_init();
}
function supportsInterface(
bytes4 interfaceId
) public view virtual override(ERC721Upgradeable) returns (bool) {
return
interfaceId == type(IERC2981).interfaceId ||
interfaceId == type(ICreatorToken).interfaceId ||
interfaceId == type(ICreatorTokenLegacy).interfaceId ||
super.supportsInterface(interfaceId);
}
function _requireCallerIsContractOwner() internal view virtual override {
_checkOwner();
}
function _tokenType() internal pure override returns (uint16) {
return 721;
}
function getTransferValidationFunction()
external
pure
override
returns (bytes4 functionSignature, bool isViewFunction)
{
return (
bytes4(
keccak256("validateTransfer(address,address,address,uint256)")
),
true
);
}
function royaltyInfo(
uint256 tokenId,
uint256 salePrice
) external view virtual returns (address receiver, uint256 royaltyAmount);
}{
"viaIR": true,
"optimizer": {
"enabled": true,
"runs": 2000,
"details": {
"yulDetails": {
"optimizerSteps": "u"
}
}
},
"debug": {
"revertStrings": "debug"
},
"evmVersion": "paris",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"goldOre_","type":"address"},{"internalType":"address","name":"picks_","type":"address"},{"internalType":"address","name":"theMine_","type":"address"},{"internalType":"address","name":"goldToken_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"buyer","type":"address"},{"indexed":true,"internalType":"uint256","name":"goldAmount","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"totalGoldValue","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalPremium","type":"uint256"}],"name":"GoldBought","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"oreId","type":"uint256"}],"name":"GoldExchangedForOre","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"seller","type":"address"},{"indexed":true,"internalType":"uint256","name":"goldAmount","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"totalGoldValue","type":"uint256"}],"name":"GoldSold","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"manager","type":"address"},{"indexed":false,"internalType":"uint256","name":"weiAmount","type":"uint256"}],"name":"ManagerPaymentFailed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"depositor","type":"address"},{"indexed":true,"internalType":"uint256","name":"oreId","type":"uint256"}],"name":"OreDeposited","type":"event"},{"inputs":[],"name":"averageAcquisitionPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"buyGold","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"goldAmount","type":"uint256"}],"name":"calculateWeiForGold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"oreIds","type":"uint256[]"}],"name":"depositOres","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"depositedOres","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"disableEmergencyWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"emergencyWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"oreId","type":"uint256"}],"name":"emergencyWithdrawOre","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"emergencyWithdrawToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"oreId","type":"uint256"}],"name":"exchangeGoldForOre","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"goldCap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"goldForSale","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"goldValue","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"orePreviouslyDeposited","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"goldWeiAmount","type":"uint256"}],"name":"sellGold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newManager","type":"address"}],"name":"setManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"setMerchantEnabled","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"setOreDepositsEnabled","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"totalWeiSpent","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]Contract Creation Code
6101006040523461008b5761001e6100156101fa565b929190916103c0565b604051612c246104b082396080518181816114d501528181611c720152612065015260a051816127a7015260c051818181611b460152612701015260e0518181816110400152818161136301528181611778015281816119bc01528181611be90152612aca0152612c2490f35b608461009660405190565b62461bcd60e51b815260206004820152602260248201527f45746865722073656e7420746f206e6f6e2d70617961626c652066756e63746960448201526137b760f11b6064820152fd5b634e487b7160e01b600052604160045260246000fd5b90601f01601f191681019081106001600160401b0382111761011757604052565b6100e0565b9061013061012960405190565b92836100f6565b565b608461013d60405190565b62461bcd60e51b815260206004820152602260248201527f414249206465636f64696e673a207475706c65206461746120746f6f2073686f6044820152611c9d60f21b6064820152fd5b6001600160a01b031690565b90565b6001600160a01b038116036101a757565b600080fd5b9050519061013082610196565b6080818303126101f5576101cd82826101ac565b926101936101de84602085016101ac565b9360606101ee82604087016101ac565b94016101ac565b610132565b6102186130d48038038061020d8161011c565b9283398101906101b9565b90919293565b6101876101936101939290565b6101939061021e565b1561023b57565b60405162461bcd60e51b815260206004820152601960248201527f496e76616c6964204f72654368756e6b732061646472657373000000000000006044820152606490fd5b1561028757565b60405162461bcd60e51b815260206004820152601860248201527f496e76616c6964205069636b61786573206164647265737300000000000000006044820152606490fd5b156102d357565b60405162461bcd60e51b815260206004820152601760248201527f496e76616c6964205468654d696e6520616464726573730000000000000000006044820152606490fd5b1561031f57565b60405162461bcd60e51b815260206004820152601960248201527f496e76616c696420476f6c64546f6b656e2061646472657373000000000000006044820152606490fd5b906301000000600160b81b039060181b5b9181191691161790565b61019390610187906001600160a01b031682565b6101939061037f565b61019390610393565b906103b56101936103bc9261039c565b8254610364565b9055565b6103c861045a565b6104436104326103d8600061022b565b6103f66001600160a01b0382166001600160a01b0386161415610234565b6104146001600160a01b0382166001600160a01b0387161415610280565b6101876001600160a01b0382166001600160a01b03881614156102cc565b6001600160a01b0386161415610318565b60805260a05260c05260e0526101303360016103a5565b61013061013061049d565b6101936101936101939290565b6101936001610465565b9060001990610375565b906104966101936103bc92610465565b825461047c565b6101306104a8610472565b600061048656fe6080604052600436101561001d575b3661092f5761001b612527565b005b60003560e01c80630894b00f1461017d578063150b7a02146101785780631d95480f146101735780632f7b8af41461016e57806331aa1ec914610169578063481c6a7514610164578063492560471461015f5780634f4023211461015a57806350911ace14610155578063536c4c7b1461015057806370a082311461014b5780638f2c3ee914610146578063a511289f14610141578063a56fc8811461013c578063aa256f1414610137578063b039cf6f14610132578063d0ebdbe71461012d578063db2e21bc14610128578063de4e5a4514610123578063e08ac27f1461011e578063fa322935146101195763ffced28b0361000e57610914565b6108f9565b6108de565b6108ba565b6108a2565b61088a565b61086f565b610856565b6107e8565b6107d0565b6107b5565b61078e565b610762565b61074a565b610732565b61071a565b6106f3565b610687565b61065f565b610632565b610578565b61029d565b608461018d60405190565b62461bcd60e51b815260206004820152602260248201527f45746865722073656e7420746f206e6f6e2d70617961626c652066756e63746960448201527f6f6e0000000000000000000000000000000000000000000000000000000000006064820152fd5b60846101fd60405190565b62461bcd60e51b815260206004820152602260248201527f414249206465636f64696e673a207475706c65206461746120746f6f2073686f60448201527f72740000000000000000000000000000000000000000000000000000000000006064820152fd5b600091031261026d57565b6101f2565b61027d916008021c81565b90565b9061027d9154610272565b61027d60006004610280565b9052565b565b346102cd576102ad366004610262565b6102c96102b861028b565b6040515b9182918290815260200190565b0390f35b610182565b60846102dd60405190565b62461bcd60e51b815260206004820152602260248201527f414249206465636f64696e673a20696e76616c6964207475706c65206f66667360448201527f65740000000000000000000000000000000000000000000000000000000000006064820152fd5b73ffffffffffffffffffffffffffffffffffffffff1690565b61036481610342565b0361036b57565b600080fd5b9050359061029b8261035b565b80610364565b9050359061029b8261037d565b608461039b60405190565b62461bcd60e51b815260206004820152602b60248201527f414249206465636f64696e673a20696e76616c69642063616c6c64617461206160448201527f72726179206f66667365740000000000000000000000000000000000000000006064820152fd5b608461040b60405190565b62461bcd60e51b815260206004820152602b60248201527f414249206465636f64696e673a20696e76616c69642063616c6c64617461206160448201527f72726179206c656e6774680000000000000000000000000000000000000000006064820152fd5b608461047b60405190565b62461bcd60e51b815260206004820152602b60248201527f414249206465636f64696e673a20696e76616c69642063616c6c64617461206160448201527f72726179207374726964650000000000000000000000000000000000000000006064820152fd5b909182601f8301121561051a5781359167ffffffffffffffff831161051557602001926001830284011161051057565b610470565b610400565b610390565b9060808282031261026d576105348183610370565b926105428260208501610370565b926105508360408301610383565b92606082013567ffffffffffffffff81116105735761056f92016104e0565b9091565b6102d2565b346102cd576102c961059761058e36600461051f565b93929092610a4d565b604051918291827fffffffff00000000000000000000000000000000000000000000000000000000909116815260200190565b9060208282031261026d5761027d91610383565b61027d61027d61027d9290565b906105f5906105de565b600052602052604060002090565b61027d916008021c5b60ff1690565b9061027d9154610603565b600061062d61027d9260066105eb565b610612565b346102cd576102c961064d6106483660046105ca565b61061d565b60405191829182901515815260200190565b61066a366004610262565b610672611208565b604051005b600061062d61027d9260056105eb565b346102cd576102c961064d61069d3660046105ca565b610677565b61027d916008021c73ffffffffffffffffffffffffffffffffffffffff1690565b9061027d91546106a2565b61027d600360016106c3565b61029790610342565b60208101929161029b91906106da565b346102cd57610703366004610262565b6102c961070e6106ce565b604051918291826106e3565b346102cd5761072a366004610262565b610672611472565b346102cd576106726107453660046105ca565b61158b565b346102cd5761067261075d3660046105ca565b611957565b346102cd57610772366004610262565b6106726119ac565b9060208282031261026d5761027d91610370565b346102cd576102c96102b86107a436600461077a565b6119b4565b61027d60006003610280565b346102cd576107c5366004610262565b6102c96102b86107a9565b346102cd576107e0366004610262565b610672611a7d565b346102cd576106726107fb3660046105ca565b611d8f565b909182601f8301121561051a5781359167ffffffffffffffff831161051557602001926020830284011161051057565b9060208282031261026d57813567ffffffffffffffff81116105735761056f9201610800565b346102cd57610672610869366004610830565b90612250565b346102cd5761087f366004610262565b6102c96102b861225a565b346102cd5761067261089d36600461077a565b6122ff565b346102cd576108b2366004610262565b6106726123c7565b346102cd576108ca366004610262565b610672612417565b61027d60006002610280565b346102cd576108ee366004610262565b6102c96102b86108d2565b346102cd57610909366004610262565b6102c96102b861242c565b346102cd576102c96102b861092a3660046105ca565b612441565b608461093a60405190565b62461bcd60e51b815260206004820152602960248201527f556e6b6e6f776e207369676e617475726520616e64206e6f2066616c6c62616360448201527f6b20646566696e656400000000000000000000000000000000000000000000006064820152fd5b61034261027d61027d9273ffffffffffffffffffffffffffffffffffffffff1690565b61027d9061099f565b61027d906109c2565b0190565b60208082526011908201527f4e6f7420676f6c64206d65726368616e74000000000000000000000000000000604082015260600190565b610a28610a2261027d9263ffffffff1690565b60e01b90565b7fffffffff000000000000000000000000000000000000000000000000000000001690565b9350505050610a5a600090565b50610a75610a6f610a6a306109cb565b610342565b91610342565b03610a875761027d63150b7a02610a0f565b60405162461bcd60e51b815280610aa0600482016109d8565b0390fd5b610aac61259f565b610ab4610e77565b61029b6125d1565b6020808252600d908201527f4e6f2076616c75652073656e7400000000000000000000000000000000000000604082015260600190565b15610afa57565b60405162461bcd60e51b815280610aa060048201610abc565b61027d9081565b61027d9054610b13565b6020808252601e908201527f4e6f20676f6c6420617661696c61626c6520666f722070757263686173650000604082015260600190565b15610b6257565b60405162461bcd60e51b815280610aa060048201610b24565b61027d670de0b6b3a76400006105de565b634e487b7160e01b600052601160045260246000fd5b81810292918115918404141715610bb557565b610b8c565b634e487b7160e01b600052601260045260246000fd5b90610bda565b9190565b908115610be5570490565b610bba565b91908203918211610bb557565b90600019905b9181191691161790565b90610c1761027d610c1e926105de565b8254610bf7565b9055565b91908201809211610bb557565b60208082526027908201527f41637475616c20746f74616c20636f737420697320677265617465722074686160408201527f6e2076616c756500000000000000000000000000000000000000000000000000606082015260800190565b61027d9060181c610342565b61027d9054610c8c565b61034261027d61027d9290565b61027d90610ca2565b634e487b7160e01b600052604160045260246000fd5b90601f01601f1916810190811067ffffffffffffffff821117610cf057604052565b610cb8565b9061029b610d0260405190565b9283610cce565b67ffffffffffffffff8111610cf057602090601f01601f19160190565b90610d38610d3383610d09565b610cf5565b918252565b3d15610d5757610d4c3d610d26565b903d6000602084013e565b606090565b6020808252600d908201527f526566756e64206661696c656400000000000000000000000000000000000000604082015260600190565b15610d9a57565b60405162461bcd60e51b815280610aa060048201610d5c565b6084610dbe60405190565b62461bcd60e51b815260206004820152602560248201527f54617267657420636f6e747261637420646f6573206e6f7420636f6e7461696e60448201527f20636f64650000000000000000000000000000000000000000000000000000006064820152fd5b801515610364565b9050519061029b82610e23565b9060208282031261026d5761027d91610e2b565b91602061029b929493610e67604082019660008301906106da565b0152565b6040513d6000823e3d90fd5b6000610e8c610e85826105de565b3411610af3565b610e966003610b1a565b90610eaa610ea3826105de565b8311610b5b565b610eb261242c565b90610ebc346125dc565b9093610ed981610ed4610ecd610b7b565b8096610ba2565b610bd0565b9586610ee4866105de565b5081106111fe575b50610f85610f5c610f5585610f028a9586610ba2565b610ed4610f4e610f4484610f1d610f1761225a565b8b610ba2565b610ed4610f3d610f2d8389610bea565b9c610f386003610b1a565b610bea565b6003610c07565b610f386004610b1a565b6004610c07565b9687610ba2565b610f72610f7f610f7861271093610f72856105de565b90610bd0565b9589610ba2565b916105de565b92610f9984610f948589610c22565b610c22565b903482116111e557610fc7610fbd610fb7610fce9361102596610bd0565b86610c22565b610f946002610b1a565b6002610c07565b610fd86001610c98565b610fe7610a6f610a6a88610caf565b146111d45761101a8580610ffb6001610c98565b60405188816110098161027d565b03925af1611015610d3d565b501590565b611180575b34610bea565b8361102f816105de565b821161114e575b50506110696110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b6109cb565b92833b156111495760209061107d60405190565b94859182907fa9059cbb000000000000000000000000000000000000000000000000000000008252816110b48b3360048401610e4c565b03925af1928315611144576110ce93611117575b50610c22565b917f1e17537bfae89caf79a05b46debe4b0b1d37bc9187daa9436b4f50ac4b10c53f611112611108611102611102336109cb565b946105de565b946102bc60405190565b0390a4565b6111389060203d60201161113d575b6111308183610cce565b810190610e38565b6110c8565b503d611126565b610e6b565b610db3565b806111799261115c60405190565b806111668161027d565b0391335af1611173610d3d565b50610d93565b3883611036565b61118d6110646001610c98565b7fabe56b86d17916937b7768d686c74e0d99817c3e201bf0e9f1edc5173750b2136111b760405190565b868152602090a26111cf610fc785610f946002610b1a565b61101f565b6111cf610fc785610f946002610b1a565b60405162461bcd60e51b815280610aa060048201610c2f565b9550610f85610eec565b61029b610aa4565b60208082526023908201527f4f6e6c79206d616e616765722063616e2063616c6c20746869732066756e637460408201527f696f6e0000000000000000000000000000000000000000000000000000000000606082015260800190565b1561127457565b60405162461bcd60e51b815280610aa060048201611210565b6112ac61129d610a6a6001610c98565b6112a633610342565b1461126d565b61029b611342565b61027d9060101c61060c565b61027d90546112b4565b6020808252601e908201527f456d657267656e63792077697468647261772069732064697361626c65640000604082015260600190565b1561130857565b60405162461bcd60e51b815280610aa0600482016112ca565b9050519061029b8261037d565b9060208282031261026d5761027d91611321565b61135b61135661135260016112c0565b1590565b611301565b6113876110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b6113916001610c98565b61139a306109cb565b823b156111495760206113ca916113b060405190565b9283918291906370a0823160e01b5b8352600483016106e3565b0381865afa90811561114457600091611443575b50823b15611149576114179260209260006113f860405190565b80968195829461140c63a9059cbb60e01b90565b845260048401610e4c565b03925af18015611144576114285750565b6114409060203d60201161113d576111308183610cce565b50565b611465915060203d60201161146b575b61145d8183610cce565b81019061132e565b386113de565b503d611453565b61029b61128d565b61029b9061148e61129d610a6a6001610c98565b6114bd565b604090610e6761029b94969593966114b3606084019860008501906106da565b60208301906106da565b6114cd61135661135260016112c0565b6114f96110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b90611503306109cb565b9061150e6001610c98565b92803b156111495761155a936000809461152760405190565b968795869485937f42842e0e00000000000000000000000000000000000000000000000000000000855260048501611493565b03925af180156111445761156b5750565b61029b9060005b61157c8183610cce565b810190610262565b503d611572565b61029b9061147a565b610ab4906115a061259f565b611612565b61027d9060081c61060c565b61027d90546115a5565b60208082526017908201527f4d65726368616e74206973206e6f7420656e61626c6564000000000000000000604082015260600190565b156115f957565b60405162461bcd60e51b815280610aa0600482016115bb565b61029b9061162060016115b1565b8015611635575b611630906115f2565b61175c565b50611630611646610a6a6001610c98565b61164f33610342565b149050611627565b60208082526015908201527f416d6f756e742063616e6e6f74206265207a65726f0000000000000000000000604082015260600190565b1561169557565b60405162461bcd60e51b815280610aa060048201611657565b60208082526014908201527f496e73756666696369656e742062616c616e6365000000000000000000000000604082015260600190565b156116ec57565b60405162461bcd60e51b815280610aa0600482016116ae565b6020808252600e908201527f5061796d656e74206661696c6564000000000000000000000000000000000000604082015260600190565b1561174357565b60405162461bcd60e51b815280610aa060048201611705565b61177061176960006105de565b821161168e565b61179c6110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b803b15611149576040516370a0823160e01b8152602081806117c133600483016106e3565b0381855afa8015611144576117e191600091611938575b508311156116e5565b6117e961242c565b906117f48284610ba2565b90611807611800610b7b565b8093610bd0565b918293611813306109cb565b9384311061191b575b5050803b15611149578360209161185893600061183860405190565b80968195829461184c6323b872dd60e01b90565b84523360048501611493565b03925af18015611144576118fe575b50611879610f4e82610f946004610b1a565b61188a610f3d83610f946003610b1a565b6118b760008061189960405190565b806118a38161027d565b039085335af16118b1610d3d565b5061173c565b6118cc610f7f6118c6336109cb565b936105de565b917fd415b7de66dff70616d6c0c32d8ec128427a0090934a7868013ed1da68a0996f6118f760405190565b8080611112565b6119169060203d60201161113d576111308183610cce565b611867565b909350611930919450610ed483319485610ba2565b92388061181c565b611951915060203d60201161146b5761145d8183610cce565b386117d8565b61029b90611594565b61197061129d610a6a6001610c98565b61029b6119a1565b9061ff009060081b610bfd565b151590565b9061199a61027d610c1e92611985565b8254611978565b61029b60018061198a565b61029b611960565b6119e06110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b803b1561114957611a0b916020916119f760405190565b938492839182916370a0823160e01b6113bf565b03915afa90811561114457600091611a21575090565b61027d915060203d60201161146b5761145d8183610cce565b611a4a61129d610a6a6001610c98565b61029b611a72565b9060ff90610bfd565b90611a6b61027d610c1e92611985565b8254611a52565b61029b600180611a5b565b61029b611a3a565b610ab490611a9161259f565b611b23565b61027d9061060c565b61027d9054611a96565b60208082526011908201527f4f7265206e6f74206465706f7369746564000000000000000000000000000000604082015260600190565b15611ae757565b60405162461bcd60e51b815280610aa060048201611aa9565b919060408382031261026d5761027d906020611b1c8286611321565b9401611321565b611b3e611b39611b348360056105eb565b611a9f565b611ae0565b611b6a6110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b803b1561114957604080517f6d981fda0000000000000000000000000000000000000000000000000000000081526004810184905291829060249082905afa801561114457611bca91600091611d60575b50611bc4610b7b565b90610ba2565b600090611be182611bdc8560056105eb565b611a5b565b611c0d6110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b803b1561114957611c5a6020918493611c2560405190565b94859384928391907fa9059cbb0000000000000000000000000000000000000000000000000000000083523360048401610e4c565b03925af1801561114457611d43575b50611c966110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b611c9f306109cb565b90803b1561114957838391611cd99383611cb860405190565b809681958294611ccc6342842e0e60e01b90565b8452339060048501611493565b03925af1801561114457611d26575b50507fb54d766db1adee957ce2be69e3416ac7b403883b137d446c95f6f9ca60ba3892611d21611d17336109cb565b926102bc60405190565b0390a2565b81611d3c92903d106115845761157c8183610cce565b3880611ce8565b611d5b9060203d60201161113d576111308183610cce565b611c69565b611d82915060403d604011611d88575b611d7a8183610cce565b810190611b00565b90611bbb565b503d611d70565b61029b90611a85565b90610ab491611da561259f565b61201b565b60208082526018908201527f4f7265206465706f73697473206e6f7420656e61626c65640000000000000000604082015260600190565b15611de857565b60405162461bcd60e51b815280610aa060048201611daa565b6020808252601d908201527f4d757374206465706f736974206174206c65617374206f6e65206f7265000000604082015260600190565b15611e3f57565b60405162461bcd60e51b815280610aa060048201611e01565b60208082526015908201527f546f6f206d616e79206f726573206174206f6e63650000000000000000000000604082015260600190565b15611e9657565b60405162461bcd60e51b815280610aa060048201611e58565b6084611eba60405190565b62461bcd60e51b815260206004820152602160248201527f41424920656e636f64696e673a206172726179206461746120746f6f206c6f6e60448201527f67000000000000000000000000000000000000000000000000000000000000006064820152fd5b9037565b8183529091602001917f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8111611f6457829160206109d49202938491611f1f565b611eaf565b611f8661027d95939492946114b3606084019660008501906106da565b6040818503910152611f23565b67ffffffffffffffff8111610cf05760208091020190565b90610d38610d3383611f93565b369037565b9061029b611fd3611fcd84611fab565b93611f93565b601f190160208401611fb8565b60010190565b634e487b7160e01b600052603260045260246000fd5b919081101561200c576020020190565b611fe6565b3561027d8161037d565b91909161202b6113526001611a9f565b61222c575b8291600091612048612041846105de565b8511611e38565b61205d61205560326105de565b851115611e8f565b6120896110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b612092306109cb565b90803b156111495786859184836120e0956120ac60405190565b968795869485937fc8c6cbd70000000000000000000000000000000000000000000000000000000085523360048601611f69565b03925af1801561114457612210575b506120fd8493929594611fbd565b9361210784611fbd565b90612111846105de565b928397845b875b8110156121fc57889961214d97989961213a612135848888611ffc565b612011565b9161214533846126f7565b9b9192610c22565b996121578c6105de565b82116121d4575b505050612118916121c891612188600161217d81611bdc8560056105eb565b611bdc8360066105eb565b612194610f7f336109cb565b907f7463610905974ce1d33729b931934eccfdcc5ba2bb509872748763398f3c1bd06121bf60405190565b600090a3611fe0565b90509897969598612116565b988861211895936121e9936121c8969c61298f565b6121f28c612a5a565b97918c919361215e565b5097929450505061029b9491935033612abf565b61222690843d86116115845761157c8183610cce565b386120ef565b61224b61223c610a6a6001610c98565b61224533610342565b14611de1565b612030565b9061029b91611d98565b6122646003610b1a565b612271610bd660006105de565b146122985761027d61228e6122866004610b1a565b611bc4610b7b565b610f726003610b1a565b61027d60006105de565b61029b906122b661129d610a6a6001610c98565b6122f4565b9076ffffffffffffffffffffffffffffffffffffffff0000009060181b610bfd565b906122ed61027d610c1e926109cb565b82546122bb565b61029b9060016122dd565b61029b906122a2565b61231861129d610a6a6001610c98565b61029b612377565b60208082526019908201527f4661696c656420746f2073656e6420746f206d616e6167657200000000000000604082015260600190565b1561235e57565b60405162461bcd60e51b815280610aa060048201612320565b61238761135661135260016112c0565b61029b6000806123976001610c98565b6123a0306109cb565b316123aa60405190565b90816123b58161027d565b03925af16123c1610d3d565b50612357565b61029b612308565b6123df61129d610a6a6001610c98565b61029b61240c565b9062ff00009060101b610bfd565b9061240561027d610c1e92611985565b82546123e7565b61029b6001806123f5565b61029b6123cf565b61027d6301406f406105de565b61027d6124396002610b1a565b610f7261241f565b61246461245c61027d92612453600090565b50611bc461242c565b610f72610b7b565b61246e60646105de565b908161247a6002610b1a565b612490610bd6690472698b413b432000006105de565b116124bd5750610f7f610f7291611bc46124ab6103e86105de565b945b610f9461271096610f94886105de565b916124c86002610b1a565b6124de610bd6692c781f708c509f4000006105de565b106124f4575b610f7291611bc4610f7f926124ad565b9150610f7f610f7291611bc461251c6a115eec47f6cf7e35000000610ed4610f7f6002610b1a565b9492505091506124e4565b61029b610fc76125376002610b1a565b3490610c22565b61027d60026105de565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b1561258657565b60405162461bcd60e51b815280610aa060048201612548565b61029b6125ac6000610b1a565b6125c06125b761253e565b9182141561257f565b6000610c07565b61027d60016105de565b61029b6125c06125c7565b906125e760646105de565b90816125f36002610b1a565b612609610bd6690472698b413b432000006105de565b1161267d575061267861261d6103e86105de565b935b610f3861271061267261264e61263d612637846105de565b86610ba2565b610f728a610f948b610f94886105de565b91610f72610f7f8961266c6126638d88610ba2565b610f72866105de565b95610ba2565b92610bea565b929190565b926126886002610b1a565b61269e610bd6692c781f708c509f4000006105de565b106126ad575b6126789061261f565b92506126786126ce6a115eec47f6cf7e35000000610ed4610f7f6002610b1a565b9390506126a4565b9050519061029b8261035b565b9060208282031261026d5761027d916126d6565b90916127256110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b91823b1561114957604080517f6d981fda0000000000000000000000000000000000000000000000000000000081526004810183905293849060249082905afa92831561114457600080919094612938575b5061278490611bc4610b7b565b9061278f60006105de565b90819561279c6000610caf565b9081966127cb6110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b803b1561114957612819916020916127e260405190565b938492839182917f6352211e0000000000000000000000000000000000000000000000000000000083526004830190815260200190565b03915afa60009181612907575b506128fc575061283590610342565b61283e87610342565b141590816128e1575b50806128c5575b61289b575b9085612867611b34610bd6959460066105eb565b1561287657610f389192610bea565b610f38915061267261289161288b60056105de565b85610ba2565b610f7260646105de565b611b34955090610bd692916128676128b961289161263760056105de565b97505090919250612853565b506128d161dead610342565b6128da86610342565b141561284e565b6128eb9150610342565b6128f486610342565b141538612847565b965061283590610342565b61292a91925060203d602011612931575b6129228183610cce565b8101906126e3565b9038612826565b503d612918565b6127849450612956915060403d604011611d8857611d7a8183610cce565b9093612777565b90612966825190565b81101561200c576020809102010190565b61027d9051610342565b5190565b9061029790610342565b909192936000946129a060006105de565b82811015612a3d576129ba6129b5828861295d565b612977565b6129c6610a6f86610342565b146129d9576129d490611fe0565b6129a0565b84959650612a036129fc83949596610f946129f785612a069761295d565b612981565b918461295d565b52565b60005b612a15575b5050505050565b612a2e612a0393612a2984612a339861295d565b612985565b61295d565b3880808080612a0e565b509091929394612a09901590565b6000198114610bb55760010190565b906000906000612a6a60006105de565b925b612a7761027d865190565b841015612ab757612a8b6129b5858761295d565b612a9a610a6f610a6a85610caf565b14612ab757612aab612ab191612a4b565b93611fe0565b92612a6c565b925050915090565b949291612aee6110647f00000000000000000000000000000000000000000000000000000000000000006109cb565b9163a9059cbb96833b1561114957612b1b91602091612b0c60405190565b938492839261140c8d60e01b90565b03816000875af1801561114457612bd1575b50600093612b3b60006105de565b865b811015612bc757612b516129b5828561295d565b90612b5f6129f7828861295d565b853b156111495761140c8a612b84602093612b7960405190565b968794859460e01b90565b03818a895af190811561114457612b3d92612ba492612bab575b50611fe0565b9050612b3b565b612bc29060203d811161113d576111308183610cce565b612b9e565b5095505050505050565b612be99060203d60201161113d576111308183610cce565b612b2d56fea2646970667358221220a60911a12f1b755c6a7d0fb16cabedbe8e1bd30b4e2b37ac2a76f2879d2c03ce64736f6c634300081c0033000000000000000000000000d5af802f7300d1be00f175e49b1297e7c9601a9b0000000000000000000000003322b37349aefd6f50f7909b641f2177c1d34d250000000000000000000000002d342ef1c5dea66851a3e604c9e663836405cf5400000000000000000000000072cddb64a72176b442bdfd9c8bb7968e652d8d1a
Deployed Bytecode
0x6080604052600436101561001d575b3661092f5761001b612527565b005b60003560e01c80630894b00f1461017d578063150b7a02146101785780631d95480f146101735780632f7b8af41461016e57806331aa1ec914610169578063481c6a7514610164578063492560471461015f5780634f4023211461015a57806350911ace14610155578063536c4c7b1461015057806370a082311461014b5780638f2c3ee914610146578063a511289f14610141578063a56fc8811461013c578063aa256f1414610137578063b039cf6f14610132578063d0ebdbe71461012d578063db2e21bc14610128578063de4e5a4514610123578063e08ac27f1461011e578063fa322935146101195763ffced28b0361000e57610914565b6108f9565b6108de565b6108ba565b6108a2565b61088a565b61086f565b610856565b6107e8565b6107d0565b6107b5565b61078e565b610762565b61074a565b610732565b61071a565b6106f3565b610687565b61065f565b610632565b610578565b61029d565b608461018d60405190565b62461bcd60e51b815260206004820152602260248201527f45746865722073656e7420746f206e6f6e2d70617961626c652066756e63746960448201527f6f6e0000000000000000000000000000000000000000000000000000000000006064820152fd5b60846101fd60405190565b62461bcd60e51b815260206004820152602260248201527f414249206465636f64696e673a207475706c65206461746120746f6f2073686f60448201527f72740000000000000000000000000000000000000000000000000000000000006064820152fd5b600091031261026d57565b6101f2565b61027d916008021c81565b90565b9061027d9154610272565b61027d60006004610280565b9052565b565b346102cd576102ad366004610262565b6102c96102b861028b565b6040515b9182918290815260200190565b0390f35b610182565b60846102dd60405190565b62461bcd60e51b815260206004820152602260248201527f414249206465636f64696e673a20696e76616c6964207475706c65206f66667360448201527f65740000000000000000000000000000000000000000000000000000000000006064820152fd5b73ffffffffffffffffffffffffffffffffffffffff1690565b61036481610342565b0361036b57565b600080fd5b9050359061029b8261035b565b80610364565b9050359061029b8261037d565b608461039b60405190565b62461bcd60e51b815260206004820152602b60248201527f414249206465636f64696e673a20696e76616c69642063616c6c64617461206160448201527f72726179206f66667365740000000000000000000000000000000000000000006064820152fd5b608461040b60405190565b62461bcd60e51b815260206004820152602b60248201527f414249206465636f64696e673a20696e76616c69642063616c6c64617461206160448201527f72726179206c656e6774680000000000000000000000000000000000000000006064820152fd5b608461047b60405190565b62461bcd60e51b815260206004820152602b60248201527f414249206465636f64696e673a20696e76616c69642063616c6c64617461206160448201527f72726179207374726964650000000000000000000000000000000000000000006064820152fd5b909182601f8301121561051a5781359167ffffffffffffffff831161051557602001926001830284011161051057565b610470565b610400565b610390565b9060808282031261026d576105348183610370565b926105428260208501610370565b926105508360408301610383565b92606082013567ffffffffffffffff81116105735761056f92016104e0565b9091565b6102d2565b346102cd576102c961059761058e36600461051f565b93929092610a4d565b604051918291827fffffffff00000000000000000000000000000000000000000000000000000000909116815260200190565b9060208282031261026d5761027d91610383565b61027d61027d61027d9290565b906105f5906105de565b600052602052604060002090565b61027d916008021c5b60ff1690565b9061027d9154610603565b600061062d61027d9260066105eb565b610612565b346102cd576102c961064d6106483660046105ca565b61061d565b60405191829182901515815260200190565b61066a366004610262565b610672611208565b604051005b600061062d61027d9260056105eb565b346102cd576102c961064d61069d3660046105ca565b610677565b61027d916008021c73ffffffffffffffffffffffffffffffffffffffff1690565b9061027d91546106a2565b61027d600360016106c3565b61029790610342565b60208101929161029b91906106da565b346102cd57610703366004610262565b6102c961070e6106ce565b604051918291826106e3565b346102cd5761072a366004610262565b610672611472565b346102cd576106726107453660046105ca565b61158b565b346102cd5761067261075d3660046105ca565b611957565b346102cd57610772366004610262565b6106726119ac565b9060208282031261026d5761027d91610370565b346102cd576102c96102b86107a436600461077a565b6119b4565b61027d60006003610280565b346102cd576107c5366004610262565b6102c96102b86107a9565b346102cd576107e0366004610262565b610672611a7d565b346102cd576106726107fb3660046105ca565b611d8f565b909182601f8301121561051a5781359167ffffffffffffffff831161051557602001926020830284011161051057565b9060208282031261026d57813567ffffffffffffffff81116105735761056f9201610800565b346102cd57610672610869366004610830565b90612250565b346102cd5761087f366004610262565b6102c96102b861225a565b346102cd5761067261089d36600461077a565b6122ff565b346102cd576108b2366004610262565b6106726123c7565b346102cd576108ca366004610262565b610672612417565b61027d60006002610280565b346102cd576108ee366004610262565b6102c96102b86108d2565b346102cd57610909366004610262565b6102c96102b861242c565b346102cd576102c96102b861092a3660046105ca565b612441565b608461093a60405190565b62461bcd60e51b815260206004820152602960248201527f556e6b6e6f776e207369676e617475726520616e64206e6f2066616c6c62616360448201527f6b20646566696e656400000000000000000000000000000000000000000000006064820152fd5b61034261027d61027d9273ffffffffffffffffffffffffffffffffffffffff1690565b61027d9061099f565b61027d906109c2565b0190565b60208082526011908201527f4e6f7420676f6c64206d65726368616e74000000000000000000000000000000604082015260600190565b610a28610a2261027d9263ffffffff1690565b60e01b90565b7fffffffff000000000000000000000000000000000000000000000000000000001690565b9350505050610a5a600090565b50610a75610a6f610a6a306109cb565b610342565b91610342565b03610a875761027d63150b7a02610a0f565b60405162461bcd60e51b815280610aa0600482016109d8565b0390fd5b610aac61259f565b610ab4610e77565b61029b6125d1565b6020808252600d908201527f4e6f2076616c75652073656e7400000000000000000000000000000000000000604082015260600190565b15610afa57565b60405162461bcd60e51b815280610aa060048201610abc565b61027d9081565b61027d9054610b13565b6020808252601e908201527f4e6f20676f6c6420617661696c61626c6520666f722070757263686173650000604082015260600190565b15610b6257565b60405162461bcd60e51b815280610aa060048201610b24565b61027d670de0b6b3a76400006105de565b634e487b7160e01b600052601160045260246000fd5b81810292918115918404141715610bb557565b610b8c565b634e487b7160e01b600052601260045260246000fd5b90610bda565b9190565b908115610be5570490565b610bba565b91908203918211610bb557565b90600019905b9181191691161790565b90610c1761027d610c1e926105de565b8254610bf7565b9055565b91908201809211610bb557565b60208082526027908201527f41637475616c20746f74616c20636f737420697320677265617465722074686160408201527f6e2076616c756500000000000000000000000000000000000000000000000000606082015260800190565b61027d9060181c610342565b61027d9054610c8c565b61034261027d61027d9290565b61027d90610ca2565b634e487b7160e01b600052604160045260246000fd5b90601f01601f1916810190811067ffffffffffffffff821117610cf057604052565b610cb8565b9061029b610d0260405190565b9283610cce565b67ffffffffffffffff8111610cf057602090601f01601f19160190565b90610d38610d3383610d09565b610cf5565b918252565b3d15610d5757610d4c3d610d26565b903d6000602084013e565b606090565b6020808252600d908201527f526566756e64206661696c656400000000000000000000000000000000000000604082015260600190565b15610d9a57565b60405162461bcd60e51b815280610aa060048201610d5c565b6084610dbe60405190565b62461bcd60e51b815260206004820152602560248201527f54617267657420636f6e747261637420646f6573206e6f7420636f6e7461696e60448201527f20636f64650000000000000000000000000000000000000000000000000000006064820152fd5b801515610364565b9050519061029b82610e23565b9060208282031261026d5761027d91610e2b565b91602061029b929493610e67604082019660008301906106da565b0152565b6040513d6000823e3d90fd5b6000610e8c610e85826105de565b3411610af3565b610e966003610b1a565b90610eaa610ea3826105de565b8311610b5b565b610eb261242c565b90610ebc346125dc565b9093610ed981610ed4610ecd610b7b565b8096610ba2565b610bd0565b9586610ee4866105de565b5081106111fe575b50610f85610f5c610f5585610f028a9586610ba2565b610ed4610f4e610f4484610f1d610f1761225a565b8b610ba2565b610ed4610f3d610f2d8389610bea565b9c610f386003610b1a565b610bea565b6003610c07565b610f386004610b1a565b6004610c07565b9687610ba2565b610f72610f7f610f7861271093610f72856105de565b90610bd0565b9589610ba2565b916105de565b92610f9984610f948589610c22565b610c22565b903482116111e557610fc7610fbd610fb7610fce9361102596610bd0565b86610c22565b610f946002610b1a565b6002610c07565b610fd86001610c98565b610fe7610a6f610a6a88610caf565b146111d45761101a8580610ffb6001610c98565b60405188816110098161027d565b03925af1611015610d3d565b501590565b611180575b34610bea565b8361102f816105de565b821161114e575b50506110696110647f00000000000000000000000072cddb64a72176b442bdfd9c8bb7968e652d8d1a6109cb565b6109cb565b92833b156111495760209061107d60405190565b94859182907fa9059cbb000000000000000000000000000000000000000000000000000000008252816110b48b3360048401610e4c565b03925af1928315611144576110ce93611117575b50610c22565b917f1e17537bfae89caf79a05b46debe4b0b1d37bc9187daa9436b4f50ac4b10c53f611112611108611102611102336109cb565b946105de565b946102bc60405190565b0390a4565b6111389060203d60201161113d575b6111308183610cce565b810190610e38565b6110c8565b503d611126565b610e6b565b610db3565b806111799261115c60405190565b806111668161027d565b0391335af1611173610d3d565b50610d93565b3883611036565b61118d6110646001610c98565b7fabe56b86d17916937b7768d686c74e0d99817c3e201bf0e9f1edc5173750b2136111b760405190565b868152602090a26111cf610fc785610f946002610b1a565b61101f565b6111cf610fc785610f946002610b1a565b60405162461bcd60e51b815280610aa060048201610c2f565b9550610f85610eec565b61029b610aa4565b60208082526023908201527f4f6e6c79206d616e616765722063616e2063616c6c20746869732066756e637460408201527f696f6e0000000000000000000000000000000000000000000000000000000000606082015260800190565b1561127457565b60405162461bcd60e51b815280610aa060048201611210565b6112ac61129d610a6a6001610c98565b6112a633610342565b1461126d565b61029b611342565b61027d9060101c61060c565b61027d90546112b4565b6020808252601e908201527f456d657267656e63792077697468647261772069732064697361626c65640000604082015260600190565b1561130857565b60405162461bcd60e51b815280610aa0600482016112ca565b9050519061029b8261037d565b9060208282031261026d5761027d91611321565b61135b61135661135260016112c0565b1590565b611301565b6113876110647f00000000000000000000000072cddb64a72176b442bdfd9c8bb7968e652d8d1a6109cb565b6113916001610c98565b61139a306109cb565b823b156111495760206113ca916113b060405190565b9283918291906370a0823160e01b5b8352600483016106e3565b0381865afa90811561114457600091611443575b50823b15611149576114179260209260006113f860405190565b80968195829461140c63a9059cbb60e01b90565b845260048401610e4c565b03925af18015611144576114285750565b6114409060203d60201161113d576111308183610cce565b50565b611465915060203d60201161146b575b61145d8183610cce565b81019061132e565b386113de565b503d611453565b61029b61128d565b61029b9061148e61129d610a6a6001610c98565b6114bd565b604090610e6761029b94969593966114b3606084019860008501906106da565b60208301906106da565b6114cd61135661135260016112c0565b6114f96110647f000000000000000000000000d5af802f7300d1be00f175e49b1297e7c9601a9b6109cb565b90611503306109cb565b9061150e6001610c98565b92803b156111495761155a936000809461152760405190565b968795869485937f42842e0e00000000000000000000000000000000000000000000000000000000855260048501611493565b03925af180156111445761156b5750565b61029b9060005b61157c8183610cce565b810190610262565b503d611572565b61029b9061147a565b610ab4906115a061259f565b611612565b61027d9060081c61060c565b61027d90546115a5565b60208082526017908201527f4d65726368616e74206973206e6f7420656e61626c6564000000000000000000604082015260600190565b156115f957565b60405162461bcd60e51b815280610aa0600482016115bb565b61029b9061162060016115b1565b8015611635575b611630906115f2565b61175c565b50611630611646610a6a6001610c98565b61164f33610342565b149050611627565b60208082526015908201527f416d6f756e742063616e6e6f74206265207a65726f0000000000000000000000604082015260600190565b1561169557565b60405162461bcd60e51b815280610aa060048201611657565b60208082526014908201527f496e73756666696369656e742062616c616e6365000000000000000000000000604082015260600190565b156116ec57565b60405162461bcd60e51b815280610aa0600482016116ae565b6020808252600e908201527f5061796d656e74206661696c6564000000000000000000000000000000000000604082015260600190565b1561174357565b60405162461bcd60e51b815280610aa060048201611705565b61177061176960006105de565b821161168e565b61179c6110647f00000000000000000000000072cddb64a72176b442bdfd9c8bb7968e652d8d1a6109cb565b803b15611149576040516370a0823160e01b8152602081806117c133600483016106e3565b0381855afa8015611144576117e191600091611938575b508311156116e5565b6117e961242c565b906117f48284610ba2565b90611807611800610b7b565b8093610bd0565b918293611813306109cb565b9384311061191b575b5050803b15611149578360209161185893600061183860405190565b80968195829461184c6323b872dd60e01b90565b84523360048501611493565b03925af18015611144576118fe575b50611879610f4e82610f946004610b1a565b61188a610f3d83610f946003610b1a565b6118b760008061189960405190565b806118a38161027d565b039085335af16118b1610d3d565b5061173c565b6118cc610f7f6118c6336109cb565b936105de565b917fd415b7de66dff70616d6c0c32d8ec128427a0090934a7868013ed1da68a0996f6118f760405190565b8080611112565b6119169060203d60201161113d576111308183610cce565b611867565b909350611930919450610ed483319485610ba2565b92388061181c565b611951915060203d60201161146b5761145d8183610cce565b386117d8565b61029b90611594565b61197061129d610a6a6001610c98565b61029b6119a1565b9061ff009060081b610bfd565b151590565b9061199a61027d610c1e92611985565b8254611978565b61029b60018061198a565b61029b611960565b6119e06110647f00000000000000000000000072cddb64a72176b442bdfd9c8bb7968e652d8d1a6109cb565b803b1561114957611a0b916020916119f760405190565b938492839182916370a0823160e01b6113bf565b03915afa90811561114457600091611a21575090565b61027d915060203d60201161146b5761145d8183610cce565b611a4a61129d610a6a6001610c98565b61029b611a72565b9060ff90610bfd565b90611a6b61027d610c1e92611985565b8254611a52565b61029b600180611a5b565b61029b611a3a565b610ab490611a9161259f565b611b23565b61027d9061060c565b61027d9054611a96565b60208082526011908201527f4f7265206e6f74206465706f7369746564000000000000000000000000000000604082015260600190565b15611ae757565b60405162461bcd60e51b815280610aa060048201611aa9565b919060408382031261026d5761027d906020611b1c8286611321565b9401611321565b611b3e611b39611b348360056105eb565b611a9f565b611ae0565b611b6a6110647f0000000000000000000000002d342ef1c5dea66851a3e604c9e663836405cf546109cb565b803b1561114957604080517f6d981fda0000000000000000000000000000000000000000000000000000000081526004810184905291829060249082905afa801561114457611bca91600091611d60575b50611bc4610b7b565b90610ba2565b600090611be182611bdc8560056105eb565b611a5b565b611c0d6110647f00000000000000000000000072cddb64a72176b442bdfd9c8bb7968e652d8d1a6109cb565b803b1561114957611c5a6020918493611c2560405190565b94859384928391907fa9059cbb0000000000000000000000000000000000000000000000000000000083523360048401610e4c565b03925af1801561114457611d43575b50611c966110647f000000000000000000000000d5af802f7300d1be00f175e49b1297e7c9601a9b6109cb565b611c9f306109cb565b90803b1561114957838391611cd99383611cb860405190565b809681958294611ccc6342842e0e60e01b90565b8452339060048501611493565b03925af1801561114457611d26575b50507fb54d766db1adee957ce2be69e3416ac7b403883b137d446c95f6f9ca60ba3892611d21611d17336109cb565b926102bc60405190565b0390a2565b81611d3c92903d106115845761157c8183610cce565b3880611ce8565b611d5b9060203d60201161113d576111308183610cce565b611c69565b611d82915060403d604011611d88575b611d7a8183610cce565b810190611b00565b90611bbb565b503d611d70565b61029b90611a85565b90610ab491611da561259f565b61201b565b60208082526018908201527f4f7265206465706f73697473206e6f7420656e61626c65640000000000000000604082015260600190565b15611de857565b60405162461bcd60e51b815280610aa060048201611daa565b6020808252601d908201527f4d757374206465706f736974206174206c65617374206f6e65206f7265000000604082015260600190565b15611e3f57565b60405162461bcd60e51b815280610aa060048201611e01565b60208082526015908201527f546f6f206d616e79206f726573206174206f6e63650000000000000000000000604082015260600190565b15611e9657565b60405162461bcd60e51b815280610aa060048201611e58565b6084611eba60405190565b62461bcd60e51b815260206004820152602160248201527f41424920656e636f64696e673a206172726179206461746120746f6f206c6f6e60448201527f67000000000000000000000000000000000000000000000000000000000000006064820152fd5b9037565b8183529091602001917f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8111611f6457829160206109d49202938491611f1f565b611eaf565b611f8661027d95939492946114b3606084019660008501906106da565b6040818503910152611f23565b67ffffffffffffffff8111610cf05760208091020190565b90610d38610d3383611f93565b369037565b9061029b611fd3611fcd84611fab565b93611f93565b601f190160208401611fb8565b60010190565b634e487b7160e01b600052603260045260246000fd5b919081101561200c576020020190565b611fe6565b3561027d8161037d565b91909161202b6113526001611a9f565b61222c575b8291600091612048612041846105de565b8511611e38565b61205d61205560326105de565b851115611e8f565b6120896110647f000000000000000000000000d5af802f7300d1be00f175e49b1297e7c9601a9b6109cb565b612092306109cb565b90803b156111495786859184836120e0956120ac60405190565b968795869485937fc8c6cbd70000000000000000000000000000000000000000000000000000000085523360048601611f69565b03925af1801561114457612210575b506120fd8493929594611fbd565b9361210784611fbd565b90612111846105de565b928397845b875b8110156121fc57889961214d97989961213a612135848888611ffc565b612011565b9161214533846126f7565b9b9192610c22565b996121578c6105de565b82116121d4575b505050612118916121c891612188600161217d81611bdc8560056105eb565b611bdc8360066105eb565b612194610f7f336109cb565b907f7463610905974ce1d33729b931934eccfdcc5ba2bb509872748763398f3c1bd06121bf60405190565b600090a3611fe0565b90509897969598612116565b988861211895936121e9936121c8969c61298f565b6121f28c612a5a565b97918c919361215e565b5097929450505061029b9491935033612abf565b61222690843d86116115845761157c8183610cce565b386120ef565b61224b61223c610a6a6001610c98565b61224533610342565b14611de1565b612030565b9061029b91611d98565b6122646003610b1a565b612271610bd660006105de565b146122985761027d61228e6122866004610b1a565b611bc4610b7b565b610f726003610b1a565b61027d60006105de565b61029b906122b661129d610a6a6001610c98565b6122f4565b9076ffffffffffffffffffffffffffffffffffffffff0000009060181b610bfd565b906122ed61027d610c1e926109cb565b82546122bb565b61029b9060016122dd565b61029b906122a2565b61231861129d610a6a6001610c98565b61029b612377565b60208082526019908201527f4661696c656420746f2073656e6420746f206d616e6167657200000000000000604082015260600190565b1561235e57565b60405162461bcd60e51b815280610aa060048201612320565b61238761135661135260016112c0565b61029b6000806123976001610c98565b6123a0306109cb565b316123aa60405190565b90816123b58161027d565b03925af16123c1610d3d565b50612357565b61029b612308565b6123df61129d610a6a6001610c98565b61029b61240c565b9062ff00009060101b610bfd565b9061240561027d610c1e92611985565b82546123e7565b61029b6001806123f5565b61029b6123cf565b61027d6301406f406105de565b61027d6124396002610b1a565b610f7261241f565b61246461245c61027d92612453600090565b50611bc461242c565b610f72610b7b565b61246e60646105de565b908161247a6002610b1a565b612490610bd6690472698b413b432000006105de565b116124bd5750610f7f610f7291611bc46124ab6103e86105de565b945b610f9461271096610f94886105de565b916124c86002610b1a565b6124de610bd6692c781f708c509f4000006105de565b106124f4575b610f7291611bc4610f7f926124ad565b9150610f7f610f7291611bc461251c6a115eec47f6cf7e35000000610ed4610f7f6002610b1a565b9492505091506124e4565b61029b610fc76125376002610b1a565b3490610c22565b61027d60026105de565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b1561258657565b60405162461bcd60e51b815280610aa060048201612548565b61029b6125ac6000610b1a565b6125c06125b761253e565b9182141561257f565b6000610c07565b61027d60016105de565b61029b6125c06125c7565b906125e760646105de565b90816125f36002610b1a565b612609610bd6690472698b413b432000006105de565b1161267d575061267861261d6103e86105de565b935b610f3861271061267261264e61263d612637846105de565b86610ba2565b610f728a610f948b610f94886105de565b91610f72610f7f8961266c6126638d88610ba2565b610f72866105de565b95610ba2565b92610bea565b929190565b926126886002610b1a565b61269e610bd6692c781f708c509f4000006105de565b106126ad575b6126789061261f565b92506126786126ce6a115eec47f6cf7e35000000610ed4610f7f6002610b1a565b9390506126a4565b9050519061029b8261035b565b9060208282031261026d5761027d916126d6565b90916127256110647f0000000000000000000000002d342ef1c5dea66851a3e604c9e663836405cf546109cb565b91823b1561114957604080517f6d981fda0000000000000000000000000000000000000000000000000000000081526004810183905293849060249082905afa92831561114457600080919094612938575b5061278490611bc4610b7b565b9061278f60006105de565b90819561279c6000610caf565b9081966127cb6110647f0000000000000000000000003322b37349aefd6f50f7909b641f2177c1d34d256109cb565b803b1561114957612819916020916127e260405190565b938492839182917f6352211e0000000000000000000000000000000000000000000000000000000083526004830190815260200190565b03915afa60009181612907575b506128fc575061283590610342565b61283e87610342565b141590816128e1575b50806128c5575b61289b575b9085612867611b34610bd6959460066105eb565b1561287657610f389192610bea565b610f38915061267261289161288b60056105de565b85610ba2565b610f7260646105de565b611b34955090610bd692916128676128b961289161263760056105de565b97505090919250612853565b506128d161dead610342565b6128da86610342565b141561284e565b6128eb9150610342565b6128f486610342565b141538612847565b965061283590610342565b61292a91925060203d602011612931575b6129228183610cce565b8101906126e3565b9038612826565b503d612918565b6127849450612956915060403d604011611d8857611d7a8183610cce565b9093612777565b90612966825190565b81101561200c576020809102010190565b61027d9051610342565b5190565b9061029790610342565b909192936000946129a060006105de565b82811015612a3d576129ba6129b5828861295d565b612977565b6129c6610a6f86610342565b146129d9576129d490611fe0565b6129a0565b84959650612a036129fc83949596610f946129f785612a069761295d565b612981565b918461295d565b52565b60005b612a15575b5050505050565b612a2e612a0393612a2984612a339861295d565b612985565b61295d565b3880808080612a0e565b509091929394612a09901590565b6000198114610bb55760010190565b906000906000612a6a60006105de565b925b612a7761027d865190565b841015612ab757612a8b6129b5858761295d565b612a9a610a6f610a6a85610caf565b14612ab757612aab612ab191612a4b565b93611fe0565b92612a6c565b925050915090565b949291612aee6110647f00000000000000000000000072cddb64a72176b442bdfd9c8bb7968e652d8d1a6109cb565b9163a9059cbb96833b1561114957612b1b91602091612b0c60405190565b938492839261140c8d60e01b90565b03816000875af1801561114457612bd1575b50600093612b3b60006105de565b865b811015612bc757612b516129b5828561295d565b90612b5f6129f7828861295d565b853b156111495761140c8a612b84602093612b7960405190565b968794859460e01b90565b03818a895af190811561114457612b3d92612ba492612bab575b50611fe0565b9050612b3b565b612bc29060203d811161113d576111308183610cce565b612b9e565b5095505050505050565b612be99060203d60201161113d576111308183610cce565b612b2d56fea2646970667358221220a60911a12f1b755c6a7d0fb16cabedbe8e1bd30b4e2b37ac2a76f2879d2c03ce64736f6c634300081c0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000d5af802f7300d1be00f175e49b1297e7c9601a9b0000000000000000000000003322b37349aefd6f50f7909b641f2177c1d34d250000000000000000000000002d342ef1c5dea66851a3e604c9e663836405cf5400000000000000000000000072cddb64a72176b442bdfd9c8bb7968e652d8d1a
-----Decoded View---------------
Arg [0] : goldOre_ (address): 0xD5Af802F7300D1bE00f175e49B1297e7c9601a9B
Arg [1] : picks_ (address): 0x3322b37349AeFD6F50F7909B641f2177c1D34D25
Arg [2] : theMine_ (address): 0x2d342eF1C5dEA66851A3e604C9E663836405cF54
Arg [3] : goldToken_ (address): 0x72CddB64A72176B442bdfD9C8Bb7968E652d8D1a
-----Encoded View---------------
4 Constructor Arguments found :
Arg [0] : 000000000000000000000000d5af802f7300d1be00f175e49b1297e7c9601a9b
Arg [1] : 0000000000000000000000003322b37349aefd6f50f7909b641f2177c1d34d25
Arg [2] : 0000000000000000000000002d342ef1c5dea66851a3e604c9e663836405cf54
Arg [3] : 00000000000000000000000072cddb64a72176b442bdfd9c8bb7968e652d8d1a
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.