Skip to content
Verified contractExactUNLICENSED

UnizFactory

Address0x5321962d54a734f2ed264a3a849e2bc27caa02b6
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
paris
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,387,082
Creation transaction
0x66dd45bf12…9f84314c1a

src/UnizFactory.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.24;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {UnizForwarder} from "./UnizForwarder.sol";
import {BridgeParams, Terms} from "./UnizTypes.sol";
import {IAcrossSpokePool} from "./interfaces/IAcrossSpokePool.sol";

/// @title UnizFactory
/// @notice Issues counterfactual deposit addresses and settles them to merchants.
/// @dev Security model (see docs/SPEC.md §8.3):
///      - No owner, no upgrade, no pause. The swap allowlist and the Across SpokePool are
///        fixed at construction; changes ship as a new factory version used only by new
///        deposit addresses.
///      - Funds in a forwarder can only reach terms.merchant (on terms.outputChainId),
///        terms.fallbackAddr or terms.feeRecipient, and the fee is taken at most once.
///      - `sweep` is permissionless. Swaps and bridges are always reserved to
///        terms.preferredCaller: the caller picks the route (and, for a bridge, the Across
///        quote, relayer and deadline), and the terms only fix terms.minNetOut, so anyone else
///        could convert an overpaid or late deposit for exactly the minimum and keep the rest.
///        Raw sweeps of the expected input are reserved to terms.preferredCaller until
///        terms.rescueAfter; from then on anyone may deliver the funds unconverted to
///        terms.fallbackAddr, so they never depend on the relayer.
///      - The fee is taken in full or not at all, so a dust deposit cannot use it up. After
///        rescueAfter a raw sweep of a balance below the fee delivers it all to fallbackAddr,
///        fee-free, leaving the fee untaken.
///      - Settlement runs only on terms.sourceChainId. Funds sent to the same address on
///        another network can only be rescued to terms.fallbackAddr, without a fee.
///      Deployment (script/Deploy.s.sol): the forwarder implementation and this factory are
///      deployed separately, so each stays under the per-transaction gas cap on networks
///      that price code storage high (Ethereum Sepolia measured ~1,600 gas per byte). The factory
///      address comes from CREATE3 (salt only), which lets the implementation be created
///      first, pointing at the factory's future address; the constructor checks the pair.
contract UnizFactory is ReentrancyGuard {
    /// @notice Longest an Across deposit may wait for a fill before it is refunded.
    uint256 public constant MAX_FILL_WINDOW = 1 days;

    /// @notice Forwarder implementation cloned at every deposit address.
    address public immutable implementation;

    /// @notice Across SpokePool on this network; address(0) where Across is unavailable.
    /// @dev Chosen from the constructor's per-network list by block.chainid, so the init
    ///      code (and the factory address via CreateX) is identical on every network.
    address public immutable spokePool;

    /// @notice Contracts the forwarder may call during a swap.
    mapping(address => bool) public isAllowedTarget;
    /// @notice Contracts the forwarder may approve during a swap.
    mapping(address => bool) public isAllowedSpender;

    event ForwarderDeployed(address indexed forwarder, bytes32 indexed paymentRef);
    event Swept(
        address indexed forwarder,
        bytes32 indexed paymentRef,
        address indexed token,
        address to,
        uint256 amount,
        uint256 fee
    );
    event Swapped(
        address indexed forwarder,
        bytes32 indexed paymentRef,
        address tokenIn,
        uint256 amountIn,
        address tokenOut,
        uint256 amountOut,
        uint256 fee
    );
    event Bridged(
        address indexed forwarder,
        bytes32 indexed paymentRef,
        address bridgeToken,
        uint256 amountIn,
        uint256 outputChainId,
        address outputToken,
        uint256 outputAmount,
        uint256 fee
    );

    error SameTokenRequired();
    error DifferentTokenRequired();
    error NothingToSweep();
    error RouteNotAllowed();
    error ExclusiveWindow();
    error InsufficientOutput(uint256 received, uint256 required);
    error WrongNetwork();
    error BridgeUnavailable();
    error BridgeAmountMismatch();
    error FillDeadlineTooLate();
    error FeeNotCovered(uint256 balance, uint256 fee);
    error LengthMismatch();
    error SpokePoolInSwapAllowlist();
    error ImplementationMismatch();
    error InvalidRoute(address route);

    /// @param implementation_ Forwarder implementation whose `factory` is this contract.
    /// @param targets Swap targets the forwarder may call (e.g. 0x AllowanceHolder).
    /// @param spenders Swap spenders the forwarder may approve.
    /// @param spokeChainIds Networks with an Across SpokePool.
    /// @param spokePools SpokePool address for each entry of `spokeChainIds`.
    constructor(
        address implementation_,
        address[] memory targets,
        address[] memory spenders,
        uint256[] memory spokeChainIds,
        address[] memory spokePools
    ) {
        if (spokeChainIds.length != spokePools.length) revert LengthMismatch();
        address pool;
        for (uint256 i; i < spokeChainIds.length; ++i) {
            if (spokeChainIds[i] == block.chainid) pool = spokePools[i];
        }
        spokePool = pool;

        // Clones of a forwarder that obeys another factory would be uncontrollable here.
        if (
            implementation_.code.length == 0
                || UnizForwarder(payable(implementation_)).factory() != address(this)
        ) {
            revert ImplementationMismatch();
        }
        implementation = implementation_;
        for (uint256 i; i < targets.length; ++i) {
            // The bridge call is built by this contract alone; it must never be reachable
            // through the free-form swap path with caller-chosen calldata.
            if (pool != address(0) && targets[i] == pool) revert SpokePoolInSwapAllowlist();
            _requireContract(targets[i]);
            isAllowedTarget[targets[i]] = true;
        }
        for (uint256 i; i < spenders.length; ++i) {
            if (pool != address(0) && spenders[i] == pool) revert SpokePoolInSwapAllowlist();
            _requireContract(spenders[i]);
            isAllowedSpender[spenders[i]] = true;
        }
    }

    // ---------------------------------------------------------------------
    // Views
    // ---------------------------------------------------------------------

    /// @notice CREATE2 salt for `t`.
    function saltOf(Terms calldata t) public pure returns (bytes32) {
        return keccak256(abi.encode(t));
    }

    /// @notice Deposit address for `t`. Valid before deployment.
    function predict(Terms calldata t) public view returns (address) {
        return Clones.predictDeterministicAddress(implementation, saltOf(t), address(this));
    }

    // ---------------------------------------------------------------------
    // Settlement
    // ---------------------------------------------------------------------

    /// @notice Delivers the input token to the merchant when no conversion is needed.
    /// @dev Permissionless: the destination is fixed by the terms.
    function sweep(Terms calldata t) external nonReentrant {
        _requireSameNetwork(t);
        if (t.inputToken != t.outputToken) revert SameTokenRequired();
        UnizForwarder f = _forwarder(t);

        uint256 balance = _balanceOf(t.inputToken, address(f));
        if (balance == 0) revert NothingToSweep();

        uint256 fee = _takeFee(f, t.feeIn + t.gasFeeIn, balance);
        f.push(t.inputToken, t.feeRecipient, fee);
        f.push(t.inputToken, t.merchant, balance - fee);

        emit Swept(address(f), t.paymentRef, t.inputToken, t.merchant, balance - fee, fee);
    }

    /// @notice Converts the input token through an allowlisted route and delivers the output.
    /// @dev Reserved to `preferredCaller` at all times: the route is caller-chosen and the
    ///      terms only guarantee `minNetOut`, so anyone else could keep the surplus of an
    ///      overpaid or late deposit. If the relayer never converts, `sweepRaw` after
    ///      `rescueAfter` delivers the funds unconverted to `fallbackAddr`.
    /// @param target Allowlisted contract to call (e.g. 0x AllowanceHolder).
    /// @param spender Allowlisted contract to approve; ignored for native input.
    /// @param data Calldata for `target`, built off-chain from an aggregator quote.
    function sweepAndSwap(Terms calldata t, address target, address spender, bytes calldata data)
        external
        nonReentrant
    {
        _requireSameNetwork(t);
        if (t.inputToken == t.outputToken) revert DifferentTokenRequired();
        if (msg.sender != t.preferredCaller) revert ExclusiveWindow();

        UnizForwarder f = _forwarder(t);
        (uint256 amountIn, uint256 received) = _swap(f, t.inputToken, t.outputToken, target, spender, data);
        uint256 fee = f.feeCharged() ? 0 : t.feeOut + t.gasFeeOut;
        if (received < t.minNetOut + fee) revert InsufficientOutput(received, t.minNetOut + fee);
        if (fee != 0) f.chargeFeeOnce();

        uint256 toMerchant = _balanceOf(t.outputToken, address(f)) - fee;
        f.push(t.outputToken, t.feeRecipient, fee);
        f.push(t.outputToken, t.merchant, toMerchant);
        // Any unspent input also belongs to the merchant.
        f.push(t.inputToken, t.merchant, _balanceOf(t.inputToken, address(f)));

        emit Swapped(address(f), t.paymentRef, t.inputToken, amountIn, t.outputToken, toMerchant, fee);
    }

    /// @notice Delivers the payment to the merchant on another network through Across,
    ///         converting the input into `terms.bridgeToken` first when they differ.
    /// @dev This contract builds the deposit itself: recipient = merchant, destination and
    ///      output token from the terms, refunds to fallbackAddr, empty message. The caller
    ///      only supplies the Across quote values in `b`; `b.outputAmount` must cover
    ///      `minNetOut`, and the amount deposited must cover `minBridgeIn`. Swap arguments are
    ///      ignored when no conversion is needed. Reserved to `preferredCaller` at all times.
    function sweepAndBridge(
        Terms calldata t,
        address target,
        address spender,
        bytes calldata swapData,
        BridgeParams calldata b
    ) external nonReentrant {
        if (t.sourceChainId != block.chainid || t.outputChainId == block.chainid) {
            revert WrongNetwork();
        }
        if (spokePool == address(0)) revert BridgeUnavailable();
        if (msg.sender != t.preferredCaller) revert ExclusiveWindow();
        if (b.outputAmount < t.minNetOut) revert InsufficientOutput(b.outputAmount, t.minNetOut);
        if (b.fillDeadline > block.timestamp + MAX_FILL_WINDOW) revert FillDeadlineTooLate();

        UnizForwarder f = _forwarder(t);
        if (t.inputToken != t.bridgeToken) {
            _swap(f, t.inputToken, t.bridgeToken, target, spender, swapData);
            // Unspent input stays on this network; the merchant may not control this address here.
            f.push(t.inputToken, t.fallbackAddr, _balanceOf(t.inputToken, address(f)));
        }

        uint256 balance = _balanceOf(t.bridgeToken, address(f));
        uint256 fee = f.feeCharged() ? 0 : t.feeOut + t.gasFeeOut;
        if (balance <= fee || balance - fee < t.minBridgeIn) {
            revert InsufficientOutput(balance, fee + t.minBridgeIn);
        }
        if (fee != 0) f.chargeFeeOnce();
        f.push(t.bridgeToken, t.feeRecipient, fee);
        uint256 amountIn = balance - fee;

        _deposit(f, t, b, amountIn);
        emit Bridged(
            address(f),
            t.paymentRef,
            t.bridgeToken,
            amountIn,
            t.outputChainId,
            t.outputToken,
            b.outputAmount,
            fee
        );
    }

    /// @notice Delivers `token` unconverted to the merchant's fallback address.
    /// @dev For the expected input token on the source network this is reserved to
    ///      `preferredCaller` until `rescueAfter`, so third parties cannot pre-empt a pending
    ///      conversion. Any other token, and anything sent on another network, can be
    ///      rescued by anyone at any time, without a fee. The expected input pays the fee
    ///      (once); a balance below the fee cannot be swept before `rescueAfter`, and after it
    ///      goes to `fallbackAddr` whole, without taking the fee, so a dust deposit can neither
    ///      use up the fee nor stay stuck.
    function sweepRaw(Terms calldata t, address token) external nonReentrant {
        bool isInput = token == t.inputToken && t.sourceChainId == block.chainid;
        if (isInput && block.timestamp < t.rescueAfter && msg.sender != t.preferredCaller) {
            revert ExclusiveWindow();
        }
        UnizForwarder f = _forwarder(t);

        uint256 balance = _balanceOf(token, address(f));
        if (balance == 0) revert NothingToSweep();

        uint256 fee = 0;
        if (isInput) {
            uint256 due = t.feeIn + t.gasFeeIn;
            // Below the fee after rescueAfter: fee-free, and the fee stays untaken.
            bool rescueBelowFee = balance < due && block.timestamp >= t.rescueAfter;
            if (!rescueBelowFee) fee = _takeFee(f, due, balance);
        }
        f.push(token, t.feeRecipient, fee);
        f.push(token, t.fallbackAddr, balance - fee);

        emit Swept(address(f), t.paymentRef, token, t.fallbackAddr, balance - fee, fee);
    }

    // ---------------------------------------------------------------------
    // Internal
    // ---------------------------------------------------------------------

    function _requireSameNetwork(Terms calldata t) internal view {
        if (t.sourceChainId != block.chainid || t.outputChainId != block.chainid) revert WrongNetwork();
    }

    /// @dev Swaps the forwarder's whole `tokenIn` balance through an allowlisted route.
    ///      Returns the input amount and the `tokenOut` actually received (balance delta;
    ///      the router's return value is never trusted).
    function _swap(
        UnizForwarder f,
        address tokenIn,
        address tokenOut,
        address target,
        address spender,
        bytes calldata data
    ) internal returns (uint256 amountIn, uint256 received) {
        bool nativeIn = tokenIn == address(0);
        if (!isAllowedTarget[target] || (!nativeIn && !isAllowedSpender[spender])) revert RouteNotAllowed();

        amountIn = _balanceOf(tokenIn, address(f));
        if (amountIn == 0) revert NothingToSweep();
        uint256 outBefore = _balanceOf(tokenOut, address(f));

        if (nativeIn) {
            f.execute(target, amountIn, data);
        } else {
            f.approve(tokenIn, spender, amountIn);
            f.execute(target, 0, data);
            f.approve(tokenIn, spender, 0);
        }
        received = _balanceOf(tokenOut, address(f)) - outBefore;
    }

    /// @dev Has the forwarder deposit `amountIn` of the bridge token into Across.
    function _deposit(UnizForwarder f, Terms calldata t, BridgeParams calldata b, uint256 amountIn) internal {
        bool nativeIn = t.bridgeToken == address(0);
        address inputToken = nativeIn ? IAcrossSpokePool(spokePool).wrappedNativeToken() : t.bridgeToken;
        bytes memory call = abi.encodeCall(
            IAcrossSpokePool.depositV3,
            (
                t.fallbackAddr, // depositor: receives the refund if the deposit is never filled
                t.merchant,
                inputToken,
                t.outputToken,
                amountIn,
                b.outputAmount,
                t.outputChainId,
                b.exclusiveRelayer,
                b.quoteTimestamp,
                b.fillDeadline,
                b.exclusivityParameter,
                ""
            )
        );

        uint256 before = _balanceOf(t.bridgeToken, address(f));
        if (nativeIn) {
            f.execute(spokePool, amountIn, call);
        } else {
            f.approve(t.bridgeToken, spokePool, amountIn);
            f.execute(spokePool, 0, call);
            f.approve(t.bridgeToken, spokePool, 0);
        }
        // The pool must have taken exactly the deposited amount.
        if (before - _balanceOf(t.bridgeToken, address(f)) != amountIn) revert BridgeAmountMismatch();
    }

    /// @dev The input-side fee for `balance`: all of `fee` the first time, else nothing.
    ///      Reverts rather than charging part of it, so a dust deposit cannot use it up.
    function _takeFee(UnizForwarder f, uint256 fee, uint256 balance) internal returns (uint256) {
        if (fee == 0 || f.feeCharged()) return 0;
        if (balance < fee) revert FeeNotCovered(balance, fee);
        f.chargeFeeOnce();
        return fee;
    }

    function _requireContract(address route) internal view {
        if (route.code.length == 0) revert InvalidRoute(route);
    }

    function _forwarder(Terms calldata t) internal returns (UnizForwarder) {
        address addr = predict(t);
        if (addr.code.length == 0) {
            Clones.cloneDeterministic(implementation, saltOf(t));
            emit ForwarderDeployed(addr, t.paymentRef);
        }
        return UnizForwarder(payable(addr));
    }

    function _balanceOf(address token, address account) internal view returns (uint256) {
        return token == address(0) ? account.balance : IERC20(token).balanceOf(account);
    }
}

node_modules/@openzeppelin/contracts/interfaces/IERC1363.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

node_modules/@openzeppelin/contracts/interfaces/IERC165.sol

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

pragma solidity ^0.8.20;

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

node_modules/@openzeppelin/contracts/interfaces/IERC20.sol

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

pragma solidity ^0.8.20;

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

node_modules/@openzeppelin/contracts/proxy/Clones.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/Clones.sol)

pragma solidity ^0.8.20;

import {Errors} from "../utils/Errors.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        return clone(implementation, 0);
    }

    /**
     * @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency
     * to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function clone(address implementation, uint256 value) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(value, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        return cloneDeterministic(implementation, salt, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with
     * a `value` parameter to send native currency to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneDeterministic(
        address implementation,
        bytes32 salt,
        uint256 value
    ) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(value, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

node_modules/@openzeppelin/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

node_modules/@openzeppelin/contracts/utils/Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/UnizForwarder.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.24;

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

/// @title UnizForwarder
/// @notice Minimal per-payment vault, deployed as an EIP-1167 clone at a deposit address.
/// @dev Holds no logic of its own: every action is decided and checked by the immutable
///      factory that deployed it. The `factory` immutable lives in the implementation's
///      bytecode, so every clone shares it.
contract UnizForwarder {
    using SafeERC20 for IERC20;

    address public immutable factory;

    /// @notice True once the platform fee has been taken from this deposit address.
    bool public feeCharged;

    error OnlyFactory();

    modifier onlyFactory() {
        if (msg.sender != factory) revert OnlyFactory();
        _;
    }

    constructor(address factory_) {
        factory = factory_;
    }

    receive() external payable {}

    /// @notice Marks the fee as charged. Returns true only on the first call.
    function chargeFeeOnce() external onlyFactory returns (bool firstTime) {
        if (feeCharged) return false;
        feeCharged = true;
        return true;
    }

    /// @notice Sends `amount` of `token` (address(0) = native) to `to`.
    function push(address token, address to, uint256 amount) external onlyFactory {
        if (amount == 0) return;
        if (token == address(0)) {
            Address.sendValue(payable(to), amount);
        } else {
            IERC20(token).safeTransfer(to, amount);
        }
    }

    /// @notice Sets the allowance of `spender` to exactly `amount`.
    function approve(address token, address spender, uint256 amount) external onlyFactory {
        IERC20(token).forceApprove(spender, amount);
    }

    /// @notice Calls `target` with `value` native coin and `data`.
    function execute(address target, uint256 value, bytes calldata data) external onlyFactory {
        Address.functionCallWithValue(target, data, value);
    }
}

src/UnizTypes.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.24;

/// @notice Settlement terms locked into a deposit address.
/// @dev The deposit address is CREATE2(factory, keccak256(abi.encode(terms)), cloneInitCode),
///      so changing any field yields a different address. Field order is part of the
///      protocol: the off-chain encoder in packages/shared/src/terms.ts must match exactly.
struct Terms {
    /// Receives the net output.
    address merchant;
    /// Receives unconverted input when conversion is impossible.
    address fallbackAddr;
    /// Receives the platform fee and the network-cost reimbursement.
    address feeRecipient;
    /// Relayer: the only caller of swaps and bridges, and of raw sweeps of the expected input
    /// before `rescueAfter`.
    address preferredCaller;
    /// Expected input token; address(0) = native coin.
    address inputToken;
    /// Desired output token on `outputChainId`; address(0) = native coin. Cross-network
    /// native ETH is expressed as the destination WETH, which Across unwraps for EOAs.
    address outputToken;
    /// Network the payer pays on. Settlement other than `sweepRaw` runs only here.
    uint256 sourceChainId;
    /// Network the merchant is paid on (== sourceChainId for same-network routes).
    uint256 outputChainId;
    /// Cross-network only: the source-network asset handed to Across (address(0) = native).
    address bridgeToken;
    /// Fixed platform fee ($0.10) in input-token units.
    uint256 feeIn;
    /// Network cost (deploy + sweep gas) in input-token units.
    uint256 gasFeeIn;
    /// Fixed platform fee ($0.10) after conversion: output-token units, or bridge-token
    /// units for cross-network routes.
    uint256 feeOut;
    /// Network cost in the same units as `feeOut`.
    uint256 gasFeeOut;
    /// Minimum net amount the merchant must receive, in output-token units, after fees.
    uint256 minNetOut;
    /// Cross-network only: minimum bridge-token amount handed to Across, after fees. Bounds
    ///   the source-side swap, so the deposit cannot be drained before it is bridged.
    uint256 minBridgeIn;
    /// Unused on-chain by this factory version (swaps are always reserved to
    /// `preferredCaller`); kept so the layout, and every address derived from it, is unchanged.
    uint64 exclusiveUntil;
    /// From this timestamp anyone may push unconverted input to `fallbackAddr`.
    uint64 rescueAfter;
    /// Unique reference of the deposit address (off-chain payment link).
    bytes32 paymentRef;
}

/// @notice Per-call Across quote values. Everything that decides where funds go comes from
///         `Terms`; the caller only supplies these, `outputAmount` must meet `minNetOut`, and
///         `fillDeadline` is capped by `UnizFactory.MAX_FILL_WINDOW`.
struct BridgeParams {
    /// Exact amount the Across relayer must deliver to the merchant (output-token units).
    uint256 outputAmount;
    uint32 quoteTimestamp;
    uint32 fillDeadline;
    address exclusiveRelayer;
    /// 0 = no exclusivity; otherwise an offset or timestamp as defined by Across.
    uint32 exclusivityParameter;
}

src/interfaces/IAcrossSpokePool.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.24;

/// @notice The subset of the Across SpokePool used to bridge settlements.
/// @dev `depositV3` pulls `inputAmount` of `inputToken` from msg.sender (or takes msg.value
///      when `inputToken` is the wrapped native token). An unfilled deposit is refunded to
///      `depositor` on the origin network after `fillDeadline`.
interface IAcrossSpokePool {
    function depositV3(
        address depositor,
        address recipient,
        address inputToken,
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 destinationChainId,
        address exclusiveRelayer,
        uint32 quoteTimestamp,
        uint32 fillDeadline,
        uint32 exclusivityParameter,
        bytes calldata message
    ) external payable;

    function wrappedNativeToken() external view returns (address);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": [
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "forge-std/=node_modules/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.