Перейти к содержимому
Проверенный контрактТочноеMIT

UserWallet

Адрес0x2d3e0ef084e93cfec8ed8a70ace112bacd1adf3a
Баланс

0 ETH

 

Транзакций

8

 

Компилятор

solc 0.8.24

 

Тот же код

ещё 250 контрактов

 

Подробности

Компилятор
solc 0.8.24+commit.e11b9ed9
Язык
solidity
Оптимизация
Да, 200 прогонов
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 285 484
Транзакция создания
0xfd3cf774da…87950bcb58
Основная копия (больше всего транзакций)
0x5f5cd160…60189491

contract.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";


interface IUserVault {
    function credit(bytes32 uidHash, uint256 amount) external;
    function creditWithReferral(bytes32 uidHash, uint256 amount, bytes4 referrerCode) external;
}

// ─────────────────────────────────────────────────────────────────────────────
//  UserWallet
//  - No constructor arguments: creationCode is chain-agnostic,
//    guaranteeing the same CREATE2 address on every EVM chain
//  - Initialized by the factory right after deployment via init()
//  - kardpayUserVault can only be registered on Avalanche (chainId 43114)
//  - credit() is called by the factory and forwards USDC to the vault
// ─────────────────────────────────────────────────────────────────────────────
contract UserWallet {
    using SafeERC20 for IERC20;
    uint256 private constant AVALANCHE_CHAIN_ID = 43114;

    address public immutable factory;
    address public owner;

    // Set once via init() right after deployment
    IERC20   public usdc;
    IERC20   public usdt;
    bytes32  public uidHash;
    bool     private initialized;

    // Avalanche only
    IUserVault public kardpayUserVault;

    modifier onlyFactory() {
        require(msg.sender == factory, "UserWallet: caller is not factory");
        _;
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "UserWallet: caller is not the owner");
        _;
    }

    /// @dev No args → creationCode identical on all chains → same CREATE2 address everywhere
    constructor() {
        factory = msg.sender;
    }

    receive() external payable {}

    // ─────────────────────────────────────────────────────────────────────────
    //  Initialization (called by factory immediately after CREATE2 deployment)
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice One-time setup called by the factory right after deployment.
    ///         Sets token addresses and the user's uidHash, then approves the factory.
    function init(address _owner, address _usdc, address _usdt, bytes32 _uidHash) external onlyFactory {
        require(!initialized, "UserWallet: already initialized");
        require(_owner != address(0), "zero owner");
        require(_usdc != address(0), "zero usdc");
        require(_usdt != address(0), "zero usdt");

        owner   = _owner;
        usdc    = IERC20(_usdc);
        usdt    = IERC20(_usdt);
        uidHash = _uidHash;

        initialized = true;

        usdc.forceApprove(factory, type(uint256).max);
        usdt.forceApprove(factory, type(uint256).max);

        if(block.chainid == AVALANCHE_CHAIN_ID){
            kardpayUserVault = IUserVault(0xDB654089bF026aebC6c96D238F5AC6fcec586A58);
        }
    }

    /// @notice get revert message
    function _getRevertMsg(bytes memory returnData) internal pure returns (string memory) {
        if (returnData.length < 68) return "Transaction reverted silently";
        assembly {
            returnData := add(returnData, 0x04)
        }
        return abi.decode(returnData, (string));
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Credit (Avalanche only in the workflow)
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice Forwards the entire USDC balance of this wallet to the KardPay vault.
    ///         The wallet itself calls kardpayUserVault.credit(), so the vault must
    ///         accept transferFrom from this address (approval is set inside this call).
    ///         Triggered by the factory; intended for Avalanche only.
    function credit() external onlyFactory {
        require(address(kardpayUserVault) != address(0), "UserWallet: vault not set");

        uint256 amount = usdc.balanceOf(address(this));
        require(amount > 0, "UserWallet: zero balance");

        // Approve vault for the exact amount before calling credit()
        usdc.forceApprove(address(kardpayUserVault), amount);
        kardpayUserVault.credit(uidHash, amount);
    }

    function creditWithReferral(bytes4 referrerCode) external onlyFactory {
        require(address(kardpayUserVault) != address(0), "UserWallet: vault not set");

        uint256 amount = usdc.balanceOf(address(this));
        require(amount > 0, "UserWallet: zero balance");

        // Approve vault for the exact amount before calling credit()
        usdc.forceApprove(address(kardpayUserVault), amount);
        kardpayUserVault.creditWithReferral(uidHash, amount, referrerCode);
    }

    function bridge(IERC20 asset, address dlnSource, bytes memory rawData, uint256 value) onlyOwner public payable returns (bytes memory){
        if(address(asset) != address(0)){
            asset.forceApprove(dlnSource, asset.balanceOf(address(this)));
        }
        (bool success, bytes memory returnData) = dlnSource.call{value: value}(rawData);
        require(success, _getRevertMsg(returnData));
        return returnData;
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Recover funds
    // ─────────────────────────────────────────────────────────────────────────

    function recoverFunds(address asset) external onlyOwner {
        uint256 assetBal = IERC20(asset).balanceOf(address(this));
        if (assetBal > 0) IERC20(asset).safeTransfer(owner, assetBal);
    }

    function recoverNative() external onlyOwner {
        uint256 bal = address(this).balance;
        if (bal == 0) return;
        (bool sent, ) = payable(owner).call{value: bal}("");
        require(sent, "UserWallet: native transfer failed");
    }

    function sendNative(address treasury) external onlyFactory {
        uint256 bal = address(this).balance;
        if (bal == 0) return;
        (bool sent, ) = payable(treasury).call{value: bal}("");
        require(sent, "UserWallet: native transfer failed");
    }

}


// ─────────────────────────────────────────────────────────────────────────────
//  WalletFactory
//
//  - createWallet(bytes32 uidHash)             deploy + init a UserWallet via CREATE2
//  - computeAddress(bytes32 uidHash)           deterministic address before/after deploy
//  - isDeployed[uidHash]                       deployed flag
//  - deployedWallets / deployedUIDs            tracking arrays
//  - walletToUID[wallet]                       reverse mapping
//  - scanFunds()                               wallets with USDC or USDT > 0
//  - collectFunds(address wallet)              sweep one wallet to treasury
//  - collectAllFunds()                         sweep all wallets to treasury
//  - triggerCredit(bytes32 uidHash)            call credit() on a specific wallet
// ─────────────────────────────────────────────────────────────────────────────
contract WalletFactory {
    using SafeERC20 for IERC20;
    // ── Tokens & treasury ────────────────────────────────────────────────────
    IERC20  public immutable usdc;
    IERC20  public immutable usdt;
    address public treasury;

    // ── Access control ───────────────────────────────────────────────────────
    address public owner;

    modifier onlyOwner() {
        require(msg.sender == owner, "WalletFactory: caller is not owner");
        _;
    }

    // ── Registries ───────────────────────────────────────────────────────────
    mapping(bytes32 => bool)    public isDeployed;
    mapping(bytes32 => address) public uidToWallet;
    mapping(address => bytes32) public walletToUID;

    bytes32[] public deployedUIDs;
    address[] public deployedWallets;

    // ── Events ───────────────────────────────────────────────────────────────
    event WalletCreated(bytes32 indexed uidHash, address indexed wallet);
    event FundsCollected(address indexed wallet, uint256 usdcAmount, uint256 usdtAmount, uint256 nativeBalance);
    event CreditTriggered(bytes32 indexed uidHash, address indexed wallet);

    constructor(address _usdc, address _usdt, address _treasury) {
        require(_usdc     != address(0), "zero usdc");
        require(_usdt     != address(0), "zero usdt");
        require(_treasury != address(0), "zero treasury");

        usdc     = IERC20(_usdc);
        usdt     = IERC20(_usdt);
        treasury = _treasury;
        owner    = msg.sender;
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Deterministic deployment
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice Deploys a UserWallet via CREATE2 and immediately calls init().
    ///         UserWallet has no constructor args → identical creationCode on all chains
    ///         → same address for the same uidHash on every EVM network.
    function createWallet(bytes32 uidHash) external onlyOwner returns (address wallet) {
        require(!isDeployed[uidHash], "WalletFactory: already deployed");
        require(uidHash != bytes32(0), "WalletFactory: zero uidHash");
        
        bytes memory bytecode = type(UserWallet).creationCode;

        assembly {
            wallet := create2(
                0,
                add(bytecode, 0x20),
                mload(bytecode),
                uidHash
            )
        }
        require(wallet != address(0), "WalletFactory: deployment failed");

        // Initialize token addresses and uidHash on the wallet
        UserWallet(payable(wallet)).init(owner, address(usdc), address(usdt), uidHash);

        isDeployed[uidHash]  = true;
        uidToWallet[uidHash] = wallet;
        walletToUID[wallet]  = uidHash;
        deployedUIDs.push(uidHash);
        deployedWallets.push(wallet);

        emit WalletCreated(uidHash, wallet);
    }

    /// @notice Returns the deterministic address for a given uidHash.
    ///         Uses pure creationCode (no constructor args) for the hash.
    function computeAddress(bytes32 uidHash) external view returns (address predicted) {
        bytes32 bytecodeHash = keccak256(type(UserWallet).creationCode);
        predicted = address(
            uint160(
                uint256(
                    keccak256(
                        abi.encodePacked(
                            bytes1(0xff),
                            address(this),
                            uidHash,
                            bytecodeHash
                        )
                    )
                )
            )
        );
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Credit trigger
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice Triggers credit() on a specific UserWallet, which forwards
    ///         its USDC balance to the registered KardPay vault.
    function triggerCredit(bytes32 uidHash) external onlyOwner {
        require(isDeployed[uidHash], "WalletFactory: wallet not deployed");
        address wallet = uidToWallet[uidHash];
        UserWallet(payable(wallet)).credit();
        emit CreditTriggered(uidHash, wallet);
    }

    function triggerCreditWithReferral(bytes32 uidHash, bytes4 referrerCode) external onlyOwner {
        require(isDeployed[uidHash], "WalletFactory: wallet not deployed");
        address wallet = uidToWallet[uidHash];
        UserWallet(payable(wallet)).creditWithReferral(referrerCode);
        emit CreditTriggered(uidHash, wallet);
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Fund scanning
    // ─────────────────────────────────────────────────────────────────────────

    struct WalletFunds {
        address wallet;
        bytes32 uidHash;
        uint256 usdcBalance;
        uint256 usdtBalance;
        uint256 nativeBalance;
    }

    function scanFunds(uint256 start, uint256 limit)
        external
        view
        returns (WalletFunds[] memory results, uint256 nextStart)
    {
        uint256 total = deployedWallets.length;
        if (start >= total) {
            WalletFunds[] memory empty;
            return (empty, total);
        }

        uint256 end = start + limit;
        if (end > total) end = total;

        uint256 count;
        for (uint256 i = start; i < end; i++) {
            address w = deployedWallets[i];
            if (usdc.balanceOf(w) > 0 || usdt.balanceOf(w) > 0 || w.balance > 0) {
                count++;
            }
        }

        results = new WalletFunds[](count);
        uint256 idx;

        for (uint256 i = start; i < end; i++) {
            address w = deployedWallets[i];
            uint256 uBal = usdc.balanceOf(w);
            uint256 tBal = usdt.balanceOf(w);
            uint256 nBal = w.balance;

            if (uBal > 0 || tBal > 0 || nBal > 0) {
                results[idx++] = WalletFunds({
                    wallet: w,
                    uidHash: deployedUIDs[i],
                    usdcBalance: uBal,
                    usdtBalance: tBal,
                    nativeBalance: nBal

                });
            }
        }

        nextStart = end;
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Fund collection → treasury
    // ─────────────────────────────────────────────────────────────────────────

    function collectFundsBatch(uint256 start, uint256 limit) external onlyOwner {
        uint256 total = deployedWallets.length;
        require(start < total, "WalletFactory: start out of bounds");

        uint256 end = start + limit;
        if (end > total) end = total;

        for (uint256 i = start; i < end; i++) {
            address w = deployedWallets[i];
            uint256 uBal = usdc.balanceOf(w);
            uint256 tBal = usdt.balanceOf(w);
            uint256 nBal = w.balance;

            if (uBal > 0) usdc.safeTransferFrom(w, treasury, uBal);
            if (tBal > 0) usdt.safeTransferFrom(w, treasury, tBal);
            if (nBal > 0) UserWallet(payable(w)).sendNative(treasury);
            if (uBal > 0 || tBal > 0 || nBal > 0) {
                emit FundsCollected(w, uBal, tBal, nBal);
            }
        }
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Helpers
    // ─────────────────────────────────────────────────────────────────────────

    function totalDeployed() external view returns (uint256) {
        return deployedWallets.length;
    }

    function changeTreasury(address _treasury) external onlyOwner {
        treasury = _treasury;
    }

}

@openzeppelin/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

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);
}

@openzeppelin/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

@openzeppelin/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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 {
        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)
        }
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Настройки компилятораПоказать
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.