Проверенный контрактЧастичноеMIT
WishGarden
Адрес0x33a514c5e2028f1affd70b82f170e8193df030a5
- Баланс
0 ETH
- Транзакций
16
- Компилятор
solc 0.8.26
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.26+commit.8a97fa7a
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Версия EVM
- cancun
- Лицензия
- MIT
- Совпадение
- Частичноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 448 736
- Транзакция создания
- 0x9305085fac…10a6004a8e
19 файлов
- src/WishGarden.solглавный5,04 КБ
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3,1 КБ
- lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol2,48 КБ
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4,47 КБ
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 Б
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 Б
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2,78 КБ
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 Б
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9,41 КБ
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 Б
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol3,38 КБ
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 Б
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34,94 КБ
- src/GardenEconomy.sol1,62 КБ
- src/Utf8Wish.sol1,63 КБ
- src/WishGardenTreasury.sol7,24 КБ
- src/base/EverlightBurnReceiver.sol10,4 КБ
- src/bridge/EverlightBridgeQueue.sol13,28 КБ
- src/bridge/IMDBridge.sol3,5 КБ
src/WishGarden.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {EverlightBridgeQueue} from "./bridge/EverlightBridgeQueue.sol";
import {Utf8Wish} from "./Utf8Wish.sol";
/// @notice EVERLIGHT GARDEN: paid, permanent, nontransferable records. No NFT or free entitlement.
contract WishGarden is EverlightBridgeQueue {
using SafeERC20 for IERC20;
using SafeCast for uint256;
uint8 public constant STYLE_COUNT = 7;
uint256 public constant MAX_PAGE_SIZE = 100;
struct Candle {
address purchaser;
address beneficiary;
uint64 createdAt;
uint8 style;
uint256 position;
string wish;
}
mapping(uint256 => Candle) private _candles;
mapping(address => uint256[]) private _purchaserCandles;
error PurchasesDisabled();
error InvalidStyle(uint8 style);
error LengthMismatch();
error CandleNotFound(uint256 candleId);
error InvalidPage();
event CandleCreated(
uint256 indexed candleId,
address indexed purchaser,
address indexed beneficiary,
uint256 position,
uint8 style,
uint64 createdAt,
string wish
);
event CandlesPurchased(
address indexed purchaser, uint256 indexed firstCandleId, uint256 quantity, uint256 totalIMD
);
/// @dev Factory-safe: no external calls, explicit owner, static argument, no ETH or initializer.
constructor(address owner_) EverlightBridgeQueue(owner_) {}
/// @notice Buy 1..50 candles with individual styles and public, immutable wishes (empty is optional).
/// @dev Purchaser is always beneficiary. Only msg.sender's IMD can be spent.
function buyCandles(uint8[] calldata styles, string[] calldata wishes)
external
nonReentrant
returns (uint256 firstCandleId)
{
if (!activated || purchasesPaused) revert PurchasesDisabled();
uint256 quantity = styles.length;
_checkQuantity(quantity);
if (quantity != wishes.length) revert LengthMismatch();
// Bridge route state is NOT a purchase precondition: it is checked when burn funds are dispatched.
_requireIMD();
firstCandleId = totalCandles + 1;
uint64 createdAt = block.timestamp.toUint64();
for (uint256 i; i < quantity; ++i) {
if (styles[i] >= STYLE_COUNT) revert InvalidStyle(styles[i]);
Utf8Wish.validate(wishes[i]);
_allocateCandle(msg.sender);
uint256 id = totalCandles;
_candles[id] = Candle(msg.sender, msg.sender, createdAt, styles[i], id - 1, wishes[i]);
_purchaserCandles[msg.sender].push(id);
emit CandleCreated(id, msg.sender, msg.sender, id - 1, styles[i], createdAt, wishes[i]);
}
uint256 payment = quantity * CANDLE_PRICE;
IERC20 token = IERC20(IMD);
uint256 heldBefore = token.balanceOf(address(this));
uint256 buyerBefore = token.balanceOf(msg.sender);
token.safeTransferFrom(msg.sender, address(this), payment);
if (
token.balanceOf(address(this)) != heldBefore + payment
|| token.balanceOf(msg.sender) != buyerBefore - payment
) {
revert InexactTransfer();
}
emit CandlesPurchased(msg.sender, firstCandleId, quantity, payment);
}
function getCandle(uint256 id) external view returns (Candle memory) {
if (id == 0 || id > totalCandles) revert CandleNotFound(id);
return _candles[id];
}
function candleCountOf(address purchaser) external view returns (uint256) {
return _purchaserCandles[purchaser].length;
}
function candleIdsOf(address purchaser, uint256 offset, uint256 limit)
external
view
returns (uint256[] memory ids, uint256 nextOffset)
{
uint256 length = _purchaserCandles[purchaser].length;
if (limit == 0 || limit > MAX_PAGE_SIZE || offset > length) revert InvalidPage();
uint256 count = length - offset;
if (count > limit) count = limit;
ids = new uint256[](count);
for (uint256 i; i < count; ++i) {
ids[i] = _purchaserCandles[purchaser][offset + i];
}
nextOffset = offset + count;
}
function getCandles(uint256 firstId, uint256 limit)
external
view
returns (Candle[] memory records, uint256 nextId)
{
if (limit == 0 || limit > MAX_PAGE_SIZE || firstId == 0 || firstId > totalCandles + 1) {
revert InvalidPage();
}
uint256 count = totalCandles + 1 - firstId;
if (count > limit) count = limit;
records = new Candle[](count);
for (uint256 i; i < count; ++i) {
records[i] = _candles[firstId + i];
}
nextId = firstId + count;
}
}
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/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data)
external
returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
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/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(
address spender, uint256 currentAllowance, uint256 requestedDecrease
);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
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;
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
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;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
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
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
src/GardenEconomy.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @notice Fixed Ethereum IMD economy shared by the garden and its treasury.
abstract contract GardenEconomy {
address public constant IMD = 0xD34a99Bc0f67aE1bbd63C660e6d0b0dd03E263B7;
uint256 public constant CHAIN_ID = 1;
uint8 public constant IMD_DECIMALS = 18;
uint256 public constant CANDLE_PRICE = 1e18;
uint256 public constant MAX_BATCH_SIZE = 50;
uint256 public constant BURN_ALLOCATION_PER_CANDLE = 0.3e18;
uint256 public constant REWARD_PER_CANDLE = 0.6e18;
uint256 public constant ECOSYSTEM_PER_CANDLE = 0;
uint256 public constant OPERATIONS_PER_CANDLE = 0.05e18;
uint256 public constant FOUNDER_PER_CANDLE = 0.05e18;
error WrongChain(uint256 actualChainId);
error IMDUnavailable();
error UnexpectedIMDDecimals(uint8 actualDecimals);
error InvalidQuantity(uint256 quantity);
error InexactTransfer();
error InvalidAddress();
function _requireEthereum() internal view {
if (block.chainid != CHAIN_ID) revert WrongChain(block.chainid);
}
function _requireIMD() internal view {
_requireEthereum();
if (IMD.code.length == 0) revert IMDUnavailable();
uint8 decimals = IERC20Metadata(IMD).decimals();
if (decimals != IMD_DECIMALS) revert UnexpectedIMDDecimals(decimals);
}
function _checkQuantity(uint256 quantity) internal pure {
if (quantity == 0 || quantity > MAX_BATCH_SIZE) revert InvalidQuantity(quantity);
}
}
src/Utf8Wish.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @dev Strict Unicode scalar-value UTF-8. No normalization: original bytes are permanent.
library Utf8Wish {
error InvalidUTF8();
error WishTooLong();
function validate(string calldata text) internal pure {
bytes calldata b = bytes(text);
if (b.length > 1120) revert WishTooLong();
uint256 count = 0;
uint256 i = 0;
while (i < b.length) {
uint8 c = uint8(b[i]);
uint256 n;
uint32 cp;
uint32 minimum = 0;
if (c < 0x80) {
n = 1;
cp = c;
} else if (c >= 0xc2 && c <= 0xdf) {
n = 2;
cp = c & 0x1f;
minimum = 0x80;
} else if (c >= 0xe0 && c <= 0xef) {
n = 3;
cp = c & 0x0f;
minimum = 0x800;
} else if (c >= 0xf0 && c <= 0xf4) {
n = 4;
cp = c & 0x07;
minimum = 0x10000;
} else {
revert InvalidUTF8();
}
if (i + n > b.length) revert InvalidUTF8();
for (uint256 j = 1; j < n; ++j) {
uint8 continuation = uint8(b[i + j]);
if (continuation < 0x80 || continuation > 0xbf) revert InvalidUTF8();
cp = (cp << 6) | (continuation & 0x3f);
}
if (cp < minimum || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) revert InvalidUTF8();
if (++count > 280) revert WishTooLong();
i += n;
}
}
}
src/WishGardenTreasury.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {GardenEconomy} from "./GardenEconomy.sol";
/// @notice Internal treasury of WishGarden. Not a separately deployed or bindable application.
abstract contract WishGardenTreasury is GardenEconomy, Ownable2Step, ReentrancyGuard {
using SafeERC20 for IERC20;
uint256 public constant REWARD_SCALE = 1e27;
enum Bucket {
Ecosystem,
Operations,
Founder
}
struct RewardAccount {
uint256 candles;
uint256 checkpoint;
uint256 earnedScaled;
uint256 claimed;
}
mapping(address => RewardAccount) internal _rewards;
uint256 public totalCandles;
uint256 public rewardPerCandle;
uint256 public rewardDustScaled;
uint256 public totalRewardsAllocated;
uint256 public totalRewardsClaimed;
// Preserve the original read API and bucket numbers for indexers.
uint256 public constant ecosystemBalance = 0;
uint256 public operationsBalance;
uint256 public founderBalance;
uint256 public constant totalEcosystemWithdrawn = 0;
uint256 public totalOperationsWithdrawn;
uint256 public totalFounderWithdrawn;
uint256 public burnQueued;
uint256 public burnReserved;
uint256 public totalBurnAllocated;
error NothingToClaim();
error InvalidWithdrawal();
error InsufficientBucketBalance();
error OwnershipRequired();
event RewardAllocated(
uint256 indexed candleId, uint256 priorCandles, uint256 increment, bool fallbackToBurn
);
event BurnAllocated(uint256 indexed candleId, uint256 amount);
event RewardsClaimed(address indexed beneficiary, uint256 amount, uint256 cumulativeClaimed);
event BucketWithdrawn(
Bucket indexed bucket, address indexed caller, address indexed destination, uint256 amount
);
constructor(address owner_) Ownable(owner_) {}
function totalPayments() public view returns (uint256) {
return totalCandles * CANDLE_PRICE;
}
function paidCandles() external view returns (uint256) {
return totalCandles;
}
function rewardLiability() public view returns (uint256) {
return totalRewardsAllocated - totalRewardsClaimed;
}
function ownerWithdrawable() public view returns (uint256) {
return operationsBalance + founderBalance;
}
function accountedBalance() public view returns (uint256) {
return ownerWithdrawable() + rewardLiability() + burnQueued + burnReserved;
}
function unallocatedBalance() external view returns (uint256) {
uint256 held = IERC20(IMD).balanceOf(address(this));
uint256 accounted = accountedBalance();
return held > accounted ? held - accounted : 0;
}
function rewardState(address beneficiary)
public
view
returns (uint256 candles, uint256 earned, uint256 claimed, uint256 claimable, uint256 fractionScaled)
{
RewardAccount storage a = _rewards[beneficiary];
uint256 scaled = a.earnedScaled + a.candles * (rewardPerCandle - a.checkpoint);
earned = scaled / REWARD_SCALE;
return (a.candles, earned, a.claimed, earned - a.claimed, scaled % REWARD_SCALE);
}
function claimableRewards(address beneficiary) public view returns (uint256 claimable) {
(,,, claimable,) = rewardState(beneficiary);
}
/// @notice Only the beneficiary can claim, and payment always goes to that beneficiary.
/// @dev Purchases/bridge activation and purchase pause never gate claims.
function claimRewards() external nonReentrant returns (uint256 amount) {
_requireIMD();
RewardAccount storage a = _rewards[msg.sender];
_settle(a);
amount = a.earnedScaled / REWARD_SCALE - a.claimed;
if (amount == 0) revert NothingToClaim();
a.claimed += amount;
totalRewardsClaimed += amount;
_transferExact(msg.sender, amount);
emit RewardsClaimed(msg.sender, amount, a.claimed);
}
function withdrawBucket(Bucket bucket, address destination, uint256 amount)
external
nonReentrant
onlyOwner
{
_requireIMD();
if (amount == 0 || destination == address(0) || destination == address(this) || destination == IMD) {
revert InvalidWithdrawal();
}
if (bucket == Bucket.Ecosystem) revert InsufficientBucketBalance();
if (bucket == Bucket.Operations) {
if (amount > operationsBalance) revert InsufficientBucketBalance();
operationsBalance -= amount;
totalOperationsWithdrawn += amount;
} else {
if (amount > founderBalance) revert InsufficientBucketBalance();
founderBalance -= amount;
totalFounderWithdrawn += amount;
}
_transferExact(destination, amount);
emit BucketWithdrawn(bucket, msg.sender, destination, amount);
}
function renounceOwnership() public view override onlyOwner {
revert OwnershipRequired();
}
function _allocateCandle(address beneficiary) internal {
uint256 prior = totalCandles;
uint256 increment = 0;
uint256 burnAmount = BURN_ALLOCATION_PER_CANDLE;
if (prior == 0) {
burnAmount += REWARD_PER_CANDLE;
} else {
uint256 scaled = REWARD_PER_CANDLE * REWARD_SCALE;
increment = scaled / prior;
rewardPerCandle += increment;
// Never recycle dust into later allocations: that could reward newly purchased candles.
rewardDustScaled += scaled % prior;
totalRewardsAllocated += REWARD_PER_CANDLE;
}
RewardAccount storage a = _rewards[beneficiary];
_settle(a); // Old candles receive this share; the new candle receives none.
++a.candles;
++totalCandles;
operationsBalance += OPERATIONS_PER_CANDLE;
founderBalance += FOUNDER_PER_CANDLE;
burnQueued += burnAmount;
totalBurnAllocated += burnAmount;
emit BurnAllocated(totalCandles, burnAmount);
emit RewardAllocated(totalCandles, prior, increment, prior == 0);
}
function _settle(RewardAccount storage a) private {
a.earnedScaled += a.candles * (rewardPerCandle - a.checkpoint);
a.checkpoint = rewardPerCandle;
}
function _transferExact(address destination, uint256 amount) internal {
IERC20 token = IERC20(IMD);
uint256 beforeHeld = token.balanceOf(address(this));
uint256 beforeRecipient = token.balanceOf(destination);
token.safeTransfer(destination, amount);
if (
token.balanceOf(address(this)) != beforeHeld - amount
|| token.balanceOf(destination) != beforeRecipient + amount
) {
revert InexactTransfer();
}
}
}
src/base/EverlightBurnReceiver.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {
IMDBridge,
IIMDOFT,
IBaseIMD,
ILZEndpoint,
MessagingParams,
MessagingFee,
MessagingReceipt
} from "../bridge/IMDBridge.sol";
/// @notice BASE ONLY. Separate owner deployment, explicitly excluded from Ethereum's launch manifest.
/// @dev No token withdrawal, approval, arbitrary call, token creation, or owner-reported burns.
contract EverlightBurnReceiver is Ownable2Step, ReentrancyGuard {
address public constant IMD = IMDBridge.BASE_IMD;
address public constant ETHEREUM_IMD = 0xD34a99Bc0f67aE1bbd63C660e6d0b0dd03E263B7;
uint256 public constant BURN_GAS = 150_000;
uint256 public constant MAX_NATIVE_FEE = 0.05 ether;
address public immutable ethereumGarden;
bool public activated;
bytes32 public configHash;
bytes32 public evidenceHash;
bytes32 public tokenCodeHash;
bytes32 public adapterCodeHash;
bytes32 public endpointCodeHash;
enum Status {
None,
Received,
Failed,
Burned
}
struct Delivery {
uint256 jobId;
uint256 amount;
uint32 attempts;
Status status;
bool acknowledged;
}
mapping(bytes32 => Delivery) public deliveries;
mapping(uint256 => bytes32) public jobGuids;
uint256 public pendingBurn;
uint256 public failedBurn;
uint256 public totalReceived;
uint256 public totalBurned;
uint256 public totalFailures;
uint256 public totalRetries;
error WrongChain();
error InvalidConfiguration();
error InvalidDelivery();
error InvalidFee();
error OnlySelf();
error InexactBurn();
error InsufficientExecutionGas();
error OwnershipRequired();
event ReceiverActivated(bytes32 indexed configHash, bytes32 evidenceHash);
event BurnReceived(bytes32 indexed guid, uint256 indexed jobId, uint256 amount);
event BurnFailed(bytes32 indexed guid, uint32 attempt, bytes32 reasonHash);
event SupplyBurned(bytes32 indexed guid, uint256 indexed jobId, uint256 amount, uint256 cumulativeBurned);
event ReceiptSent(bytes32 indexed burnGuid, bytes32 indexed messageGuid, uint8 kind);
constructor(address owner_, address ethereumGarden_) Ownable(owner_) {
if (ethereumGarden_ == address(0)) revert InvalidConfiguration();
ethereumGarden = ethereumGarden_;
}
function activate(bytes32 evidence) external nonReentrant onlyOwner {
_requireBase();
if (activated || evidence == bytes32(0)) revert InvalidConfiguration();
_checkRoute();
activated = true;
evidenceHash = evidence;
configHash = keccak256(abi.encode(uint256(1), ethereumGarden, uint256(8453), address(this), evidence));
tokenCodeHash = IMD.codehash;
adapterCodeHash = IMDBridge.BASE_ADAPTER.codehash;
endpointCodeHash = IMDBridge.ENDPOINT.codehash;
emit ReceiverActivated(configHash, evidence);
}
/// @notice Separate native-gas payment for readiness; does not move IMD.
function announceReady() external payable nonReentrant onlyOwner {
_requireReady();
_sendReceipt(1, bytes32(0));
}
/// @notice Official OFT compose format: nonce[8], srcEid[4], amount[32], composeFrom[32], jobId[32].
function lzCompose(address from, bytes32 guid, bytes calldata message, address, bytes calldata)
external
payable
nonReentrant
{
_requireBase();
// The adapter credited this delivery in its own earlier lzReceive. A later adapter peer or code
// change must not strand it unrecorded: authenticate by endpoint + adapter + message only, as
// retryBurn does. The full live route check still gates activate and announceReady.
if (!activated || IMD.codehash != tokenCodeHash) revert InvalidConfiguration();
if (
msg.sender != IMDBridge.ENDPOINT || from != IMDBridge.BASE_ADAPTER || msg.value != 0
|| message.length != 108 || guid == bytes32(0) || deliveries[guid].status != Status.None
|| uint32(bytes4(message[8:12])) != IMDBridge.ETH_EID
|| bytes32(message[44:76]) != IMDBridge.asBytes32(ethereumGarden)
) revert InvalidDelivery();
uint256 amount = uint256(bytes32(message[12:44]));
uint256 jobId = abi.decode(message[76:], (uint256));
if (
amount == 0 || amount % IMDBridge.CONVERSION_RATE != 0 || jobId == 0
|| jobGuids[jobId] != bytes32(0)
|| IERC20(IMD).balanceOf(address(this)) < pendingBurn + amount
) revert InvalidDelivery();
jobGuids[jobId] = guid;
deliveries[guid] = Delivery(jobId, amount, 0, Status.Received, false);
totalReceived += amount;
pendingBurn += amount;
emit BurnReceived(guid, jobId, amount);
_attemptBurn(guid);
}
/// @notice Anyone can pay gas to retry the same authenticated, funded delivery. Cannot redirect it.
function retryBurn(bytes32 guid) external nonReentrant {
_requireBase();
// This delivery was already authenticated and funded. A later bridge-peer change must not
// prevent burning its retained balance; only the fixed token is involved in a retry.
if (!activated || IMD.codehash != tokenCodeHash) revert InvalidConfiguration();
if (deliveries[guid].status != Status.Failed) revert InvalidDelivery();
failedBurn -= deliveries[guid].amount;
++totalRetries;
_attemptBurn(guid);
}
function performBurn(uint256 amount) external {
if (msg.sender != address(this)) revert OnlySelf();
IERC20 token = IERC20(IMD);
uint256 held = token.balanceOf(address(this));
uint256 supply = token.totalSupply();
IBaseIMD(IMD).burn(amount);
if (token.balanceOf(address(this)) != held - amount || token.totalSupply() != supply - amount) {
revert InexactBurn();
}
}
/// @notice Send a confirmed burn back to Ethereum, funded by caller's native ETH, exactly once.
/// @dev A delivery failure is retried on LayerZero using this SAME packet; never burn or send tokens again.
function sendBurnReceipt(bytes32 guid) external payable nonReentrant {
_requireBase();
Delivery storage d = deliveries[guid];
if (d.status != Status.Burned || d.acknowledged) revert InvalidDelivery();
d.acknowledged = true;
_sendReceipt(2, guid);
}
function quoteReceipt(uint8 kind, bytes32 guid) external view returns (MessagingFee memory) {
return ILZEndpoint(IMDBridge.ENDPOINT).quote(_receiptParams(kind, guid), address(this));
}
function renounceOwnership() public view override onlyOwner {
revert OwnershipRequired();
}
function _attemptBurn(bytes32 guid) private {
Delivery storage d = deliveries[guid];
++d.attempts;
// Effects precede the token call; failure restores pending custody below.
d.status = Status.Burned;
pendingBurn -= d.amount;
totalBurned += d.amount;
if (gasleft() < BURN_GAS * 64 / 63 + 120_000) revert InsufficientExecutionGas();
try this.performBurn{gas: BURN_GAS}(d.amount) {
emit SupplyBurned(guid, d.jobId, d.amount, totalBurned);
} catch (bytes memory reason) {
d.status = Status.Failed;
pendingBurn += d.amount;
totalBurned -= d.amount;
failedBurn += d.amount;
++totalFailures;
emit BurnFailed(guid, d.attempts, keccak256(reason));
}
}
function _sendReceipt(uint8 kind, bytes32 guid) private {
MessagingParams memory params = _receiptParams(kind, guid);
MessagingFee memory fee = ILZEndpoint(IMDBridge.ENDPOINT).quote(params, address(this));
if (fee.lzTokenFee != 0 || fee.nativeFee > MAX_NATIVE_FEE || msg.value != fee.nativeFee) {
revert InvalidFee();
}
MessagingReceipt memory receipt =
ILZEndpoint(IMDBridge.ENDPOINT).send{value: msg.value}(params, msg.sender);
if (
receipt.guid == bytes32(0) || receipt.fee.nativeFee != fee.nativeFee
|| receipt.fee.lzTokenFee != 0
) revert InvalidFee();
emit ReceiptSent(guid, receipt.guid, kind);
}
function _receiptParams(uint8 kind, bytes32 guid) private view returns (MessagingParams memory) {
Delivery storage d = deliveries[guid];
if (
!activated || (kind != 1 && kind != 2) || (kind == 1 && guid != bytes32(0))
|| (kind == 2 && d.status != Status.Burned)
) revert InvalidDelivery();
return MessagingParams(
IMDBridge.ETH_EID,
IMDBridge.asBytes32(ethereumGarden),
abi.encode(kind, configHash, d.jobId, guid, d.amount),
IMDBridge.receiveOptions(),
false
);
}
function _requireBase() private view {
if (block.chainid != 8453) revert WrongChain();
}
function _requireReady() private view {
_requireBase();
if (
!activated || IMD.codehash != tokenCodeHash || IMDBridge.BASE_ADAPTER.codehash != adapterCodeHash
|| IMDBridge.ENDPOINT.codehash != endpointCodeHash
) revert InvalidConfiguration();
_checkRoute();
}
function _checkRoute() private view {
IIMDOFT adapter = IIMDOFT(IMDBridge.BASE_ADAPTER);
if (
IMD.code.length == 0 || IERC20Metadata(IMD).decimals() != 18 || adapter.token() != IMD
|| !adapter.approvalRequired() || adapter.endpoint() != IMDBridge.ENDPOINT
|| adapter.decimalConversionRate() != IMDBridge.CONVERSION_RATE
|| adapter.peers(IMDBridge.ETH_EID) != IMDBridge.asBytes32(ETHEREUM_IMD)
|| ILZEndpoint(IMDBridge.ENDPOINT).eid() != IMDBridge.BASE_EID
) revert InvalidConfiguration();
}
}
src/bridge/EverlightBridgeQueue.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {WishGardenTreasury} from "../WishGardenTreasury.sol";
import {EverlightBurnReceiver} from "../base/EverlightBurnReceiver.sol";
import {
IMDBridge,
IIMDOFT,
ILZEndpoint,
SendParam,
MessagingFee,
MessagingReceipt,
OFTReceipt,
Origin
} from "./IMDBridge.sol";
/// @notice Restricted IMD -> official Base adapter -> source-pinned burn-only receiver route.
/// @dev The only possible destination is the CREATE2 address of this repository's EverlightBurnReceiver
/// (its creation code is compiled into this contract's constructor) deployed on Base through the
/// canonical deterministic deployer with this garden and its initial owner as constructor arguments.
/// The owner cannot name another destination, and no other address can author confirmations.
abstract contract EverlightBridgeQueue is WishGardenTreasury {
enum BurnStatus {
None,
Queued,
Failed,
InTransit,
Completed
}
struct BurnJob {
uint256 amount;
bytes32 guid;
uint32 attempts;
BurnStatus status;
}
uint256 public constant MAX_NATIVE_FEE = 0.05 ether;
uint256 public constant SEND_GAS = 1_000_000;
/// @notice Canonical deterministic-deployment proxy (same address on Ethereum and Base).
address public constant CREATE2_DEPLOYER = 0x4e59b44847b379578588920cA78FbF26c0B4956C;
bytes32 public constant BASE_RECEIVER_SALT = keccak256("EVERLIGHT GARDEN Base burn receiver v1");
/// @notice The fixed Base destination. Derived in the constructor without any external call.
address public immutable pinnedBaseReceiver;
address public baseReceiver;
bytes32 public bridgeEvidence;
bytes32 public bridgeConfigHash;
bytes32 public imdCodeHash;
bytes32 public endpointCodeHash;
bool public baseReady;
bool public activated;
bool public purchasesPaused = true;
uint256 public burnJobCount;
uint256 public burnInTransit;
uint256 public confirmedBurn;
uint256 public failedBurnAmount;
uint256 public totalSendFailures;
uint256 public totalSendRetries;
mapping(uint256 => BurnJob) public burnJobs;
mapping(bytes32 => bool) public sentGuids;
mapping(bytes32 => bool) public receivedGuids;
error BridgeNotReady();
error InvalidBridgeConfiguration();
error ConfigurationFrozen();
error InvalidBurnJob();
error InvalidFee();
error OnlySelf();
error InsufficientExecutionGas();
error RefundFailed();
error InvalidMessage();
event BridgeConfigured(address indexed receiver, bytes32 configHash, bytes32 evidenceHash);
event BaseReadinessConfirmed(address indexed receiver, bytes32 configHash);
event Activated(bytes32 indexed configHash);
event PurchasesPaused(bool paused);
event BurnQueued(uint256 indexed jobId, uint256 amount);
event BurnDispatched(uint256 indexed jobId, bytes32 indexed guid, uint256 amount, uint32 attempt);
event BurnSendFailed(uint256 indexed jobId, uint32 attempt, bytes32 reasonHash);
event BurnConfirmed(uint256 indexed jobId, bytes32 indexed guid, uint256 amount);
constructor(address owner_) WishGardenTreasury(owner_) {
bytes32 initCodeHash = keccak256(
bytes.concat(type(EverlightBurnReceiver).creationCode, abi.encode(owner_, address(this)))
);
pinnedBaseReceiver = address(
uint160(
uint256(
keccak256(
abi.encodePacked(bytes1(0xff), CREATE2_DEPLOYER, BASE_RECEIVER_SALT, initCodeHash)
)
)
)
);
}
/// @notice Owner confirms the source-pinned Base receiver and reviewed evidence before any purchase.
/// @dev `receiver` MUST equal pinnedBaseReceiver: the owner cannot choose the destination. Token,
/// bridge, endpoints, chains, gas options, fee ceiling and all rates are fixed in source.
function configureBridge(address receiver, bytes32 evidenceHash) external nonReentrant onlyOwner {
if (activated) revert ConfigurationFrozen();
_requireIMD();
if (
receiver != pinnedBaseReceiver || receiver == address(0) || receiver == IMDBridge.BASE_IMD
|| receiver == IMDBridge.BASE_ADAPTER || receiver == IMDBridge.ENDPOINT
|| evidenceHash == bytes32(0)
) revert InvalidBridgeConfiguration();
_checkOfficialRoute();
baseReceiver = receiver;
bridgeEvidence = evidenceHash;
imdCodeHash = IMD.codehash;
endpointCodeHash = IMDBridge.ENDPOINT.codehash;
bridgeConfigHash =
keccak256(abi.encode(uint256(1), address(this), uint256(8453), receiver, evidenceHash));
baseReady = false;
emit BridgeConfigured(receiver, bridgeConfigHash, evidenceHash);
}
function activate() external nonReentrant onlyOwner {
if (activated) revert ConfigurationFrozen();
if (!baseReady) revert BridgeNotReady();
_checkFrozenRoute();
activated = true;
purchasesPaused = false;
emit Activated(bridgeConfigHash);
emit PurchasesPaused(false);
}
function setPurchasesPaused(bool paused) external nonReentrant onlyOwner {
if (!activated) revert BridgeNotReady();
purchasesPaused = paused;
emit PurchasesPaused(paused);
}
function queueBurn(uint256 maximumAmount) external nonReentrant onlyOwner returns (uint256 jobId) {
if (!activated) revert BridgeNotReady();
uint256 amount = maximumAmount < burnQueued ? maximumAmount : burnQueued;
amount = amount / IMDBridge.CONVERSION_RATE * IMDBridge.CONVERSION_RATE;
if (amount == 0 || amount / IMDBridge.CONVERSION_RATE > type(uint64).max) revert InvalidBurnJob();
burnQueued -= amount;
burnReserved += amount;
jobId = ++burnJobCount;
burnJobs[jobId] = BurnJob(amount, bytes32(0), 0, BurnStatus.Queued);
emit BurnQueued(jobId, amount);
}
function bridgeDust() external view returns (uint256) {
return burnQueued % IMDBridge.CONVERSION_RATE;
}
function quoteBurn(uint256 jobId) public view returns (MessagingFee memory fee) {
BurnJob storage job = burnJobs[jobId];
if (job.status != BurnStatus.Queued && job.status != BurnStatus.Failed) revert InvalidBurnJob();
fee = IIMDOFT(IMD).quoteSend(_sendParam(jobId), false);
}
/// @notice A failed source send stays reserved and retryable under the SAME ID. No fund withdrawal.
function dispatchBurn(uint256 jobId) external payable nonReentrant onlyOwner returns (bool sent) {
_checkFrozenRoute();
MessagingFee memory fee = quoteBurn(jobId);
if (fee.nativeFee > MAX_NATIVE_FEE || fee.lzTokenFee != 0 || msg.value != fee.nativeFee) {
revert InvalidFee();
}
BurnJob storage job = burnJobs[jobId];
if (job.status == BurnStatus.Failed) {
failedBurnAmount -= job.amount;
++totalSendRetries;
}
++job.attempts;
// Effects precede the bridge call; the catch restores custody if the atomic subcall fails.
job.status = BurnStatus.InTransit;
burnReserved -= job.amount;
burnInTransit += job.amount;
// EIP-150 headroom plus storage/log/refund margin. Underfunded outer calls MUST revert.
if (gasleft() < SEND_GAS * 64 / 63 + 150_000) revert InsufficientExecutionGas();
try this.performBridgeSend{value: msg.value, gas: SEND_GAS}(jobId, fee) returns (bytes32 guid) {
job.guid = guid;
sentGuids[guid] = true;
emit BurnDispatched(jobId, guid, job.amount, job.attempts);
return true;
} catch (bytes memory reason) {
job.status = BurnStatus.Failed;
burnReserved += job.amount;
burnInTransit -= job.amount;
failedBurnAmount += job.amount;
++totalSendFailures;
emit BurnSendFailed(jobId, job.attempts, keccak256(reason));
if (msg.value != 0) {
(bool refunded,) = payable(msg.sender).call{value: msg.value}("");
if (!refunded) revert RefundFailed();
}
return false;
}
}
/// @dev Isolated subcall makes malformed receipts/inexact debits atomic with bridge failure.
/// Only callable by dispatchBurn; the outer entrypoint holds the reentrancy guard.
function performBridgeSend(uint256 jobId, MessagingFee calldata fee) external payable returns (bytes32) {
if (msg.sender != address(this)) revert OnlySelf();
uint256 beforeHeld = IERC20(IMD).balanceOf(address(this));
uint256 amount = burnJobs[jobId].amount;
// Official Ethereum OFT burns msg.sender's debit. approvalRequired() == false; allowance stays ZERO.
(MessagingReceipt memory receipt, OFTReceipt memory oftReceipt) =
IIMDOFT(IMD).send{value: msg.value}(_sendParam(jobId), fee, owner());
if (
receipt.guid == bytes32(0) || sentGuids[receipt.guid] || receipt.fee.nativeFee != fee.nativeFee
|| receipt.fee.lzTokenFee != 0 || oftReceipt.amountSentLD != amount
|| oftReceipt.amountReceivedLD != amount
|| IERC20(IMD).balanceOf(address(this)) != beforeHeld - amount
) revert InexactTransfer();
return receipt.guid;
}
function allowInitializePath(Origin calldata origin) external view returns (bool) {
return baseReceiver != address(0) && origin.srcEid == IMDBridge.BASE_EID
&& origin.sender == IMDBridge.asBytes32(baseReceiver);
}
function nextNonce(uint32, bytes32) external pure returns (uint64) {
return 0;
}
/// @notice LayerZero authenticated readiness / burn acknowledgements; never owner attestations of a burn.
function lzReceive(
Origin calldata origin,
bytes32 messageGuid,
bytes calldata message,
address,
bytes calldata
) external payable nonReentrant {
_requireEthereum();
if (
msg.sender != IMDBridge.ENDPOINT || baseReceiver == address(0)
|| origin.srcEid != IMDBridge.BASE_EID || origin.sender != IMDBridge.asBytes32(baseReceiver)
|| msg.value != 0 || messageGuid == bytes32(0) || receivedGuids[messageGuid]
|| message.length != 160
) {
revert InvalidMessage();
}
(uint8 kind, bytes32 configHash, uint256 jobId, bytes32 burnGuid, uint256 amount) =
abi.decode(message, (uint8, bytes32, uint256, bytes32, uint256));
if (configHash != bridgeConfigHash) revert InvalidMessage();
receivedGuids[messageGuid] = true;
if (kind == 1) {
if (jobId != 0 || burnGuid != bytes32(0) || amount != 0) revert InvalidMessage();
baseReady = true;
emit BaseReadinessConfirmed(baseReceiver, configHash);
} else if (kind == 2) {
BurnJob storage job = burnJobs[jobId];
if (job.status != BurnStatus.InTransit || job.guid != burnGuid || job.amount != amount) {
revert InvalidMessage();
}
job.status = BurnStatus.Completed;
burnInTransit -= amount;
confirmedBurn += amount;
emit BurnConfirmed(jobId, burnGuid, amount);
} else {
revert InvalidMessage();
}
}
function _sendParam(uint256 jobId) private view returns (SendParam memory) {
uint256 amount = burnJobs[jobId].amount;
return SendParam(
IMDBridge.BASE_EID,
IMDBridge.asBytes32(baseReceiver),
amount,
amount,
IMDBridge.burnOptions(),
abi.encode(jobId),
bytes("")
);
}
function _checkOfficialRoute() private view {
IIMDOFT oft = IIMDOFT(IMD);
if (
oft.endpoint() != IMDBridge.ENDPOINT || IMDBridge.ENDPOINT.code.length == 0
|| ILZEndpoint(IMDBridge.ENDPOINT).eid() != IMDBridge.ETH_EID || oft.token() != IMD
|| oft.approvalRequired()
|| oft.peers(IMDBridge.BASE_EID) != IMDBridge.asBytes32(IMDBridge.BASE_ADAPTER)
|| oft.decimalConversionRate() != IMDBridge.CONVERSION_RATE
) revert InvalidBridgeConfiguration();
}
/// @dev Custody-relevant route only: token, endpoint, peer, debit mode, decimals and code hashes.
/// Enforced executor options belong to the IMD OFT owner and only change the quoted fee, which
/// dispatchBurn bounds by MAX_NATIVE_FEE; they are deliberately not part of the frozen route.
/// Purchases never call this: a purchase moves IMD into this contract and touches no bridge.
function _checkFrozenRoute() internal view {
_requireIMD();
_checkOfficialRoute();
if (IMD.codehash != imdCodeHash || IMDBridge.ENDPOINT.codehash != endpointCodeHash) {
revert InvalidBridgeConfiguration();
}
}
}
src/bridge/IMDBridge.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
// ABI subset of the verified IMD OFT / LayerZero V2 source. See docs/verification.md.
struct SendParam {
uint32 dstEid;
bytes32 to;
uint256 amountLD;
uint256 minAmountLD;
bytes extraOptions;
bytes composeMsg;
bytes oftCmd;
}
struct OFTReceipt {
uint256 amountSentLD;
uint256 amountReceivedLD;
}
struct MessagingFee {
uint256 nativeFee;
uint256 lzTokenFee;
}
struct MessagingReceipt {
bytes32 guid;
uint64 nonce;
MessagingFee fee;
}
struct MessagingParams {
uint32 dstEid;
bytes32 receiver;
bytes message;
bytes options;
bool payInLzToken;
}
struct Origin {
uint32 srcEid;
bytes32 sender;
uint64 nonce;
}
interface IIMDOFT {
function token() external view returns (address);
function approvalRequired() external view returns (bool);
function endpoint() external view returns (address);
function peers(uint32 eid) external view returns (bytes32);
function decimalConversionRate() external view returns (uint256);
function enforcedOptions(uint32 eid, uint16 msgType) external view returns (bytes memory);
function quoteSend(SendParam calldata param, bool payInLzToken)
external
view
returns (MessagingFee memory);
function send(SendParam calldata param, MessagingFee calldata fee, address refundAddress)
external
payable
returns (MessagingReceipt memory, OFTReceipt memory);
}
interface ILZEndpoint {
function eid() external view returns (uint32);
function quote(MessagingParams calldata params, address sender)
external
view
returns (MessagingFee memory);
function send(MessagingParams calldata params, address refundAddress)
external
payable
returns (MessagingReceipt memory);
}
interface IBaseIMD {
function burn(uint256 amount) external;
}
library IMDBridge {
uint32 internal constant ETH_EID = 30101;
uint32 internal constant BASE_EID = 30184;
address internal constant ENDPOINT = 0x1a44076050125825900e736c501f859c50fE728c;
address internal constant BASE_ADAPTER = 0xab152db8aaC047b6757fFCF495FfE88d7712690A;
address internal constant BASE_IMD = 0xFF0C532FDB8Cd566Ae169C1CB157ff2Bdc83E105;
uint256 internal constant CONVERSION_RATE = 1e12;
uint128 internal constant RECEIVE_GAS = 200_000;
// The executor gives this to EndpointV2.lzCompose, whose queue bookkeeping and the 63/64 forwarding
// rule come out of it. A first delivery measured about 466.5k that way (test/RevisionFindings.t.sol).
uint128 internal constant COMPOSE_GAS = 650_000;
function asBytes32(address account) internal pure returns (bytes32) {
return bytes32(uint256(uint160(account)));
}
// LayerZero OptionsBuilder Type 3: executor worker=1; receive=1, compose=3.
// Each option size includes its one-byte type; compose includes uint16 index 0.
function receiveOptions() internal pure returns (bytes memory) {
return abi.encodePacked(uint16(3), uint8(1), uint16(17), uint8(1), RECEIVE_GAS);
}
function burnOptions() internal pure returns (bytes memory) {
return abi.encodePacked(
uint16(3),
uint8(1),
uint16(17),
uint8(1),
RECEIVE_GAS,
uint8(1),
uint16(19),
uint8(3),
uint16(0),
COMPOSE_GAS
);
}
}
Настройки компилятораПоказать
{
"metadata": {
"bytecodeHash": "none"
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
":forge-std/=lib/forge-std/src/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.