Skip to content
Verified contractExactMIT

BuyForwarderFactory

Address0x9d9d5d596d9157b00317fca7faccb885dd3faa60
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,500,767
Creation transaction
0x0758e4d8a6…6a0b4e81ec

src/BuyForwarderFactory.sol

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

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

interface IERC20 {
    function balanceOf(address) external view returns (uint256);
}

/// EIP-2612, which USDC on Ethereum implements.
interface IERC20Permit {
    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
    function allowance(address owner, address spender) external view returns (uint256);
}

interface IKusdtVault {
    function depositAtLeast(uint256 units, uint8 ownerScheme, bytes32 owner, uint256 minMinted) external returns (uint64);
    function depositMinted(uint64 nonce) external view returns (uint256);
    function isRefunded(uint64 nonce) external view returns (bool);
    function pendingRefunds(uint64 nonce) external view returns (address recipient, uint64 readyAt, uint256 units, uint256 fee);
    function scale() external view returns (uint256);
    function minDeposit() external view returns (uint256);
    function maxDeposit() external view returns (uint256);
}

/// Uniswap SwapRouter02's exactInputSingle (no deadline field).
interface ISwapRouter02 {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256);
}

/// Bridges a card purchase's USDC from the buyer's own wallet into the kUSDT vault for the buyer's Kaspa key.
/// There is no owner, no admin and no way to send the money anywhere but the vault, for the key the buyer signed for.
///
/// The buyer signs a USDC permit (EIP-2612) whose spender is a deposit address (a BuyForwarder at a CREATE2 address
/// known before it exists) made for their Kaspa key, the largest network fee they accept and the largest bridge fee
/// they accept. So the permit can serve only one deposit, for that key, within both fees, before its deadline:
/// - the network fee, up to its maximum, goes to `feeTo` (the gas wallet), and only the gas wallet can charge it;
/// - the vault's deposit fee is held to the maximum the buyer was shown, whoever sends and whenever;
/// - exactly the permitted USDC is swapped to USDT, at no worse than 0.1% below one for one, and deposited, or
///   nothing happens and the USDC stays in the buyer's wallet.
/// If the vault refunds such a deposit (it pays the deposit's sender, the deposit address), `returnRefund` sends it on
/// to the buyer's own wallet. Anything else sent to a deposit address directly stays there: it is not a way to bridge.
contract BuyForwarderFactory {
    IERC20 public immutable usdc;
    IERC20 public immutable usdt;
    ISwapRouter02 public immutable router;
    uint24 public immutable poolFee;
    IKusdtVault public immutable vault;
    address public immutable feeTo;

    /// What `returnRefund` needs for a deposit made by `forwardFrom`: whose USDC it was and how much was minted.
    struct Bought {
        address buyer;
        uint96 minted;
        address forwarder;
        bool returned;
    }

    mapping(uint64 => Bought) public bought;

    uint256 public constant MAX_SLIPPAGE_BPS = 10;

    event Forwarded(address indexed forwarder, uint8 ownerScheme, bytes32 indexed owner, uint256 usdcIn, uint256 units, uint64 nonce);
    event NetworkFeePaid(address indexed forwarder, address indexed to, uint256 fee);
    event RefundReturned(uint64 indexed nonce, address indexed buyer, uint256 amount);

    constructor(IERC20 usdc_, IERC20 usdt_, ISwapRouter02 router_, uint24 poolFee_, IKusdtVault vault_, address feeTo_) {
        require(feeTo_ != address(0), "no fee address");
        feeTo = feeTo_;
        usdc = usdc_;
        usdt = usdt_;
        router = router_;
        poolFee = poolFee_;
        vault = vault_;
    }

    /// A deposit address is made for a Kaspa key, the largest network fee its buyer accepts (USDC units) and the
    /// largest bridge fee they accept (vault units): a permit to it carries both.
    function salt(uint8 ownerScheme, bytes32 owner, uint256 maxFee, uint256 maxDepositFee) public pure returns (bytes32) {
        return keccak256(abi.encode(ownerScheme, owner, maxFee, maxDepositFee));
    }

    /// The deposit address of a Kaspa key with its two fee caps, whether or not it has been made yet.
    function forwarderOf(uint8 ownerScheme, bytes32 owner, uint256 maxFee, uint256 maxDepositFee) public view returns (address) {
        bytes32 h = keccak256(
            abi.encodePacked(bytes1(0xff), address(this), salt(ownerScheme, owner, maxFee, maxDepositFee), keccak256(type(BuyForwarder).creationCode))
        );
        return address(uint160(uint256(h)));
    }

    /// Bridges `amount` USDC from `buyer`'s wallet to kUSDT for the Kaspa key (`ownerScheme`, `owner`), with the
    /// buyer's permit for the deposit address of that key, `maxFee` and `maxDepositFee`. `fee` (at most `maxFee`, and
    /// only when the gas wallet sends) goes to `feeTo` for the gas; all of the rest is swapped and deposited with at
    /// least `minMinted` kUSDT minted and a deposit fee of at most `maxDepositFee`, or it reverts.
    function forwardFrom(
        address buyer, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s,
        uint8 ownerScheme, bytes32 owner, uint256 maxFee, uint256 maxDepositFee, uint256 fee, uint256 minMinted
    ) external returns (uint64 nonce, uint256 units) {
        require(maxFee > 0, "no fee cap");
        require(fee <= maxFee, "fee above the buyer's maximum");
        // Anyone may send a buyer's permit (it can only bridge their USDC to their own key), but only the gas wallet,
        // which pays the gas of the buys it sends, takes a network fee for it.
        require(fee == 0 || msg.sender == feeTo, "only the gas wallet charges a fee");
        require(amount > fee, "nothing to bridge");
        address f = _deployed(ownerScheme, owner, maxFee, maxDepositFee);
        _pull(buyer, f, amount, deadline, v, r, s);
        if (fee > 0) {
            BuyForwarder(f).call(address(usdc), abi.encodeWithSignature("transfer(address,uint256)", feeTo, fee), true);
            emit NetworkFeePaid(f, feeTo, fee);
        }
        (nonce, units) = _swapAndDeposit(f, amount - fee, ownerScheme, owner, maxDepositFee, minMinted);
        bought[nonce] = Bought(buyer, uint96(vault.depositMinted(nonce)), f, false);
    }

    /// Takes `amount` USDC from the buyer to `f` with their permit, which USDC checks here and now (signature, nonce,
    /// deadline). Nothing else moves the buyer's USDC: an allowance a permit left when it was sent some other way
    /// (copied from a pending transaction, say) is never used, since an allowance never expires and nothing on chain
    /// would tie a later use to the deadline the buyer signed. The buyer then signs again.
    function _pull(address buyer, address f, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) private {
        IERC20Permit(address(usdc)).permit(buyer, f, amount, deadline, v, r, s);
        BuyForwarder(f).call(address(usdc), abi.encodeWithSignature("transferFrom(address,address,uint256)", buyer, f, amount), true);
    }

    /// Sends the refund of a `forwardFrom` deposit, which the vault paid to the deposit address, to the buyer's own
    /// wallet. Anyone may call it; the money can only go to that buyer.
    function returnRefund(uint64 nonce) external {
        Bought memory b = bought[nonce];
        require(b.buyer != address(0), "not a card deposit");
        require(!b.returned, "already returned");
        require(vault.isRefunded(nonce), "not refunded");
        (address recipient,,,) = vault.pendingRefunds(nonce);
        require(recipient == address(0), "refund not paid yet");
        uint256 amount = uint256(b.minted) * vault.scale();
        require(usdt.balanceOf(b.forwarder) >= amount, "refund not at the deposit address");
        bought[nonce].returned = true;
        BuyForwarder(b.forwarder).call(address(usdt), abi.encodeWithSignature("transfer(address,uint256)", b.buyer, amount), true);
        emit RefundReturned(nonce, b.buyer, amount);
    }

    function _deployed(uint8 ownerScheme, bytes32 owner, uint256 maxFee, uint256 maxDepositFee) private returns (address f) {
        f = forwarderOf(ownerScheme, owner, maxFee, maxDepositFee);
        if (f.code.length == 0) new BuyForwarder{salt: salt(ownerScheme, owner, maxFee, maxDepositFee)}();
    }

    /// Swaps exactly `usdcIn` (what the permit brought, less the fee) and deposits exactly the USDT that swap
    /// returned: whatever else is at the address (a refund waiting for `returnRefund`, anything sent there directly)
    /// is left alone. Reverts unless it is all deposited, within the vault's limits, with a deposit fee of at most
    /// `maxDepositFee` and at least `minMinted` minted.
    function _swapAndDeposit(address f, uint256 usdcIn, uint8 ownerScheme, bytes32 owner, uint256 maxDepositFee, uint256 minMinted)
        private
        returns (uint64 nonce, uint256 units)
    {
        uint256 before = usdt.balanceOf(f);
        _swap(BuyForwarder(f), usdcIn);
        units = (usdt.balanceOf(f) - before) / vault.scale();
        require(units >= vault.minDeposit(), "below what the bridge takes");
        require(units <= vault.maxDeposit(), "above what the bridge takes");
        // The buyer's bound on the deposit fee holds whoever sends: the vault's fee can rise between signing and the
        // deposit (its surcharge when busy), and a sender may ask for any minMinted.
        uint256 floor = units > maxDepositFee ? units - maxDepositFee : 1;
        if (minMinted < floor) minMinted = floor;
        nonce = _deposit(BuyForwarder(f), units, ownerScheme, owner, minMinted);
        emit Forwarded(f, ownerScheme, owner, usdcIn, units, nonce);
    }

    /// USDC at the deposit address to USDT, at no worse than MAX_SLIPPAGE_BPS below one for one.
    function _swap(BuyForwarder fwd, uint256 usdcIn) private {
        address f = address(fwd);
        fwd.call(address(usdc), abi.encodeWithSignature("approve(address,uint256)", address(router), usdcIn), true);
        fwd.call(
            address(router),
            abi.encodeCall(
                ISwapRouter02.exactInputSingle,
                (ISwapRouter02.ExactInputSingleParams({
                    tokenIn: address(usdc),
                    tokenOut: address(usdt),
                    fee: poolFee,
                    recipient: f,
                    amountIn: usdcIn,
                    amountOutMinimum: usdcIn * (10_000 - MAX_SLIPPAGE_BPS) / 10_000,
                    sqrtPriceLimitX96: 0
                }))
            ),
            false
        );
    }

    function _deposit(BuyForwarder fwd, uint256 units, uint8 ownerScheme, bytes32 owner, uint256 minMinted) private returns (uint64) {
        fwd.call(address(usdt), abi.encodeWithSignature("approve(address,uint256)", address(vault), 0), true);
        fwd.call(address(usdt), abi.encodeWithSignature("approve(address,uint256)", address(vault), units * vault.scale()), true);
        return abi.decode(
            fwd.call(address(vault), abi.encodeCall(IKusdtVault.depositAtLeast, (units, ownerScheme, owner, minMinted)), false), (uint64)
        );
    }
}

src/BuyForwarder.sol

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

/// One per buyer: a card purchase delivers USDC here. It holds no logic of its own and obeys only the
/// factory that made it, whose code can do one thing with what lands here: put it into the kUSDT vault
/// for this buyer's Kaspa key.
contract BuyForwarder {
    address private immutable factory;

    constructor() {
        factory = msg.sender;
    }

    /// Calls `target`. With `isToken`, an empty return (USDT) or `true` is success, `false` is not.
    function call(address target, bytes calldata data, bool isToken) external returns (bytes memory ret) {
        require(msg.sender == factory, "not factory");
        bool ok;
        (ok, ret) = target.call(data);
        if (!ok) {
            assembly {
                revert(add(ret, 32), mload(ret))
            }
        }
        if (isToken) require(ret.length == 0 || abi.decode(ret, (bool)), "token call returned false");
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.