Skip to content
Verified contractPartialMIT

FlashSwapModule

Address0x799179824043c1bb72607f79fd7aba306444aa2e
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.16

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.16+commit.07a7930e
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
london
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
16,705,938
Creation transaction
0x8bccc0336d…153097822f

src/FlashSwapModule.sol

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

import {RLPReader} from "solidity-rlp/RLPReader.sol";

interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
}

interface IUniswapV2Router {
    function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
}

interface IUniswapV2Pair {
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
}

/// Storage layout shared by the router 0x00000000000Ba9Cd9F5175108141A82B6c24d727 and the modules it
/// delegatecalls into.
abstract contract RouterStorage {
    address public owner;
    bytes32 public checksum; // bytes32 in this early build (uint256 in later modules): same slot, same getter selector
    mapping(address => bool) public allowed_searchers;
    mapping(uint256 => address) public map_address;
    mapping(uint256 => uint256) public map_uint256;
    mapping(uint256 => bytes32) public map_bytes32;
    mapping(uint256 => bool) public map_bool;
    mapping(uint256 => uint256) public gas_garbage;
    uint256 public gas_garbage_count;
    mapping(bytes4 => address) public implementations;

    address public immutable self;

    modifier isOwner() {
        require(msg.sender == owner, "Caller is not owner");
        _;
    }

    constructor() {
        self = address(this);
    }

    function generate_garbage(uint256 count) external {
        gas_garbage_count += count;
        for (uint256 i = 0; i < count; i++) {
            gas_garbage[i] = type(uint256).max;
        }
    }
}

/// Uniswap V2 flash-swap step for the router's trading modules (2023-02-25). `doTrade(amount, data)` is delegatecalled
/// as one step of a trade: it quotes `amount` through the pair's router, records a checksum of the parameters and
/// calls `pair.swap` with this contract as recipient. In the pair's callback (25 fork names, one body) it checks the
/// checksum, the pair and the initiator, optionally runs the next step on the output (`doTrade` on `nextModule`), and
/// repays the pair with `amountIn` of the input token.
contract FlashSwapModule is RouterStorage {
    using RLPReader for RLPReader.RLPItem;
    using RLPReader for bytes;

    struct Params {
        address router; // Uniswap V2-style router used for getAmountsOut
        address pair;
        address token0;
        address token1;
        bool zeroForOne; // true: sell token0 for token1
        uint256 amountIn;
        bool hasNext; // RLP input only: nextModule and nextData follow
        address nextModule; // step to run inside the callback, address(0) for none
        bytes nextData;
    }

    /// Run by the router's `adopt(module)` (delegatecall). Registers the pair callbacks; on Ethereum mainnet only the
    /// five forks that exist there.
    function adopt() external {
        implementations[this.uniswapV2Call.selector] = self;
        implementations[this.SakeSwapCall.selector] = self;
        implementations[this.apeCall.selector] = self;
        implementations[this.croDefiSwapCall.selector] = self;
        implementations[this.unicSwapV2Call.selector] = self;
        if (block.chainid != 1) {
            implementations[this.jetswapCall.selector] = self;
            implementations[this.elkCall.selector] = self;
            implementations[this.waultSwapCall.selector] = self;
            implementations[this.MeerkatCall.selector] = self;
            implementations[this.polydexCall.selector] = self;
            implementations[this.pangolinCall.selector] = self;
            implementations[this.yetiswapCall.selector] = self;
            implementations[this.baguetteCall.selector] = self;
            implementations[this.canaryCall.selector] = self;
            implementations[this.lydiaCall.selector] = self;
            implementations[this.oliveCall.selector] = self;
            implementations[this.joeCall.selector] = self;
            implementations[this.pancakeCall.selector] = self;
            implementations[this.babyCall.selector] = self;
            implementations[this.BiswapCall.selector] = self;
            implementations[this.swapV2Call.selector] = self;
            implementations[this.fstswapCall.selector] = self;
            implementations[this.BSCswapCall.selector] = self;
            implementations[this.ThugswapCall.selector] = self;
            implementations[this.SwychCall.selector] = self;
        }
    }

    /// Does nothing; it only puts the Params tuple into the ABI for off-chain encoders.
    function helper(Params memory) external pure returns (bool) {
        return false;
    }

    /// Step entry point. `data` is the RLP list
    /// [router, pair, token0, token1, zeroForOne, amountIn, hasNext, (nextModule, nextData)]; amountIn is replaced by
    /// `amount`. Returns the quoted output amount.
    function doTrade(uint256 amount, bytes calldata data) external payable returns (uint256) {
        Params memory p = _decode(data);
        address[] memory path = new address[](2);
        if (p.zeroForOne) {
            path[0] = p.token0;
            path[1] = p.token1;
        } else {
            path[0] = p.token1;
            path[1] = p.token0;
        }
        p.amountIn = amount;
        uint256[] memory amounts = IUniswapV2Router(p.router).getAmountsOut(amount, path);
        uint256 amount0Out;
        uint256 amount1Out;
        if (p.zeroForOne) amount1Out = amounts[1];
        else amount0Out = amounts[1];
        bytes memory encoded = abi.encode(p);
        checksum = keccak256(encoded);
        IUniswapV2Pair(p.pair).swap(amount0Out, amount1Out, address(this), encoded);
        return amounts[1];
    }

    function uniswapV2Call(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function SakeSwapCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function apeCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function croDefiSwapCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function unicSwapV2Call(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function jetswapCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function elkCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function waultSwapCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function MeerkatCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function polydexCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function pangolinCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function yetiswapCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function baguetteCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function canaryCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function lydiaCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function oliveCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function joeCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function pancakeCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function babyCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function BiswapCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function swapV2Call(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function fstswapCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function BSCswapCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function ThugswapCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function SwychCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {
        _callback(sender, amount0, amount1, data);
    }

    function _callback(address sender, uint256 amount0, uint256 amount1, bytes calldata data) internal {
        require(checksum == keccak256(data), "params mismatch");
        checksum = 0;
        Params memory p = abi.decode(data, (Params));
        require(msg.sender == p.pair, "msg.sender not pair");
        require(sender == address(this), "sender not self");
        if (p.nextModule != address(0)) {
            uint256 amount;
            if (p.zeroForOne) amount = amount1;
            else amount = amount0;
            (bool success, bytes memory result) =
                p.nextModule.delegatecall(abi.encodeWithSignature("doTrade(uint256,bytes)", amount, p.nextData));
            require(success, string(result));
        }
        // The transfer results are ignored, as deployed.
        if (p.zeroForOne) IERC20(p.token0).transfer(p.pair, p.amountIn);
        else IERC20(p.token1).transfer(p.pair, p.amountIn);
    }

    function _decode(bytes calldata data) internal pure returns (Params memory) {
        Params memory p;
        RLPReader.RLPItem[] memory items = data.toRlpItem().toList();
        p.router = items[0].toAddress();
        p.pair = items[1].toAddress();
        p.token0 = items[2].toAddress();
        p.token1 = items[3].toAddress();
        p.zeroForOne = items[4].toBoolean();
        p.amountIn = items[5].toUint();
        p.hasNext = items[6].toBoolean();
        if (p.hasNext) {
            p.nextModule = items[7].toAddress();
            p.nextData = items[8].toBytes();
        }
        return p;
    }
}

lib/solidity-rlp/RLPReader.sol

// SPDX-License-Identifier: Apache-2.0

/*
 * @author Hamdi Allam [email protected]
 * Please reach out with any questions or concerns
 */
pragma solidity >=0.5.10 <0.9.0;

library RLPReader {
    uint8 constant STRING_SHORT_START = 0x80;
    uint8 constant STRING_LONG_START = 0xb8;
    uint8 constant LIST_SHORT_START = 0xc0;
    uint8 constant LIST_LONG_START = 0xf8;
    uint8 constant WORD_SIZE = 32;

    struct RLPItem {
        uint256 len;
        uint256 memPtr;
    }

    struct Iterator {
        RLPItem item; // Item that's being iterated over.
        uint256 nextPtr; // Position of the next item in the list.
    }

    /*
     * @dev Returns the next element in the iteration. Reverts if it has not next element.
     * @param self The iterator.
     * @return The next element in the iteration.
     */
    function next(Iterator memory self) internal pure returns (RLPItem memory) {
        require(hasNext(self));

        uint256 ptr = self.nextPtr;
        uint256 itemLength = _itemLength(ptr);
        self.nextPtr = ptr + itemLength;

        return RLPItem(itemLength, ptr);
    }

    /*
     * @dev Returns true if the iteration has more elements.
     * @param self The iterator.
     * @return true if the iteration has more elements.
     */
    function hasNext(Iterator memory self) internal pure returns (bool) {
        RLPItem memory item = self.item;
        return self.nextPtr < item.memPtr + item.len;
    }

    /*
     * @param item RLP encoded bytes
     */
    function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
        uint256 memPtr;
        assembly {
            memPtr := add(item, 0x20)
        }

        return RLPItem(item.length, memPtr);
    }

    /*
     * @dev Create an iterator. Reverts if item is not a list.
     * @param self The RLP item.
     * @return An 'Iterator' over the item.
     */
    function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
        require(isList(self));

        uint256 ptr = self.memPtr + _payloadOffset(self.memPtr);
        return Iterator(self, ptr);
    }

    /*
     * @param the RLP item.
     */
    function rlpLen(RLPItem memory item) internal pure returns (uint256) {
        return item.len;
    }

    /*
     * @param the RLP item.
     * @return (memPtr, len) pair: location of the item's payload in memory.
     */
    function payloadLocation(RLPItem memory item) internal pure returns (uint256, uint256) {
        uint256 offset = _payloadOffset(item.memPtr);
        uint256 memPtr = item.memPtr + offset;
        uint256 len = item.len - offset; // data length
        return (memPtr, len);
    }

    /*
     * @param the RLP item.
     */
    function payloadLen(RLPItem memory item) internal pure returns (uint256) {
        (, uint256 len) = payloadLocation(item);
        return len;
    }

    /*
     * @param the RLP item containing the encoded list.
     */
    function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
        require(isList(item));

        uint256 items = numItems(item);
        RLPItem[] memory result = new RLPItem[](items);

        uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr);
        uint256 dataLen;
        for (uint256 i = 0; i < items; i++) {
            dataLen = _itemLength(memPtr);
            result[i] = RLPItem(dataLen, memPtr);
            memPtr = memPtr + dataLen;
        }

        return result;
    }

    // @return indicator whether encoded payload is a list. negate this function call for isData.
    function isList(RLPItem memory item) internal pure returns (bool) {
        if (item.len == 0) return false;

        uint8 byte0;
        uint256 memPtr = item.memPtr;
        assembly {
            byte0 := byte(0, mload(memPtr))
        }

        if (byte0 < LIST_SHORT_START) return false;
        return true;
    }

    /*
     * @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory.
     * @return keccak256 hash of RLP encoded bytes.
     */
    function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) {
        uint256 ptr = item.memPtr;
        uint256 len = item.len;
        bytes32 result;
        assembly {
            result := keccak256(ptr, len)
        }
        return result;
    }

    /*
     * @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory.
     * @return keccak256 hash of the item payload.
     */
    function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) {
        (uint256 memPtr, uint256 len) = payloadLocation(item);
        bytes32 result;
        assembly {
            result := keccak256(memPtr, len)
        }
        return result;
    }

    /** RLPItem conversions into data types **/

    // @returns raw rlp encoding in bytes
    function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
        bytes memory result = new bytes(item.len);
        if (result.length == 0) return result;

        uint256 ptr;
        assembly {
            ptr := add(0x20, result)
        }

        copy(item.memPtr, ptr, item.len);
        return result;
    }

    // any non-zero byte except "0x80" is considered true
    function toBoolean(RLPItem memory item) internal pure returns (bool) {
        require(item.len == 1);
        uint256 result;
        uint256 memPtr = item.memPtr;
        assembly {
            result := byte(0, mload(memPtr))
        }

        // SEE Github Issue #5.
        // Summary: Most commonly used RLP libraries (i.e Geth) will encode
        // "0" as "0x80" instead of as "0". We handle this edge case explicitly
        // here.
        if (result == 0 || result == STRING_SHORT_START) {
            return false;
        } else {
            return true;
        }
    }

    function toAddress(RLPItem memory item) internal pure returns (address) {
        // 1 byte for the length prefix
        require(item.len == 21);

        return address(uint160(toUint(item)));
    }

    function toUint(RLPItem memory item) internal pure returns (uint256) {
        require(item.len > 0 && item.len <= 33);

        (uint256 memPtr, uint256 len) = payloadLocation(item);

        uint256 result;
        assembly {
            result := mload(memPtr)

            // shift to the correct location if neccesary
            if lt(len, 32) {
                result := div(result, exp(256, sub(32, len)))
            }
        }

        return result;
    }

    // enforces 32 byte length
    function toUintStrict(RLPItem memory item) internal pure returns (uint256) {
        // one byte prefix
        require(item.len == 33);

        uint256 result;
        uint256 memPtr = item.memPtr + 1;
        assembly {
            result := mload(memPtr)
        }

        return result;
    }

    function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
        require(item.len > 0);

        (uint256 memPtr, uint256 len) = payloadLocation(item);
        bytes memory result = new bytes(len);

        uint256 destPtr;
        assembly {
            destPtr := add(0x20, result)
        }

        copy(memPtr, destPtr, len);
        return result;
    }

    /*
     * Private Helpers
     */

    // @return number of payload items inside an encoded list.
    function numItems(RLPItem memory item) private pure returns (uint256) {
        if (item.len == 0) return 0;

        uint256 count = 0;
        uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr);
        uint256 endPtr = item.memPtr + item.len;
        while (currPtr < endPtr) {
            currPtr = currPtr + _itemLength(currPtr); // skip over an item
            count++;
        }

        return count;
    }

    // @return entire rlp item byte length
    function _itemLength(uint256 memPtr) private pure returns (uint256) {
        uint256 itemLen;
        uint256 byte0;
        assembly {
            byte0 := byte(0, mload(memPtr))
        }

        if (byte0 < STRING_SHORT_START) {
            itemLen = 1;
        } else if (byte0 < STRING_LONG_START) {
            itemLen = byte0 - STRING_SHORT_START + 1;
        } else if (byte0 < LIST_SHORT_START) {
            assembly {
                let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
                memPtr := add(memPtr, 1) // skip over the first byte

                /* 32 byte word size */
                let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
                itemLen := add(dataLen, add(byteLen, 1))
            }
        } else if (byte0 < LIST_LONG_START) {
            itemLen = byte0 - LIST_SHORT_START + 1;
        } else {
            assembly {
                let byteLen := sub(byte0, 0xf7)
                memPtr := add(memPtr, 1)

                let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
                itemLen := add(dataLen, add(byteLen, 1))
            }
        }

        return itemLen;
    }

    // @return number of bytes until the data
    function _payloadOffset(uint256 memPtr) private pure returns (uint256) {
        uint256 byte0;
        assembly {
            byte0 := byte(0, mload(memPtr))
        }

        if (byte0 < STRING_SHORT_START) {
            return 0;
        } else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) {
            return 1;
        } else if (byte0 < LIST_SHORT_START) {
            // being explicit
            return byte0 - (STRING_LONG_START - 1) + 1;
        } else {
            return byte0 - (LIST_LONG_START - 1) + 1;
        }
    }

    /*
     * @param src Pointer to source
     * @param dest Pointer to destination
     * @param len Amount of memory to copy from the source
     */
    function copy(uint256 src, uint256 dest, uint256 len) private pure {
        if (len == 0) return;

        // copy as many word sizes as possible
        for (; len >= WORD_SIZE; len -= WORD_SIZE) {
            assembly {
                mstore(dest, mload(src))
            }

            src += WORD_SIZE;
            dest += WORD_SIZE;
        }

        if (len > 0) {
            // left over bytes. Mask is used to remove unwanted bytes from the word
            uint256 mask = 256**(WORD_SIZE - len) - 1;
            assembly {
                let srcpart := and(mload(src), not(mask)) // zero out src
                let destpart := and(mload(dest), mask) // retrieve the bytes
                mstore(dest, or(destpart, srcpart))
            }
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "evmVersion": "london",
  "remappings": [
    "solidity-rlp/=lib/solidity-rlp/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.