// SPDX-License-Identifier: MIT pragma solidity 0.8.30; // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol) /** * @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); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.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); } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract 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; } } // File: @openzeppelin/contracts/interfaces/draft-IERC6093.sol // OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol) /** * @dev Standard ERC-20 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens. */ interface IERC20Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC20InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC20InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers. * @param spender Address that may be allowed to operate on tokens without being their owner. * @param allowance Amount of tokens a `spender` is allowed to operate with. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC20InvalidApprover(address approver); /** * @dev Indicates a failure with the `spender` to be approved. Used in approvals. * @param spender Address that may be allowed to operate on tokens without being their owner. */ error ERC20InvalidSpender(address spender); } /** * @dev Standard ERC-721 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens. */ interface IERC721Errors { /** * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721. * Used in balance queries. * @param owner Address of the current owner of a token. */ error ERC721InvalidOwner(address owner); /** * @dev Indicates a `tokenId` whose `owner` is the zero address. * @param tokenId Identifier number of a token. */ error ERC721NonexistentToken(uint256 tokenId); /** * @dev Indicates an error related to the ownership over a particular token. Used in transfers. * @param sender Address whose tokens are being transferred. * @param tokenId Identifier number of a token. * @param owner Address of the current owner of a token. */ error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC721InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC721InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param tokenId Identifier number of a token. */ error ERC721InsufficientApproval(address operator, uint256 tokenId); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC721InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC721InvalidOperator(address operator); } /** * @dev Standard ERC-1155 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens. */ interface IERC1155Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. * @param tokenId Identifier number of a token. */ error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC1155InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC1155InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param owner Address of the current owner of a token. */ error ERC1155MissingApprovalForAll(address operator, address owner); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC1155InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC1155InvalidOperator(address operator); /** * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation. * Used in batch transfers. * @param idsLength Length of the array of token identifiers * @param valuesLength Length of the array of token amounts */ error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol) /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC-20 * applications. */ abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors { mapping(address account => uint256) private _balances; mapping(address account => mapping(address spender => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * Both values are immutable: they can only be set once during construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /// @inheritdoc IERC20 function totalSupply() public view virtual returns (uint256) { return _totalSupply; } /// @inheritdoc IERC20 function balanceOf(address account) public view virtual returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _transfer(owner, to, value); return true; } /// @inheritdoc IERC20 function allowance(address owner, address spender) public view virtual returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Skips emitting an {Approval} event indicating an allowance update. This is not * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve]. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, value); _transfer(from, to, value); return true; } /** * @dev Moves a `value` amount of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _transfer(address from, address to, uint256 value) internal { if (from == address(0)) { revert ERC20InvalidSender(address(0)); } if (to == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(from, to, value); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding * this function. * * Emits a {Transfer} event. */ function _update(address from, address to, uint256 value) internal virtual { if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows _totalSupply += value; } else { uint256 fromBalance = _balances[from]; if (fromBalance < value) { revert ERC20InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. _balances[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. _totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. _balances[to] += value; } } emit Transfer(from, to, value); } /** * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _mint(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(address(0), account, value); } /** * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply. * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead */ function _burn(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidSender(address(0)); } _update(account, address(0), value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. */ function _approve(address owner, address spender, uint256 value) internal { _approve(owner, spender, value, true); } /** * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event. * * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by * `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any * `Approval` event during `transferFrom` operations. * * Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to * true using the following override: * * ```solidity * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { * super._approve(owner, spender, value, true); * } * ``` * * Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } _allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } } /** * @dev Updates `owner`'s allowance for `spender` based on spent `value`. * * Does not update the allowance value in case of infinite allowance. * Revert if not enough allowance is available. * * Does not emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 value) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance < type(uint256).max) { if (currentAllowance < value) { revert ERC20InsufficientAllowance(spender, currentAllowance, value); } unchecked { _approve(owner, spender, currentAllowance - value, false); } } } } // File: @openzeppelin/contracts/interfaces/IERC20.sol // OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol) // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol) /** * @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); } // File: @openzeppelin/contracts/interfaces/IERC165.sol // OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol) // File: @openzeppelin/contracts/interfaces/IERC1363.sol // OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.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); } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.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 { if (!_safeTransfer(token, to, value, true)) { revert SafeERC20FailedOperation(address(token)); } } /** * @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 { if (!_safeTransferFrom(token, from, to, value, true)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful. */ function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) { return _safeTransfer(token, to, value, false); } /** * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful. */ function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) { return _safeTransferFrom(token, from, to, value, false); } /** * @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 { if (!_safeApprove(token, spender, value, false)) { if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token)); if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token)); } } /** * @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 relies 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 relies 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}. * Oppositely, 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 `token.transfer(to, value)` call, 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 to The recipient of the tokens * @param value The amount of token to transfer * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean. */ function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) { bytes4 selector = IERC20.transfer.selector; assembly ("memory-safe") { let fmp := mload(0x40) mstore(0x00, selector) mstore(0x04, and(to, shr(96, not(0)))) mstore(0x24, value) success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20) // if call success and return is true, all is good. // otherwise (not success or return is not true), we need to perform further checks if iszero(and(success, eq(mload(0x00), 1))) { // if the call was a failure and bubble is enabled, bubble the error if and(iszero(success), bubble) { returndatacopy(fmp, 0x00, returndatasize()) revert(fmp, returndatasize()) } // if the return value is not true, then the call is only successful if: // - the token address has code // - the returndata is empty success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0))) } mstore(0x40, fmp) } } /** * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens * @param to The recipient of the tokens * @param value The amount of token to transfer * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean. */ function _safeTransferFrom( IERC20 token, address from, address to, uint256 value, bool bubble ) private returns (bool success) { bytes4 selector = IERC20.transferFrom.selector; assembly ("memory-safe") { let fmp := mload(0x40) mstore(0x00, selector) mstore(0x04, and(from, shr(96, not(0)))) mstore(0x24, and(to, shr(96, not(0)))) mstore(0x44, value) success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20) // if call success and return is true, all is good. // otherwise (not success or return is not true), we need to perform further checks if iszero(and(success, eq(mload(0x00), 1))) { // if the call was a failure and bubble is enabled, bubble the error if and(iszero(success), bubble) { returndatacopy(fmp, 0x00, returndatasize()) revert(fmp, returndatasize()) } // if the return value is not true, then the call is only successful if: // - the token address has code // - the returndata is empty success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0))) } mstore(0x40, fmp) mstore(0x60, 0) } } /** * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens * @param value The amount of token to transfer * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean. */ function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) { bytes4 selector = IERC20.approve.selector; assembly ("memory-safe") { let fmp := mload(0x40) mstore(0x00, selector) mstore(0x04, and(spender, shr(96, not(0)))) mstore(0x24, value) success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20) // if call success and return is true, all is good. // otherwise (not success or return is not true), we need to perform further checks if iszero(and(success, eq(mload(0x00), 1))) { // if the call was a failure and bubble is enabled, bubble the error if and(iszero(success), bubble) { returndatacopy(fmp, 0x00, returndatasize()) revert(fmp, returndatasize()) } // if the return value is not true, then the call is only successful if: // - the token address has code // - the returndata is empty success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0))) } mstore(0x40, fmp) } } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.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); } } // File: @openzeppelin/contracts/utils/StorageSlot.sol // OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol) // This file was procedurally generated from scripts/generate/templates/StorageSlot.js. /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC-1967 implementation slot: * ```solidity * contract ERC1967 { * // Define the slot. Alternatively, use the SlotDerivation library to derive the slot. * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(newImplementation.code.length > 0); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * TIP: Consider using this library along with {SlotDerivation}. */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } struct Int256Slot { int256 value; } struct StringSlot { string value; } struct BytesSlot { bytes value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Int256Slot` with member `value` located at `slot`. */ function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `StringSlot` with member `value` located at `slot`. */ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns an `StringSlot` representation of the string storage pointer `store`. */ function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { assembly ("memory-safe") { r.slot := store.slot } } /** * @dev Returns a `BytesSlot` with member `value` located at `slot`. */ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. */ function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { assembly ("memory-safe") { r.slot := store.slot } } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol // OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol) /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at, * consider using {ReentrancyGuardTransient} instead. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced * by the {ReentrancyGuardTransient} variant in v6.0. * * @custom:stateless */ abstract contract ReentrancyGuard { using StorageSlot for bytes32; // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant REENTRANCY_GUARD_STORAGE = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00; // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = 2; /** * @dev Unauthorized reentrant call. */ error ReentrancyGuardReentrantCall(); constructor() { _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } /** * @dev A `view` only version of {nonReentrant}. Use to block view functions * from being called, preventing reading from inconsistent contract state. * * CAUTION: This is a "view" modifier and does not change the reentrancy * status. Use it only on view functions. For payable or non-payable functions, * use the standard {nonReentrant} modifier instead. */ modifier nonReentrantView() { _nonReentrantBeforeView(); _; } function _nonReentrantBeforeView() private view { if (_reentrancyGuardEntered()) { revert ReentrancyGuardReentrantCall(); } } function _nonReentrantBefore() private { // On the first call to nonReentrant, _status will be NOT_ENTERED _nonReentrantBeforeView(); // Any calls to nonReentrant after this point will fail _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED; } function _nonReentrantAfter() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED; } /** * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a * `nonReentrant` function in the call stack. */ function _reentrancyGuardEntered() internal view returns (bool) { return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED; } function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) { return REENTRANCY_GUARD_STORAGE; } } // File: BianYangNianToken.sol interface IGoatCard { function token() external view returns (address); function MAX_SUPPLY() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function mintFromToken(address to) external returns (uint256); function forwardSwapUSDT(uint256 amount) external; } interface IGoatFactory { function getPair(address a, address b) external view returns (address); function createPair(address a, address b) external returns (address); } interface IGoatPair is IERC20 { function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112, uint112, uint32); function sync() external; function mint(address to) external returns (uint256); } interface IGoatRouter { function factory() external view returns (address); function getAmountsOut(uint256 amount, address[] calldata path) external view returns (uint256[] memory); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amount, uint256 minOut, address[] calldata path, address to, uint256 deadline ) external; } /// @notice Fixed-supply Mint, locked initial LP and equal-address USDT dividends. contract BianYangNianToken is ERC20, Ownable, ReentrancyGuard { using SafeERC20 for IERC20; address public constant DEAD = 0x000000000000000000000000000000000000dEaD; uint256 public constant MAX_SHARES = 1200; uint256 public constant TOKENS_PER_SHARE = 100_000 ether; uint256 public constant MINT_PRICE = 60 ether; // BSC USDT has 18 decimals. uint256 public constant INITIAL_SUPPLY = 240_000_000 ether; uint256 public constant MIN_REWARD_HOLDING = 50_000 ether; uint256 public constant POOL_BURN_FLOOR = 1_000_000 ether; uint256 private constant SCALE = 1e30; IERC20 public immutable usdt; IGoatRouter public immutable router; address public immutable mainPair; address public nft; address public marketingWallet; uint256 public mintedShares; uint256 public liquidityUSDT; bool public tradingOpen; mapping(address => bool) public hasMinted; mapping(address => bool) public feeWhitelist; mapping(address => bool) public blacklist; mapping(address => bool) public automatedMarketMakerPairs; struct Tax { uint16 buyback; uint16 reward; uint16 marketing; } Tax public buyTax = Tax(50, 150, 100); Tax public sellTax = Tax(50, 150, 100); uint256 public pendingBuybackTokens; uint256 public pendingRewardTokens; uint256 public pendingMarketingTokens; uint256 public pendingBuybackUSDT; uint256 public feeSwapThreshold = 1; // Raw token units; no artificial large threshold. uint256 public swapSlippageBps = 500; uint256 public lastPoolBurnTime; bool private processing; uint256 public rewardThreshold = 50 ether; uint256 public queuedRewardUSDT; uint256 public rewardLiabilityUSDT; uint256 public rewardIndex; uint256 public rewardCursor; uint256 public rewardBatchSize = 25; uint256 public rewardCycleRemaining; uint256 public totalPaidUSDT; address[] private activeHolders; mapping(address => uint256) private holderPosition; // Index + 1; zero = ineligible. mapping(address => uint256) private lastRewardIndex; mapping(address => uint256) private creditUnits; mapping(address => uint256) public paidUSDT; error InvalidConfiguration(); error MintClosed(); error AlreadyMinted(); error TradingClosed(); error Blacklisted(); error OnlySelf(); error OnlyNFT(); error PoolBusy(); error NotEligible(); error ProcessingGasRequired(uint256 minimumRemainingGas); event Minted(address indexed account, uint256 indexed share, uint256 nftId); event TradingOpened(uint256 shares, uint256 tokens, uint256 usdtAmount, uint256 lockedLP); event NFTLinked(address indexed nft); event FeesConverted(uint256 tokens, uint256 usdtReceived, uint256 reward, uint256 marketing, uint256 buyback); event BuybackBurned(uint256 usdtSpent, uint256 tokensBurned); event RewardAllocated(uint256 amount, uint256 eligibleAddresses, uint256 index); event RewardPaid(address indexed account, uint256 amount); event PoolBurned(uint256 amount, uint256 hoursProcessed); event ProcessingDeferred(bytes reason); event WhitelistChanged(address indexed account, bool value); event BlacklistChanged(address indexed account, bool value); event TaxChanged(bool indexed buy, uint16 buyback, uint16 reward, uint16 marketing); event MarketingWalletChanged(address indexed wallet); event PairChanged(address indexed pair, bool value); event ProcessingParametersChanged(); constructor(string memory symbol_, address usdt_, address router_, address marketing_, address owner_) ERC20(unicode"币安羊年", symbol_) Ownable(owner_) { if (usdt_.code.length == 0 || router_.code.length == 0 || marketing_ == address(0)) revert InvalidConfiguration(); if (IERC20Metadata(usdt_).decimals() != 18) revert InvalidConfiguration(); usdt = IERC20(usdt_); router = IGoatRouter(router_); marketingWallet = marketing_; IGoatFactory factory = IGoatFactory(router.factory()); address pair = factory.getPair(address(this), usdt_); if (pair == address(0)) pair = factory.createPair(address(this), usdt_); mainPair = pair; automatedMarketMakerPairs[pair] = true; feeWhitelist[address(this)] = true; _approve(address(this), router_, type(uint256).max); usdt.forceApprove(router_, type(uint256).max); _mint(address(this), INITIAL_SUPPLY); } function setNFTContract(address value) external onlyOwner { if (nft != address(0) || value.code.length == 0) revert InvalidConfiguration(); if (IGoatCard(value).token() != address(this) || IGoatCard(value).MAX_SUPPLY() != MAX_SHARES || IGoatCard(value).totalSupply() != 0) revert InvalidConfiguration(); nft = value; emit NFTLinked(value); } function mint() external nonReentrant { if (tradingOpen || nft == address(0) || mintedShares >= MAX_SHARES) revert MintClosed(); if (hasMinted[msg.sender]) revert AlreadyMinted(); hasMinted[msg.sender] = true; ++mintedShares; uint256 beforeBalance = usdt.balanceOf(address(this)); usdt.safeTransferFrom(msg.sender, address(this), MINT_PRICE); if (usdt.balanceOf(address(this)) - beforeBalance != MINT_PRICE) revert InvalidConfiguration(); liquidityUSDT += 42 ether; usdt.safeTransfer(marketingWallet, 18 ether); super._update(address(this), msg.sender, TOKENS_PER_SHARE); _syncHolder(msg.sender); uint256 id = IGoatCard(nft).mintFromToken(msg.sender); emit Minted(msg.sender, mintedShares, id); if (mintedShares == MAX_SHARES) _launch(); } function openTrading() external onlyOwner nonReentrant { _launch(); } function _launch() private { if (tradingOpen || mintedShares == 0) revert InvalidConfiguration(); // Token transfers into pairs are gated before launch. A donated USDT balance // or one-sided sync cannot block the initial mint, unlike router.addLiquidity. if (IGoatPair(mainPair).totalSupply() != 0) revert InvalidConfiguration(); uint256 poolTokens = mintedShares * TOKENS_PER_SHARE; uint256 funds = liquidityUSDT; liquidityUSDT = 0; processing = true; super._update(address(this), mainPair, poolTokens); usdt.safeTransfer(mainPair, funds); uint256 lp = IGoatPair(mainPair).mint(DEAD); uint256 unused = (MAX_SHARES - mintedShares) * TOKENS_PER_SHARE * 2; if (unused != 0) super._update(address(this), DEAD, unused); tradingOpen = true; lastPoolBurnTime = block.timestamp; processing = false; emit TradingOpened(mintedShares, poolTokens, funds, lp); } function onNFTTransfer(address from, address to) external { if (msg.sender != nft) revert OnlyNFT(); _syncHolder(from); if (to != from) _syncHolder(to); } function isRewardEligible(address account) public view returns (bool) { return account != address(0) && account != DEAD && account != address(this) && account != nft && !automatedMarketMakerPairs[account] && nft != address(0) && balanceOf(account) >= MIN_REWARD_HOLDING && IGoatCard(nft).balanceOf(account) > 0; } function eligibleAddressCount() external view returns (uint256) { return activeHolders.length; } function eligibleAddressAt(uint256 index) external view returns (address) { return activeHolders[index]; } function pendingUSDT(address account) public view returns (uint256) { uint256 units = creditUnits[account]; if (holderPosition[account] != 0) units += rewardIndex - lastRewardIndex[account]; return units / SCALE; } function _settle(address account) private { if (holderPosition[account] != 0) creditUnits[account] += rewardIndex - lastRewardIndex[account]; lastRewardIndex[account] = rewardIndex; } function _syncHolder(address account) private { if (account == address(0) || account == DEAD || account == address(this)) return; _settle(account); bool eligible = isRewardEligible(account); uint256 position = holderPosition[account]; if (eligible && position == 0) { activeHolders.push(account); holderPosition[account] = activeHolders.length; if (rewardCycleRemaining != 0 || creditUnits[account] >= SCALE) rewardCycleRemaining = activeHolders.length; } else if (!eligible && position != 0) { uint256 last = activeHolders.length; if (position != last) { address moved = activeHolders[last - 1]; activeHolders[position - 1] = moved; holderPosition[moved] = position; } activeHolders.pop(); delete holderPosition[account]; if (rewardCursor >= activeHolders.length) rewardCursor = 0; if (rewardCycleRemaining != 0) rewardCycleRemaining = activeHolders.length; } } function _allocateRewards() private { uint256 count = activeHolders.length; uint256 amount = queuedRewardUSDT; if (count == 0 || amount == 0 || amount < rewardThreshold) return; queuedRewardUSDT = 0; rewardLiabilityUSDT += amount; rewardIndex += amount * SCALE / count; rewardCycleRemaining = count; emit RewardAllocated(amount, count, rewardIndex); } function processRewards(uint256 maxAccounts) external nonReentrant { if (maxAccounts == 0) revert InvalidConfiguration(); if (activeHolders.length != 0 && (queuedRewardUSDT >= rewardThreshold || rewardLiabilityUSDT > MAX_SHARES)) { if (gasleft() < 350_000) revert ProcessingGasRequired(350_000); if (rewardCycleRemaining == 0) rewardCycleRemaining = activeHolders.length; } _allocateRewards(); _payBatch(maxAccounts); } function autoPayRewards() external { if (msg.sender != address(this)) revert OnlySelf(); _allocateRewards(); _payBatch(rewardBatchSize); } function payOne(address account) external { if (msg.sender != address(this)) revert OnlySelf(); if (!isRewardEligible(account)) revert NotEligible(); _settle(account); uint256 amount = creditUnits[account] / SCALE; if (amount == 0) return; creditUnits[account] -= amount * SCALE; rewardLiabilityUSDT -= amount; paidUSDT[account] += amount; totalPaidUSDT += amount; usdt.safeTransfer(account, amount); emit RewardPaid(account, amount); } function _payBatch(uint256 maxAccounts) private { uint256 count = activeHolders.length; uint256 limit = maxAccounts < count ? maxAccounts : count; if (limit > rewardCycleRemaining) limit = rewardCycleRemaining; for (uint256 i; i < limit && gasleft() > 230_000; ++i) { if (rewardCursor >= count) rewardCursor = 0; address account = activeHolders[rewardCursor++]; --rewardCycleRemaining; // A rejected transfer rolls back only this account's debit and is retried. try this.payOne{gas: 200_000}(account) {} catch (bytes memory reason) { emit ProcessingDeferred(reason); } } } function pendingFeeTokens() public view returns (uint256) { return pendingBuybackTokens + pendingRewardTokens + pendingMarketingTokens; } function processFees() external nonReentrant { if (!tradingOpen || !_poolIdle()) revert PoolBusy(); _convertFees(); _buyback(); _allocateRewards(); if (rewardCycleRemaining != 0 && gasleft() < 350_000) revert ProcessingGasRequired(350_000); _payBatch(rewardBatchSize); } function autoProcessFees() external { if (msg.sender != address(this)) revert OnlySelf(); if (!_poolIdle()) revert PoolBusy(); _convertFees(); _buyback(); } function _quote(uint256 amount, address a, address b) private view returns (uint256) { address[] memory path = new address[](2); path[0] = a; path[1] = b; uint256[] memory result = router.getAmountsOut(amount, path); return result[1] * (10_000 - swapSlippageBps) / 10_000; } function _swap(uint256 amount, uint256 minimum, address a, address b, address to) private { address[] memory path = new address[](2); path[0] = a; path[1] = b; router.swapExactTokensForTokensSupportingFeeOnTransferTokens(amount, minimum, path, to, block.timestamp); } function _convertFees() private { uint256 amount = pendingFeeTokens(); if (amount == 0 || amount < feeSwapThreshold) return; uint256 minimum = _quote(amount, address(this), address(usdt)); if (minimum == 0) return; uint256 buybackTokens = pendingBuybackTokens; uint256 marketingTokens = pendingMarketingTokens; pendingBuybackTokens = 0; pendingRewardTokens = 0; pendingMarketingTokens = 0; uint256 beforeBalance = usdt.balanceOf(address(this)); uint256 beforeNFTBalance = usdt.balanceOf(nft); processing = true; _swap(amount, minimum, address(this), address(usdt), nft); IGoatCard(nft).forwardSwapUSDT(usdt.balanceOf(nft) - beforeNFTBalance); uint256 received = usdt.balanceOf(address(this)) - beforeBalance; uint256 buyback = received * buybackTokens / amount; uint256 marketing = received * marketingTokens / amount; uint256 reward = received - buyback - marketing; pendingBuybackUSDT += buyback; queuedRewardUSDT += reward; if (marketing != 0) usdt.safeTransfer(marketingWallet, marketing); processing = false; emit FeesConverted(amount, received, reward, marketing, buyback); } function _buyback() private { uint256 amount = pendingBuybackUSDT; if (amount == 0) return; uint256 minimum = _quote(amount, address(usdt), address(this)); if (minimum == 0) return; pendingBuybackUSDT = 0; uint256 beforeBalance = balanceOf(DEAD); processing = true; _swap(amount, minimum, address(usdt), address(this), DEAD); processing = false; emit BuybackBurned(amount, balanceOf(DEAD) - beforeBalance); } function burnPool() external nonReentrant returns (uint256) { return _burnPool(); } function autoBurnPool() external returns (uint256) { if (msg.sender != address(this)) revert OnlySelf(); return _burnPool(); } function _poolIdle() private view returns (bool) { (uint112 r0, uint112 r1,) = IGoatPair(mainPair).getReserves(); bool first = IGoatPair(mainPair).token0() == address(this); return balanceOf(mainPair) == (first ? r0 : r1) && usdt.balanceOf(mainPair) == (first ? r1 : r0); } function _burnPool() private returns (uint256 amount) { if (!tradingOpen || block.timestamp < lastPoolBurnTime + 1 hours) return 0; uint256 balance = balanceOf(mainPair); uint256 periods = (block.timestamp - lastPoolBurnTime) / 1 hours; if (balance <= POOL_BURN_FLOOR) { lastPoolBurnTime += periods * 1 hours; return 0; } if (!_poolIdle()) return 0; // Compound missed hours in O(log n), never one unbounded loop per hour. uint256 ratio = 1e18; uint256 base = 995e15; uint256 n = periods; while (n != 0) { if (n & 1 != 0) ratio = ratio * base / 1e18; base = base * base / 1e18; n >>= 1; } amount = balance - balance * ratio / 1e18; if (amount > balance - POOL_BURN_FLOOR) amount = balance - POOL_BURN_FLOOR; lastPoolBurnTime += periods * 1 hours; if (amount != 0) { super._update(mainPair, DEAD, amount); IGoatPair(mainPair).sync(); emit PoolBurned(amount, periods); } } function _update(address from, address to, uint256 amount) internal override { if (from == address(0) || processing) { super._update(from, to, amount); if (from != address(0)) { _syncHolder(from); if (from != to) _syncHolder(to); } return; } bool buy = automatedMarketMakerPairs[from]; bool sell = automatedMarketMakerPairs[to]; if (buy || sell) { if (blacklist[from] || blacklist[to]) revert Blacklisted(); if (!tradingOpen) revert TradingClosed(); } if (tradingOpen && !buy && block.timestamp >= lastPoolBurnTime + 1 hours) { if (gasleft() < 220_000) revert ProcessingGasRequired(220_000); try this.autoBurnPool{gas: 160_000}() {} catch (bytes memory reason) { emit ProcessingDeferred(reason); } } uint256 fee; if ((buy || sell) && !feeWhitelist[from] && !feeWhitelist[to]) { Tax memory tax = buy ? buyTax : sellTax; uint256 burnPart = amount * tax.buyback / 10_000; uint256 rewardPart = amount * tax.reward / 10_000; uint256 marketingPart = amount * tax.marketing / 10_000; fee = burnPart + rewardPart + marketingPart; if (fee != 0) { super._update(from, address(this), fee); pendingBuybackTokens += burnPart; pendingRewardTokens += rewardPart; pendingMarketingTokens += marketingPart; } } // Sell the tax before placing this user's net input into the pair. Selling // after that deposit would consume the user's AMM input in the nested swap. if (tradingOpen && !buy && (pendingFeeTokens() >= feeSwapThreshold || pendingBuybackUSDT != 0)) { if (gasleft() < 750_000) revert ProcessingGasRequired(750_000); try this.autoProcessFees{gas: 650_000}() {} catch (bytes memory reason) { emit ProcessingDeferred(reason); } } super._update(from, to, amount - fee); _syncHolder(from); if (from != to) _syncHolder(to); if (tradingOpen && (rewardCycleRemaining != 0 || (activeHolders.length != 0 && queuedRewardUSDT >= rewardThreshold))) { // Prevent eth_estimateGas from finding a cheap successful path where // every automatic payout silently runs out of gas and is caught. if (gasleft() < 1_900_000) revert ProcessingGasRequired(1_900_000); try this.autoPayRewards{gas: 1_800_000}() {} catch (bytes memory reason) { emit ProcessingDeferred(reason); } } } function setBuyTax(uint16 buybackBps, uint16 rewardBps, uint16 marketingBps) external onlyOwner { _validateTax(buybackBps, rewardBps, marketingBps); buyTax = Tax(buybackBps, rewardBps, marketingBps); emit TaxChanged(true, buybackBps, rewardBps, marketingBps); } function setSellTax(uint16 buybackBps, uint16 rewardBps, uint16 marketingBps) external onlyOwner { _validateTax(buybackBps, rewardBps, marketingBps); sellTax = Tax(buybackBps, rewardBps, marketingBps); emit TaxChanged(false, buybackBps, rewardBps, marketingBps); } function _validateTax(uint16 a, uint16 b, uint16 c) private pure { if (uint256(a) + b + c > 10_000) revert InvalidConfiguration(); } function setMarketingWallet(address value) external onlyOwner { if (value == address(0) || value == address(this) || automatedMarketMakerPairs[value]) revert InvalidConfiguration(); marketingWallet = value; emit MarketingWalletChanged(value); } function setRewardThreshold(uint256 wholeUSDT) external onlyOwner { if (wholeUSDT == 0 || wholeUSDT > type(uint256).max / 1 ether) revert InvalidConfiguration(); rewardThreshold = wholeUSDT * 1 ether; emit ProcessingParametersChanged(); } function setFeeSwapThreshold(uint256 rawTokenUnits) external onlyOwner { if (rawTokenUnits == 0) revert InvalidConfiguration(); feeSwapThreshold = rawTokenUnits; emit ProcessingParametersChanged(); } function setRewardBatchSize(uint256 addressesPerCall) external onlyOwner { if (addressesPerCall == 0) revert InvalidConfiguration(); rewardBatchSize = addressesPerCall; emit ProcessingParametersChanged(); } function setSwapSlippageBps(uint256 bps) external onlyOwner { if (bps >= 10_000) revert InvalidConfiguration(); swapSlippageBps = bps; emit ProcessingParametersChanged(); } function setFeeWhitelist(address account, bool value) public onlyOwner { feeWhitelist[account] = value; emit WhitelistChanged(account, value); } function setBlacklist(address account, bool value) public onlyOwner { blacklist[account] = value; emit BlacklistChanged(account, value); } function batchSetWhitelist(string calldata accounts, bool value) external onlyOwner { address[] memory list = _parseAddresses(accounts); for (uint256 i; i < list.length; ++i) setFeeWhitelist(list[i], value); } function batchSetBlacklist(string calldata accounts, bool value) external onlyOwner { address[] memory list = _parseAddresses(accounts); for (uint256 i; i < list.length; ++i) setBlacklist(list[i], value); } function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner { if (pair == mainPair || pair.code.length == 0) revert InvalidConfiguration(); if (IGoatPair(pair).token0() != address(this) && IGoatPair(pair).token1() != address(this)) revert InvalidConfiguration(); automatedMarketMakerPairs[pair] = value; _syncHolder(pair); emit PairChanged(pair, value); } function _parseAddresses(string calldata text) private pure returns (address[] memory result) { bytes calldata data = bytes(text); result = new address[](data.length / 42 + 1); uint256 count; uint256 i; while (i < data.length) { if (_separator(uint8(data[i]))) { ++i; continue; } if (i + 42 > data.length || data[i] != '0' || (data[i+1] != 'x' && data[i+1] != 'X')) revert InvalidConfiguration(); uint160 value; for (uint256 k = i + 2; k < i + 42; ++k) { uint8 c = uint8(data[k]); uint8 digit; if (c >= 48 && c <= 57) digit = c - 48; else if (c >= 65 && c <= 70) digit = c - 55; else if (c >= 97 && c <= 102) digit = c - 87; else revert InvalidConfiguration(); value = (value << 4) | digit; } result[count++] = address(value); i += 42; if (i < data.length && !_separator(uint8(data[i]))) revert InvalidConfiguration(); } if (count == 0) revert InvalidConfiguration(); assembly ("memory-safe") { mstore(result, count) } } function _separator(uint8 c) private pure returns (bool) { return c == 44 || c == 32 || c == 10 || c == 13 || c == 9; } }