Skip to content
Verified contractExactMIT

AlcorDepositAddress

Address0x54f86d30da2cee4b9b9c5f65117f824007d253b0
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,243,680
Creation transaction
0xb0f1051c46…9f87b3671e

src/AlcorDepositAddresses.sol

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

/**
 * AlcorDepositAddresses — a personal deposit address for every destination,
 * for money that arrives by a plain transfer.
 *
 * An exchange withdrawal, or a wallet that only knows "send", cannot call
 * `deposit` on the vault. So each destination gets an address of its own, and
 * whatever lands there is carried into the vault for that destination by
 * `forward`. The address is computed, never registered on chain:
 *
 *     address = CREATE2(this factory, keccak256(telosTo, leg), clone of AlcorDepositAddress)
 *
 * so it can be handed out before anything exists at it, and money sent to it
 * then is already safe: the address has no private key, and the only code that
 * can ever run there is a clone this factory deploys, which obeys only this
 * factory, which only ever sends it on to the vault for the destination the
 * address was computed from.
 *
 * ## The destination
 *
 * `telosTo` is the account credited on Telos. `leg` is empty for a deposit that
 * stays on Telos, or `<domain>:<recipient>` for one that goes on through the hop
 * (`telosTo` is then `hop.alcor`). The hop needs a way back, and the way back is
 * this same address on this chain, so it is not part of the hash — it could not
 * be, being the hash's output — but appended here when the memo is built:
 *
 *     <leg>|<chain id>:<this address>
 *
 * A refund then comes back to the deposit address; sending it to the exchange
 * that withdrew it would lose it. A forward would only send it where it was
 * refused, so the owner may `redirect` it to another destination — announced
 * DELAY ahead, like a change of vault.
 *
 * ## Deployed for a moment
 *
 * `forward` deploys the clone, moves the money, and destroys it again in the
 * same transaction. Since Cancun (EIP-6780) SELFDESTRUCT only removes a contract
 * created in the transaction that runs it, which this one always is. The point
 * is the next deposit: exchanges send native coins with a 21,000 gas limit, and
 * a transfer to an address with code runs that code and fails. With nothing left
 * at the address, every later transfer behaves as the first one did.
 *
 * So the clone always closes. A native balance below the vault's minimum, which
 * could not be forwarded, goes to `feeTo` with it; one at or above the minimum
 * has to be forwarded in the same call, or the call reverts. And a closed clone
 * refuses money for the rest of its transaction: what it took then would be
 * deleted with the account when the transaction ends.
 *
 * Nothing depends on the destruction working. Should a future fork stop it, the
 * clone simply stays, `forward` finds it and uses it, and only that one native
 * coin quirk comes back.
 *
 * ## The fee
 *
 * Whoever forwards pays the gas, so the operator may take a fee out of what it
 * forwards, in the same token, to `feeTo`. It names the fee per call, from the
 * price of gas at that moment, and the clone caps it at MAX_FEE_BPS of the
 * amount forwarded. Anyone else may forward too, with no fee — so nothing
 * depends on the operator being alive.
 *
 * Each sweep names its amount, so a balance over a cap or a route's limit can
 * go in parts, several sweeps of one token in one call if need be.
 *
 * ## The privileged surface
 *
 * The owner sets `vault`, `operator` and `feeTo`. The vault decides where every
 * later forward goes, so it is set at once only the first time; a change is
 * announced and takes effect DELAY later. So does a `redirect`. A stolen owner
 * key then takes only what arrives after the delay, and the courier, which
 * watches for announcements, forwards everything into the old vault meanwhile.
 * The fee cap holds against a stolen operator key, not against the owner.
 *
 * `rescue` sends a token the vault does not take back to whoever it belongs to.
 * Only such a token: one the vault takes goes to the vault, for the address's
 * destination or, DELAY after an announcement, for another.
 *
 * ## The same address on every chain
 *
 * Deployed by the same CREATE2 deployer with the same constructor argument, this
 * factory has one address on Ethereum, BSC and Polygon, and so does every deposit
 * address it computes. Nothing chain-specific is in its bytecode: the vault is
 * set after deployment.
 */
interface IAlcorVault {
    function deposit(
        address token,
        uint256 amount,
        uint64 telosTo,
        address refundTo,
        uint64 fillFee,
        uint64 filler,
        bytes calldata memo
    ) external;

    function depositNative(uint64 telosTo, address refundTo, uint64 fillFee, uint64 filler, bytes calldata memo)
        external
        payable;

    function assets(address token) external view returns (uint64 scale, uint64 minDeposit, bool enabled, uint96 cap);
}

interface IERC20 {
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
}

/**
 * The code behind every deposit address, reached through a minimal proxy.
 *
 * It does what its factory says and nothing else, and what the factory can say
 * is short: forward a balance to the vault, pay out a token the vault does not
 * take, and close.
 */
contract AlcorDepositAddress {
    address public constant NATIVE = address(0);

    /// The most the operator may keep of what it forwards: 1%.
    uint256 public constant MAX_FEE_BPS = 100;

    /// Set at construction, so a clone reads it from the code it delegates to.
    address private immutable FACTORY;

    error NotFactory();
    error FeeTooLarge();
    error NativeSendFailed();
    error TransferFailed();
    error Closed();

    /// Set by `close`: a closed clone refuses money until its transaction ends.
    bool private transient closed;

    constructor() {
        FACTORY = msg.sender;
    }

    modifier onlyFactory() {
        if (msg.sender != FACTORY) revert NotFactory();
        _;
    }

    /**
     * Take `amount` of `token` from this address: `fee` of it to `feeTo`, the
     * rest to the vault. Returns what the vault was handed.
     *
     * The vault floors an ERC-20 deposit to a whole canonical unit and leaves the
     * rest here, where the next forward picks it up. A native deposit's remainder
     * the vault sends straight back, and that goes on to `feeTo` with the fee: it
     * is less than one canonical unit (1e-8 of the coin).
     */
    function forward(
        IAlcorVault vault,
        address token,
        uint256 amount,
        uint256 fee,
        address feeTo,
        uint64 telosTo,
        bytes calldata memo
    ) external onlyFactory returns (uint256 deposited) {
        if (fee * 10_000 > amount * MAX_FEE_BPS) revert FeeTooLarge();
        deposited = amount - fee;

        if (token == NATIVE) {
            // Reverts if there is less than `amount` here.
            uint256 kept = address(this).balance - amount;
            vault.depositNative{value: deposited}(telosTo, address(this), 0, 0, memo);
            // Above what stays here: the fee and the remainder the vault sent back.
            _sendNative(feeTo, address(this).balance - kept);
        } else {
            if (fee != 0) _call(token, abi.encodeCall(IERC20.transfer, (feeTo, fee)));
            _approve(token, address(vault), deposited);
            vault.deposit(token, deposited, telosTo, address(this), 0, 0, memo);
        }
    }

    /** Pay `amount` of a token, or of the native coin, out of this address. */
    function pay(address token, address to, uint256 amount) external onlyFactory {
        if (token == NATIVE) _sendNative(to, amount);
        else _call(token, abi.encodeCall(IERC20.transfer, (to, amount)));
    }

    /**
     * Remove the code from this address, sending its native balance to `to`.
     * The factory checks first that the balance is one the vault would not take.
     * ERC-20 balances are untouched by the destruction and simply wait at the
     * address.
     */
    function close(address payable to) external onlyFactory {
        closed = true;
        // EIP-6780: deletes the account because the factory created it in this
        // same transaction; that is the only way `close` is ever called.
        selfdestruct(to);
    }

    /**
     * A native deposit's remainder from the vault, or a plain transfer while the
     * clone exists. Not after `close`: the account, and whatever it holds, is
     * deleted when the transaction ends — a refund delivered then would be
     * marked paid and burned.
     */
    receive() external payable {
        if (closed) revert Closed();
    }

    function _sendNative(address to, uint256 amount) private {
        if (amount == 0) return;
        (bool ok, ) = to.call{value: amount}("");
        if (!ok) revert NativeSendFailed();
    }

    /**
     * `approve` the way USDT on Ethereum accepts it: that token refuses to move
     * an allowance from one non-zero value to another. The vault leaves a
     * sub-unit allowance behind whenever it floors a deposit, and the allowance
     * outlives the clone, so the second forward would meet one.
     */
    function _approve(address token, address spender, uint256 amount) private {
        if (_tryCall(token, abi.encodeCall(IERC20.approve, (spender, amount)))) return;
        _call(token, abi.encodeCall(IERC20.approve, (spender, 0)));
        _call(token, abi.encodeCall(IERC20.approve, (spender, amount)));
    }

    function _call(address token, bytes memory data) private {
        if (!_tryCall(token, data)) revert TransferFailed();
    }

    /** True for success that returned nothing or `true`: ERC-20s that return nothing are common. */
    function _tryCall(address token, bytes memory data) private returns (bool) {
        (bool ok, bytes memory ret) = token.call(data);
        // Reads the first word, which the length check guarantees is there.
        // forge-lint: disable-next-line(unsafe-typecast)
        return ok && (ret.length == 0 || (ret.length >= 32 && uint256(bytes32(ret)) == 1));
    }
}

contract AlcorDepositAddresses {
    address public constant NATIVE = address(0);

    /// How long a change of vault or a redirect waits after it is announced.
    uint256 public constant DELAY = 48 hours;

    /// An amount of one token to take from an address, and the operator's fee out of it.
    struct Sweep {
        address token;
        uint256 amount;
        uint256 fee;
    }

    /// The code every deposit address runs, deployed by this factory at its first nonce.
    AlcorDepositAddress public immutable implementation;
    /// keccak256 of a clone's creation code: the third input of every address.
    bytes32 public immutable cloneCodeHash;

    address public owner;
    address public pendingOwner;
    /// The vault every forward deposits into. Zero until the owner sets it.
    IAlcorVault public vault;
    /// The vault announced to replace it, and when it may.
    IAlcorVault public pendingVault;
    uint256 public pendingVaultAt;
    /// keccak256(abi.encode(telosTo, leg, toTelos, toLeg)) → when that redirect may run.
    mapping(bytes32 => uint256) public redirectAt;
    /// The one key that may take a fee. Zero means nobody may.
    address public operator;
    /// Where fees go.
    address public feeTo;

    event Forwarded(address indexed depositAddress, address indexed token, uint256 amount, uint256 fee);
    event Rescued(address indexed depositAddress, address indexed token, address to, uint256 amount);
    event Redirected(address indexed depositAddress, uint64 toTelos, string toLeg);
    event RedirectAnnounced(address indexed depositAddress, uint64 toTelos, string toLeg, uint256 readyAt);
    event RedirectCancelled(address indexed depositAddress, uint64 toTelos, string toLeg);
    event VaultAnnounced(address vault, uint256 readyAt);
    event VaultCancelled(address vault);
    event VaultSet(address vault);
    event OperatorSet(address operator);
    event FeeToSet(address feeTo);
    event OwnershipOffered(address indexed to);
    event OwnerSet(address indexed owner);

    error NotOwner();
    error NotPendingOwner();
    error NotOperator();
    error NoVault();
    error ZeroAddress();
    error VaultTakesIt();
    error DeployFailed();
    error NothingToForward();
    error NativeLeft(uint256 balance);
    error NotAnnounced();
    error TooEarly(uint256 readyAt);

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    /**
     * `owner` is an argument, not `msg.sender`: deployed through a CREATE2
     * deployer, the sender is the deployer contract.
     */
    constructor(address _owner) {
        if (_owner == address(0)) revert ZeroAddress();
        owner = _owner;
        implementation = new AlcorDepositAddress();
        cloneCodeHash = keccak256(_cloneCode(address(implementation)));
        emit OwnerSet(_owner);
    }

    // ------------------------------ the addresses -------------------------------

    function saltOf(uint64 telosTo, string calldata leg) public pure returns (bytes32) {
        return keccak256(abi.encode(telosTo, leg));
    }

    /** The deposit address for a destination, whether or not anything was ever deployed there. */
    function addressOf(uint64 telosTo, string calldata leg) public view returns (address) {
        bytes32 h = keccak256(abi.encodePacked(bytes1(0xff), address(this), saltOf(telosTo, leg), cloneCodeHash));
        return address(uint160(uint256(h)));
    }

    /** The memo a deposit from `at` carries: none for Telos, the leg and the way back for a hop. */
    function memoOf(address depositAddress, string calldata leg) public view returns (bytes memory) {
        if (bytes(leg).length == 0) return "";
        return abi.encodePacked(leg, "|", _decimal(block.chainid), ":", _hex(depositAddress));
    }

    // ------------------------------- forwarding ---------------------------------

    /**
     * Carry what sits at a destination's address into the vault, in sweeps, all
     * in one transaction.
     *
     * Anyone may call it. A fee is the operator's alone, because the caller names
     * it: open to all, the first caller to see a large deposit would take the cap.
     */
    function forward(uint64 telosTo, string calldata leg, Sweep[] calldata sweeps) external {
        _forward(telosTo, leg, telosTo, leg, sweeps);
    }

    /**
     * Carry what sits at a destination's address into the vault for another
     * destination, DELAY after `announceRedirect` — for a refund from a
     * destination that will never take it. The way back stays this address.
     * Runs once per announcement.
     */
    function redirect(
        uint64 telosTo,
        string calldata leg,
        uint64 toTelos,
        string calldata toLeg,
        Sweep[] calldata sweeps
    ) external onlyOwner {
        bytes32 id = redirectId(telosTo, leg, toTelos, toLeg);
        uint256 readyAt = redirectAt[id];
        if (readyAt == 0) revert NotAnnounced();
        if (block.timestamp < readyAt) revert TooEarly(readyAt);
        delete redirectAt[id];
        emit Redirected(addressOf(telosTo, leg), toTelos, toLeg);
        _forward(telosTo, leg, toTelos, toLeg, sweeps);
    }

    function _forward(
        uint64 telosTo,
        string calldata leg,
        uint64 toTelos,
        string calldata toLeg,
        Sweep[] calldata sweeps
    ) private {
        IAlcorVault v = vault;
        if (address(v) == address(0)) revert NoVault();
        if (sweeps.length == 0) revert NothingToForward();
        for (uint256 i = 0; i < sweeps.length; i++) {
            if (sweeps[i].fee != 0 && msg.sender != operator) revert NotOperator();
        }

        (AlcorDepositAddress depositAddress, bool created) = _open(telosTo, leg);
        bytes memory memo = memoOf(address(depositAddress), toLeg);
        for (uint256 i = 0; i < sweeps.length; i++) _sweep(depositAddress, v, sweeps[i], toTelos, memo);
        if (created) _close(depositAddress, v);
    }

    /** One sweep of a forward. Its own function so that `_forward` has room on the stack. */
    function _sweep(
        AlcorDepositAddress depositAddress,
        IAlcorVault v,
        Sweep calldata s,
        uint64 telosTo,
        bytes memory memo
    ) private {
        uint256 deposited = depositAddress.forward(v, s.token, s.amount, s.fee, feeTo, telosTo, memo);
        emit Forwarded(address(depositAddress), s.token, deposited, s.fee);
    }

    /**
     * Pay out a token (or a native coin) the vault does not take: it would sit at the address
     * forever otherwise. The owner sends it wherever its sender proves it should
     * go. A token the vault takes is refused: that goes to the vault, through
     * `forward` or `redirect`.
     */
    function rescue(uint64 telosTo, string calldata leg, address token, address to, uint256 amount)
        external
        onlyOwner
    {
        IAlcorVault v = vault;
        if (address(v) == address(0)) revert NoVault();
        (uint64 scale, , , ) = v.assets(token);
        if (scale != 0) revert VaultTakesIt();
        (AlcorDepositAddress depositAddress, bool created) = _open(telosTo, leg);
        depositAddress.pay(token, to, amount);
        emit Rescued(address(depositAddress), token, to, amount);
        if (created) _close(depositAddress, v);
    }

    /**
     * Close a clone created in this transaction. A native balance the vault
     * would take must have been forwarded: closing sends it to `feeTo`, which is
     * only right for one below the vault's minimum.
     */
    function _close(AlcorDepositAddress depositAddress, IAlcorVault v) private {
        uint256 left = address(depositAddress).balance;
        if (left != 0) {
            (uint64 scale, uint64 minDeposit, , ) = v.assets(NATIVE);
            if (left >= uint256(minDeposit) * scale) revert NativeLeft(left);
        }
        depositAddress.close(payable(feeTo));
    }

    /** The clone at a destination's address, deployed now if nothing is there. */
    function _open(uint64 telosTo, string calldata leg)
        private
        returns (AlcorDepositAddress depositAddress, bool created)
    {
        address predicted = addressOf(telosTo, leg);
        if (predicted.code.length != 0) return (AlcorDepositAddress(payable(predicted)), false);

        bytes memory code = _cloneCode(address(implementation));
        bytes32 salt = saltOf(telosTo, leg);
        address deployed;
        assembly {
            deployed := create2(0, add(code, 0x20), mload(code), salt)
        }
        // CREATE2 to the address `addressOf` computed, or nothing: the only way
        // to land elsewhere is a different code hash, which this code cannot make.
        if (deployed != predicted) revert DeployFailed();
        return (AlcorDepositAddress(payable(deployed)), true);
    }

    // ------------------------------ administration ------------------------------

    /**
     * The first vault is set at once: there is nothing at any address before it.
     * A change is announced here and made by `acceptVault` DELAY later.
     */
    function setVault(IAlcorVault _vault) external onlyOwner {
        if (address(_vault) == address(0)) revert ZeroAddress();
        if (address(vault) == address(0)) {
            vault = _vault;
            emit VaultSet(address(_vault));
            return;
        }
        pendingVault = _vault;
        pendingVaultAt = block.timestamp + DELAY;
        emit VaultAnnounced(address(_vault), pendingVaultAt);
    }

    function acceptVault() external onlyOwner {
        IAlcorVault next = pendingVault;
        if (address(next) == address(0)) revert NotAnnounced();
        if (block.timestamp < pendingVaultAt) revert TooEarly(pendingVaultAt);
        vault = next;
        pendingVault = IAlcorVault(address(0));
        pendingVaultAt = 0;
        emit VaultSet(address(next));
    }

    function cancelVault() external onlyOwner {
        IAlcorVault next = pendingVault;
        if (address(next) == address(0)) revert NotAnnounced();
        pendingVault = IAlcorVault(address(0));
        pendingVaultAt = 0;
        emit VaultCancelled(address(next));
    }

    function redirectId(uint64 telosTo, string calldata leg, uint64 toTelos, string calldata toLeg)
        public
        pure
        returns (bytes32)
    {
        return keccak256(abi.encode(telosTo, leg, toTelos, toLeg));
    }

    /** Let `redirect` move what sits at `(telosTo, leg)`'s address to `(toTelos, toLeg)`, DELAY from now. */
    function announceRedirect(uint64 telosTo, string calldata leg, uint64 toTelos, string calldata toLeg)
        external
        onlyOwner
    {
        uint256 readyAt = block.timestamp + DELAY;
        redirectAt[redirectId(telosTo, leg, toTelos, toLeg)] = readyAt;
        emit RedirectAnnounced(addressOf(telosTo, leg), toTelos, toLeg, readyAt);
    }

    function cancelRedirect(uint64 telosTo, string calldata leg, uint64 toTelos, string calldata toLeg)
        external
        onlyOwner
    {
        bytes32 id = redirectId(telosTo, leg, toTelos, toLeg);
        if (redirectAt[id] == 0) revert NotAnnounced();
        delete redirectAt[id];
        emit RedirectCancelled(addressOf(telosTo, leg), toTelos, toLeg);
    }

    function setOperator(address _operator) external onlyOwner {
        operator = _operator;
        emit OperatorSet(_operator);
    }

    /** Never zero: a fee sent to the zero address is burned, and a closing clone sends there too. */
    function setFeeTo(address _feeTo) external onlyOwner {
        if (_feeTo == address(0)) revert ZeroAddress();
        feeTo = _feeTo;
        emit FeeToSet(_feeTo);
    }

    /** Two steps, as on the vault: a mistyped owner would leave nobody to set anything. */
    function offerOwnership(address to) external onlyOwner {
        pendingOwner = to;
        emit OwnershipOffered(to);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotPendingOwner();
        owner = msg.sender;
        pendingOwner = address(0);
        emit OwnerSet(msg.sender);
    }

    // --------------------------------- encoding ---------------------------------

    /** EIP-1167: a 45-byte proxy that delegates every call to `impl`. */
    function _cloneCode(address impl) private pure returns (bytes memory) {
        return abi.encodePacked(
            hex"3d602d80600a3d3981f3363d3d373d3d3d363d73", impl, hex"5af43d82803e903d91602b57fd5bf3"
        );
    }

    function _decimal(uint256 v) private pure returns (bytes memory out) {
        if (v == 0) return "0";
        uint256 digits;
        for (uint256 t = v; t != 0; t /= 10) digits++;
        out = new bytes(digits);
        for (; v != 0; v /= 10) out[--digits] = bytes1(uint8(48 + (v % 10)));
    }

    /** `0x` and forty lowercase hex digits, the one spelling the ledger writes back. */
    function _hex(address a) private pure returns (bytes memory out) {
        bytes16 digits = "0123456789abcdef";
        out = new bytes(42);
        out[0] = "0";
        out[1] = "x";
        uint160 v = uint160(a);
        for (uint256 i = 41; i > 1; i--) {
            out[i] = digits[v & 0xf];
            v >>= 4;
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.