File size: 14,386 Bytes
f998fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
{
  "language": "Solidity",
  "sources": {
    "lib/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Gas optimized reentrancy protection for smart contracts.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/ReentrancyGuard.sol)\n/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)\nabstract contract ReentrancyGuard {\n    uint256 private locked = 1;\n\n    modifier nonReentrant() {\n        require(locked == 1, \"REENTRANCY\");\n\n        locked = 2;\n\n        _;\n\n        locked = 1;\n    }\n}\n"
    },
    "lib/SafeTransferLib.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)\n/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.\nlibrary SafeTransferLib {\n    /*///////////////////////////////////////////////////////////////\n                            ETH OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferETH(address to, uint256 amount) internal {\n        bool callStatus;\n\n        assembly {\n            // Transfer the ETH and store if it succeeded or not.\n            callStatus := call(gas(), to, amount, 0, 0, 0, 0)\n        }\n\n        require(callStatus, \"ETH_TRANSFER_FAILED\");\n    }\n\n    /*///////////////////////////////////////////////////////////////\n                           ERC20 OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferFrom(\n        address token,\n        address from,\n        address to,\n        uint256 amount\n    ) internal {\n        bool callStatus;\n\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata to memory piece by piece:\n            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.\n            mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"from\" argument.\n            mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 68), amount) // Finally append the \"amount\" argument. No mask as it's a full 32 byte value.\n\n            // Call the token and store if it succeeded or not.\n            // We use 100 because the calldata length is 4 + 32 * 3.\n            callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)\n        }\n\n        require(didLastOptionalReturnCallSucceed(callStatus), \"TRANSFER_FROM_FAILED\");\n    }\n\n    function safeTransfer(\n        address token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool callStatus;\n\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata to memory piece by piece:\n            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.\n            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Finally append the \"amount\" argument. No mask as it's a full 32 byte value.\n\n            // Call the token and store if it succeeded or not.\n            // We use 68 because the calldata length is 4 + 32 * 2.\n            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)\n        }\n\n        require(didLastOptionalReturnCallSucceed(callStatus), \"TRANSFER_FAILED\");\n    }\n\n    function safeApprove(\n        address token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool callStatus;\n\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata to memory piece by piece:\n            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector.\n            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Finally append the \"amount\" argument. No mask as it's a full 32 byte value.\n\n            // Call the token and store if it succeeded or not.\n            // We use 68 because the calldata length is 4 + 32 * 2.\n            callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)\n        }\n\n        require(didLastOptionalReturnCallSucceed(callStatus), \"APPROVE_FAILED\");\n    }\n\n    /*///////////////////////////////////////////////////////////////\n                         INTERNAL HELPER LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) {\n        assembly {\n            // Get how many bytes the call returned.\n            let returnDataSize := returndatasize()\n\n            // If the call reverted:\n            if iszero(callStatus) {\n                // Copy the revert message into memory.\n                returndatacopy(0, 0, returnDataSize)\n\n                // Revert with the same message.\n                revert(0, returnDataSize)\n            }\n\n            switch returnDataSize\n            case 32 {\n                // Copy the return data into memory.\n                returndatacopy(0, 0, returnDataSize)\n\n                // Set success to whether it returned true.\n                success := iszero(iszero(mload(0)))\n            }\n            case 0 {\n                // There was no return data.\n                success := 1\n            }\n            default {\n                // It returned some malformed input.\n                success := 0\n            }\n        }\n    }\n}\n"
    },
    "src/Owners.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\nabstract contract Owners {\n    event OwnerSet(address indexed owner, bool active);\n\n    mapping(address => bool) public owners;\n\n    modifier isOwner() {\n        require(owners[msg.sender], \"Unauthorized\");\n        _;\n    }\n\n    function _setOwner(address owner, bool active) internal virtual {\n      owners[owner] = active;\n      emit OwnerSet(owner, active);\n    }\n\n    function setOwner(address owner, bool active) external virtual isOwner {\n      _setOwner(owner, active);\n    }\n}\n"
    },
    "src/TSAggregator.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\nimport { SafeTransferLib } from \"../lib/SafeTransferLib.sol\";\nimport { ReentrancyGuard } from \"../lib/ReentrancyGuard.sol\";\nimport { Owners } from \"./Owners.sol\";\nimport { TSAggregatorTokenTransferProxy } from './TSAggregatorTokenTransferProxy.sol';\n\nabstract contract TSAggregator is Owners, ReentrancyGuard {\n    using SafeTransferLib for address;\n\n    event FeeSet(uint256 fee, address feeRecipient);\n\n    uint256 public fee;\n    address public feeRecipient;\n    TSAggregatorTokenTransferProxy public tokenTransferProxy;\n\n    constructor(address _tokenTransferProxy) {\n        _setOwner(msg.sender, true);\n        tokenTransferProxy = TSAggregatorTokenTransferProxy(_tokenTransferProxy);\n    }\n\n    // Needed for the swap router to be able to send back ETH\n    receive() external payable {}\n\n    function setFee(uint256 _fee, address _feeRecipient) external isOwner {\n        require(_fee <= 1000, \"fee can not be more than 10%\");\n        fee = _fee;\n        feeRecipient = _feeRecipient;\n        emit FeeSet(_fee, _feeRecipient);\n    }\n\n    function skimFee(uint256 amount) internal returns (uint256) {\n        uint256 amountFee = getFee(amount);\n        if (amountFee > 0) {\n            feeRecipient.safeTransferETH(amountFee);\n            amount -= amountFee;\n        }\n        return amount;\n    }\n\n    function getFee(uint256 amount) internal view returns (uint256) {\n        if (fee != 0 && feeRecipient != address(0)) {\n            return (amount * fee) / 10000;\n        }\n        return 0;\n    }\n\n    // Parse amountOutMin treating the last 2 digits as an exponent\n    // So 15e4 = 150000. This allows for compressed memos on chains\n    // with limited space like Bitcoin\n    function _parseAmountOutMin(uint256 amount) internal pure returns (uint256) {\n      return amount / 100 * (10 ** (amount % 100));\n    }\n}\n"
    },
    "src/TSAggregatorGeneric.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\nimport { SafeTransferLib } from \"../lib/SafeTransferLib.sol\";\nimport { TSAggregator } from \"./TSAggregator.sol\";\nimport { IERC20 } from \"./interfaces/IERC20.sol\";\nimport { IThorchainRouter } from \"./interfaces/IThorchainRouter.sol\";\nimport { TSAggregatorTokenTransferProxy } from './TSAggregatorTokenTransferProxy.sol';\n\ncontract TSAggregatorGeneric is TSAggregator {\n    using SafeTransferLib for address;\n\n    event SwapIn(address from, address token, uint256 amount, uint256 out, uint256 fee, address vault, string memo);\n\n    constructor(address _ttp) TSAggregator(_ttp) {\n    }\n\n    // Use 1inch's swap API endpoint to get data to send\n    // e.g. https://api.1inch.io/v4.0/1/swap?toTokenAddress=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&fromTokenAddress=0x111111111117dc0aa78b770fa6a738034120c302&amount=10000000000000000&fromAddress=0x2f8aedd149afbdb5206ecaf8b1a3abb9186c8053&slippage=1&disableEstimate=true\n    // toTokenAddress needs to be 0xeeee so ETH is sent back to swapIn\n    // fromAddress needs to be the address of this contract\n    // disableEstimate makes the API return a result even if there's no token balance in the contract\n    function swapIn(\n        address router,\n        address vault,\n        string calldata memo,\n        address token,\n        uint amount,\n        address swapRouter,\n        bytes calldata data,\n        uint deadline\n    ) public nonReentrant {\n        require(swapRouter != address(tokenTransferProxy), \"no calling ttp\");\n        tokenTransferProxy.transferTokens(token, msg.sender, address(this), amount);\n        token.safeApprove(address(swapRouter), 0); // USDT quirk\n        token.safeApprove(address(swapRouter), amount);\n\n        {\n            (bool success,) = swapRouter.call(data);\n            require(success, \"failed to swap\");\n        }\n\n        uint256 out = address(this).balance;\n        {\n            uint256 outMinusFee = skimFee(out);\n            IThorchainRouter(router).depositWithExpiry{value: outMinusFee}(\n                payable(vault),\n                address(0),\n                outMinusFee,\n                memo,\n                deadline\n            );\n        }\n        emit SwapIn(msg.sender, token, amount, out+getFee(out), getFee(out), vault, memo);\n    }\n}\n"
    },
    "src/TSAggregatorTokenTransferProxy.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\nimport { SafeTransferLib } from \"../lib/SafeTransferLib.sol\";\nimport { Owners } from \"./Owners.sol\";\n\ncontract TSAggregatorTokenTransferProxy is Owners {\n    using SafeTransferLib for address;\n\n    constructor() {\n        _setOwner(msg.sender, true);\n    }\n\n    function transferTokens(address token, address from, address to, uint256 amount) external isOwner {\n        require(from == tx.origin || _isContract(from), \"Invalid from address\");\n        token.safeTransferFrom(from, to, amount);\n    }\n\n    function _isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize, which returns 0 for contracts in\n        // construction, since the code is only stored at the end of the\n        // constructor execution.\n        uint256 size;\n        // solhint-disable-next-line no-inline-assembly\n        assembly { size := extcodesize(account) }\n        return size > 0;\n    }\n}\n"
    },
    "src/interfaces/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\ninterface IERC20 {\n    function totalSupply() external view returns (uint256);\n    function balanceOf(address account) external view returns (uint256);\n    function transfer(address recipient, uint256 amount) external returns (bool);\n    function allowance(address owner, address spender) external view returns (uint256);\n    function approve(address spender, uint256 amount) external returns (bool);\n    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n}\n"
    },
    "src/interfaces/IThorchainRouter.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\ninterface IThorchainRouter {\n    function depositWithExpiry(\n        address payable vault,\n        address asset,\n        uint amount,\n        string memory memo,\n        uint expiration\n    ) external payable;\n}\n"
    }
  },
  "settings": {
    "remappings": [
      "hardhat/=node_modules/hardhat/"
    ],
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "metadata": {
      "bytecodeHash": "ipfs"
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "evmVersion": "london",
    "libraries": {}
  }
}