Проверенный контрактЧастичноеMIT
RelicsToken
Адрес0x8f294a99a0609822c233b24867f331c292ce2da9
- Баланс
0 ETH
- Транзакций
2 911
- Компилятор
solc 0.8.26
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.26+commit.8a97fa7a
- Язык
- solidity
- Оптимизация
- Да, 1 прогонов
- Версия EVM
- cancun
- Через IR
- да
- Лицензия
- MIT
- Совпадение
- Частичноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 25 678 475
- Транзакция создания
- 0xd78531bf89…52b541ced9
10 файлов
- src/RelicsToken.solглавный16,69 КБ
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3,1 КБ
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6,54 КБ
- lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol10,8 КБ
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2,78 КБ
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 Б
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 Б
- src/interfaces/IRelicsHook.sol2,35 КБ
- src/interfaces/IRelicsNFT.sol6,12 КБ
- src/interfaces/IRelicsToken.sol1,27 КБ
src/RelicsToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IRelicsToken } from "./interfaces/IRelicsToken.sol";
import { IRelicsNFT } from "./interfaces/IRelicsNFT.sol";
contract RelicsToken is ERC20, Ownable, IRelicsToken {
error InvalidHolderThreshold();
error InvalidInitialRecipient();
error ZeroAddress();
error RelicSyncAlreadyConfigured();
error RelicSyncPoolAlreadySet();
error RelicLockerAlreadySet();
error RelicSyncNotConfigured();
error UnauthorizedRelicSync();
error AddressCannotReceiveRelic(address account);
error ExcludedAddressHoldsRelics(address account);
uint256 public constant FIXED_SUPPLY = 10_000 ether;
uint256 public constant UNIT_PER_RELIC = 1 ether;
/// @notice Canonical entombment address. $RELICS sent here are permanently
/// inaccessible but are NOT burned: they remain in {totalSupply}.
///
/// The tomb is PERMANENTLY EXCLUDED from the whole-unit sync layer (see
/// {canReceiveRelic}): no Relic NFT can ever be minted to, moved to, or held
/// by this address. This is a hard liveness requirement, not an aesthetic
/// choice, and it survives the move to explicit awakening -- with a simpler
/// reason than the one it was introduced with.
///
/// ORIGINALLY: awakening happened automatically on an inbound $RELICS transfer, in
/// a quantity derived from the recipient's CUMULATIVE balance. The tomb's balance
/// only ever grows, so a transfer into it would have driven one ERC-721 write per
/// whole unit it had ever accumulated -- an unbounded, externally-fundable loop that
/// anyone could push past a block's gas limit, permanently bricking every contract
/// whose only exit is a transfer to the tomb.
///
/// NOW: nothing awakens on inbound $RELICS at all, so that loop no longer exists for
/// ANY address. The exclusion stays because the tomb has no key and no code, and
/// therefore can never call `RelicsNFT.awaken`: a Relic that reached it would be
/// permanently immobile liveness debt against a balance that only grows. Keeping
/// `relicEntitlement` at zero is what makes every transfer into and out of the tomb
/// O(1) forever, and what keeps `RelicsNFT.retireStranded` able to clear anything
/// that arrives by hand -- most importantly for
/// RelicsGenesisPositionLocker.collectFees(), the treasury's sole fee route.
address public constant ENTOMBMENT_ADDRESS = 0x000000000000000000000000000000000000dEaD;
/// @notice The canonical deterministic CREATE2 deployer (Arachnid's, present at the
/// same address on every chain this launches on). {setRelicLocker} derives the
/// locker's address through it instead of accepting one, which is what stops the
/// pre-renounce owner from branding an address that already holds Relics.
address public constant CREATE2_DEPLOYER = 0x4e59b44847b379578588920cA78FbF26c0B4956C;
uint256 public immutable HOLDER_THRESHOLD;
address public immutable notMintableAccount;
address public relicsNFT;
address public relicSyncPool;
/// @notice The immutable genesis LP fee locker (RelicsGenesisPositionLocker).
/// Set once, before the locker can ever hold $RELICS, and never changed.
/// Excluded from the whole-unit sync layer for the same reason as
/// {ENTOMBMENT_ADDRESS}: its crank must forward its ENTIRE $RELICS balance
/// atomically, anyone can push $RELICS into it, and it has no code path that could
/// ever call `RelicsNFT.awaken` -- so any Relic that reached it would be immobile
/// liveness debt on the treasury's only fee route.
address public relicLocker;
uint256 private _activeHolderCount;
mapping(address account => bool active) private _activeHolders;
bool private _relicTransferInProgress;
constructor(
address initialRecipient,
uint256 holderThreshold
)
ERC20("Relics", "RELICS")
Ownable(initialRecipient)
{
if (initialRecipient == address(0)) revert InvalidInitialRecipient();
if (holderThreshold == 0 || holderThreshold > FIXED_SUPPLY) {
revert InvalidHolderThreshold();
}
HOLDER_THRESHOLD = holderThreshold;
notMintableAccount = initialRecipient;
_mint(initialRecipient, FIXED_SUPPLY);
}
function setRelicsNFT(address relicsNFT_) external onlyOwner {
if (relicsNFT != address(0)) revert RelicSyncAlreadyConfigured();
if (relicsNFT_ == address(0)) revert ZeroAddress();
relicsNFT = relicsNFT_;
emit RelicSyncConfigured(relicsNFT_);
}
function setRelicSyncPool(address pool) external onlyOwner {
if (relicSyncPool != address(0)) revert RelicSyncPoolAlreadySet();
if (pool == address(0)) revert ZeroAddress();
_requireHoldsNoRelics(pool);
relicSyncPool = pool;
_deactivateHolder(pool);
emit RelicSyncPoolSet(pool);
}
/// @notice One-shot registration of the immutable genesis LP fee locker.
/// Mirrors {setRelicSyncPool}: owner-only, single-assignment, zero-address
/// rejecting, and it removes the locker from the active-holder count (holder
/// count is a live art input; the locker is protocol infrastructure, not a
/// participant). Once registered the locker can never receive a Relic NFT, so
/// RelicsGenesisPositionLocker.collectFees() is O(1) in its $RELICS balance
/// forever after -- see {ENTOMBMENT_ADDRESS} for why that matters.
///
/// SHOULD be called before the locker can hold any $RELICS. The canonical
/// deployment (script/deployment/AddGenesisLiquidityLadder.s.sol) computes the
/// locker's CREATE2 address and registers it here in the transaction immediately
/// after the genesis LP mint -- before the locker is deployed and before the pool
/// has been open long enough for anyone to act -- so there is no window in which
/// the locker exists unregistered.
///
/// DELIBERATELY NOT GUARDED BY {_requireHoldsNoRelics}, unlike {setRelicSyncPool}.
/// The locker's address is a CREATE2 address derived from the genesis position ids,
/// so it becomes publicly computable the moment the genesis LP is minted and cannot
/// be known before then. A `_requireHoldsNoRelics` guard here therefore hands any
/// third party a permanent veto over the registration: a Relic delivered by hand to
/// the (code-less, key-less) predicted address can never be moved off it again, and
/// the registration would revert forever. That is fatal once ownership is renounced.
///
/// The price of that veto ROSE with explicit awakening and is stated exactly. A
/// $RELICS push at the predicted address now awakens NOTHING -- no inbound-$RELICS
/// path materialises a Relic, and the address has no code with which to call
/// `RelicsNFT.awaken` -- so the one-whole-unit version of this attack no longer
/// exists. What remains is an ERC-721 `transferFrom` of a Relic the attacker
/// already owns, which costs them the Relic and its whole backing unit and is
/// visible on chain. Dropping the guard is the same decision either way; only the
/// attacker's cost changed, and it changed upward.
///
/// Registering regardless is safe because the state it admits is transient and
/// publicly repairable, not permanent: from this call on, the locker's
/// {relicEntitlement} is zero and {canReceiveRelic} is false, so NOT ONE further
/// Relic can reach it by any path, and anyone may retire whatever arrived first
/// through `RelicsNFT.retireStranded` in batches of {IRelicsNFT.PREPARE_SELL_MAX}.
/// The canonical deployment does exactly that before taking custody and asserts a
/// zero balance afterwards. {setRelicSyncPool} keeps its guard because it is
/// registered before the sync layer is live at all, when no Relic can exist.
///
/// GUARDED INSTEAD BY THE CREATE2 DERIVATION, which is what makes dropping the
/// emptiness guard safe for HOLDERS as well as for the launch. The caller does not
/// name an address; it names the `(salt, initCodeHash)` pair the locker will be
/// deployed with, and the address is DERIVED here from {CREATE2_DEPLOYER}. Pointing
/// this registration at an address that already exists -- a holder's wallet, a vault,
/// an exchange -- therefore requires finding a CREATE2 preimage for that exact 160-bit
/// address, which is ~2^160 work. Without this, an owner who had not yet renounced
/// could register a LIVE HOLDER as the locker: their {relicEntitlement} would fall to
/// zero forever, {canReceiveRelic} would be false forever, and their entire Relic
/// inventory would become permissionlessly burnable through `retireStranded`. That
/// power no longer exists, and it is closed in the contract rather than only in the
/// deployment runbook.
///
/// The trade the emptiness guard could not make is now available: a THIRD PARTY still
/// cannot veto the registration (nothing about the target's balance is checked), and
/// the OWNER still cannot aim it at a bystander.
function setRelicLocker(
bytes32 create2Salt,
bytes32 initCodeHash
)
external
onlyOwner
returns (address locker)
{
if (relicLocker != address(0)) revert RelicLockerAlreadySet();
locker = address(
uint160(
uint256(
keccak256(
abi.encodePacked(bytes1(0xff), CREATE2_DEPLOYER, create2Salt, initCodeHash)
)
)
)
);
// Unreachable in practice -- it would be a 160-bit collision with the zero
// address -- but the state it would create is permanent, so it is refused rather
// than argued about.
if (locker == address(0)) revert ZeroAddress();
relicLocker = locker;
_deactivateHolder(locker);
emit RelicLockerSet(locker);
}
function transferRelicToken(address from, address to) external {
if (msg.sender != relicsNFT) revert UnauthorizedRelicSync();
if (!canReceiveRelic(to)) revert AddressCannotReceiveRelic(to);
_relicTransferInProgress = true;
_transfer(from, to, UNIT_PER_RELIC);
_relicTransferInProgress = false;
}
/// @notice The whole-unit backing line for `account`: the maximum number of Relic
/// NFTs it may hold at this instant.
///
/// The ERC-721 layer does NOT derive its balances from this. `RelicsNFT.balanceOf`
/// is OpenZeppelin's stored balance and changes only through eventful ownership
/// transitions; this value is the bound that `RelicsNFT._update` ENFORCES BY
/// REVERT after every inbound transition. A shortfall in $RELICS can therefore
/// never silently invalidate a Relic -- it can only make a further transfer either
/// retire Relics with real burn events or revert outright.
///
/// Pure storage reads and one division. It CANNOT REVERT, so no read or settlement
/// path can be bricked through it.
function relicEntitlement(address account) external view returns (uint256) {
return canReceiveRelic(account) ? balanceOf(account) / UNIT_PER_RELIC : 0;
}
function activeHolderCount() external view returns (uint256) {
return _activeHolderCount;
}
function isActiveHolder(address account) external view returns (bool) {
return _activeHolders[account];
}
function totalSupply() public view override(ERC20, IRelicsToken) returns (uint256) {
return super.totalSupply();
}
function balanceOf(address account)
public
view
override(ERC20, IRelicsToken)
returns (uint256)
{
return super.balanceOf(account);
}
/// @dev O(1) in `value`. Exactly ONE external call into the ERC-721 layer per
/// ERC-20 transfer. `value` is deliberately not passed: the NFT reads the live
/// post-transfer balances through {relicEntitlement}, so there is no pre/post-state
/// ambiguity and no delta arithmetic that could desync.
///
/// `syncBalances` MAY REVERT, and that is the point: when the sender is over its
/// post-transfer backing line by more than RelicsNFT.SEND_BUDGET, the whole
/// transfer unwinds and the holder is told exactly how much preparation it owes.
/// Nothing is settled halfway and no Relic is ever quietly invalidated.
function _update(address from, address to, uint256 value) internal override {
super._update(from, to, value);
_syncHolder(from);
if (to != from) _syncHolder(to);
address nft = relicsNFT;
if (nft == address(0) || relicSyncPool == address(0)) return;
// A self-transfer changes no entitlement on either side. Returning early is
// what stops the sync layer double-counting one account as both sender and
// receiver of the same units.
if (from == to) return;
// The reciprocal leg of a DIRECT Relic transfer. The ERC-721 layer is already
// mid-transfer and is moving the matching whole unit itself: both sides end
// with their Relic count and their entitlement changed by the same one, so
// there is nothing for the sync layer to settle and re-entering it here would
// let the receiving side act twice on a unit that is already spoken for.
if (_relicTransferInProgress) return;
IRelicsNFT(nft).syncBalances(from, to);
}
function _requireHoldsNoRelics(address account) private view {
address nft = relicsNFT;
if (nft == address(0)) return;
if (IRelicsNFT(nft).balanceOf(account) != 0) {
revert ExcludedAddressHoldsRelics(account);
}
}
function _syncHolder(address account) private {
if (account == address(0) || account == relicSyncPool || account == relicLocker) return;
bool active = balanceOf(account) >= HOLDER_THRESHOLD;
bool wasActive = _activeHolders[account];
if (active == wasActive) return;
_activeHolders[account] = active;
if (active) {
unchecked {
++_activeHolderCount;
}
} else {
unchecked {
--_activeHolderCount;
}
}
emit HolderThresholdCrossed(account, active, balanceOf(account));
}
function _deactivateHolder(address account) private {
if (!_activeHolders[account]) return;
_activeHolders[account] = false;
unchecked {
--_activeHolderCount;
}
emit HolderThresholdCrossed(account, false, balanceOf(account));
}
/// @notice The set of addresses that can never hold a Relic NFT.
/// - address(0): not an account.
/// - relicSyncPool: the AMM's vault; its balance is the float, not a holding.
/// - notMintableAccount: the deployer, which seeds the pool and must not
/// materialise Relics on the way through.
/// - relicLocker and ENTOMBMENT_ADDRESS: excluded to keep every transfer into
/// and out of them O(1). Both are monotone-balance sinks on the fee path, and
/// neither has any code path that could call `RelicsNFT.awaken`, so a Relic that
/// reached either would be permanently immobile. See {ENTOMBMENT_ADDRESS}.
///
/// Consequence, stated plainly: NO Relic NFT ever awakens at the tomb. $RELICS
/// entombed at {ENTOMBMENT_ADDRESS} are ERC-20 only. A holder who sends whole
/// $RELICS units to the tomb has their Relics RETIRED to the dormancy pool with
/// real ERC-721 burn events rather than moved into the tomb; the DNA is preserved
/// and those token ids reawaken, unchanged, when the next holders explicitly
/// materialise capacity of their own.
///
/// The exclusion is enforced on BOTH ERC-721 entry points. An excluded address has
/// `relicEntitlement == 0`, so `RelicsNFT._update` reverts any mint or inbound
/// transfer to it, and {transferRelicToken} rejects it outright, so nobody can
/// hand-deliver a Relic to the tomb, the pool or the locker either.
function canReceiveRelic(address account) public view returns (bool) {
return account != address(0) && account != relicSyncPool && account != notMintableAccount
&& account != relicLocker && account != ENTOMBMENT_ADDRESS;
}
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
src/interfaces/IRelicsHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
interface IRelicsHook {
struct GlobalMarketState {
uint64 swapCount;
uint64 liquidityEventCount;
uint64 lastSwapBlock;
uint64 epoch;
uint128 cumulativeBuyVolume;
uint128 cumulativeSellVolume;
uint128 cumulativeLiquidityMagnitude;
int128 netFlow;
int24 lastTick;
int24 athTick;
uint32 drawdownBand;
uint32 stress;
uint32 volatility;
bytes32 marketSeed;
}
event CanonicalPoolBound(
bytes32 indexed poolId,
address indexed currency0,
address indexed currency1,
uint24 fee,
int24 tickSpacing,
uint160 expectedSqrtPriceX96,
int24 expectedInitialTick
);
event SwapObserved(
bytes32 indexed poolId,
int256 amount0,
int256 amount1,
int24 tick,
uint64 swapCount,
bytes32 marketSeed
);
event LiquidityObserved(
bytes32 indexed poolId,
int128 liquidityDelta,
uint256 amount0,
uint256 amount1,
uint64 liquidityEventCount
);
event MarketStateUpdated(
uint64 indexed epoch,
uint32 stress,
uint32 volatility,
uint32 drawdownBand,
bytes32 marketSeed
);
event EpochAdvanced(uint64 indexed previousEpoch, uint64 indexed newEpoch);
function bindCanonicalPool(
bytes32 poolId,
address currency0,
address currency1,
uint24 fee,
int24 tickSpacing,
uint160 expectedSqrtPriceX96,
int24 expectedInitialTick
)
external;
function observeSwap(
bytes32 poolId,
int256 amount0,
int256 amount1,
int24 tick,
bytes32 salt
)
external;
function observeLiquidity(
bytes32 poolId,
int128 liquidityDelta,
uint256 amount0,
uint256 amount1,
int24 tick
)
external;
function getGlobalState() external view returns (GlobalMarketState memory);
function canonicalPoolId() external view returns (bytes32);
function expectedSqrtPriceX96() external view returns (uint160);
function expectedInitialTick() external view returns (int24);
function isPoolBound() external view returns (bool);
}
src/interfaces/IRelicsNFT.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { IRelicsHook } from "./IRelicsHook.sol";
interface IRelicsNFT {
/// @notice Every input, other than the token id and the recipient, that influences
/// a VIRGIN Relic's identity. Read live inside {IRelicsNFT-awaken}, in the block its
/// caller chose, and passed as a memory value -- it is NEVER stored. (The stored
/// forge commitment that used to pin it, `_forgeCommitment` and `_pinnedBacklog`, is
/// what was removed; this struct was not.) A dormant id reawakening is unaffected:
/// its identity is storage.
struct ForgeWitness {
IRelicsHook.GlobalMarketState market;
uint256 holders;
bytes32 entropy;
uint64 mintBlock;
}
event RelicForged(uint256 indexed tokenId, address indexed owner, uint256 dna);
event RelicTransmuted(uint256 indexed tokenId, uint256 state);
/// @notice `tokenId` went dormant. ALWAYS accompanied, in the same frame, by the
/// canonical `Transfer(owner, address(0), tokenId)`; this event is the semantic
/// annotation, never the substitute for it.
event RelicDormant(uint256 indexed tokenId, address indexed owner);
/// @notice A dormant id came back with its original DNA, art, provenance and
/// history. Always accompanied by `Transfer(address(0), owner, tokenId)`.
event RelicReawakened(uint256 indexed tokenId, address indexed owner);
event MetadataUpdate(uint256 indexed tokenId);
event BatchMetadataUpdate(uint256 indexed fromTokenId, uint256 indexed toTokenId);
/// @notice `count` Relics were retired to dormancy by their owner's own selection,
/// ahead of a sale larger than one automatic send budget.
event RelicsPrepared(address indexed owner, uint256 count);
/// @notice `count` Relics were materialised by their owner's own explicit call.
/// ALWAYS accompanied, in the same frame, by one canonical
/// `Transfer(address(0), owner, id)` per id. `count` is never zero: a call that
/// cannot reach its own floor reverts instead of emitting.
event RelicsAwakened(address indexed owner, uint256 count);
function MAX_SUPPLY() external view returns (uint256);
function SEND_BUDGET() external view returns (uint256);
function AUTO_AWAKEN_CAP_PER_OWNER() external view returns (uint256);
function PREPARE_SELL_MAX() external view returns (uint256);
function mint() external returns (uint256 tokenId);
// -- token-only sync surface --------------------------------------------
function syncBalances(address from, address to) external;
// -- owner-paced ---------------------------------------------------------
/// @notice Materialise Relics against the CALLER'S OWN latent capacity. The only
/// mint site in the collection: `msg.sender` is always the recipient, there is no
/// recipient parameter, and no inbound-$RELICS path mints anything. An unrelated
/// account therefore cannot cause a dormant Relic to become active for another
/// address by any route, at any price.
///
/// `namedRelicIds` -- normally {nextAwakening}/{awakenPreview}, strictly ascending --
/// is the set of identities the caller authorises itself to receive. NOTHING OUTSIDE
/// IT CAN BE MATERIALISED BY THIS CALL. The canonical lowest-id-first draw decides
/// what is actually offered, and the call fills the longest prefix of that draw which
/// lies inside the named set, clipped to the caller's latent capacity and to
/// {AUTO_AWAKEN_CAP_PER_OWNER}.
///
/// `minCount` is the caller's floor: at least 1, at most `namedRelicIds.length`.
/// Below it the whole call unwinds and nothing is written. Pass
/// `namedRelicIds.length` for strict all-or-nothing; pass 1 to take whatever of the
/// named set is still drawable rather than be reverted by unrelated pool churn.
function awaken(
uint256[] calldata namedRelicIds,
uint256 minCount
)
external
returns (uint256 awakened);
function prepareSell(uint256[] calldata tokenIds) external returns (uint256 count);
// -- views ---------------------------------------------------------------
function evolve(uint256 tokenId) external returns (uint256 newState);
function dnaOf(uint256 tokenId) external view returns (uint256);
function packedStateOf(uint256 tokenId) external view returns (uint256);
function visualFingerprintOf(uint256 tokenId) external view returns (bytes32);
function originalMinterOf(uint256 tokenId) external view returns (address);
function dormantIdentityOf(uint256 tokenId)
external
view
returns (uint256 dna, uint256 packedState, address originalMinter, bytes32 fingerprint);
function balanceOf(address owner) external view returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address);
function totalSupply() external view returns (uint256);
function dormantSupply() external view returns (uint256);
function forgedSupply() external view returns (uint256);
function relicOfOwnerByIndex(address account, uint256 index) external view returns (uint256);
function relicIndexOf(uint256 tokenId) external view returns (uint256);
function backlogOf(address account) external view returns (uint256);
function wholeUnitCapacity(address account) external view returns (uint256);
function activeRelicCount(address account) external view returns (uint256);
function latentRelicCapacity(address account) external view returns (uint256);
function awakenPreview(uint256 count) external view returns (uint256[] memory ids);
function nextAwakening(address account) external view returns (uint256[] memory ids);
function lastOwnedRelic(address owner) external view returns (uint256 tokenId);
function preparationFor(
address owner,
uint256 relicsAmount
)
external
view
returns (uint256 deficit, uint256 callsRequired);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
src/interfaces/IRelicsToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
interface IRelicsToken {
event HolderThresholdCrossed(address indexed account, bool active, uint256 balance);
event RelicSyncConfigured(address indexed relicsNFT);
event RelicSyncPoolSet(address indexed pool);
event RelicLockerSet(address indexed locker);
function HOLDER_THRESHOLD() external view returns (uint256);
function UNIT_PER_RELIC() external view returns (uint256);
function ENTOMBMENT_ADDRESS() external view returns (address);
function relicsNFT() external view returns (address);
function relicSyncPool() external view returns (address);
function relicLocker() external view returns (address);
function activeHolderCount() external view returns (uint256);
function isActiveHolder(address account) external view returns (bool);
/// @notice The whole-unit backing line. Cannot revert.
function relicEntitlement(address account) external view returns (uint256);
function canReceiveRelic(address account) external view returns (bool);
function balanceOf(address account) external view returns (uint256);
function totalSupply() external view returns (uint256);
function transferRelicToken(address from, address to) external;
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/uniswap-hooks/=lib/uniswap-hooks/",
"@uniswap/v4-core/=lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"forge-std/=lib/forge-std/src/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"permit2/=lib/v4-periphery/lib/permit2/",
"solmate/=lib/v4-core/lib/solmate/",
"uniswap-hooks/=lib/uniswap-hooks/src/",
"v4-core/=lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.