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

PulseSwap

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

0 ETH

 

Транзакций

1

 

Компилятор

solc 0.8.24

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.24+commit.e11b9ed9
Язык
solidity
Оптимизация
Да, 200 прогонов
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 444 284
Транзакция создания
0xfc1cf1f8d3…23d168f2a6

PulseSwap.sol

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

/// @title PulseSwap: hash time-locked escrow for trustless peer-to-peer bundle swaps,
///        with a fixed 0.5% fee and an on-chain track record.
/// @notice Each side locks a bundle of assets (native coin, ERC-20 tokens, ERC-721 NFTs) for the
///         other side under one sha256 hash. Revealing the secret to claim one side's bundle lets
///         the other side claim theirs. If anyone stalls, each sender gets a refund after their own
///         timelock. Locked assets can only ever go to the fixed recipient or back to the sender.
///         Claims keep 0.5% of fungible amounts as a fee; refunds are free.
///         `stats` and `delivered` are a public track record written only by real settlements:
///         nobody, including the website operator, can add to them.
/// @dev No owner, no admin, no upgrade path. The fee rate and fee recipient are fixed at deploy.
///      Fees accrue inside the contract and are pulled to the fee recipient, so a misbehaving fee
///      recipient can never block a swap. ERC-20s that return no bool (USDT) are supported;
///      fee-on-transfer tokens are refused. Tokens whose balances change after a transfer (rebasing) can't be told
///      apart at lock time and must not be locked: a negative rebase shorts the last claim or refund in that token.
contract PulseSwap {
    enum State { None, Open, Claimed, Refunded }

    uint8 public constant FUNGIBLE = 0; // native coin (token = 0) or ERC-20
    uint8 public constant NFT = 1; // ERC-721; `amount` is the token id
    uint256 public constant FEE_BPS = 50; // 0.5%
    uint256 public constant MAX_ASSETS = 10;

    /// @param amount Fungible: gross units. NFT: token id.
    /// @param extraFee Fungible only: a fee paid on top, by a sender who receives nothing the fee can be taken from.
    struct Asset {
        address token;
        uint8 kind;
        uint256 amount;
        uint256 extraFee;
    }

    struct Lock {
        address sender;
        address recipient;
        address token;
        uint8 kind;
        uint256 amount;
        uint256 extraFee;
        bytes32 hashlock; // sha256(preimage)
        uint64 timelock; // unix time after which the sender may refund
        State state;
    }

    /// @notice Public track record. `swaps`: swap sides this address delivered (its locks were
    ///         claimed, or it paid through payBatch). `refunds`: swap sides it took back.
    struct Stats {
        uint64 swaps;
        uint64 refunds;
    }

    address public immutable feeRecipient;
    mapping(bytes32 => Lock) public locks;
    mapping(address => uint256) public accruedFees; // token => fees held for the fee recipient
    mapping(address => Stats) public stats;
    mapping(address => mapping(address => uint256)) public delivered; // trader => token => units (NFTs: count)
    mapping(bytes32 => bool) private counted; // (trader, hashlock, kind of record) already counted

    event Locked(
        bytes32 indexed id, address indexed sender, address indexed recipient,
        address token, uint8 kind, uint256 amount, uint256 extraFee, bytes32 hashlock, uint64 timelock
    );
    event Claimed(bytes32 indexed id, bytes32 preimage);
    event Refunded(bytes32 indexed id);
    event Paid(
        address indexed from, address indexed to, address indexed token,
        uint8 kind, uint256 amount, uint256 extraFee, uint256 fee
    );
    event FeesWithdrawn(address indexed token, address indexed to, uint256 amount);

    uint256 private entered = 1;
    modifier nonReentrant() {
        require(entered == 1, "reentrant");
        entered = 2;
        _;
        entered = 1;
    }

    constructor(address feeRecipient_) {
        require(feeRecipient_ != address(0), "no fee recipient");
        feeRecipient = feeRecipient_;
    }

    /// @notice The fee kept from a fungible amount: 0.5%, rounded up so even tiny amounts pay.
    function feeOf(uint256 amount) public pure returns (uint256) {
        // Same as ceil(amount * 0.5%), split so it can't overflow for any amount.
        return (amount / 10_000) * FEE_BPS + ((amount % 10_000) * FEE_BPS + 9_999) / 10_000;
    }

    /// @notice Lock a bundle for `recipient` under `hashlock` until `timelock`.
    /// @return ids One per asset: sha256(abi.encode(chainid, this contract, sender, recipient,
    ///         token, kind, amount, extraFee, hashlock, timelock)). Binding the chain and contract
    ///         means a lock on one chain can never pass for a lock on another.
    function lockBatch(address recipient, Asset[] calldata assets, bytes32 hashlock, uint64 timelock)
        external payable nonReentrant returns (bytes32[] memory ids)
    {
        require(recipient != address(0) && recipient != msg.sender, "bad recipient");
        require(assets.length > 0 && assets.length <= MAX_ASSETS, "bad bundle size");
        require(timelock > block.timestamp, "timelock in past");
        require(timelock <= block.timestamp + 30 days, "timelock too far");

        ids = new bytes32[](assets.length);
        uint256 nativeIn;
        for (uint256 i = 0; i < assets.length; i++) {
            Asset calldata a = assets[i];
            _checkAsset(a);
            bytes32 id = sha256(abi.encode(
                block.chainid, address(this), msg.sender, recipient, a.token, a.kind, a.amount, a.extraFee, hashlock, timelock
            ));
            require(locks[id].state == State.None, "lock exists");
            nativeIn += _collect(a);
            locks[id] = Lock(msg.sender, recipient, a.token, a.kind, a.amount, a.extraFee, hashlock, timelock, State.Open);
            ids[i] = id;
            emit Locked(id, msg.sender, recipient, a.token, a.kind, a.amount, a.extraFee, hashlock, timelock);
        }
        require(msg.value == nativeIn, "wrong value");
    }

    /// @notice Claim locks by revealing the secret. Anyone may call; assets only go to each lock's recipient.
    function claimBatch(bytes32[] calldata ids, bytes32 preimage) external nonReentrant {
        require(ids.length > 0 && ids.length <= MAX_ASSETS, "bad batch size");
        for (uint256 i = 0; i < ids.length; i++) _claim(ids[i], preimage);
    }

    /// @notice Return locked assets, in full, to their senders once the timelock has passed. Anyone may call.
    function refundBatch(bytes32[] calldata ids) external nonReentrant {
        require(ids.length > 0 && ids.length <= MAX_ASSETS, "bad batch size");
        for (uint256 i = 0; i < ids.length; i++) _refund(ids[i]);
    }

    /// @notice Direct (non-escrow) bundle payment to `to`, with the fee taken in the same transaction.
    ///         Fungible: `to` receives amount - fee. NFTs move straight from the sender to `to`.
    function payBatch(address to, Asset[] calldata assets) external payable nonReentrant {
        require(to != address(0) && to != msg.sender, "bad recipient");
        require(assets.length > 0 && assets.length <= MAX_ASSETS, "bad bundle size");
        uint256 nativeIn;
        for (uint256 i = 0; i < assets.length; i++) {
            Asset calldata a = assets[i];
            _checkAsset(a);
            uint256 fee;
            if (a.kind == FUNGIBLE) {
                nativeIn += _collect(a);
                fee = feeOf(a.amount);
                accruedFees[a.token] += fee + a.extraFee;
                delivered[msg.sender][a.token] += a.amount;
                _send(a.token, FUNGIBLE, to, a.amount - fee);
            } else {
                _call(a.token, abi.encodeWithSelector(0x23b872dd, msg.sender, to, a.amount)); // transferFrom
                require(_ownerOf(a.token, a.amount) == to, "nft not delivered");
                delivered[msg.sender][a.token] += 1;
            }
            emit Paid(msg.sender, to, a.token, a.kind, a.amount, a.extraFee, fee);
        }
        require(msg.value == nativeIn, "wrong value");
        stats[msg.sender].swaps += 1;
    }

    /// @notice Send all accrued fees in `token` to the fixed fee recipient. Anyone may call.
    function withdrawFees(address token) external nonReentrant {
        _withdrawFees(token, feeRecipient);
    }

    /// @notice For the fee recipient only: send its fees somewhere else, e.g. if its own address
    ///         can't receive a token (frozen by the issuer). Only accrued fees can move this way.
    function withdrawFeesTo(address token, address to) external nonReentrant {
        require(msg.sender == feeRecipient, "only fee recipient");
        require(to != address(0), "bad recipient");
        _withdrawFees(token, to);
    }

    /* ───────────── internals ───────────── */

    function _claim(bytes32 id, bytes32 preimage) private {
        Lock storage l = locks[id];
        require(l.state == State.Open, "not open");
        require(block.timestamp < l.timelock, "expired");
        require(sha256(abi.encodePacked(preimage)) == l.hashlock, "wrong preimage");
        l.state = State.Claimed;
        _countOnce(l.sender, l.hashlock, 1);
        uint256 fee = l.kind == FUNGIBLE ? feeOf(l.amount) : 0;
        if (l.kind == FUNGIBLE) {
            accruedFees[l.token] += fee + l.extraFee;
            delivered[l.sender][l.token] += l.amount;
        } else {
            delivered[l.sender][l.token] += 1;
        }
        emit Claimed(id, preimage);
        _send(l.token, l.kind, l.recipient, l.amount - fee);
    }

    function _refund(bytes32 id) private {
        Lock storage l = locks[id];
        require(l.state == State.Open, "not open");
        require(block.timestamp >= l.timelock, "not expired");
        l.state = State.Refunded;
        _countOnce(l.sender, l.hashlock, 2);
        emit Refunded(id);
        _send(l.token, l.kind, l.sender, l.kind == FUNGIBLE ? l.amount + l.extraFee : l.amount);
    }

    // One swap side = all of a sender's locks under one hash: count it once, not per asset.
    function _countOnce(address trader, bytes32 hashlock, uint8 what) private {
        bytes32 key = keccak256(abi.encode(trader, hashlock, what));
        if (counted[key]) return;
        counted[key] = true;
        if (what == 1) stats[trader].swaps += 1;
        else stats[trader].refunds += 1;
    }

    function _checkAsset(Asset calldata a) private view {
        if (a.kind == FUNGIBLE) {
            require(a.amount > 0, "zero amount");
            // An NFT locked as a fungible token could never be paid out or refunded (no transfer()).
            if (a.token != address(0)) require(!_isErc721(a.token), "nft must use kind 1");
        } else {
            require(a.kind == NFT, "bad kind");
            require(a.token != address(0), "nft needs a contract");
            require(a.extraFee == 0, "no extra fee on nfts");
        }
    }

    // True if `token` says it implements ERC-721 (ERC-165 interface 0x80ac58cd).
    function _isErc721(address token) private view returns (bool) {
        (bool ok, bytes memory ret) = token.staticcall{gas: 30_000}(abi.encodeWithSelector(0x01ffc9a7, bytes4(0x80ac58cd)));
        return ok && ret.length >= 32 && abi.decode(ret, (bool));
    }

    // Take an asset from msg.sender into this contract. Returns the native coin it should have brought.
    function _collect(Asset calldata a) private returns (uint256 nativeIn) {
        if (a.kind == NFT) {
            _call(a.token, abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), a.amount)); // transferFrom
            require(_ownerOf(a.token, a.amount) == address(this), "nft not received");
            return 0;
        }
        uint256 total = a.amount + a.extraFee;
        if (a.token == address(0)) return total;
        require(a.token.code.length > 0, "not a token");
        uint256 before = _balanceOf(a.token);
        _call(a.token, abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), total)); // transferFrom
        // Refuse fee-on-transfer tokens (and tokens that rebase during the transfer): the contract must receive exactly what was locked.
        require(_balanceOf(a.token) - before == total, "token amount mismatch");
        return 0;
    }

    function _send(address token, uint8 kind, address to, uint256 amount) private {
        if (kind == NFT) {
            _call(token, abi.encodeWithSelector(0x23b872dd, address(this), to, amount)); // transferFrom
        } else if (amount == 0) {
            return;
        } else if (token == address(0)) {
            (bool ok, ) = to.call{value: amount}("");
            require(ok, "native transfer failed");
        } else {
            _call(token, abi.encodeWithSelector(0xa9059cbb, to, amount)); // transfer
        }
    }

    function _withdrawFees(address token, address to) private {
        uint256 amount = accruedFees[token];
        require(amount > 0, "no fees");
        accruedFees[token] = 0;
        emit FeesWithdrawn(token, to, amount);
        _send(token, FUNGIBLE, to, amount);
    }

    function _balanceOf(address token) private view returns (uint256) {
        (bool ok, bytes memory data) = token.staticcall(abi.encodeWithSelector(0x70a08231, address(this)));
        require(ok && data.length >= 32, "balanceOf failed");
        return abi.decode(data, (uint256));
    }

    function _ownerOf(address token, uint256 id) private view returns (address) {
        (bool ok, bytes memory data) = token.staticcall(abi.encodeWithSelector(0x6352211e, id));
        require(ok && data.length >= 32, "ownerOf failed");
        return abi.decode(data, (address));
    }

    // Accepts tokens that return true, and tokens (like USDT) that return nothing.
    function _call(address token, bytes memory data) private {
        require(token.code.length > 0, "not a token");
        (bool ok, bytes memory ret) = token.call(data);
        require(ok && (ret.length == 0 || abi.decode(ret, (bool))), "token call failed");
    }
}
Настройки компилятораПоказать
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

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

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