diff --git a/CHANGELOG.md b/CHANGELOG.md index 84566d6518..3b126b20ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Features +- [#8472](https://github.com/blockscout/blockscout/pull/8472) - Integrate `/api/v2/bytecodes/sources:search-all` of `eth_bytecode_db` - [#8544](https://github.com/blockscout/blockscout/pull/8544) - Fix `nil` `"structLogs"` - [#8561](https://github.com/blockscout/blockscout/pull/8561), [#8564](https://github.com/blockscout/blockscout/pull/8564) - Get historical market cap data from CoinGecko - [#8386](https://github.com/blockscout/blockscout/pull/8386) - Add `owner_address_hash` to the `token_instances` diff --git a/apps/block_scout_web/lib/block_scout_web/controllers/api/v2/smart_contract_controller.ex b/apps/block_scout_web/lib/block_scout_web/controllers/api/v2/smart_contract_controller.ex index 7002858350..fa4b48b5d7 100644 --- a/apps/block_scout_web/lib/block_scout_web/controllers/api/v2/smart_contract_controller.ex +++ b/apps/block_scout_web/lib/block_scout_web/controllers/api/v2/smart_contract_controller.ex @@ -14,7 +14,6 @@ defmodule BlockScoutWeb.API.V2.SmartContractController do alias Explorer.Chain alias Explorer.Chain.SmartContract alias Explorer.SmartContract.{Reader, Writer} - alias Explorer.SmartContract.Solidity.PublishHelper @smart_contract_address_options [ necessity_by_association: %{ @@ -32,9 +31,8 @@ defmodule BlockScoutWeb.API.V2.SmartContractController do def smart_contract(conn, %{"address_hash" => address_hash_string} = params) do with {:format, {:ok, address_hash}} <- {:format, Chain.string_to_address_hash(address_hash_string)}, {:ok, false} <- AccessHelper.restricted_access?(address_hash_string, params), - _ <- PublishHelper.check_and_verify(address_hash_string), {:not_found, {:ok, address}} <- - {:not_found, Chain.find_contract_address(address_hash, @smart_contract_address_options, true)} do + {:not_found, Chain.find_contract_address(address_hash, @smart_contract_address_options, false)} do conn |> put_status(200) |> render(:smart_contract, %{address: address}) diff --git a/apps/block_scout_web/test/block_scout_web/controllers/api/v2/smart_contract_controller_test.exs b/apps/block_scout_web/test/block_scout_web/controllers/api/v2/smart_contract_controller_test.exs index 6799c10396..e93544ea64 100644 --- a/apps/block_scout_web/test/block_scout_web/controllers/api/v2/smart_contract_controller_test.exs +++ b/apps/block_scout_web/test/block_scout_web/controllers/api/v2/smart_contract_controller_test.exs @@ -303,9 +303,14 @@ defmodule BlockScoutWeb.API.V2.SmartContractControllerTest do assert correct_response == response end + end - test "automatically verify contract via Eth Bytecode Interface", %{conn: conn} do + describe "/smart-contracts/{address_hash} <> eth_bytecode_db" do + test "automatically verify contract", %{conn: conn} do {:ok, pid} = Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand.start_link([]) + old_chain_id = Application.get_env(:block_scout_web, :chain_id) + + Application.put_env(:block_scout_web, :chain_id, 5) bypass = Bypass.open() eth_bytecode_response = File.read!("./test/support/fixture/smart_contract/eth_bytecode_db_search_response.json") @@ -333,7 +338,77 @@ defmodule BlockScoutWeb.API.V2.SmartContractControllerTest do |> socket("no_id", %{}) |> subscribe_and_join(topic) - Bypass.expect_once(bypass, "POST", "/api/v2/bytecodes/sources:search", fn conn -> + Bypass.expect_once(bypass, "POST", "/api/v2/bytecodes/sources_search_all", fn conn -> + Conn.resp(conn, 200, eth_bytecode_response) + end) + + request = get(conn, "/api/v2/smart-contracts/#{Address.checksum(address.hash)}") + + assert_receive %Phoenix.Socket.Message{ + payload: %{}, + event: "smart_contract_was_verified", + topic: ^topic + }, + :timer.seconds(1) + + response = json_response(request, 200) + + assert response == + %{ + "is_self_destructed" => false, + "deployed_bytecode" => to_string(address.contract_code), + "creation_bytecode" => + "0x608060405234801561001057600080fd5b5060df8061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c146078575b600080fd5b348015605957600080fd5b5060766004803603810190808035906020019092919050505060a0565b005b348015608357600080fd5b50608a60aa565b6040518082815260200191505060405180910390f35b8060008190555050565b600080549050905600a165627a7a7230582061b7676067d537e410bb704932a9984739a959416170ea17bda192ac1218d2790029" + } + + request = get(conn, "/api/v2/smart-contracts/#{Address.checksum(address.hash)}") + assert response = json_response(request, 200) + assert %{"is_verified" => true} = response + assert %{"is_verified_via_eth_bytecode_db" => true} = response + assert %{"is_partially_verified" => true} = response + assert %{"is_fully_verified" => false} = response + + Application.put_env(:block_scout_web, :chain_id, old_chain_id) + Application.put_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour, old_env) + Bypass.down(bypass) + GenServer.stop(pid) + end + + test "automatically verify contract using search-all (ethBytecodeDbSources) endpoint", %{conn: conn} do + {:ok, pid} = Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand.start_link([]) + old_chain_id = Application.get_env(:block_scout_web, :chain_id) + + Application.put_env(:block_scout_web, :chain_id, 5) + + bypass = Bypass.open() + + eth_bytecode_response = + File.read!("./test/support/fixture/smart_contract/eth_bytecode_db_search_all_local_sources_response.json") + + old_env = Application.get_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour) + + Application.put_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour, + service_url: "http://localhost:#{bypass.port}", + enabled: true + ) + + address = insert(:contract_address) + + insert(:transaction, + created_contract_address_hash: address.hash, + input: + "0x608060405234801561001057600080fd5b5060df8061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c146078575b600080fd5b348015605957600080fd5b5060766004803603810190808035906020019092919050505060a0565b005b348015608357600080fd5b50608a60aa565b6040518082815260200191505060405180910390f35b8060008190555050565b600080549050905600a165627a7a7230582061b7676067d537e410bb704932a9984739a959416170ea17bda192ac1218d2790029" + ) + |> with_block() + + topic = "addresses:#{address.hash}" + + {:ok, _reply, _socket} = + BlockScoutWeb.UserSocketV2 + |> socket("no_id", %{}) + |> subscribe_and_join(topic) + + Bypass.expect_once(bypass, "POST", "/api/v2/bytecodes/sources_search_all", fn conn -> Conn.resp(conn, 200, eth_bytecode_response) end) @@ -363,13 +438,236 @@ defmodule BlockScoutWeb.API.V2.SmartContractControllerTest do assert %{"is_partially_verified" => true} = response assert %{"is_fully_verified" => false} = response + smart_contract = Jason.decode!(eth_bytecode_response)["ethBytecodeDbSources"] |> List.first() + assert response["compiler_settings"] == Jason.decode!(smart_contract["compilerSettings"]) + assert response["name"] == smart_contract["contractName"] + assert response["compiler_version"] == smart_contract["compilerVersion"] + assert response["file_path"] == smart_contract["fileName"] + assert response["constructor_args"] == smart_contract["constructorArguments"] + assert response["abi"] == Jason.decode!(smart_contract["abi"]) + + assert response["decoded_constructor_args"] == [ + [ + "0xc35dadb65012ec5796536bd9864ed8773abc74c4", + %{ + "internalType" => "address", + "name" => "_factory", + "type" => "address" + } + ], + [ + "0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6", + %{ + "internalType" => "address", + "name" => "_WETH", + "type" => "address" + } + ] + ] + + assert response["source_code"] == smart_contract["sourceFiles"][smart_contract["fileName"]] + + assert response["external_libraries"] == [ + %{ + "address_hash" => "0x00000000D41867734BBee4C6863D9255b2b06aC1", + "name" => "__CACHE_BREAKER__" + } + ] + + additional_sources = + for file_name <- Map.keys(smart_contract["sourceFiles"]), smart_contract["fileName"] != file_name do + %{ + "source_code" => smart_contract["sourceFiles"][file_name], + "file_path" => file_name + } + end + + assert response["additional_sources"] |> Enum.sort_by(fn x -> x["file_path"] end) == + additional_sources |> Enum.sort_by(fn x -> x["file_path"] end) + + Application.put_env(:block_scout_web, :chain_id, old_chain_id) Application.put_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour, old_env) Bypass.down(bypass) GenServer.stop(pid) end - test "check fetch interval for LookUpSmartContractSourcesOnDemand", %{conn: conn} do + test "automatically verify contract using search-all (sourcifySources) endpoint", %{conn: conn} do {:ok, pid} = Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand.start_link([]) + old_chain_id = Application.get_env(:block_scout_web, :chain_id) + + Application.put_env(:block_scout_web, :chain_id, 5) + + bypass = Bypass.open() + + eth_bytecode_response = + File.read!("./test/support/fixture/smart_contract/eth_bytecode_db_search_all_sourcify_sources_response.json") + + old_env = Application.get_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour) + + Application.put_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour, + service_url: "http://localhost:#{bypass.port}", + enabled: true + ) + + address = insert(:contract_address) + + insert(:transaction, + created_contract_address_hash: address.hash, + input: + "0x608060405234801561001057600080fd5b5060df8061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c146078575b600080fd5b348015605957600080fd5b5060766004803603810190808035906020019092919050505060a0565b005b348015608357600080fd5b50608a60aa565b6040518082815260200191505060405180910390f35b8060008190555050565b600080549050905600a165627a7a7230582061b7676067d537e410bb704932a9984739a959416170ea17bda192ac1218d2790029" + ) + |> with_block() + + topic = "addresses:#{address.hash}" + + {:ok, _reply, _socket} = + BlockScoutWeb.UserSocketV2 + |> socket("no_id", %{}) + |> subscribe_and_join(topic) + + Bypass.expect_once(bypass, "POST", "/api/v2/bytecodes/sources_search_all", fn conn -> + Conn.resp(conn, 200, eth_bytecode_response) + end) + + request = get(conn, "/api/v2/smart-contracts/#{Address.checksum(address.hash)}") + + assert_receive %Phoenix.Socket.Message{ + payload: %{}, + event: "smart_contract_was_verified", + topic: ^topic + }, + :timer.seconds(1) + + response = json_response(request, 200) + + assert response == + %{ + "is_self_destructed" => false, + "deployed_bytecode" => to_string(address.contract_code), + "creation_bytecode" => + "0x608060405234801561001057600080fd5b5060df8061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c146078575b600080fd5b348015605957600080fd5b5060766004803603810190808035906020019092919050505060a0565b005b348015608357600080fd5b50608a60aa565b6040518082815260200191505060405180910390f35b8060008190555050565b600080549050905600a165627a7a7230582061b7676067d537e410bb704932a9984739a959416170ea17bda192ac1218d2790029" + } + + request = get(conn, "/api/v2/smart-contracts/#{Address.checksum(address.hash)}") + assert response = json_response(request, 200) + assert %{"is_verified" => true} = response + assert %{"is_verified_via_eth_bytecode_db" => true} = response + assert %{"is_verified_via_sourcify" => true} = response + assert %{"is_partially_verified" => true} = response + assert %{"is_fully_verified" => false} = response + assert response["file_path"] == "Test.sol" + + Application.put_env(:block_scout_web, :chain_id, old_chain_id) + Application.put_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour, old_env) + Bypass.down(bypass) + GenServer.stop(pid) + end + + test "automatically verify contract using search-all (sourcifySources with libraries) endpoint", %{conn: conn} do + {:ok, pid} = Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand.start_link([]) + old_chain_id = Application.get_env(:block_scout_web, :chain_id) + + Application.put_env(:block_scout_web, :chain_id, 5) + + bypass = Bypass.open() + + eth_bytecode_response = + File.read!( + "./test/support/fixture/smart_contract/eth_bytecode_db_search_all_sourcify_sources_with_libs_response.json" + ) + + old_env = Application.get_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour) + + Application.put_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour, + service_url: "http://localhost:#{bypass.port}", + enabled: true + ) + + address = insert(:contract_address) + + insert(:transaction, + created_contract_address_hash: address.hash, + input: + "0x608060405234801561001057600080fd5b5060df8061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c146078575b600080fd5b348015605957600080fd5b5060766004803603810190808035906020019092919050505060a0565b005b348015608357600080fd5b50608a60aa565b6040518082815260200191505060405180910390f35b8060008190555050565b600080549050905600a165627a7a7230582061b7676067d537e410bb704932a9984739a959416170ea17bda192ac1218d2790029" + ) + |> with_block() + + topic = "addresses:#{address.hash}" + + {:ok, _reply, _socket} = + BlockScoutWeb.UserSocketV2 + |> socket("no_id", %{}) + |> subscribe_and_join(topic) + + Bypass.expect_once(bypass, "POST", "/api/v2/bytecodes/sources_search_all", fn conn -> + Conn.resp(conn, 200, eth_bytecode_response) + end) + + request = get(conn, "/api/v2/smart-contracts/#{Address.checksum(address.hash)}") + + assert_receive %Phoenix.Socket.Message{ + payload: %{}, + event: "smart_contract_was_verified", + topic: ^topic + }, + :timer.seconds(1) + + response = json_response(request, 200) + + assert response == + %{ + "is_self_destructed" => false, + "deployed_bytecode" => to_string(address.contract_code), + "creation_bytecode" => + "0x608060405234801561001057600080fd5b5060df8061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c146078575b600080fd5b348015605957600080fd5b5060766004803603810190808035906020019092919050505060a0565b005b348015608357600080fd5b50608a60aa565b6040518082815260200191505060405180910390f35b8060008190555050565b600080549050905600a165627a7a7230582061b7676067d537e410bb704932a9984739a959416170ea17bda192ac1218d2790029" + } + + request = get(conn, "/api/v2/smart-contracts/#{Address.checksum(address.hash)}") + assert response = json_response(request, 200) + + smart_contract = Jason.decode!(eth_bytecode_response)["sourcifySources"] |> List.first() + + assert %{"is_verified" => true} = response + assert %{"is_verified_via_eth_bytecode_db" => true} = response + assert %{"is_verified_via_sourcify" => true} = response + assert %{"is_partially_verified" => true} = response + assert %{"is_fully_verified" => false} = response + assert response["file_path"] == "src/zkbob/ZkBobPool.sol" + + assert response["external_libraries"] == [ + %{ + "address_hash" => "0x22DE6B06544Ee5Cd907813a04bcdEd149A2f49D2", + "name" => "lib/base58-solidity/contracts/Base58.sol:Base58" + }, + %{ + "address_hash" => "0x019d3788F00a7087234f3844CB1ceCe1F9982B7A", + "name" => "src/libraries/ZkAddress.sol:ZkAddress" + } + ] + + additional_sources = + for file_name <- Map.keys(smart_contract["sourceFiles"]), smart_contract["fileName"] != file_name do + %{ + "source_code" => smart_contract["sourceFiles"][file_name], + "file_path" => file_name + } + end + + assert response["additional_sources"] |> Enum.sort_by(fn x -> x["file_path"] end) == + additional_sources |> Enum.sort_by(fn x -> x["file_path"] end) + + Application.put_env(:block_scout_web, :chain_id, old_chain_id) + Application.put_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour, old_env) + Bypass.down(bypass) + GenServer.stop(pid) + end + + test "check fetch interval for LookUpSmartContractSourcesOnDemand and use sources:search endpoint since chain_id is unset", + %{conn: conn} do + {:ok, pid} = Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand.start_link([]) + old_chain_id = Application.get_env(:block_scout_web, :chain_id) + + Application.put_env(:block_scout_web, :chain_id, nil) bypass = Bypass.open() address = insert(:contract_address) @@ -392,7 +690,7 @@ defmodule BlockScoutWeb.API.V2.SmartContractControllerTest do Application.put_env(:explorer, Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand, fetch_interval: 0) - Bypass.expect_once(bypass, "POST", "/api/v2/bytecodes/sources:search", fn conn -> + Bypass.expect_once(bypass, "POST", "/api/v2/bytecodes/sources_search", fn conn -> Conn.resp(conn, 200, "{\"sources\": []}") end) @@ -400,7 +698,7 @@ defmodule BlockScoutWeb.API.V2.SmartContractControllerTest do :timer.sleep(10) - Bypass.expect_once(bypass, "POST", "/api/v2/bytecodes/sources:search", fn conn -> + Bypass.expect_once(bypass, "POST", "/api/v2/bytecodes/sources_search", fn conn -> Conn.resp(conn, 200, "{\"sources\": []}") end) @@ -408,7 +706,7 @@ defmodule BlockScoutWeb.API.V2.SmartContractControllerTest do :timer.sleep(10) - Bypass.expect_once(bypass, "POST", "/api/v2/bytecodes/sources:search", fn conn -> + Bypass.expect_once(bypass, "POST", "/api/v2/bytecodes/sources_search", fn conn -> Conn.resp(conn, 200, "{\"sources\": []}") end) @@ -420,6 +718,7 @@ defmodule BlockScoutWeb.API.V2.SmartContractControllerTest do _request = get(conn, "/api/v2/smart-contracts/#{Address.checksum(address.hash)}") + Application.put_env(:block_scout_web, :chain_id, old_chain_id) Application.put_env(:explorer, Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand, old_interval_env) Application.put_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour, old_env) Bypass.down(bypass) diff --git a/apps/block_scout_web/test/support/fixture/smart_contract/eth_bytecode_db_search_all_local_sources_response.json b/apps/block_scout_web/test/support/fixture/smart_contract/eth_bytecode_db_search_all_local_sources_response.json new file mode 100644 index 0000000000..69d1e1876b --- /dev/null +++ b/apps/block_scout_web/test/support/fixture/smart_contract/eth_bytecode_db_search_all_local_sources_response.json @@ -0,0 +1,59 @@ +{ + "ethBytecodeDbSources": [ + { + "fileName": "contracts/uniswapv2/UniswapV2Router02.sol", + "contractName": "UniswapV2Router02", + "compilerVersion": "v0.6.12+commit.27d51765", + "compilerSettings": "{\"libraries\":{\"\":{\"__CACHE_BREAKER__\":\"0x00000000d41867734bbee4c6863d9255b2b06ac1\"}},\"metadata\":{\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"outputSelection\":{\"*\":{\"*\":[\"abi\",\"evm.bytecode\",\"evm.deployedBytecode\",\"evm.methodIdentifiers\"]}}}", + "sourceType": "SOLIDITY", + "sourceFiles": { + "@openzeppelin/contracts/access/Ownable.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../utils/Context.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor () internal {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n", + "@openzeppelin/contracts/math/SafeMath.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b <= a, \"SafeMath: subtraction overflow\");\n return a - b;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0) return 0;\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: division by zero\");\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n return a - b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryDiv}.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a % b;\n }\n}\n", + "@openzeppelin/contracts/token/ERC20/ERC20.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../../utils/Context.sol\";\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20 {\n using SafeMath for uint256;\n\n mapping (address => uint256) private _balances;\n\n mapping (address => mapping (address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n uint8 private _decimals;\n\n /**\n * @dev Sets the values for {name} and {symbol}, initializes {decimals} with\n * a default value of 18.\n *\n * To select a different value for {decimals}, use {_setupDecimals}.\n *\n * All three of these values are immutable: they can only be set once during\n * construction.\n */\n constructor (string memory name_, string memory symbol_) public {\n _name = name_;\n _symbol = symbol_;\n _decimals = 18;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is\n * called.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual returns (uint8) {\n return _decimals;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `recipient` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * Requirements:\n *\n * - `sender` and `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n * - the caller must have allowance for ``sender``'s tokens of at least\n * `amount`.\n */\n function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n /**\n * @dev Moves tokens `amount` from `sender` to `recipient`.\n *\n * This is internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `sender` cannot be the zero address.\n * - `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n */\n function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(sender, recipient, amount);\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 amount) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Sets {decimals} to a value other than the default one of 18.\n *\n * WARNING: This function should only be called from the constructor. Most\n * applications that interact with token contracts will not expect\n * {decimals} to ever change, and may work incorrectly if it does.\n */\n function _setupDecimals(uint8 decimals_) internal virtual {\n _decimals = decimals_;\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be to transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\n}\n", + "@openzeppelin/contracts/token/ERC20/IERC20.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n", + "@openzeppelin/contracts/token/ERC20/SafeERC20.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using SafeMath for uint256;\n using Address for address;\n\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n // solhint-disable-next-line max-line-length\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n", + "@openzeppelin/contracts/utils/Address.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\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\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n", + "@openzeppelin/contracts/utils/Context.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n", + "@openzeppelin/contracts/utils/EnumerableSet.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping (bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) { // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs\n // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.\n\n bytes32 lastvalue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastvalue;\n // Update the index for the moved value\n set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n require(set._values.length > index, \"EnumerableSet: index out of bounds\");\n return set._values[index];\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n}\n", + "contracts/MasterChef.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/utils/EnumerableSet.sol\";\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"./SushiToken.sol\";\n\ninterface IMigratorChef {\n // Perform LP token migration from legacy UniswapV2 to SushiSwap.\n // Take the current LP token address and return the new LP token address.\n // Migrator should have full access to the caller's LP token.\n // Return the new LP token address.\n //\n // XXX Migrator must have allowance access to UniswapV2 LP tokens.\n // SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or\n // else something bad will happen. Traditional UniswapV2 does not\n // do that so be careful!\n function migrate(IERC20 token) external returns (IERC20);\n}\n\n// MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.\n//\n// Note that it's ownable and the owner wields tremendous power. The ownership\n// will be transferred to a governance smart contract once SUSHI is sufficiently\n// distributed and the community can show to govern itself.\n//\n// Have fun reading it. Hopefully it's bug-free. God bless.\ncontract MasterChef is Ownable {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n // Info of each user.\n struct UserInfo {\n uint256 amount; // How many LP tokens the user has provided.\n uint256 rewardDebt; // Reward debt. See explanation below.\n //\n // We do some fancy math here. Basically, any point in time, the amount of SUSHIs\n // entitled to a user but is pending to be distributed is:\n //\n // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt\n //\n // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:\n // 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.\n // 2. User receives the pending reward sent to his/her address.\n // 3. User's `amount` gets updated.\n // 4. User's `rewardDebt` gets updated.\n }\n // Info of each pool.\n struct PoolInfo {\n IERC20 lpToken; // Address of LP token contract.\n uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.\n uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.\n uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.\n }\n // The SUSHI TOKEN!\n SushiToken public sushi;\n // Dev address.\n address public devaddr;\n // Block number when bonus SUSHI period ends.\n uint256 public bonusEndBlock;\n // SUSHI tokens created per block.\n uint256 public sushiPerBlock;\n // Bonus muliplier for early sushi makers.\n uint256 public constant BONUS_MULTIPLIER = 10;\n // The migrator contract. It has a lot of power. Can only be set through governance (owner).\n IMigratorChef public migrator;\n // Info of each pool.\n PoolInfo[] public poolInfo;\n // Info of each user that stakes LP tokens.\n mapping(uint256 => mapping(address => UserInfo)) public userInfo;\n // Total allocation poitns. Must be the sum of all allocation points in all pools.\n uint256 public totalAllocPoint = 0;\n // The block number when SUSHI mining starts.\n uint256 public startBlock;\n event Deposit(address indexed user, uint256 indexed pid, uint256 amount);\n event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);\n event EmergencyWithdraw(\n address indexed user,\n uint256 indexed pid,\n uint256 amount\n );\n\n constructor(\n SushiToken _sushi,\n address _devaddr,\n uint256 _sushiPerBlock,\n uint256 _startBlock,\n uint256 _bonusEndBlock\n ) public {\n sushi = _sushi;\n devaddr = _devaddr;\n sushiPerBlock = _sushiPerBlock;\n bonusEndBlock = _bonusEndBlock;\n startBlock = _startBlock;\n }\n\n function poolLength() external view returns (uint256) {\n return poolInfo.length;\n }\n\n // Add a new lp to the pool. Can only be called by the owner.\n // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.\n function add(\n uint256 _allocPoint,\n IERC20 _lpToken,\n bool _withUpdate\n ) public onlyOwner {\n if (_withUpdate) {\n massUpdatePools();\n }\n uint256 lastRewardBlock =\n block.number > startBlock ? block.number : startBlock;\n totalAllocPoint = totalAllocPoint.add(_allocPoint);\n poolInfo.push(\n PoolInfo({\n lpToken: _lpToken,\n allocPoint: _allocPoint,\n lastRewardBlock: lastRewardBlock,\n accSushiPerShare: 0\n })\n );\n }\n\n // Update the given pool's SUSHI allocation point. Can only be called by the owner.\n function set(\n uint256 _pid,\n uint256 _allocPoint,\n bool _withUpdate\n ) public onlyOwner {\n if (_withUpdate) {\n massUpdatePools();\n }\n totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(\n _allocPoint\n );\n poolInfo[_pid].allocPoint = _allocPoint;\n }\n\n // Set the migrator contract. Can only be called by the owner.\n function setMigrator(IMigratorChef _migrator) public onlyOwner {\n migrator = _migrator;\n }\n\n // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.\n function migrate(uint256 _pid) public {\n require(address(migrator) != address(0), \"migrate: no migrator\");\n PoolInfo storage pool = poolInfo[_pid];\n IERC20 lpToken = pool.lpToken;\n uint256 bal = lpToken.balanceOf(address(this));\n lpToken.safeApprove(address(migrator), bal);\n IERC20 newLpToken = migrator.migrate(lpToken);\n require(bal == newLpToken.balanceOf(address(this)), \"migrate: bad\");\n pool.lpToken = newLpToken;\n }\n\n // Return reward multiplier over the given _from to _to block.\n function getMultiplier(uint256 _from, uint256 _to)\n public\n view\n returns (uint256)\n {\n if (_to <= bonusEndBlock) {\n return _to.sub(_from).mul(BONUS_MULTIPLIER);\n } else if (_from >= bonusEndBlock) {\n return _to.sub(_from);\n } else {\n return\n bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(\n _to.sub(bonusEndBlock)\n );\n }\n }\n\n // View function to see pending SUSHIs on frontend.\n function pendingSushi(uint256 _pid, address _user)\n external\n view\n returns (uint256)\n {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][_user];\n uint256 accSushiPerShare = pool.accSushiPerShare;\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\n if (block.number > pool.lastRewardBlock && lpSupply != 0) {\n uint256 multiplier =\n getMultiplier(pool.lastRewardBlock, block.number);\n uint256 sushiReward =\n multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(\n totalAllocPoint\n );\n accSushiPerShare = accSushiPerShare.add(\n sushiReward.mul(1e12).div(lpSupply)\n );\n }\n return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);\n }\n\n // Update reward vairables for all pools. Be careful of gas spending!\n function massUpdatePools() public {\n uint256 length = poolInfo.length;\n for (uint256 pid = 0; pid < length; ++pid) {\n updatePool(pid);\n }\n }\n\n // Update reward variables of the given pool to be up-to-date.\n function updatePool(uint256 _pid) public {\n PoolInfo storage pool = poolInfo[_pid];\n if (block.number <= pool.lastRewardBlock) {\n return;\n }\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\n if (lpSupply == 0) {\n pool.lastRewardBlock = block.number;\n return;\n }\n uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);\n uint256 sushiReward =\n multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(\n totalAllocPoint\n );\n sushi.mint(devaddr, sushiReward.div(10));\n sushi.mint(address(this), sushiReward);\n pool.accSushiPerShare = pool.accSushiPerShare.add(\n sushiReward.mul(1e12).div(lpSupply)\n );\n pool.lastRewardBlock = block.number;\n }\n\n // Deposit LP tokens to MasterChef for SUSHI allocation.\n function deposit(uint256 _pid, uint256 _amount) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n if (user.amount > 0) {\n uint256 pending =\n user.amount.mul(pool.accSushiPerShare).div(1e12).sub(\n user.rewardDebt\n );\n safeSushiTransfer(msg.sender, pending);\n }\n pool.lpToken.safeTransferFrom(\n address(msg.sender),\n address(this),\n _amount\n );\n user.amount = user.amount.add(_amount);\n user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\n emit Deposit(msg.sender, _pid, _amount);\n }\n\n // Withdraw LP tokens from MasterChef.\n function withdraw(uint256 _pid, uint256 _amount) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n require(user.amount >= _amount, \"withdraw: not good\");\n updatePool(_pid);\n uint256 pending =\n user.amount.mul(pool.accSushiPerShare).div(1e12).sub(\n user.rewardDebt\n );\n safeSushiTransfer(msg.sender, pending);\n user.amount = user.amount.sub(_amount);\n user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\n emit Withdraw(msg.sender, _pid, _amount);\n }\n\n // Withdraw without caring about rewards. EMERGENCY ONLY.\n function emergencyWithdraw(uint256 _pid) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n pool.lpToken.safeTransfer(address(msg.sender), user.amount);\n emit EmergencyWithdraw(msg.sender, _pid, user.amount);\n user.amount = 0;\n user.rewardDebt = 0;\n }\n\n // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.\n function safeSushiTransfer(address _to, uint256 _amount) internal {\n uint256 sushiBal = sushi.balanceOf(address(this));\n if (_amount > sushiBal) {\n sushi.transfer(_to, sushiBal);\n } else {\n sushi.transfer(_to, _amount);\n }\n }\n\n // Update dev address by the previous dev.\n function dev(address _devaddr) public {\n require(msg.sender == devaddr, \"dev: wut?\");\n devaddr = _devaddr;\n }\n\n // Update bonus end block\n function updateBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner {\n bonusEndBlock = _bonusEndBlock;\n }\n}\n", + "contracts/Migrator.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"./uniswapv2/interfaces/IUniswapV2Pair.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Factory.sol\";\n\n\ncontract Migrator {\n address public chef;\n address public oldFactory;\n IUniswapV2Factory public factory;\n uint256 public notBeforeBlock;\n uint256 public desiredLiquidity = uint256(-1);\n\n constructor(\n address _chef,\n address _oldFactory,\n IUniswapV2Factory _factory,\n uint256 _notBeforeBlock\n ) public {\n chef = _chef;\n oldFactory = _oldFactory;\n factory = _factory;\n notBeforeBlock = _notBeforeBlock;\n }\n\n function migrate(IUniswapV2Pair orig) public returns (IUniswapV2Pair) {\n require(msg.sender == chef, \"not from master chef\");\n require(block.number >= notBeforeBlock, \"too early to migrate\");\n require(orig.factory() == oldFactory, \"not from old factory\");\n address token0 = orig.token0();\n address token1 = orig.token1();\n IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1));\n if (pair == IUniswapV2Pair(address(0))) {\n pair = IUniswapV2Pair(factory.createPair(token0, token1));\n }\n uint256 lp = orig.balanceOf(msg.sender);\n if (lp == 0) return pair;\n desiredLiquidity = lp;\n orig.transferFrom(msg.sender, address(orig), lp);\n orig.burn(address(pair));\n pair.mint(msg.sender);\n desiredLiquidity = uint256(-1);\n return pair;\n }\n}", + "contracts/Ownable.sol": "// SPDX-License-Identifier: MIT\n// Audit on 5-Jan-2021 by Keno and BoringCrypto\n\n// P1 - P3: OK\npragma solidity 0.6.12;\n\n// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol\n// Edited by BoringCrypto\n\n// T1 - T4: OK\ncontract OwnableData {\n // V1 - V5: OK\n address public owner;\n // V1 - V5: OK\n address public pendingOwner;\n}\n\n// T1 - T4: OK\ncontract Ownable is OwnableData {\n // E1: OK\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n constructor () internal {\n owner = msg.sender;\n emit OwnershipTransferred(address(0), msg.sender);\n }\n\n // F1 - F9: OK\n // C1 - C21: OK\n function transferOwnership(address newOwner, bool direct, bool renounce) public onlyOwner {\n if (direct) {\n // Checks\n require(newOwner != address(0) || renounce, \"Ownable: zero address\");\n\n // Effects\n emit OwnershipTransferred(owner, newOwner);\n owner = newOwner;\n } else {\n // Effects\n pendingOwner = newOwner;\n }\n }\n\n // F1 - F9: OK\n // C1 - C21: OK\n function claimOwnership() public {\n address _pendingOwner = pendingOwner;\n\n // Checks\n require(msg.sender == _pendingOwner, \"Ownable: caller != pending owner\");\n\n // Effects\n emit OwnershipTransferred(owner, _pendingOwner);\n owner = _pendingOwner;\n pendingOwner = address(0);\n }\n\n // M1 - M5: OK\n // C1 - C21: OK\n modifier onlyOwner() {\n require(msg.sender == owner, \"Ownable: caller is not the owner\");\n _;\n }\n}\n", + "contracts/SushiBar.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\n\n// SushiBar is the coolest bar in town. You come in with some Sushi, and leave with more! The longer you stay, the more Sushi you get.\n//\n// This contract handles swapping to and from xSushi, SushiSwap's staking token.\ncontract SushiBar is ERC20(\"SushiBar\", \"xSUSHI\"){\n using SafeMath for uint256;\n IERC20 public sushi;\n\n // Define the Sushi token contract\n constructor(IERC20 _sushi) public {\n sushi = _sushi;\n }\n\n // Enter the bar. Pay some SUSHIs. Earn some shares.\n // Locks Sushi and mints xSushi\n function enter(uint256 _amount) public {\n // Gets the amount of Sushi locked in the contract\n uint256 totalSushi = sushi.balanceOf(address(this));\n // Gets the amount of xSushi in existence\n uint256 totalShares = totalSupply();\n // If no xSushi exists, mint it 1:1 to the amount put in\n if (totalShares == 0 || totalSushi == 0) {\n _mint(msg.sender, _amount);\n } \n // Calculate and mint the amount of xSushi the Sushi is worth. The ratio will change overtime, as xSushi is burned/minted and Sushi deposited + gained from fees / withdrawn.\n else {\n uint256 what = _amount.mul(totalShares).div(totalSushi);\n _mint(msg.sender, what);\n }\n // Lock the Sushi in the contract\n sushi.transferFrom(msg.sender, address(this), _amount);\n }\n\n // Leave the bar. Claim back your SUSHIs.\n // Unlocks the staked + gained Sushi and burns xSushi\n function leave(uint256 _share) public {\n // Gets the amount of xSushi in existence\n uint256 totalShares = totalSupply();\n // Calculates the amount of Sushi the xSushi is worth\n uint256 what = _share.mul(sushi.balanceOf(address(this))).div(totalShares);\n _burn(msg.sender, _share);\n sushi.transfer(msg.sender, what);\n }\n}\n", + "contracts/SushiMaker.sol": "// SPDX-License-Identifier: MIT\n\n// P1 - P3: OK\npragma solidity 0.6.12;\nimport \"./libraries/SafeMath.sol\";\nimport \"./libraries/SafeERC20.sol\";\n\nimport \"./uniswapv2/interfaces/IUniswapV2ERC20.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Pair.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Factory.sol\";\n\nimport \"./Ownable.sol\";\n\n// SushiMaker is MasterChef's left hand and kinda a wizard. He can cook up Sushi from pretty much anything!\n// This contract handles \"serving up\" rewards for xSushi holders by trading tokens collected from fees for Sushi.\n\n// T1 - T4: OK\ncontract SushiMaker is Ownable {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n // V1 - V5: OK\n IUniswapV2Factory public immutable factory;\n //0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac\n // V1 - V5: OK\n address public immutable bar;\n //0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272\n // V1 - V5: OK\n address private immutable sushi;\n //0x6B3595068778DD592e39A122f4f5a5cF09C90fE2\n // V1 - V5: OK\n address private immutable weth;\n //0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\n\n // V1 - V5: OK\n mapping(address => address) internal _bridges;\n\n // E1: OK\n event LogBridgeSet(address indexed token, address indexed bridge);\n // E1: OK\n event LogConvert(\n address indexed server,\n address indexed token0,\n address indexed token1,\n uint256 amount0,\n uint256 amount1,\n uint256 amountSUSHI\n );\n\n constructor(\n address _factory,\n address _bar,\n address _sushi,\n address _weth\n ) public {\n factory = IUniswapV2Factory(_factory);\n bar = _bar;\n sushi = _sushi;\n weth = _weth;\n }\n\n // F1 - F10: OK\n // C1 - C24: OK\n function bridgeFor(address token) public view returns (address bridge) {\n bridge = _bridges[token];\n if (bridge == address(0)) {\n bridge = weth;\n }\n }\n\n // F1 - F10: OK\n // C1 - C24: OK\n function setBridge(address token, address bridge) external onlyOwner {\n // Checks\n require(\n token != sushi && token != weth && token != bridge,\n \"SushiMaker: Invalid bridge\"\n );\n\n // Effects\n _bridges[token] = bridge;\n emit LogBridgeSet(token, bridge);\n }\n\n // M1 - M5: OK\n // C1 - C24: OK\n // C6: It's not a fool proof solution, but it prevents flash loans, so here it's ok to use tx.origin\n modifier onlyEOA() {\n // Try to make flash-loan exploit harder to do by only allowing externally owned addresses.\n require(msg.sender == tx.origin, \"SushiMaker: must use EOA\");\n _;\n }\n\n // F1 - F10: OK\n // F3: _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple\n // F6: There is an exploit to add lots of SUSHI to the bar, run convert, then remove the SUSHI again.\n // As the size of the SushiBar has grown, this requires large amounts of funds and isn't super profitable anymore\n // The onlyEOA modifier prevents this being done with a flash loan.\n // C1 - C24: OK\n function convert(address token0, address token1) external onlyEOA() {\n _convert(token0, token1);\n }\n\n // F1 - F10: OK, see convert\n // C1 - C24: OK\n // C3: Loop is under control of the caller\n function convertMultiple(\n address[] calldata token0,\n address[] calldata token1\n ) external onlyEOA() {\n // TODO: This can be optimized a fair bit, but this is safer and simpler for now\n uint256 len = token0.length;\n for (uint256 i = 0; i < len; i++) {\n _convert(token0[i], token1[i]);\n }\n }\n\n // F1 - F10: OK\n // C1- C24: OK\n function _convert(address token0, address token1) internal {\n // Interactions\n // S1 - S4: OK\n IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1));\n require(address(pair) != address(0), \"SushiMaker: Invalid pair\");\n // balanceOf: S1 - S4: OK\n // transfer: X1 - X5: OK\n IERC20(address(pair)).safeTransfer(\n address(pair),\n pair.balanceOf(address(this))\n );\n // X1 - X5: OK\n (uint256 amount0, uint256 amount1) = pair.burn(address(this));\n if (token0 != pair.token0()) {\n (amount0, amount1) = (amount1, amount0);\n }\n emit LogConvert(\n msg.sender,\n token0,\n token1,\n amount0,\n amount1,\n _convertStep(token0, token1, amount0, amount1)\n );\n }\n\n // F1 - F10: OK\n // C1 - C24: OK\n // All safeTransfer, _swap, _toSUSHI, _convertStep: X1 - X5: OK\n function _convertStep(\n address token0,\n address token1,\n uint256 amount0,\n uint256 amount1\n ) internal returns (uint256 sushiOut) {\n // Interactions\n if (token0 == token1) {\n uint256 amount = amount0.add(amount1);\n if (token0 == sushi) {\n IERC20(sushi).safeTransfer(bar, amount);\n sushiOut = amount;\n } else if (token0 == weth) {\n sushiOut = _toSUSHI(weth, amount);\n } else {\n address bridge = bridgeFor(token0);\n amount = _swap(token0, bridge, amount, address(this));\n sushiOut = _convertStep(bridge, bridge, amount, 0);\n }\n } else if (token0 == sushi) {\n // eg. SUSHI - ETH\n IERC20(sushi).safeTransfer(bar, amount0);\n sushiOut = _toSUSHI(token1, amount1).add(amount0);\n } else if (token1 == sushi) {\n // eg. USDT - SUSHI\n IERC20(sushi).safeTransfer(bar, amount1);\n sushiOut = _toSUSHI(token0, amount0).add(amount1);\n } else if (token0 == weth) {\n // eg. ETH - USDC\n sushiOut = _toSUSHI(\n weth,\n _swap(token1, weth, amount1, address(this)).add(amount0)\n );\n } else if (token1 == weth) {\n // eg. USDT - ETH\n sushiOut = _toSUSHI(\n weth,\n _swap(token0, weth, amount0, address(this)).add(amount1)\n );\n } else {\n // eg. MIC - USDT\n address bridge0 = bridgeFor(token0);\n address bridge1 = bridgeFor(token1);\n if (bridge0 == token1) {\n // eg. MIC - USDT - and bridgeFor(MIC) = USDT\n sushiOut = _convertStep(\n bridge0,\n token1,\n _swap(token0, bridge0, amount0, address(this)),\n amount1\n );\n } else if (bridge1 == token0) {\n // eg. WBTC - DSD - and bridgeFor(DSD) = WBTC\n sushiOut = _convertStep(\n token0,\n bridge1,\n amount0,\n _swap(token1, bridge1, amount1, address(this))\n );\n } else {\n sushiOut = _convertStep(\n bridge0,\n bridge1, // eg. USDT - DSD - and bridgeFor(DSD) = WBTC\n _swap(token0, bridge0, amount0, address(this)),\n _swap(token1, bridge1, amount1, address(this))\n );\n }\n }\n }\n\n // F1 - F10: OK\n // C1 - C24: OK\n // All safeTransfer, swap: X1 - X5: OK\n function _swap(\n address fromToken,\n address toToken,\n uint256 amountIn,\n address to\n ) internal returns (uint256 amountOut) {\n // Checks\n // X1 - X5: OK\n IUniswapV2Pair pair =\n IUniswapV2Pair(factory.getPair(fromToken, toToken));\n require(address(pair) != address(0), \"SushiMaker: Cannot convert\");\n\n // Interactions\n // X1 - X5: OK\n (uint256 reserve0, uint256 reserve1, ) = pair.getReserves();\n uint256 amountInWithFee = amountIn.mul(997);\n if (fromToken == pair.token0()) {\n amountOut =\n amountInWithFee.mul(reserve1) /\n reserve0.mul(1000).add(amountInWithFee);\n IERC20(fromToken).safeTransfer(address(pair), amountIn);\n pair.swap(0, amountOut, to, new bytes(0));\n // TODO: Add maximum slippage?\n } else {\n amountOut =\n amountInWithFee.mul(reserve0) /\n reserve1.mul(1000).add(amountInWithFee);\n IERC20(fromToken).safeTransfer(address(pair), amountIn);\n pair.swap(amountOut, 0, to, new bytes(0));\n // TODO: Add maximum slippage?\n }\n }\n\n // F1 - F10: OK\n // C1 - C24: OK\n function _toSUSHI(address token, uint256 amountIn)\n internal\n returns (uint256 amountOut)\n {\n // X1 - X5: OK\n amountOut = _swap(token, sushi, amountIn, bar);\n }\n}\n", + "contracts/SushiMakerKashi.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\nimport \"./libraries/SafeMath.sol\";\nimport \"./libraries/SafeERC20.sol\";\n\nimport \"./uniswapv2/interfaces/IUniswapV2Pair.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Factory.sol\";\n\nimport \"./Ownable.sol\";\n\ninterface IBentoBoxWithdraw {\n function withdraw(\n IERC20 token_,\n address from,\n address to,\n uint256 amount,\n uint256 share\n ) external returns (uint256 amountOut, uint256 shareOut);\n}\n\ninterface IKashiWithdrawFee {\n function asset() external view returns (address);\n function balanceOf(address account) external view returns (uint256);\n function withdrawFees() external;\n function removeAsset(address to, uint256 fraction) external returns (uint256 share);\n}\n\n// SushiMakerKashi is MasterChef's left hand and kinda a wizard. He can cook up Sushi from pretty much anything!\n// This contract handles \"serving up\" rewards for xSushi holders by trading tokens collected from Kashi fees for Sushi.\ncontract SushiMakerKashi is Ownable {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n IUniswapV2Factory private immutable factory;\n //0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac\n address private immutable bar;\n //0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272\n IBentoBoxWithdraw private immutable bentoBox;\n //0xF5BCE5077908a1b7370B9ae04AdC565EBd643966 \n address private immutable sushi;\n //0x6B3595068778DD592e39A122f4f5a5cF09C90fE2\n address private immutable weth;\n //0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\n bytes32 private immutable pairCodeHash;\n //0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303\n\n mapping(address => address) private _bridges;\n\n event LogBridgeSet(address indexed token, address indexed bridge);\n event LogConvert(\n address indexed server,\n address indexed token0,\n uint256 amount0,\n uint256 amountBENTO,\n uint256 amountSUSHI\n );\n\n constructor(\n IUniswapV2Factory _factory,\n address _bar,\n IBentoBoxWithdraw _bentoBox,\n address _sushi,\n address _weth,\n bytes32 _pairCodeHash\n ) public {\n factory = _factory;\n bar = _bar;\n bentoBox = _bentoBox;\n sushi = _sushi;\n weth = _weth;\n pairCodeHash = _pairCodeHash;\n }\n\n function setBridge(address token, address bridge) external onlyOwner {\n // Checks\n require(\n token != sushi && token != weth && token != bridge,\n \"Maker: Invalid bridge\"\n );\n // Effects\n _bridges[token] = bridge;\n emit LogBridgeSet(token, bridge);\n }\n\n modifier onlyEOA() {\n // Try to make flash-loan exploit harder to do by only allowing externally-owned addresses.\n require(msg.sender == tx.origin, \"Maker: Must use EOA\");\n _;\n }\n\n function convert(IKashiWithdrawFee kashiPair) external onlyEOA {\n _convert(kashiPair);\n }\n\n function convertMultiple(IKashiWithdrawFee[] calldata kashiPair) external onlyEOA {\n for (uint256 i = 0; i < kashiPair.length; i++) {\n _convert(kashiPair[i]);\n }\n }\n\n function _convert(IKashiWithdrawFee kashiPair) private {\n // update Kashi fees for this Maker contract (`feeTo`)\n kashiPair.withdrawFees();\n\n // convert updated Kashi balance to Bento shares\n uint256 bentoShares = kashiPair.removeAsset(address(this), kashiPair.balanceOf(address(this)));\n\n // convert Bento shares to underlying Kashi asset (`token0`) balance (`amount0`) for Maker\n address token0 = kashiPair.asset();\n (uint256 amount0, ) = bentoBox.withdraw(IERC20(token0), address(this), address(this), 0, bentoShares);\n\n emit LogConvert(\n msg.sender,\n token0,\n amount0,\n bentoShares,\n _convertStep(token0, amount0)\n );\n }\n\n function _convertStep(address token0, uint256 amount0) private returns (uint256 sushiOut) {\n if (token0 == sushi) {\n IERC20(token0).safeTransfer(bar, amount0);\n sushiOut = amount0;\n } else if (token0 == weth) {\n sushiOut = _swap(token0, sushi, amount0, bar);\n } else {\n address bridge = _bridges[token0];\n if (bridge == address(0)) {\n bridge = weth;\n }\n uint256 amountOut = _swap(token0, bridge, amount0, address(this));\n sushiOut = _convertStep(bridge, amountOut);\n }\n }\n\n function _swap(\n address fromToken,\n address toToken,\n uint256 amountIn,\n address to\n ) private returns (uint256 amountOut) {\n (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);\n IUniswapV2Pair pair =\n IUniswapV2Pair(\n uint256(\n keccak256(abi.encodePacked(hex\"ff\", factory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))\n )\n );\n \n (uint256 reserve0, uint256 reserve1, ) = pair.getReserves();\n uint256 amountInWithFee = amountIn.mul(997);\n \n if (toToken > fromToken) {\n amountOut =\n amountInWithFee.mul(reserve1) /\n reserve0.mul(1000).add(amountInWithFee);\n IERC20(fromToken).safeTransfer(address(pair), amountIn);\n pair.swap(0, amountOut, to, \"\");\n } else {\n amountOut =\n amountInWithFee.mul(reserve0) /\n reserve1.mul(1000).add(amountInWithFee);\n IERC20(fromToken).safeTransfer(address(pair), amountIn);\n pair.swap(amountOut, 0, to, \"\");\n }\n }\n}\n", + "contracts/SushiRoll.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Pair.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Router01.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Factory.sol\";\nimport \"./uniswapv2/libraries/UniswapV2Library.sol\";\n\n// SushiRoll helps your migrate your existing Uniswap LP tokens to SushiSwap LP ones\ncontract SushiRoll {\n using SafeERC20 for IERC20;\n\n IUniswapV2Router01 public oldRouter;\n IUniswapV2Router01 public router;\n\n constructor(IUniswapV2Router01 _oldRouter, IUniswapV2Router01 _router) public {\n oldRouter = _oldRouter;\n router = _router;\n }\n\n function migrateWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public {\n IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB));\n pair.permit(msg.sender, address(this), liquidity, deadline, v, r, s);\n\n migrate(tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline);\n }\n\n // msg.sender should have approved 'liquidity' amount of LP token of 'tokenA' and 'tokenB'\n function migrate(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n uint256 deadline\n ) public {\n require(deadline >= block.timestamp, 'SushiSwap: EXPIRED');\n\n // Remove liquidity from the old router with permit\n (uint256 amountA, uint256 amountB) = removeLiquidity(\n tokenA,\n tokenB,\n liquidity,\n amountAMin,\n amountBMin,\n deadline\n );\n\n // Add liquidity to the new router\n (uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB);\n\n // Send remaining tokens to msg.sender\n if (amountA > pooledAmountA) {\n IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA);\n }\n if (amountB > pooledAmountB) {\n IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB);\n }\n }\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n uint256 deadline\n ) internal returns (uint256 amountA, uint256 amountB) {\n IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB));\n pair.transferFrom(msg.sender, address(pair), liquidity);\n (uint256 amount0, uint256 amount1) = pair.burn(address(this));\n (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);\n (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);\n require(amountA >= amountAMin, 'SushiRoll: INSUFFICIENT_A_AMOUNT');\n require(amountB >= amountBMin, 'SushiRoll: INSUFFICIENT_B_AMOUNT');\n }\n\n // calculates the CREATE2 address for a pair without making any external calls\n function pairForOldRouter(address tokenA, address tokenB) internal view returns (address pair) {\n (address token0, address token1) = UniswapV2Library.sortTokens(tokenA, tokenB);\n pair = address(uint(keccak256(abi.encodePacked(\n hex'ff',\n oldRouter.factory(),\n keccak256(abi.encodePacked(token0, token1)),\n hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash\n ))));\n }\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired\n ) internal returns (uint amountA, uint amountB) {\n (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired);\n address pair = UniswapV2Library.pairFor(router.factory(), tokenA, tokenB);\n IERC20(tokenA).safeTransfer(pair, amountA);\n IERC20(tokenB).safeTransfer(pair, amountB);\n IUniswapV2Pair(pair).mint(msg.sender);\n }\n\n function _addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired\n ) internal returns (uint256 amountA, uint256 amountB) {\n // create the pair if it doesn't exist yet\n IUniswapV2Factory factory = IUniswapV2Factory(router.factory());\n if (factory.getPair(tokenA, tokenB) == address(0)) {\n factory.createPair(tokenA, tokenB);\n }\n (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB);\n if (reserveA == 0 && reserveB == 0) {\n (amountA, amountB) = (amountADesired, amountBDesired);\n } else {\n uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\n if (amountBOptimal <= amountBDesired) {\n (amountA, amountB) = (amountADesired, amountBOptimal);\n } else {\n uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\n assert(amountAOptimal <= amountADesired);\n (amountA, amountB) = (amountAOptimal, amountBDesired);\n }\n }\n }\n}\n", + "contracts/SushiToken.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\n// WARNING: There is a known vuln contained within this contract related to vote delegation, \n// it's NOT recommmended to use this in production. \n\n// SushiToken with Governance.\ncontract SushiToken is ERC20(\"Powswap\", \"POW\"), Ownable {\n /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).\n function mint(address _to, uint256 _amount) public onlyOwner {\n _mint(_to, _amount);\n _moveDelegates(address(0), _delegates[_to], _amount);\n }\n\n // Copied and modified from YAM code:\n // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol\n // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol\n // Which is copied and modified from COMPOUND:\n // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol\n\n /// @notice A record of each accounts delegate\n mapping (address => address) internal _delegates;\n\n /// @notice A checkpoint for marking number of votes from a given block\n struct Checkpoint {\n uint32 fromBlock;\n uint256 votes;\n }\n\n /// @notice A record of votes checkpoints for each account, by index\n mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;\n\n /// @notice The number of checkpoints for each account\n mapping (address => uint32) public numCheckpoints;\n\n /// @notice The EIP-712 typehash for the contract's domain\n bytes32 public constant DOMAIN_TYPEHASH = keccak256(\"EIP712Domain(string name,uint256 chainId,address verifyingContract)\");\n\n /// @notice The EIP-712 typehash for the delegation struct used by the contract\n bytes32 public constant DELEGATION_TYPEHASH = keccak256(\"Delegation(address delegatee,uint256 nonce,uint256 expiry)\");\n\n /// @notice A record of states for signing / validating signatures\n mapping (address => uint) public nonces;\n\n /// @notice An event thats emitted when an account changes its delegate\n event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);\n\n /// @notice An event thats emitted when a delegate account's vote balance changes\n event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);\n\n /**\n * @notice Delegate votes from `msg.sender` to `delegatee`\n * @param delegator The address to get delegatee for\n */\n function delegates(address delegator)\n external\n view\n returns (address)\n {\n return _delegates[delegator];\n }\n\n /**\n * @notice Delegate votes from `msg.sender` to `delegatee`\n * @param delegatee The address to delegate votes to\n */\n function delegate(address delegatee) external {\n return _delegate(msg.sender, delegatee);\n }\n\n /**\n * @notice Delegates votes from signatory to `delegatee`\n * @param delegatee The address to delegate votes to\n * @param nonce The contract state required to match the signature\n * @param expiry The time at which to expire the signature\n * @param v The recovery byte of the signature\n * @param r Half of the ECDSA signature pair\n * @param s Half of the ECDSA signature pair\n */\n function delegateBySig(\n address delegatee,\n uint nonce,\n uint expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n )\n external\n {\n bytes32 domainSeparator = keccak256(\n abi.encode(\n DOMAIN_TYPEHASH,\n keccak256(bytes(name())),\n getChainId(),\n address(this)\n )\n );\n\n bytes32 structHash = keccak256(\n abi.encode(\n DELEGATION_TYPEHASH,\n delegatee,\n nonce,\n expiry\n )\n );\n\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n domainSeparator,\n structHash\n )\n );\n\n address signatory = ecrecover(digest, v, r, s);\n require(signatory != address(0), \"SUSHI::delegateBySig: invalid signature\");\n require(nonce == nonces[signatory]++, \"SUSHI::delegateBySig: invalid nonce\");\n require(now <= expiry, \"SUSHI::delegateBySig: signature expired\");\n return _delegate(signatory, delegatee);\n }\n\n /**\n * @notice Gets the current votes balance for `account`\n * @param account The address to get votes balance\n * @return The number of current votes for `account`\n */\n function getCurrentVotes(address account)\n external\n view\n returns (uint256)\n {\n uint32 nCheckpoints = numCheckpoints[account];\n return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;\n }\n\n /**\n * @notice Determine the prior number of votes for an account as of a block number\n * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.\n * @param account The address of the account to check\n * @param blockNumber The block number to get the vote balance at\n * @return The number of votes the account had as of the given block\n */\n function getPriorVotes(address account, uint blockNumber)\n external\n view\n returns (uint256)\n {\n require(blockNumber < block.number, \"SUSHI::getPriorVotes: not yet determined\");\n\n uint32 nCheckpoints = numCheckpoints[account];\n if (nCheckpoints == 0) {\n return 0;\n }\n\n // First check most recent balance\n if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {\n return checkpoints[account][nCheckpoints - 1].votes;\n }\n\n // Next check implicit zero balance\n if (checkpoints[account][0].fromBlock > blockNumber) {\n return 0;\n }\n\n uint32 lower = 0;\n uint32 upper = nCheckpoints - 1;\n while (upper > lower) {\n uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow\n Checkpoint memory cp = checkpoints[account][center];\n if (cp.fromBlock == blockNumber) {\n return cp.votes;\n } else if (cp.fromBlock < blockNumber) {\n lower = center;\n } else {\n upper = center - 1;\n }\n }\n return checkpoints[account][lower].votes;\n }\n\n function _delegate(address delegator, address delegatee)\n internal\n {\n address currentDelegate = _delegates[delegator];\n uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled);\n _delegates[delegator] = delegatee;\n\n emit DelegateChanged(delegator, currentDelegate, delegatee);\n\n _moveDelegates(currentDelegate, delegatee, delegatorBalance);\n }\n\n function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {\n if (srcRep != dstRep && amount > 0) {\n if (srcRep != address(0)) {\n // decrease old representative\n uint32 srcRepNum = numCheckpoints[srcRep];\n uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;\n uint256 srcRepNew = srcRepOld.sub(amount);\n _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);\n }\n\n if (dstRep != address(0)) {\n // increase new representative\n uint32 dstRepNum = numCheckpoints[dstRep];\n uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;\n uint256 dstRepNew = dstRepOld.add(amount);\n _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);\n }\n }\n }\n\n function _writeCheckpoint(\n address delegatee,\n uint32 nCheckpoints,\n uint256 oldVotes,\n uint256 newVotes\n )\n internal\n {\n uint32 blockNumber = safe32(block.number, \"SUSHI::_writeCheckpoint: block number exceeds 32 bits\");\n\n if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {\n checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;\n } else {\n checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);\n numCheckpoints[delegatee] = nCheckpoints + 1;\n }\n\n emit DelegateVotesChanged(delegatee, oldVotes, newVotes);\n }\n\n function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {\n require(n < 2**32, errorMessage);\n return uint32(n);\n }\n\n function getChainId() internal pure returns (uint) {\n uint256 chainId;\n assembly { chainId := chainid() }\n return chainId;\n }\n}", + "contracts/governance/Timelock.sol": "// SPDX-License-Identifier: MIT\n\n// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol\n// Copyright 2020 Compound Labs, Inc.\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Ctrl+f for XXX to see all the modifications.\n\n// XXX: pragma solidity ^0.5.16;\npragma solidity 0.6.12;\n\n// XXX: import \"./SafeMath.sol\";\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\n\ncontract Timelock {\n using SafeMath for uint;\n\n event NewAdmin(address indexed newAdmin);\n event NewPendingAdmin(address indexed newPendingAdmin);\n event NewDelay(uint indexed newDelay);\n event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);\n event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);\n event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);\n\n uint public constant GRACE_PERIOD = 14 days;\n uint public constant MINIMUM_DELAY = 2 days;\n uint public constant MAXIMUM_DELAY = 30 days;\n\n address public admin;\n address public pendingAdmin;\n uint public delay;\n bool public admin_initialized;\n\n mapping (bytes32 => bool) public queuedTransactions;\n\n\n constructor(address admin_, uint delay_) public {\n require(delay_ >= MINIMUM_DELAY, \"Timelock::constructor: Delay must exceed minimum delay.\");\n require(delay_ <= MAXIMUM_DELAY, \"Timelock::constructor: Delay must not exceed maximum delay.\");\n\n admin = admin_;\n delay = delay_;\n admin_initialized = false;\n }\n\n // XXX: function() external payable { }\n receive() external payable { }\n\n function setDelay(uint delay_) public {\n require(msg.sender == address(this), \"Timelock::setDelay: Call must come from Timelock.\");\n require(delay_ >= MINIMUM_DELAY, \"Timelock::setDelay: Delay must exceed minimum delay.\");\n require(delay_ <= MAXIMUM_DELAY, \"Timelock::setDelay: Delay must not exceed maximum delay.\");\n delay = delay_;\n\n emit NewDelay(delay);\n }\n\n function acceptAdmin() public {\n require(msg.sender == pendingAdmin, \"Timelock::acceptAdmin: Call must come from pendingAdmin.\");\n admin = msg.sender;\n pendingAdmin = address(0);\n\n emit NewAdmin(admin);\n }\n\n function setPendingAdmin(address pendingAdmin_) public {\n // allows one time setting of admin for deployment purposes\n if (admin_initialized) {\n require(msg.sender == address(this), \"Timelock::setPendingAdmin: Call must come from Timelock.\");\n } else {\n require(msg.sender == admin, \"Timelock::setPendingAdmin: First call must come from admin.\");\n admin_initialized = true;\n }\n pendingAdmin = pendingAdmin_;\n\n emit NewPendingAdmin(pendingAdmin);\n }\n\n function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {\n require(msg.sender == admin, \"Timelock::queueTransaction: Call must come from admin.\");\n require(eta >= getBlockTimestamp().add(delay), \"Timelock::queueTransaction: Estimated execution block must satisfy delay.\");\n\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n queuedTransactions[txHash] = true;\n\n emit QueueTransaction(txHash, target, value, signature, data, eta);\n return txHash;\n }\n\n function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {\n require(msg.sender == admin, \"Timelock::cancelTransaction: Call must come from admin.\");\n\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n queuedTransactions[txHash] = false;\n\n emit CancelTransaction(txHash, target, value, signature, data, eta);\n }\n\n function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {\n require(msg.sender == admin, \"Timelock::executeTransaction: Call must come from admin.\");\n\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n require(queuedTransactions[txHash], \"Timelock::executeTransaction: Transaction hasn't been queued.\");\n require(getBlockTimestamp() >= eta, \"Timelock::executeTransaction: Transaction hasn't surpassed time lock.\");\n require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), \"Timelock::executeTransaction: Transaction is stale.\");\n\n queuedTransactions[txHash] = false;\n\n bytes memory callData;\n\n if (bytes(signature).length == 0) {\n callData = data;\n } else {\n callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);\n }\n\n // solium-disable-next-line security/no-call-value\n (bool success, bytes memory returnData) = target.call.value(value)(callData);\n require(success, \"Timelock::executeTransaction: Transaction execution reverted.\");\n\n emit ExecuteTransaction(txHash, target, value, signature, data, eta);\n\n return returnData;\n }\n\n function getBlockTimestamp() internal view returns (uint) {\n // solium-disable-next-line security/no-block-members\n return block.timestamp;\n }\n}", + "contracts/interfaces/IERC20.sol": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.12;\n\ninterface IERC20 {\n function totalSupply() external view returns (uint256);\n function balanceOf(address account) external view returns (uint256);\n function allowance(address owner, address spender) external view returns (uint256);\n function approve(address spender, uint256 amount) external returns (bool);\n event Transfer(address indexed from, address indexed to, uint256 value);\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n // EIP 2612\n function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;\n}", + "contracts/libraries/SafeERC20.sol": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.12;\n\nimport \"../interfaces/IERC20.sol\";\n\nlibrary SafeERC20 {\n function safeSymbol(IERC20 token) internal view returns(string memory) {\n (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41));\n return success && data.length > 0 ? abi.decode(data, (string)) : \"???\";\n }\n\n function safeName(IERC20 token) internal view returns(string memory) {\n (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03));\n return success && data.length > 0 ? abi.decode(data, (string)) : \"???\";\n }\n\n function safeDecimals(IERC20 token) public view returns (uint8) {\n (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567));\n return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;\n }\n\n function safeTransfer(IERC20 token, address to, uint256 amount) internal {\n (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount));\n require(success && (data.length == 0 || abi.decode(data, (bool))), \"SafeERC20: Transfer failed\");\n }\n\n function safeTransferFrom(IERC20 token, address from, uint256 amount) internal {\n (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, address(this), amount));\n require(success && (data.length == 0 || abi.decode(data, (bool))), \"SafeERC20: TransferFrom failed\");\n }\n}\n", + "contracts/libraries/SafeMath.sol": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.12;\n// a library for performing overflow-safe math, updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math)\nlibrary SafeMath {\n function add(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a + b) >= b, \"SafeMath: Add Overflow\");}\n function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a - b) <= a, \"SafeMath: Underflow\");}\n function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {require(b == 0 || (c = a * b)/b == a, \"SafeMath: Mul Overflow\");}\n function to128(uint256 a) internal pure returns (uint128 c) {\n require(a <= uint128(-1), \"SafeMath: uint128 Overflow\");\n c = uint128(a);\n }\n}\n\nlibrary SafeMath128 {\n function add(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a + b) >= b, \"SafeMath: Add Overflow\");}\n function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a - b) <= a, \"SafeMath: Underflow\");}\n}\n", + "contracts/mocks/ERC20Mock.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract ERC20Mock is ERC20 {\n constructor(\n string memory name,\n string memory symbol,\n uint256 supply\n ) public ERC20(name, symbol) {\n _mint(msg.sender, supply);\n }\n}", + "contracts/mocks/SushiMakerExploitMock.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"../SushiMaker.sol\";\n\ncontract SushiMakerExploitMock {\n SushiMaker public immutable sushiMaker;\n constructor (address _sushiMaker) public{\n sushiMaker = SushiMaker(_sushiMaker);\n } \n function convert(address token0, address token1) external {\n sushiMaker.convert(token0, token1);\n }\n}", + "contracts/mocks/SushiMakerKashiExploitMock.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"../SushiMakerKashi.sol\";\n\ncontract SushiMakerKashiExploitMock {\n SushiMakerKashi public immutable sushiMaker;\n \n constructor(address _sushiMaker) public {\n sushiMaker = SushiMakerKashi(_sushiMaker);\n } \n \n function convert(IKashiWithdrawFee kashiPair) external {\n sushiMaker.convert(kashiPair);\n }\n}\n", + "contracts/mocks/SushiSwapFactoryMock.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"../uniswapv2/UniswapV2Factory.sol\";\n\ncontract SushiSwapFactoryMock is UniswapV2Factory {\n constructor(address _feeToSetter) public UniswapV2Factory(_feeToSetter) {}\n}", + "contracts/mocks/SushiSwapPairMock.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"../uniswapv2/UniswapV2Pair.sol\";\n\ncontract SushiSwapPairMock is UniswapV2Pair {\n constructor() public UniswapV2Pair() {}\n}", + "contracts/uniswapv2/UniswapV2ERC20.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\nimport './libraries/SafeMath.sol';\n\ncontract UniswapV2ERC20 {\n using SafeMathUniswap for uint;\n\n string public constant name = 'SushiSwap LP Token';\n string public constant symbol = 'SLP';\n uint8 public constant decimals = 18;\n uint public totalSupply;\n mapping(address => uint) public balanceOf;\n mapping(address => mapping(address => uint)) public allowance;\n\n bytes32 public DOMAIN_SEPARATOR;\n // keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;\n mapping(address => uint) public nonces;\n\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n constructor() public {\n uint chainId;\n assembly {\n chainId := chainid()\n }\n DOMAIN_SEPARATOR = keccak256(\n abi.encode(\n keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),\n keccak256(bytes(name)),\n keccak256(bytes('1')),\n chainId,\n address(this)\n )\n );\n }\n\n function _mint(address to, uint value) internal {\n totalSupply = totalSupply.add(value);\n balanceOf[to] = balanceOf[to].add(value);\n emit Transfer(address(0), to, value);\n }\n\n function _burn(address from, uint value) internal {\n balanceOf[from] = balanceOf[from].sub(value);\n totalSupply = totalSupply.sub(value);\n emit Transfer(from, address(0), value);\n }\n\n function _approve(address owner, address spender, uint value) private {\n allowance[owner][spender] = value;\n emit Approval(owner, spender, value);\n }\n\n function _transfer(address from, address to, uint value) private {\n balanceOf[from] = balanceOf[from].sub(value);\n balanceOf[to] = balanceOf[to].add(value);\n emit Transfer(from, to, value);\n }\n\n function approve(address spender, uint value) external returns (bool) {\n _approve(msg.sender, spender, value);\n return true;\n }\n\n function transfer(address to, uint value) external returns (bool) {\n _transfer(msg.sender, to, value);\n return true;\n }\n\n function transferFrom(address from, address to, uint value) external returns (bool) {\n if (allowance[from][msg.sender] != uint(-1)) {\n allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);\n }\n _transfer(from, to, value);\n return true;\n }\n\n function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {\n require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');\n bytes32 digest = keccak256(\n abi.encodePacked(\n '\\x19\\x01',\n DOMAIN_SEPARATOR,\n keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))\n )\n );\n address recoveredAddress = ecrecover(digest, v, r, s);\n require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');\n _approve(owner, spender, value);\n }\n}\n", + "contracts/uniswapv2/UniswapV2Factory.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\nimport './interfaces/IUniswapV2Factory.sol';\nimport './UniswapV2Pair.sol';\n\ncontract UniswapV2Factory is IUniswapV2Factory {\n address public override feeTo;\n address public override feeToSetter;\n address public override migrator;\n\n mapping(address => mapping(address => address)) public override getPair;\n address[] public override allPairs;\n\n event PairCreated(address indexed token0, address indexed token1, address pair, uint);\n\n constructor(address _feeToSetter) public {\n feeToSetter = _feeToSetter;\n }\n\n function allPairsLength() external override view returns (uint) {\n return allPairs.length;\n }\n\n function pairCodeHash() external pure returns (bytes32) {\n return keccak256(type(UniswapV2Pair).creationCode);\n }\n\n function createPair(address tokenA, address tokenB) external override returns (address pair) {\n require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');\n (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');\n require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient\n bytes memory bytecode = type(UniswapV2Pair).creationCode;\n bytes32 salt = keccak256(abi.encodePacked(token0, token1));\n assembly {\n pair := create2(0, add(bytecode, 32), mload(bytecode), salt)\n }\n UniswapV2Pair(pair).initialize(token0, token1);\n getPair[token0][token1] = pair;\n getPair[token1][token0] = pair; // populate mapping in the reverse direction\n allPairs.push(pair);\n emit PairCreated(token0, token1, pair, allPairs.length);\n }\n\n function setFeeTo(address _feeTo) external override {\n require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');\n feeTo = _feeTo;\n }\n\n function setMigrator(address _migrator) external override {\n require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');\n migrator = _migrator;\n }\n\n function setFeeToSetter(address _feeToSetter) external override {\n require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');\n feeToSetter = _feeToSetter;\n }\n\n}\n", + "contracts/uniswapv2/UniswapV2Pair.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\nimport './UniswapV2ERC20.sol';\nimport './libraries/Math.sol';\nimport './libraries/UQ112x112.sol';\nimport './interfaces/IERC20.sol';\nimport './interfaces/IUniswapV2Factory.sol';\nimport './interfaces/IUniswapV2Callee.sol';\n\ninterface IMigrator {\n // Return the desired amount of liquidity token that the migrator wants.\n function desiredLiquidity() external view returns (uint256);\n}\n\ncontract UniswapV2Pair is UniswapV2ERC20 {\n using SafeMathUniswap for uint;\n using UQ112x112 for uint224;\n\n uint public constant MINIMUM_LIQUIDITY = 10**3;\n bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));\n\n address public factory;\n address public token0;\n address public token1;\n\n uint112 private reserve0; // uses single storage slot, accessible via getReserves\n uint112 private reserve1; // uses single storage slot, accessible via getReserves\n uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves\n\n uint public price0CumulativeLast;\n uint public price1CumulativeLast;\n uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event\n\n uint private unlocked = 1;\n modifier lock() {\n require(unlocked == 1, 'UniswapV2: LOCKED');\n unlocked = 0;\n _;\n unlocked = 1;\n }\n\n function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {\n _reserve0 = reserve0;\n _reserve1 = reserve1;\n _blockTimestampLast = blockTimestampLast;\n }\n\n function _safeTransfer(address token, address to, uint value) private {\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');\n }\n\n event Mint(address indexed sender, uint amount0, uint amount1);\n event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n event Swap(\n address indexed sender,\n uint amount0In,\n uint amount1In,\n uint amount0Out,\n uint amount1Out,\n address indexed to\n );\n event Sync(uint112 reserve0, uint112 reserve1);\n\n constructor() public {\n factory = msg.sender;\n }\n\n // called once by the factory at time of deployment\n function initialize(address _token0, address _token1) external {\n require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check\n token0 = _token0;\n token1 = _token1;\n }\n\n // update reserves and, on the first call per block, price accumulators\n function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {\n require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');\n uint32 blockTimestamp = uint32(block.timestamp % 2**32);\n uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired\n if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {\n // * never overflows, and + overflow is desired\n price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;\n price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;\n }\n reserve0 = uint112(balance0);\n reserve1 = uint112(balance1);\n blockTimestampLast = blockTimestamp;\n emit Sync(reserve0, reserve1);\n }\n\n // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)\n function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {\n address feeTo = IUniswapV2Factory(factory).feeTo();\n feeOn = feeTo != address(0);\n uint _kLast = kLast; // gas savings\n if (feeOn) {\n if (_kLast != 0) {\n uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));\n uint rootKLast = Math.sqrt(_kLast);\n if (rootK > rootKLast) {\n uint numerator = totalSupply.mul(rootK.sub(rootKLast));\n uint denominator = rootK.mul(5).add(rootKLast);\n uint liquidity = numerator / denominator;\n if (liquidity > 0) _mint(feeTo, liquidity);\n }\n }\n } else if (_kLast != 0) {\n kLast = 0;\n }\n }\n\n // this low-level function should be called from a contract which performs important safety checks\n function mint(address to) external lock returns (uint liquidity) {\n (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n uint balance0 = IERC20Uniswap(token0).balanceOf(address(this));\n uint balance1 = IERC20Uniswap(token1).balanceOf(address(this));\n uint amount0 = balance0.sub(_reserve0);\n uint amount1 = balance1.sub(_reserve1);\n\n bool feeOn = _mintFee(_reserve0, _reserve1);\n uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee\n if (_totalSupply == 0) {\n address migrator = IUniswapV2Factory(factory).migrator();\n if (msg.sender == migrator) {\n liquidity = IMigrator(migrator).desiredLiquidity();\n require(liquidity > 0 && liquidity != uint256(-1), \"Bad desired liquidity\");\n } else {\n require(migrator == address(0), \"Must not have migrator\");\n liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);\n _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens\n }\n } else {\n liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);\n }\n require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');\n _mint(to, liquidity);\n\n _update(balance0, balance1, _reserve0, _reserve1);\n if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date\n emit Mint(msg.sender, amount0, amount1);\n }\n\n // this low-level function should be called from a contract which performs important safety checks\n function burn(address to) external lock returns (uint amount0, uint amount1) {\n (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n address _token0 = token0; // gas savings\n address _token1 = token1; // gas savings\n uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this));\n uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this));\n uint liquidity = balanceOf[address(this)];\n\n bool feeOn = _mintFee(_reserve0, _reserve1);\n uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee\n amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution\n amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution\n require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');\n _burn(address(this), liquidity);\n _safeTransfer(_token0, to, amount0);\n _safeTransfer(_token1, to, amount1);\n balance0 = IERC20Uniswap(_token0).balanceOf(address(this));\n balance1 = IERC20Uniswap(_token1).balanceOf(address(this));\n\n _update(balance0, balance1, _reserve0, _reserve1);\n if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date\n emit Burn(msg.sender, amount0, amount1, to);\n }\n\n // this low-level function should be called from a contract which performs important safety checks\n function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {\n require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');\n (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');\n\n uint balance0;\n uint balance1;\n { // scope for _token{0,1}, avoids stack too deep errors\n address _token0 = token0;\n address _token1 = token1;\n require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');\n if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens\n if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens\n if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);\n balance0 = IERC20Uniswap(_token0).balanceOf(address(this));\n balance1 = IERC20Uniswap(_token1).balanceOf(address(this));\n }\n uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;\n uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;\n require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');\n { // scope for reserve{0,1}Adjusted, avoids stack too deep errors\n uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));\n uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));\n require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');\n }\n\n _update(balance0, balance1, _reserve0, _reserve1);\n emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);\n }\n\n // force balances to match reserves\n function skim(address to) external lock {\n address _token0 = token0; // gas savings\n address _token1 = token1; // gas savings\n _safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0));\n _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1));\n }\n\n // force reserves to match balances\n function sync() external lock {\n _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1);\n }\n}\n", + "contracts/uniswapv2/UniswapV2Router02.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\nimport './libraries/UniswapV2Library.sol';\nimport './libraries/SafeMath.sol';\nimport './libraries/TransferHelper.sol';\nimport './interfaces/IUniswapV2Router02.sol';\nimport './interfaces/IUniswapV2Factory.sol';\nimport './interfaces/IERC20.sol';\nimport './interfaces/IWETH.sol';\n\ncontract UniswapV2Router02 is IUniswapV2Router02 {\n using SafeMathUniswap for uint;\n\n address public immutable override factory;\n address public immutable override WETH;\n\n modifier ensure(uint deadline) {\n require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');\n _;\n }\n\n constructor(address _factory, address _WETH) public {\n factory = _factory;\n WETH = _WETH;\n }\n\n receive() external payable {\n assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract\n }\n\n // **** ADD LIQUIDITY ****\n function _addLiquidity(\n address tokenA,\n address tokenB,\n uint amountADesired,\n uint amountBDesired,\n uint amountAMin,\n uint amountBMin\n ) internal virtual returns (uint amountA, uint amountB) {\n // create the pair if it doesn't exist yet\n if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {\n IUniswapV2Factory(factory).createPair(tokenA, tokenB);\n }\n (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\n if (reserveA == 0 && reserveB == 0) {\n (amountA, amountB) = (amountADesired, amountBDesired);\n } else {\n uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\n if (amountBOptimal <= amountBDesired) {\n require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');\n (amountA, amountB) = (amountADesired, amountBOptimal);\n } else {\n uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\n assert(amountAOptimal <= amountADesired);\n require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');\n (amountA, amountB) = (amountAOptimal, amountBDesired);\n }\n }\n }\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint amountADesired,\n uint amountBDesired,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {\n (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);\n address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);\n TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);\n liquidity = IUniswapV2Pair(pair).mint(to);\n }\n function addLiquidityETH(\n address token,\n uint amountTokenDesired,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {\n (amountToken, amountETH) = _addLiquidity(\n token,\n WETH,\n amountTokenDesired,\n msg.value,\n amountTokenMin,\n amountETHMin\n );\n address pair = UniswapV2Library.pairFor(factory, token, WETH);\n TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);\n IWETH(WETH).deposit{value: amountETH}();\n assert(IWETH(WETH).transfer(pair, amountETH));\n liquidity = IUniswapV2Pair(pair).mint(to);\n // refund dust eth, if any\n if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);\n }\n\n // **** REMOVE LIQUIDITY ****\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint liquidity,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {\n address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair\n (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);\n (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);\n (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);\n require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');\n require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');\n }\n function removeLiquidityETH(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {\n (amountToken, amountETH) = removeLiquidity(\n token,\n WETH,\n liquidity,\n amountTokenMin,\n amountETHMin,\n address(this),\n deadline\n );\n TransferHelper.safeTransfer(token, to, amountToken);\n IWETH(WETH).withdraw(amountETH);\n TransferHelper.safeTransferETH(to, amountETH);\n }\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint liquidity,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external virtual override returns (uint amountA, uint amountB) {\n address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n uint value = approveMax ? uint(-1) : liquidity;\n IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);\n }\n function removeLiquidityETHWithPermit(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external virtual override returns (uint amountToken, uint amountETH) {\n address pair = UniswapV2Library.pairFor(factory, token, WETH);\n uint value = approveMax ? uint(-1) : liquidity;\n IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);\n }\n\n // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****\n function removeLiquidityETHSupportingFeeOnTransferTokens(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) public virtual override ensure(deadline) returns (uint amountETH) {\n (, amountETH) = removeLiquidity(\n token,\n WETH,\n liquidity,\n amountTokenMin,\n amountETHMin,\n address(this),\n deadline\n );\n TransferHelper.safeTransfer(token, to, IERC20Uniswap(token).balanceOf(address(this)));\n IWETH(WETH).withdraw(amountETH);\n TransferHelper.safeTransferETH(to, amountETH);\n }\n function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external virtual override returns (uint amountETH) {\n address pair = UniswapV2Library.pairFor(factory, token, WETH);\n uint value = approveMax ? uint(-1) : liquidity;\n IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(\n token, liquidity, amountTokenMin, amountETHMin, to, deadline\n );\n }\n\n // **** SWAP ****\n // requires the initial amount to have already been sent to the first pair\n function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {\n for (uint i; i < path.length - 1; i++) {\n (address input, address output) = (path[i], path[i + 1]);\n (address token0,) = UniswapV2Library.sortTokens(input, output);\n uint amountOut = amounts[i + 1];\n (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));\n address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(\n amount0Out, amount1Out, to, new bytes(0)\n );\n }\n }\n function swapExactTokensForTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n );\n _swap(amounts, path, to);\n }\n function swapTokensForExactTokens(\n uint amountOut,\n uint amountInMax,\n address[] calldata path,\n address to,\n uint deadline\n ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n );\n _swap(amounts, path, to);\n }\n function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n virtual\n override\n payable\n ensure(deadline)\n returns (uint[] memory amounts)\n {\n require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');\n amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);\n require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n IWETH(WETH).deposit{value: amounts[0]}();\n assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n _swap(amounts, path, to);\n }\n function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n external\n virtual\n override\n ensure(deadline)\n returns (uint[] memory amounts)\n {\n require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');\n amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n );\n _swap(amounts, path, address(this));\n IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n }\n function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n virtual\n override\n ensure(deadline)\n returns (uint[] memory amounts)\n {\n require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');\n amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n );\n _swap(amounts, path, address(this));\n IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n }\n function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n external\n virtual\n override\n payable\n ensure(deadline)\n returns (uint[] memory amounts)\n {\n require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');\n amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');\n IWETH(WETH).deposit{value: amounts[0]}();\n assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n _swap(amounts, path, to);\n // refund dust eth, if any\n if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);\n }\n\n // **** SWAP (supporting fee-on-transfer tokens) ****\n // requires the initial amount to have already been sent to the first pair\n function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {\n for (uint i; i < path.length - 1; i++) {\n (address input, address output) = (path[i], path[i + 1]);\n (address token0,) = UniswapV2Library.sortTokens(input, output);\n IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));\n uint amountInput;\n uint amountOutput;\n { // scope to avoid stack too deep errors\n (uint reserve0, uint reserve1,) = pair.getReserves();\n (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n amountInput = IERC20Uniswap(input).balanceOf(address(pair)).sub(reserveInput);\n amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);\n }\n (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));\n address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n pair.swap(amount0Out, amount1Out, to, new bytes(0));\n }\n }\n function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external virtual override ensure(deadline) {\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n );\n uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to);\n _swapSupportingFeeOnTransferTokens(path, to);\n require(\n IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,\n 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'\n );\n }\n function swapExactETHForTokensSupportingFeeOnTransferTokens(\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n )\n external\n virtual\n override\n payable\n ensure(deadline)\n {\n require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');\n uint amountIn = msg.value;\n IWETH(WETH).deposit{value: amountIn}();\n assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));\n uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to);\n _swapSupportingFeeOnTransferTokens(path, to);\n require(\n IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,\n 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'\n );\n }\n function swapExactTokensForETHSupportingFeeOnTransferTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n )\n external\n virtual\n override\n ensure(deadline)\n {\n require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n );\n _swapSupportingFeeOnTransferTokens(path, address(this));\n uint amountOut = IERC20Uniswap(WETH).balanceOf(address(this));\n require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n IWETH(WETH).withdraw(amountOut);\n TransferHelper.safeTransferETH(to, amountOut);\n }\n\n // **** LIBRARY FUNCTIONS ****\n function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {\n return UniswapV2Library.quote(amountA, reserveA, reserveB);\n }\n\n function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)\n public\n pure\n virtual\n override\n returns (uint amountOut)\n {\n return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);\n }\n\n function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)\n public\n pure\n virtual\n override\n returns (uint amountIn)\n {\n return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);\n }\n\n function getAmountsOut(uint amountIn, address[] memory path)\n public\n view\n virtual\n override\n returns (uint[] memory amounts)\n {\n return UniswapV2Library.getAmountsOut(factory, amountIn, path);\n }\n\n function getAmountsIn(uint amountOut, address[] memory path)\n public\n view\n virtual\n override\n returns (uint[] memory amounts)\n {\n return UniswapV2Library.getAmountsIn(factory, amountOut, path);\n }\n}\n", + "contracts/uniswapv2/interfaces/IERC20.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IERC20Uniswap {\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n function name() external view returns (string memory);\n function symbol() external view returns (string memory);\n function decimals() external view returns (uint8);\n function totalSupply() external view returns (uint);\n function balanceOf(address owner) external view returns (uint);\n function allowance(address owner, address spender) external view returns (uint);\n\n function approve(address spender, uint value) external returns (bool);\n function transfer(address to, uint value) external returns (bool);\n function transferFrom(address from, address to, uint value) external returns (bool);\n}\n", + "contracts/uniswapv2/interfaces/IUniswapV2Callee.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IUniswapV2Callee {\n function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;\n}\n", + "contracts/uniswapv2/interfaces/IUniswapV2ERC20.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IUniswapV2ERC20 {\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n function name() external pure returns (string memory);\n function symbol() external pure returns (string memory);\n function decimals() external pure returns (uint8);\n function totalSupply() external view returns (uint);\n function balanceOf(address owner) external view returns (uint);\n function allowance(address owner, address spender) external view returns (uint);\n\n function approve(address spender, uint value) external returns (bool);\n function transfer(address to, uint value) external returns (bool);\n function transferFrom(address from, address to, uint value) external returns (bool);\n\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n function PERMIT_TYPEHASH() external pure returns (bytes32);\n function nonces(address owner) external view returns (uint);\n\n function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n}", + "contracts/uniswapv2/interfaces/IUniswapV2Factory.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IUniswapV2Factory {\n event PairCreated(address indexed token0, address indexed token1, address pair, uint);\n\n function feeTo() external view returns (address);\n function feeToSetter() external view returns (address);\n function migrator() external view returns (address);\n\n function getPair(address tokenA, address tokenB) external view returns (address pair);\n function allPairs(uint) external view returns (address pair);\n function allPairsLength() external view returns (uint);\n\n function createPair(address tokenA, address tokenB) external returns (address pair);\n\n function setFeeTo(address) external;\n function setFeeToSetter(address) external;\n function setMigrator(address) external;\n}\n", + "contracts/uniswapv2/interfaces/IUniswapV2Pair.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IUniswapV2Pair {\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n function name() external pure returns (string memory);\n function symbol() external pure returns (string memory);\n function decimals() external pure returns (uint8);\n function totalSupply() external view returns (uint);\n function balanceOf(address owner) external view returns (uint);\n function allowance(address owner, address spender) external view returns (uint);\n\n function approve(address spender, uint value) external returns (bool);\n function transfer(address to, uint value) external returns (bool);\n function transferFrom(address from, address to, uint value) external returns (bool);\n\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n function PERMIT_TYPEHASH() external pure returns (bytes32);\n function nonces(address owner) external view returns (uint);\n\n function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n\n event Mint(address indexed sender, uint amount0, uint amount1);\n event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n event Swap(\n address indexed sender,\n uint amount0In,\n uint amount1In,\n uint amount0Out,\n uint amount1Out,\n address indexed to\n );\n event Sync(uint112 reserve0, uint112 reserve1);\n\n function MINIMUM_LIQUIDITY() external pure returns (uint);\n function factory() external view returns (address);\n function token0() external view returns (address);\n function token1() external view returns (address);\n function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\n function price0CumulativeLast() external view returns (uint);\n function price1CumulativeLast() external view returns (uint);\n function kLast() external view returns (uint);\n\n function mint(address to) external returns (uint liquidity);\n function burn(address to) external returns (uint amount0, uint amount1);\n function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;\n function skim(address to) external;\n function sync() external;\n\n function initialize(address, address) external;\n}", + "contracts/uniswapv2/interfaces/IUniswapV2Router01.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.6.2;\n\ninterface IUniswapV2Router01 {\n function factory() external pure returns (address);\n function WETH() external pure returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint amountADesired,\n uint amountBDesired,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n ) external returns (uint amountA, uint amountB, uint liquidity);\n function addLiquidityETH(\n address token,\n uint amountTokenDesired,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint liquidity,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n ) external returns (uint amountA, uint amountB);\n function removeLiquidityETH(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external returns (uint amountToken, uint amountETH);\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint liquidity,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external returns (uint amountA, uint amountB);\n function removeLiquidityETHWithPermit(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external returns (uint amountToken, uint amountETH);\n function swapExactTokensForTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external returns (uint[] memory amounts);\n function swapTokensForExactTokens(\n uint amountOut,\n uint amountInMax,\n address[] calldata path,\n address to,\n uint deadline\n ) external returns (uint[] memory amounts);\n function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n payable\n returns (uint[] memory amounts);\n function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n external\n returns (uint[] memory amounts);\n function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n returns (uint[] memory amounts);\n function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n external\n payable\n returns (uint[] memory amounts);\n\n function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);\n function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);\n function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);\n function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);\n function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);\n}", + "contracts/uniswapv2/interfaces/IUniswapV2Router02.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.6.2;\n\nimport './IUniswapV2Router01.sol';\n\ninterface IUniswapV2Router02 is IUniswapV2Router01 {\n function removeLiquidityETHSupportingFeeOnTransferTokens(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external returns (uint amountETH);\n function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external returns (uint amountETH);\n\n function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external;\n function swapExactETHForTokensSupportingFeeOnTransferTokens(\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external payable;\n function swapExactTokensForETHSupportingFeeOnTransferTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external;\n}", + "contracts/uniswapv2/interfaces/IWETH.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IWETH {\n function deposit() external payable;\n function transfer(address to, uint value) external returns (bool);\n function withdraw(uint) external;\n}", + "contracts/uniswapv2/libraries/Math.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\n// a library for performing various math operations\n\nlibrary Math {\n function min(uint x, uint y) internal pure returns (uint z) {\n z = x < y ? x : y;\n }\n\n // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)\n function sqrt(uint y) internal pure returns (uint z) {\n if (y > 3) {\n z = y;\n uint x = y / 2 + 1;\n while (x < z) {\n z = x;\n x = (y / x + x) / 2;\n }\n } else if (y != 0) {\n z = 1;\n }\n }\n}\n", + "contracts/uniswapv2/libraries/SafeMath.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\n// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)\n\nlibrary SafeMathUniswap {\n function add(uint x, uint y) internal pure returns (uint z) {\n require((z = x + y) >= x, 'ds-math-add-overflow');\n }\n\n function sub(uint x, uint y) internal pure returns (uint z) {\n require((z = x - y) <= x, 'ds-math-sub-underflow');\n }\n\n function mul(uint x, uint y) internal pure returns (uint z) {\n require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');\n }\n}\n", + "contracts/uniswapv2/libraries/TransferHelper.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.6.0;\n\n// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false\nlibrary TransferHelper {\n function safeApprove(address token, address to, uint value) internal {\n // bytes4(keccak256(bytes('approve(address,uint256)')));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');\n }\n\n function safeTransfer(address token, address to, uint value) internal {\n // bytes4(keccak256(bytes('transfer(address,uint256)')));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');\n }\n\n function safeTransferFrom(address token, address from, address to, uint value) internal {\n // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');\n }\n\n function safeTransferETH(address to, uint value) internal {\n (bool success,) = to.call{value:value}(new bytes(0));\n require(success, 'TransferHelper: ETH_TRANSFER_FAILED');\n }\n}\n", + "contracts/uniswapv2/libraries/UQ112x112.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\n// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))\n\n// range: [0, 2**112 - 1]\n// resolution: 1 / 2**112\n\nlibrary UQ112x112 {\n uint224 constant Q112 = 2**112;\n\n // encode a uint112 as a UQ112x112\n function encode(uint112 y) internal pure returns (uint224 z) {\n z = uint224(y) * Q112; // never overflows\n }\n\n // divide a UQ112x112 by a uint112, returning a UQ112x112\n function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {\n z = x / uint224(y);\n }\n}\n", + "contracts/uniswapv2/libraries/UniswapV2Library.sol": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\nimport '../interfaces/IUniswapV2Pair.sol';\n\nimport \"./SafeMath.sol\";\n\nlibrary UniswapV2Library {\n using SafeMathUniswap for uint;\n\n // returns sorted token addresses, used to handle return values from pairs sorted in this order\n function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {\n require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');\n (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');\n }\n\n // calculates the CREATE2 address for a pair without making any external calls\n function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\n (address token0, address token1) = sortTokens(tokenA, tokenB);\n pair = address(uint(keccak256(abi.encodePacked(\n hex'ff',\n factory,\n keccak256(abi.encodePacked(token0, token1)),\n hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash\n ))));\n }\n\n // fetches and sorts the reserves for a pair\n function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {\n (address token0,) = sortTokens(tokenA, tokenB);\n (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();\n (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n }\n\n // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset\n function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {\n require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');\n require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');\n amountB = amountA.mul(reserveB) / reserveA;\n }\n\n // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset\n function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {\n require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');\n require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');\n uint amountInWithFee = amountIn.mul(997);\n uint numerator = amountInWithFee.mul(reserveOut);\n uint denominator = reserveIn.mul(1000).add(amountInWithFee);\n amountOut = numerator / denominator;\n }\n\n // given an output amount of an asset and pair reserves, returns a required input amount of the other asset\n function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {\n require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');\n require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');\n uint numerator = reserveIn.mul(amountOut).mul(1000);\n uint denominator = reserveOut.sub(amountOut).mul(997);\n amountIn = (numerator / denominator).add(1);\n }\n\n // performs chained getAmountOut calculations on any number of pairs\n function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {\n require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');\n amounts = new uint[](path.length);\n amounts[0] = amountIn;\n for (uint i; i < path.length - 1; i++) {\n (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);\n amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);\n }\n }\n\n // performs chained getAmountIn calculations on any number of pairs\n function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {\n require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');\n amounts = new uint[](path.length);\n amounts[amounts.length - 1] = amountOut;\n for (uint i = path.length - 1; i > 0; i--) {\n (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);\n amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);\n }\n }\n}\n" + }, + "abi": "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_factory\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_WETH\",\"type\":\"address\"}],\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"WETH\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"tokenA\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenB\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountADesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBDesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountAMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"addLiquidity\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenDesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"addLiquidityETH\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountToken\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"factory\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveOut\",\"type\":\"uint256\"}],\"name\":\"getAmountIn\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveOut\",\"type\":\"uint256\"}],\"name\":\"getAmountOut\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"}],\"name\":\"getAmountsIn\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"}],\"name\":\"getAmountsOut\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveB\",\"type\":\"uint256\"}],\"name\":\"quote\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"tokenA\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenB\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountAMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"removeLiquidity\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"removeLiquidityETH\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountToken\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"removeLiquidityETHSupportingFeeOnTransferTokens\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"approveMax\",\"type\":\"bool\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"removeLiquidityETHWithPermit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountToken\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"approveMax\",\"type\":\"bool\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"removeLiquidityETHWithPermitSupportingFeeOnTransferTokens\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"tokenA\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenB\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountAMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"approveMax\",\"type\":\"bool\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"removeLiquidityWithPermit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapETHForExactTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactETHForTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactETHForTokensSupportingFeeOnTransferTokens\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForETH\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForETHSupportingFeeOnTransferTokens\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForTokensSupportingFeeOnTransferTokens\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMax\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapTokensForExactETH\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMax\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapTokensForExactTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"type\":\"receive\"}]", + "constructorArguments": "000000000000000000000000c35dadb65012ec5796536bd9864ed8773abc74c4000000000000000000000000b4fbf271143f4fbf7b91a5ded31805e42b2208d6", + "matchType": "PARTIAL" + } + ], + "sourcifySources": [] +} \ No newline at end of file diff --git a/apps/block_scout_web/test/support/fixture/smart_contract/eth_bytecode_db_search_all_sourcify_sources_response.json b/apps/block_scout_web/test/support/fixture/smart_contract/eth_bytecode_db_search_all_sourcify_sources_response.json new file mode 100644 index 0000000000..8456169ebd --- /dev/null +++ b/apps/block_scout_web/test/support/fixture/smart_contract/eth_bytecode_db_search_all_sourcify_sources_response.json @@ -0,0 +1,30 @@ +{ + "ethBytecodeDbSources": [ + { + "fileName": "Test_eth.sol", + "contractName": "Test", + "compilerVersion": "v0.8.17+commit.8df45f5f", + "compilerSettings": "{\"libraries\":{\"Test.sol\":{}},\"metadata\":{\"bytecodeHash\":\"ipfs\"},\"optimizer\":{\"enabled\":true,\"runs\":199},\"outputSelection\":{\"*\":{\"\":[\"ast\"],\"*\":[\"abi\",\"evm.bytecode\",\"evm.deployedBytecode\",\"evm.methodIdentifiers\"]}}}", + "sourceType": "SOLIDITY", + "sourceFiles": { + "Test.sol": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity 0.8.17;\r\n\r\ncontract Test {\r\n enum E {\r\n V1, V2, V3, V4\r\n }\r\n struct A {\r\n E a;\r\n uint256[] b;\r\n B[] c;\r\n }\r\n\r\n struct B {\r\n uint256 d;\r\n uint256 e;\r\n }\r\n\r\n function get(uint256 x) external pure returns (A memory) {\r\n uint256[] memory b = new uint256[](3);\r\n b[0] = 1;\r\n b[1] = 2;\r\n b[2] = 3;\r\n B[] memory c = new B[](3);\r\n c[0] = B(1, 2);\r\n c[1] = B(3, 4);\r\n c[2] = B(5, 6);\r\n return A(E.V3, b, c);\r\n }\r\n}" + }, + "abi": "[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"get\",\"outputs\":[{\"components\":[{\"type\":\"uint8\"},{\"type\":\"uint256[]\"},{\"components\":[{\"type\":\"uint256\"},{\"type\":\"uint256\"}],\"type\":\"tuple[]\"}],\"internalType\":\"struct Test.A\",\"name\":\"\",\"type\":\"tuple\"}],\"stateMutability\":\"pure\",\"type\":\"function\"}]", + "constructorArguments": "0x0000000000000000000000003e5c63644e683549055b9be8653de26e0b4cd36e", + "matchType": "PARTIAL" + } + ], + "sourcifySources": [{ + "fileName": "Test.sol", + "contractName": "Test", + "compilerVersion": "v0.8.17+commit.8df45f5f", + "compilerSettings": "{\"libraries\":{\"Test.sol\":{}},\"metadata\":{\"bytecodeHash\":\"ipfs\"},\"optimizer\":{\"enabled\":true,\"runs\":199},\"outputSelection\":{\"*\":{\"\":[\"ast\"],\"*\":[\"abi\",\"evm.bytecode\",\"evm.deployedBytecode\",\"evm.methodIdentifiers\"]}}}", + "sourceType": "SOLIDITY", + "sourceFiles": { + "Test.sol": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity 0.8.17;\r\n\r\ncontract Test {\r\n enum E {\r\n V1, V2, V3, V4\r\n }\r\n struct A {\r\n E a;\r\n uint256[] b;\r\n B[] c;\r\n }\r\n\r\n struct B {\r\n uint256 d;\r\n uint256 e;\r\n }\r\n\r\n function get(uint256 x) external pure returns (A memory) {\r\n uint256[] memory b = new uint256[](3);\r\n b[0] = 1;\r\n b[1] = 2;\r\n b[2] = 3;\r\n B[] memory c = new B[](3);\r\n c[0] = B(1, 2);\r\n c[1] = B(3, 4);\r\n c[2] = B(5, 6);\r\n return A(E.V3, b, c);\r\n }\r\n}" + }, + "abi": "[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"get\",\"outputs\":[{\"components\":[{\"type\":\"uint8\"},{\"type\":\"uint256[]\"},{\"components\":[{\"type\":\"uint256\"},{\"type\":\"uint256\"}],\"type\":\"tuple[]\"}],\"internalType\":\"struct Test.A\",\"name\":\"\",\"type\":\"tuple\"}],\"stateMutability\":\"pure\",\"type\":\"function\"}]", + "constructorArguments": "0x0000000000000000000000003e5c63644e683549055b9be8653de26e0b4cd36e", + "matchType": "PARTIAL" + }] + } \ No newline at end of file diff --git a/apps/block_scout_web/test/support/fixture/smart_contract/eth_bytecode_db_search_all_sourcify_sources_with_libs_response.json b/apps/block_scout_web/test/support/fixture/smart_contract/eth_bytecode_db_search_all_sourcify_sources_with_libs_response.json new file mode 100644 index 0000000000..494c7897b8 --- /dev/null +++ b/apps/block_scout_web/test/support/fixture/smart_contract/eth_bytecode_db_search_all_sourcify_sources_with_libs_response.json @@ -0,0 +1,47 @@ +{ + "ethBytecodeDbSources": [], + "sourcifySources": [ + { + "fileName": "src/zkbob/ZkBobPool.sol", + "contractName": "ZkBobPool", + "compilerVersion": "0.8.15+commit.e14f2714", + "compilerSettings": "{\"evmVersion\":\"london\",\"libraries\":{\"lib/base58-solidity/contracts/Base58.sol:Base58\":\"0x22de6b06544ee5cd907813a04bcded149a2f49d2\",\"src/libraries/ZkAddress.sol:ZkAddress\":\"0x019d3788f00a7087234f3844cb1cece1f9982b7a\"},\"metadata\":{\"bytecodeHash\":\"ipfs\"},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[\":@base58-solidity/=lib/base58-solidity/contracts/\",\":@gnosis/=lib/@gnosis/\",\":@gnosis/auction/=lib/@gnosis/auction/contracts/\",\":@openzeppelin/=lib/@openzeppelin/contracts/\",\":@openzeppelin/contracts/=lib/@openzeppelin/contracts/contracts/\",\":@uniswap/=lib/@uniswap/\",\":base58-solidity/=lib/base58-solidity/contracts/\",\":ds-test/=lib/forge-std/lib/ds-test/src/\",\":forge-std/=lib/forge-std/src/\"]}", + "sourceType": "SOLIDITY", + "sourceFiles": { + "lib/_openzeppelin/contracts/contracts/access/Ownable.sol": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor() {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n", + "lib/_openzeppelin/contracts/contracts/token/ERC20/IERC20.sol": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n", + "lib/_openzeppelin/contracts/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n", + "lib/_openzeppelin/contracts/contracts/token/ERC20/utils/SafeERC20.sol": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n", + "lib/_openzeppelin/contracts/contracts/utils/Address.sol": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n", + "lib/_openzeppelin/contracts/contracts/utils/Context.sol": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n", + "lib/_openzeppelin/contracts/contracts/utils/Strings.sol": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n", + "lib/_openzeppelin/contracts/contracts/utils/cryptography/ECDSA.sol": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Strings.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV\n }\n\n function _throwError(RecoverError error) private pure {\n if (error == RecoverError.NoError) {\n return; // no error: do nothing\n } else if (error == RecoverError.InvalidSignature) {\n revert(\"ECDSA: invalid signature\");\n } else if (error == RecoverError.InvalidSignatureLength) {\n revert(\"ECDSA: invalid signature length\");\n } else if (error == RecoverError.InvalidSignatureS) {\n revert(\"ECDSA: invalid signature 's' value\");\n } else if (error == RecoverError.InvalidSignatureV) {\n revert(\"ECDSA: invalid signature 'v' value\");\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature` or error string. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n *\n * Documentation for signature generation:\n * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n // Check the signature length\n // - case 65: r,s,v signature (standard)\n // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._\n if (signature.length == 65) {\n bytes32 r;\n bytes32 s;\n uint8 v;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n /// @solidity memory-safe-assembly\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n return tryRecover(hash, v, r, s);\n } else if (signature.length == 64) {\n bytes32 r;\n bytes32 vs;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n /// @solidity memory-safe-assembly\n assembly {\n r := mload(add(signature, 0x20))\n vs := mload(add(signature, 0x40))\n }\n return tryRecover(hash, r, vs);\n } else {\n return (address(0), RecoverError.InvalidSignatureLength);\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, signature);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n *\n * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n *\n * _Available since v4.3._\n */\n function tryRecover(\n bytes32 hash,\n bytes32 r,\n bytes32 vs\n ) internal pure returns (address, RecoverError) {\n bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n uint8 v = uint8((uint256(vs) >> 255) + 27);\n return tryRecover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n *\n * _Available since v4.2._\n */\n function recover(\n bytes32 hash,\n bytes32 r,\n bytes32 vs\n ) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n * `r` and `s` signature fields separately.\n *\n * _Available since v4.3._\n */\n function tryRecover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address, RecoverError) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n return (address(0), RecoverError.InvalidSignatureS);\n }\n if (v != 27 && v != 28) {\n return (address(0), RecoverError.InvalidSignatureV);\n }\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n if (signer == address(0)) {\n return (address(0), RecoverError.InvalidSignature);\n }\n\n return (signer, RecoverError.NoError);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from `s`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", Strings.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n", + "lib/_uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#swap\n/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface\ninterface IUniswapV3SwapCallback {\n /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.\n /// @dev In the implementation you must pay the pool tokens owed for the swap.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external;\n}\n", + "lib/_uniswap/v3-periphery/contracts/interfaces/IPeripheryImmutableState.sol": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Immutable state\n/// @notice Functions that return immutable state of the router\ninterface IPeripheryImmutableState {\n /// @return Returns the address of the Uniswap V3 factory\n function factory() external view returns (address);\n\n /// @return Returns the address of WETH9\n function WETH9() external view returns (address);\n}\n", + "lib/_uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';\n\n/// @title Router token swapping functionality\n/// @notice Functions for swapping tokens via Uniswap V3\ninterface ISwapRouter is IUniswapV3SwapCallback {\n struct ExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactInputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);\n\n struct ExactOutputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);\n}\n", + "lib/_uniswap/v3-periphery/contracts/interfaces/external/IWETH9.sol": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity =0.8.15;\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\n/// @title Interface for WETH9\ninterface IWETH9 is IERC20 {\n /// @notice Deposit ether to get wrapped ether\n function deposit() external payable;\n\n /// @notice Withdraw wrapped ether to get ether\n function withdraw(uint256) external;\n}\n", + "src/interfaces/IBatchDepositVerifier.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.15;\n\ninterface IBatchDepositVerifier {\n function verifyProof(uint256[1] memory input, uint256[8] memory p) external view returns (bool);\n}\n", + "src/interfaces/IERC20Permit.sol": "// SPDX-License-Identifier: CC0-1.0\n\npragma solidity 0.8.15;\n\ninterface IERC20Permit {\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n )\n external;\n\n function nonces(address owner) external view returns (uint256);\n\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n\n function PERMIT_TYPEHASH() external view returns (bytes32);\n\n function SALTED_PERMIT_TYPEHASH() external view returns (bytes32);\n\n function receiveWithPermit(\n address _holder,\n uint256 _value,\n uint256 _deadline,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n )\n external;\n\n function receiveWithSaltedPermit(\n address _holder,\n uint256 _value,\n uint256 _deadline,\n bytes32 _salt,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n )\n external;\n}\n", + "src/interfaces/IMintableERC20.sol": "// SPDX-License-Identifier: CC0-1.0\n\npragma solidity 0.8.15;\n\ninterface IMintableERC20 {\n function mint(address to, uint256 amount) external;\n}\n", + "src/interfaces/IOperatorManager.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.15;\n\ninterface IOperatorManager {\n function isOperator(address _addr) external view returns (bool);\n\n function isOperatorFeeReceiver(address _operator, address _addr) external view returns (bool);\n\n function operatorURI() external view returns (string memory);\n}\n", + "src/interfaces/ITokenSeller.sol": "// SPDX-License-Identifier: CC0-1.0\n\npragma solidity 0.8.15;\n\ninterface ITokenSeller {\n /**\n * @dev Sells tokens for ETH.\n * Prior to calling this function, contract balance of token0 should be greater than or equal to the sold amount.\n * @param _receiver native ETH receiver.\n * @param _amount amount of tokens to sell.\n * @return (received eth amount, refunded token amount).\n */\n function sellForETH(address _receiver, uint256 _amount) external returns (uint256, uint256);\n\n /**\n * @dev Estimates amount of received ETH, when selling given amount of tokens via sellForETH function.\n * @param _amount amount of tokens to sell.\n * @return received eth amount.\n */\n function quoteSellForETH(uint256 _amount) external returns (uint256);\n}\n", + "src/interfaces/ITransferVerifier.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.15;\n\ninterface ITransferVerifier {\n function verifyProof(uint256[5] memory input, uint256[8] memory p) external view returns (bool);\n}\n", + "src/interfaces/ITreeVerifier.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.15;\n\ninterface ITreeVerifier {\n function verifyProof(uint256[3] memory input, uint256[8] memory p) external view returns (bool);\n}\n", + "src/interfaces/IZkBobDirectDepositQueue.sol": "// SPDX-License-Identifier: CC0-1.0\n\npragma solidity ^0.8.0;\n\ninterface IZkBobDirectDepositQueue {\n function collect(\n uint256[] calldata _indices,\n uint256 _out_commit\n )\n external\n returns (uint256 total, uint256 totalFee, uint256 hashsum, bytes memory message);\n}\n", + "src/interfaces/IZkBobPool.sol": "// SPDX-License-Identifier: CC0-1.0\n\npragma solidity ^0.8.0;\n\ninterface IZkBobPool {\n function pool_id() external view returns (uint256);\n\n function recordDirectDeposit(address _sender, uint256 _amount) external;\n}\n", + "src/proxy/EIP1967Admin.sol": "// SPDX-License-Identifier: CC0-1.0\n\npragma solidity 0.8.15;\n\n/**\n * @title EIP1967Admin\n * @dev Upgradeable proxy pattern implementation according to minimalistic EIP1967.\n */\ncontract EIP1967Admin {\n // EIP 1967\n // bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)\n uint256 internal constant EIP1967_ADMIN_STORAGE = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n modifier onlyAdmin() {\n require(msg.sender == _admin(), \"EIP1967Admin: not an admin\");\n _;\n }\n\n function _admin() internal view returns (address res) {\n assembly {\n res := sload(EIP1967_ADMIN_STORAGE)\n }\n }\n}\n", + "src/utils/Ownable.sol": "// SPDX-License-Identifier: CC0-1.0\n\npragma solidity 0.8.15;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\" as OZOwnable;\n\n/**\n * @title Ownable\n */\ncontract Ownable is OZOwnable.Ownable {\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view override {\n require(_isOwner(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Tells if caller is the contract owner.\n * @return true, if caller is the contract owner.\n */\n function _isOwner() internal view virtual returns (bool) {\n return owner() == _msgSender();\n }\n}\n", + "src/zkbob/ZkBobPool.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.15;\n\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol\";\nimport \"@uniswap/v3-periphery/contracts/interfaces/IPeripheryImmutableState.sol\";\nimport \"@uniswap/v3-periphery/contracts/interfaces/external/IWETH9.sol\";\nimport \"../interfaces/ITransferVerifier.sol\";\nimport \"../interfaces/ITreeVerifier.sol\";\nimport \"../interfaces/IBatchDepositVerifier.sol\";\nimport \"../interfaces/IMintableERC20.sol\";\nimport \"../interfaces/IOperatorManager.sol\";\nimport \"../interfaces/IERC20Permit.sol\";\nimport \"../interfaces/ITokenSeller.sol\";\nimport \"../interfaces/IZkBobDirectDepositQueue.sol\";\nimport \"../interfaces/IZkBobPool.sol\";\nimport \"./utils/Parameters.sol\";\nimport \"./utils/ZkBobAccounting.sol\";\nimport \"../utils/Ownable.sol\";\nimport \"../proxy/EIP1967Admin.sol\";\n\n/**\n * @title ZkBobPool\n * Shielded transactions pool for BOB tokens.\n */\ncontract ZkBobPool is IZkBobPool, EIP1967Admin, Ownable, Parameters, ZkBobAccounting {\n using SafeERC20 for IERC20;\n\n uint256 internal constant MAX_POOL_ID = 0xffffff;\n uint256 internal constant TOKEN_DENOMINATOR = 1_000_000_000;\n bytes4 internal constant MESSAGE_PREFIX_COMMON_V1 = 0x00000000;\n// bytes4 internal constant MESSAGE_PREFIX_DIRECT_DEPOSIT_V1 = 0x00000001;\n// uint256 internal constant MAX_NUMBER_OF_DIRECT_DEPOSITS = 16;\n\n uint256 public immutable pool_id;\n ITransferVerifier public immutable transfer_verifier;\n ITreeVerifier public immutable tree_verifier;\n IBatchDepositVerifier public immutable batch_deposit_verifier;\n address public immutable token;\n IZkBobDirectDepositQueue public immutable direct_deposit_queue;\n\n IOperatorManager public operatorManager;\n\n mapping(uint256 => uint256) public nullifiers;\n mapping(uint256 => uint256) public roots;\n bytes32 public all_messages_hash;\n\n mapping(address => uint256) public accumulatedFee;\n\n ITokenSeller public tokenSeller;\n\n event UpdateTokenSeller(address seller);\n event UpdateOperatorManager(address manager);\n event WithdrawFee(address indexed operator, uint256 fee);\n\n event Message(uint256 indexed index, bytes32 indexed hash, bytes message);\n\n constructor(\n uint256 __pool_id,\n address _token,\n ITransferVerifier _transfer_verifier,\n ITreeVerifier _tree_verifier,\n IBatchDepositVerifier _batch_deposit_verifier,\n address _direct_deposit_queue\n ) {\n require(__pool_id <= MAX_POOL_ID, \"ZkBobPool: exceeds max pool id\");\n require(Address.isContract(_token), \"ZkBobPool: not a contract\");\n require(Address.isContract(address(_transfer_verifier)), \"ZkBobPool: not a contract\");\n require(Address.isContract(address(_tree_verifier)), \"ZkBobPool: not a contract\");\n require(Address.isContract(_direct_deposit_queue), \"ZkBobPool: not a contract\");\n pool_id = __pool_id;\n token = _token;\n transfer_verifier = _transfer_verifier;\n tree_verifier = _tree_verifier;\n batch_deposit_verifier = _batch_deposit_verifier;\n direct_deposit_queue = IZkBobDirectDepositQueue(_direct_deposit_queue);\n }\n\n /**\n * @dev Throws if called by any account other than the current relayer operator.\n */\n modifier onlyOperator() {\n require(operatorManager.isOperator(_msgSender()), \"ZkBobPool: not an operator\");\n _;\n }\n\n /**\n * @dev Initializes pool proxy storage.\n * Callable only once and only through EIP1967Proxy constructor / upgradeToAndCall.\n * @param _root initial empty merkle tree root.\n * @param _tvlCap initial upper cap on the entire pool tvl, 18 decimals.\n * @param _dailyDepositCap initial daily limit on the sum of all deposits, 18 decimals.\n * @param _dailyWithdrawalCap initial daily limit on the sum of all withdrawals, 18 decimals.\n * @param _dailyUserDepositCap initial daily limit on the sum of all per-address deposits, 18 decimals.\n * @param _depositCap initial limit on the amount of a single deposit, 18 decimals.\n * @param _dailyUserDirectDepositCap initial daily limit on the sum of all per-address direct deposits, 18 decimals.\n * @param _directDepositCap initial limit on the amount of a single direct deposit, 18 decimals.\n */\n function initialize(\n uint256 _root,\n uint256 _tvlCap,\n uint256 _dailyDepositCap,\n uint256 _dailyWithdrawalCap,\n uint256 _dailyUserDepositCap,\n uint256 _depositCap,\n uint256 _dailyUserDirectDepositCap,\n uint256 _directDepositCap\n )\n external\n {\n require(msg.sender == address(this), \"ZkBobPool: not initializer\");\n require(roots[0] == 0, \"ZkBobPool: already initialized\");\n require(_root != 0, \"ZkBobPool: zero root\");\n roots[0] = _root;\n _setLimits(\n 0,\n _tvlCap / TOKEN_DENOMINATOR,\n _dailyDepositCap / TOKEN_DENOMINATOR,\n _dailyWithdrawalCap / TOKEN_DENOMINATOR,\n _dailyUserDepositCap / TOKEN_DENOMINATOR,\n _depositCap / TOKEN_DENOMINATOR,\n _dailyUserDirectDepositCap / TOKEN_DENOMINATOR,\n _directDepositCap / TOKEN_DENOMINATOR\n );\n }\n\n /**\n * @dev Updates token seller contract used for native coin withdrawals.\n * Callable only by the contract owner / proxy admin.\n * @param _seller new token seller contract implementation. address(0) will deactivate native withdrawals.\n */\n function setTokenSeller(address _seller) external onlyOwner {\n tokenSeller = ITokenSeller(_seller);\n emit UpdateTokenSeller(_seller);\n }\n\n /**\n * @dev Updates used operator manager contract.\n * Callable only by the contract owner / proxy admin.\n * @param _operatorManager new operator manager implementation.\n */\n function setOperatorManager(IOperatorManager _operatorManager) external onlyOwner {\n require(address(_operatorManager) != address(0), \"ZkBobPool: manager is zero address\");\n operatorManager = _operatorManager;\n emit UpdateOperatorManager(address(_operatorManager));\n }\n\n /**\n * @dev Tells the denominator for converting BOB into zkBOB units.\n * 1e18 BOB units = 1e9 zkBOB units.\n */\n function denominator() external pure returns (uint256) {\n return TOKEN_DENOMINATOR;\n }\n\n /**\n * @dev Tells the current merkle tree index, which will be used for the next operation.\n * Each operation increases merkle tree size by 128, so index is equal to the total number of seen operations, multiplied by 128.\n * @return next operator merkle index.\n */\n function pool_index() external view returns (uint256) {\n return _txCount() << 7;\n }\n\n function _root() internal view override returns (uint256) {\n return roots[_transfer_index()];\n }\n\n function _pool_id() internal view override returns (uint256) {\n return pool_id;\n }\n\n /**\n * @dev Perform a zkBob pool transaction.\n * Callable only by the current operator.\n * Method uses a custom ABI encoding scheme described in CustomABIDecoder.\n * Single transact() call performs either deposit, withdrawal or shielded transfer operation.\n */\n function transact() external onlyOperator {\n address user;\n uint256 txType = _tx_type();\n if (txType == 0) {\n user = _deposit_spender();\n } else if (txType == 2) {\n user = _memo_receiver();\n } else if (txType == 3) {\n user = _memo_permit_holder();\n }\n int256 transfer_token_delta = _transfer_token_amount();\n (,, uint256 txCount) = _recordOperation(user, transfer_token_delta);\n\n uint256 nullifier = _transfer_nullifier();\n {\n uint256 _pool_index = txCount << 7;\n\n require(nullifiers[nullifier] == 0, \"ZkBobPool: doublespend detected\");\n require(_transfer_index() <= _pool_index, \"ZkBobPool: transfer index out of bounds\");\n require(transfer_verifier.verifyProof(_transfer_pub(), _transfer_proof()), \"ZkBobPool: bad transfer proof\");\n require(\n tree_verifier.verifyProof(_tree_pub(roots[_pool_index]), _tree_proof()), \"ZkBobPool: bad tree proof\"\n );\n\n nullifiers[nullifier] = uint256(keccak256(abi.encodePacked(_transfer_out_commit(), _transfer_delta())));\n _pool_index += 128;\n roots[_pool_index] = _tree_root_after();\n bytes memory message = _memo_message();\n // restrict memo message prefix (items count in little endian) to be < 2**16\n require(bytes4(message) & 0x0000ffff == MESSAGE_PREFIX_COMMON_V1, \"ZkBobPool: bad message prefix\");\n bytes32 message_hash = keccak256(message);\n bytes32 _all_messages_hash = keccak256(abi.encodePacked(all_messages_hash, message_hash));\n all_messages_hash = _all_messages_hash;\n emit Message(_pool_index, _all_messages_hash, message);\n }\n\n uint256 fee = _memo_fee();\n int256 token_amount = transfer_token_delta + int256(fee);\n int256 energy_amount = _transfer_energy_amount();\n\n if (txType == 0) {\n // Deposit\n require(transfer_token_delta > 0 && energy_amount == 0, \"ZkBobPool: incorrect deposit amounts\");\n IERC20(token).safeTransferFrom(user, address(this), uint256(token_amount) * TOKEN_DENOMINATOR);\n } else if (txType == 1) {\n // Transfer\n require(token_amount == 0 && energy_amount == 0, \"ZkBobPool: incorrect transfer amounts\");\n } else if (txType == 2) {\n // Withdraw\n require(token_amount <= 0 && energy_amount <= 0, \"ZkBobPool: incorrect withdraw amounts\");\n\n uint256 native_amount = _memo_native_amount() * TOKEN_DENOMINATOR;\n uint256 withdraw_amount = uint256(-token_amount) * TOKEN_DENOMINATOR;\n\n if (native_amount > 0) {\n ITokenSeller seller = tokenSeller;\n if (address(seller) != address(0)) {\n IERC20(token).safeTransfer(address(seller), native_amount);\n (, uint256 refunded) = seller.sellForETH(user, native_amount);\n withdraw_amount = withdraw_amount - native_amount + refunded;\n }\n }\n\n if (withdraw_amount > 0) {\n IERC20(token).safeTransfer(user, withdraw_amount);\n }\n\n // energy withdrawals are not yet implemented, any transaction with non-zero energy_amount will revert\n // future version of the protocol will support energy withdrawals through negative energy_amount\n if (energy_amount < 0) {\n revert(\"ZkBobPool: XP claiming is not yet enabled\");\n }\n } else if (txType == 3) {\n // Permittable token deposit\n require(transfer_token_delta > 0 && energy_amount == 0, \"ZkBobPool: incorrect deposit amounts\");\n (uint8 v, bytes32 r, bytes32 s) = _permittable_deposit_signature();\n IERC20Permit(token).receiveWithSaltedPermit(\n user, uint256(token_amount) * TOKEN_DENOMINATOR, _memo_permit_deadline(), bytes32(nullifier), v, r, s\n );\n } else {\n revert(\"ZkBobPool: Incorrect transaction type\");\n }\n\n if (fee > 0) {\n accumulatedFee[msg.sender] += fee;\n }\n }\n\n function appendDirectDeposits(\n uint256 _root_after,\n uint256[] calldata _indices,\n uint256 _out_commit,\n uint256[8] memory _batch_deposit_proof,\n uint256[8] memory _tree_proof\n )\n external\n onlyOperator\n {\n (uint256 total, uint256 totalFee, uint256 hashsum, bytes memory message) =\n direct_deposit_queue.collect(_indices, _out_commit);\n\n uint256 txCount = _processDirectDepositBatch(total);\n uint256 _pool_index = txCount << 7;\n\n // verify that _out_commit corresponds to zero output account + 16 chosen notes + 111 empty notes\n require(\n batch_deposit_verifier.verifyProof([hashsum], _batch_deposit_proof), \"ZkBobPool: bad batch deposit proof\"\n );\n\n uint256[3] memory tree_pub = [roots[_pool_index], _root_after, _out_commit];\n require(tree_verifier.verifyProof(tree_pub, _tree_proof), \"ZkBobPool: bad tree proof\");\n\n _pool_index += 128;\n roots[_pool_index] = _root_after;\n bytes32 message_hash = keccak256(message);\n bytes32 _all_messages_hash = keccak256(abi.encodePacked(all_messages_hash, message_hash));\n all_messages_hash = _all_messages_hash;\n\n if (totalFee > 0) {\n accumulatedFee[msg.sender] += totalFee;\n }\n\n emit Message(_pool_index, _all_messages_hash, message);\n }\n\n function recordDirectDeposit(address _sender, uint256 _amount) external {\n require(msg.sender == address(direct_deposit_queue),\"ZkBobPool: not authorized\");\n _checkDirectDepositLimits(_sender, _amount);\n }\n\n /**\n * @dev Withdraws accumulated fee on behalf of an operator.\n * Callable only by the operator itself, or by a pre-configured operator fee receiver address.\n * @param _operator address of an operator account to withdraw fee from.\n * @param _to address of the accumulated fee tokens receiver.\n */\n function withdrawFee(address _operator, address _to) external {\n require(\n _operator == msg.sender || operatorManager.isOperatorFeeReceiver(_operator, msg.sender),\n \"ZkBobPool: not authorized\"\n );\n uint256 fee = accumulatedFee[_operator] * TOKEN_DENOMINATOR;\n require(fee > 0, \"ZkBobPool: no fee to withdraw\");\n IERC20(token).safeTransfer(_to, fee);\n accumulatedFee[_operator] = 0;\n emit WithdrawFee(_operator, fee);\n }\n\n /**\n * @dev Updates pool usage limits.\n * Callable only by the contract owner / proxy admin.\n * @param _tier pool limits tier (0-254).\n * @param _tvlCap new upper cap on the entire pool tvl, 18 decimals.\n * @param _dailyDepositCap new daily limit on the sum of all deposits, 18 decimals.\n * @param _dailyWithdrawalCap new daily limit on the sum of all withdrawals, 18 decimals.\n * @param _dailyUserDepositCap new daily limit on the sum of all per-address deposits, 18 decimals.\n * @param _depositCap new limit on the amount of a single deposit, 18 decimals.\n * @param _dailyUserDirectDepositCap new daily limit on the sum of all per-address direct deposits, 18 decimals.\n * @param _directDepositCap new limit on the amount of a single direct deposit, 18 decimals.\n */\n function setLimits(\n uint8 _tier,\n uint256 _tvlCap,\n uint256 _dailyDepositCap,\n uint256 _dailyWithdrawalCap,\n uint256 _dailyUserDepositCap,\n uint256 _depositCap,\n uint256 _dailyUserDirectDepositCap,\n uint256 _directDepositCap\n )\n external\n onlyOwner\n {\n _setLimits(\n _tier,\n _tvlCap / TOKEN_DENOMINATOR,\n _dailyDepositCap / TOKEN_DENOMINATOR,\n _dailyWithdrawalCap / TOKEN_DENOMINATOR,\n _dailyUserDepositCap / TOKEN_DENOMINATOR,\n _depositCap / TOKEN_DENOMINATOR,\n _dailyUserDirectDepositCap / TOKEN_DENOMINATOR,\n _directDepositCap / TOKEN_DENOMINATOR\n );\n }\n\n /**\n * @dev Resets daily limit usage for the current day.\n * Callable only by the contract owner / proxy admin.\n * @param _tier tier id to reset daily limits for.\n */\n function resetDailyLimits(uint8 _tier) external onlyOwner {\n _resetDailyLimits(_tier);\n }\n\n /**\n * @dev Updates users limit tiers.\n * Callable only by the contract owner / proxy admin.\n * @param _tier pool limits tier (0-255).\n * 0 is the default tier.\n * 1-254 are custom pool limit tiers, configured at runtime.\n * 255 is the special tier with zero limits, used to effectively prevent some address from accessing the pool.\n * @param _users list of user account addresses to assign a tier for.\n */\n function setUsersTier(uint8 _tier, address[] memory _users) external onlyOwner {\n _setUsersTier(_tier, _users);\n }\n\n /**\n * @dev Tells if caller is the contract owner.\n * Gives ownership rights to the proxy admin as well.\n * @return true, if caller is the contract owner or proxy admin.\n */\n function _isOwner() internal view override returns (bool) {\n return super._isOwner() || _admin() == _msgSender();\n }\n}\n", + "src/zkbob/utils/CustomABIDecoder.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.15;\n\ncontract CustomABIDecoder {\n uint256 constant transfer_nullifier_pos = 4;\n uint256 constant transfer_nullifier_size = 32;\n uint256 constant uint256_size = 32;\n\n function _loaduint256(uint256 pos) internal pure returns (uint256 r) {\n assembly {\n r := calldataload(pos)\n }\n }\n\n function _transfer_nullifier() internal pure returns (uint256 r) {\n r = _loaduint256(transfer_nullifier_pos);\n }\n\n uint256 constant transfer_out_commit_pos = transfer_nullifier_pos + transfer_nullifier_size;\n uint256 constant transfer_out_commit_size = 32;\n\n function _transfer_out_commit() internal pure returns (uint256 r) {\n r = _loaduint256(transfer_out_commit_pos);\n }\n\n uint256 constant transfer_index_pos = transfer_out_commit_pos + transfer_out_commit_size;\n uint256 constant transfer_index_size = 6;\n\n function _transfer_index() internal pure returns (uint48 r) {\n r = uint48(_loaduint256(transfer_index_pos + transfer_index_size - uint256_size));\n }\n\n uint256 constant transfer_energy_amount_pos = transfer_index_pos + transfer_index_size;\n uint256 constant transfer_energy_amount_size = 14;\n\n function _transfer_energy_amount() internal pure returns (int112 r) {\n r = int112(uint112(_loaduint256(transfer_energy_amount_pos + transfer_energy_amount_size - uint256_size)));\n }\n\n uint256 constant transfer_token_amount_pos = transfer_energy_amount_pos + transfer_energy_amount_size;\n uint256 constant transfer_token_amount_size = 8;\n\n function _transfer_token_amount() internal pure returns (int64 r) {\n r = int64(uint64(_loaduint256(transfer_token_amount_pos + transfer_token_amount_size - uint256_size)));\n }\n\n uint256 constant transfer_proof_pos = transfer_token_amount_pos + transfer_token_amount_size;\n uint256 constant transfer_proof_size = 256;\n\n function _transfer_proof() internal pure returns (uint256[8] calldata r) {\n uint256 pos = transfer_proof_pos;\n assembly {\n r := pos\n }\n }\n\n uint256 constant tree_root_after_pos = transfer_proof_pos + transfer_proof_size;\n uint256 constant tree_root_after_size = 32;\n\n function _tree_root_after() internal pure returns (uint256 r) {\n r = _loaduint256(tree_root_after_pos);\n }\n\n uint256 constant tree_proof_pos = tree_root_after_pos + tree_root_after_size;\n uint256 constant tree_proof_size = 256;\n\n function _tree_proof() internal pure returns (uint256[8] calldata r) {\n uint256 pos = tree_proof_pos;\n assembly {\n r := pos\n }\n }\n\n uint256 constant tx_type_pos = tree_proof_pos + tree_proof_size;\n uint256 constant tx_type_size = 2;\n uint256 constant tx_type_mask = (1 << (tx_type_size * 8)) - 1;\n\n function _tx_type() internal pure returns (uint256 r) {\n r = _loaduint256(tx_type_pos + tx_type_size - uint256_size) & tx_type_mask;\n }\n\n uint256 constant memo_data_size_pos = tx_type_pos + tx_type_size;\n uint256 constant memo_data_size_size = 2;\n uint256 constant memo_data_size_mask = (1 << (memo_data_size_size * 8)) - 1;\n\n uint256 constant memo_data_pos = memo_data_size_pos + memo_data_size_size;\n\n function _memo_data_size() internal pure returns (uint256 r) {\n r = _loaduint256(memo_data_size_pos + memo_data_size_size - uint256_size) & memo_data_size_mask;\n }\n\n function _memo_data() internal pure returns (bytes calldata r) {\n uint256 offset = memo_data_pos;\n uint256 length = _memo_data_size();\n assembly {\n r.offset := offset\n r.length := length\n }\n }\n\n function _sign_r_vs_pos() internal pure returns (uint256) {\n return memo_data_pos + _memo_data_size();\n }\n\n uint256 constant sign_r_vs_size = 64;\n\n function _sign_r_vs() internal pure returns (bytes32 r, bytes32 vs) {\n uint256 offset = _sign_r_vs_pos();\n assembly {\n r := calldataload(offset)\n vs := calldataload(add(offset, 32))\n }\n }\n\n uint256 constant transfer_delta_size =\n transfer_index_size + transfer_energy_amount_size + transfer_token_amount_size;\n uint256 constant transfer_delta_mask = (1 << (transfer_delta_size * 8)) - 1;\n\n function _transfer_delta() internal pure returns (uint256 r) {\n r = _loaduint256(transfer_index_pos + transfer_delta_size - uint256_size) & transfer_delta_mask;\n }\n\n function _memo_fixed_size() internal pure returns (uint256 r) {\n uint256 t = _tx_type();\n if (t == 0 || t == 1) {\n // fee\n // 8\n r = 8;\n } else if (t == 2) {\n // fee + native amount + recipient\n // 8 + 8 + 20\n r = 36;\n } else if (t == 3) {\n // fee + deadline + address\n // 8 + 8 + 20\n r = 36;\n } else {\n revert();\n }\n }\n\n function _memo_message() internal pure returns (bytes calldata r) {\n uint256 memo_fixed_size = _memo_fixed_size();\n uint256 offset = memo_data_pos + memo_fixed_size;\n uint256 length = _memo_data_size() - memo_fixed_size;\n assembly {\n r.offset := offset\n r.length := length\n }\n }\n\n uint256 constant memo_fee_pos = memo_data_pos;\n uint256 constant memo_fee_size = 8;\n uint256 constant memo_fee_mask = (1 << (memo_fee_size * 8)) - 1;\n\n function _memo_fee() internal pure returns (uint256 r) {\n r = _loaduint256(memo_fee_pos + memo_fee_size - uint256_size) & memo_fee_mask;\n }\n\n // Withdraw specific data\n\n uint256 constant memo_native_amount_pos = memo_fee_pos + memo_fee_size;\n uint256 constant memo_native_amount_size = 8;\n uint256 constant memo_native_amount_mask = (1 << (memo_native_amount_size * 8)) - 1;\n\n function _memo_native_amount() internal pure returns (uint256 r) {\n r = _loaduint256(memo_native_amount_pos + memo_native_amount_size - uint256_size) & memo_native_amount_mask;\n }\n\n uint256 constant memo_receiver_pos = memo_native_amount_pos + memo_native_amount_size;\n uint256 constant memo_receiver_size = 20;\n\n function _memo_receiver() internal pure returns (address r) {\n r = address(uint160(_loaduint256(memo_receiver_pos + memo_receiver_size - uint256_size)));\n }\n\n // Permittable token deposit specific data\n\n uint256 constant memo_permit_deadline_pos = memo_fee_pos + memo_fee_size;\n uint256 constant memo_permit_deadline_size = 8;\n\n function _memo_permit_deadline() internal pure returns (uint64 r) {\n r = uint64(_loaduint256(memo_permit_deadline_pos + memo_permit_deadline_size - uint256_size));\n }\n\n uint256 constant memo_permit_holder_pos = memo_permit_deadline_pos + memo_permit_deadline_size;\n uint256 constant memo_permit_holder_size = 20;\n\n function _memo_permit_holder() internal pure returns (address r) {\n r = address(uint160(_loaduint256(memo_permit_holder_pos + memo_permit_holder_size - uint256_size)));\n }\n}\n", + "src/zkbob/utils/Parameters.sol": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.15;\n\nimport \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport \"./CustomABIDecoder.sol\";\n\nabstract contract Parameters is CustomABIDecoder {\n uint256 constant R = 21888242871839275222246405745257275088548364400416034343698204186575808495617;\n bytes32 constant S_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n function _root() internal view virtual returns (uint256);\n function _pool_id() internal view virtual returns (uint256);\n\n function _transfer_pub() internal view returns (uint256[5] memory r) {\n r[0] = _root();\n r[1] = _transfer_nullifier();\n r[2] = _transfer_out_commit();\n r[3] = _transfer_delta() + (_pool_id() << (transfer_delta_size * 8));\n r[4] = uint256(keccak256(_memo_data())) % R;\n }\n\n function _tree_pub(uint256 _root_before) internal view returns (uint256[3] memory r) {\n r[0] = _root_before;\n r[1] = _tree_root_after();\n r[2] = _transfer_out_commit();\n }\n\n // NOTE only valid in the context of normal deposit (tx_type=0)\n function _deposit_spender() internal pure returns (address) {\n (bytes32 r, bytes32 vs) = _sign_r_vs();\n return ECDSA.recover(ECDSA.toEthSignedMessageHash(bytes32(_transfer_nullifier())), r, vs);\n }\n\n // NOTE only valid in the context of permittable token deposit (tx_type=3)\n function _permittable_deposit_signature() internal pure returns (uint8, bytes32, bytes32) {\n (bytes32 r, bytes32 vs) = _sign_r_vs();\n return (uint8((uint256(vs) >> 255) + 27), r, vs & S_MASK);\n }\n}\n", + "src/zkbob/utils/ZkBobAccounting.sol": "// SPDX-License-Identifier: CC0-1.0\n\npragma solidity 0.8.15;\n\n/**\n * @title ZkBobAccounting\n * @dev On chain accounting for zkBob operations, limits and stats.\n * Units: 1 BOB = 1e18 wei = 1e9 zkBOB units\n * Limitations: Contract will only work correctly as long as pool tvl does not exceed 4.7e12 BOB (4.7 trillion)\n * and overall transaction count does not exceed 4.3e9 (4.3 billion). Pool usage limits cannot exceed 4.3e9 BOB (4.3 billion) per day.\n */\ncontract ZkBobAccounting {\n uint256 internal constant PRECISION = 1_000_000_000;\n uint256 internal constant SLOT_DURATION = 1 hours;\n uint256 internal constant DAY_SLOTS = 1 days / SLOT_DURATION;\n uint256 internal constant WEEK_SLOTS = 1 weeks / SLOT_DURATION;\n\n struct Slot0 {\n // max seen average tvl over period of at least 1 week (granularity of 1e9), might not be precise\n // max possible tvl - type(uint56).max * 1e9 zkBOB units ~= 7.2e16 BOB\n uint56 maxWeeklyAvgTvl;\n // max number of pool interactions over 1 week, might not be precise\n // max possible tx count - type(uint32).max ~= 4.3e9 transactions\n uint32 maxWeeklyTxCount;\n // 1 week behind snapshot time slot (granularity of 1 hour)\n // max possible timestamp - Dec 08 3883\n uint24 tailSlot;\n // active snapshot time slot (granularity of 1 hour)\n // max possible timestamp - Dec 08 3883\n uint24 headSlot;\n // cumulative sum of tvl over txCount interactions (granularity of 1e9)\n // max possible cumulative tvl ~= type(uint32).max * type(uint56).max = 4.3e9 transactions * 7.2e16 BOB\n uint88 cumTvl;\n // number of successful pool interactions since launch\n // max possible tx count - type(uint32).max ~= 4.3e9 transactions\n uint32 txCount;\n }\n\n struct Slot1 {\n // current pool tvl (granularity of 1)\n // max possible tvl - type(uint72).max * 1 zkBOB units ~= 4.7e21 zkBOB units ~= 4.7e12 BOB\n uint72 tvl;\n }\n\n struct Tier {\n TierLimits limits;\n TierStats stats;\n }\n\n struct TierLimits {\n // max cap on the entire pool tvl (granularity of 1e9)\n // max possible cap - type(uint56).max * 1e9 zkBOB units ~= 7.2e16 BOB\n uint56 tvlCap;\n // max cap on the daily deposits sum (granularity of 1e9)\n // max possible cap - type(uint32).max * 1e9 zkBOB units ~= 4.3e9 BOB\n uint32 dailyDepositCap;\n // max cap on the daily withdrawal sum (granularity of 1e9)\n // max possible cap - type(uint32).max * 1e9 zkBOB units ~= 4.3e9 BOB\n uint32 dailyWithdrawalCap;\n // max cap on the daily deposits sum for single user (granularity of 1e9)\n // max possible cap - type(uint32).max * 1e9 zkBOB units ~= 4.3e9 BOB\n uint32 dailyUserDepositCap;\n // max cap on a single deposit (granularity of 1e9)\n // max possible cap - type(uint32).max * 1e9 zkBOB units ~= 4.3e9 BOB\n uint32 depositCap;\n // max cap on a single direct deposit (granularity of 1e9)\n // max possible cap - type(uint32).max * 1e9 zkBOB units ~= 4.3e9 BOB\n uint32 directDepositCap;\n // max cap on the daily direct deposits sum for single user (granularity of 1e9)\n // max possible cap - type(uint32).max * 1e9 zkBOB units ~= 4.3e9 BOB\n uint32 dailyUserDirectDepositCap;\n }\n\n struct TierStats {\n uint16 day; // last update day number\n uint72 dailyDeposit; // sum of all deposits during given day\n uint72 dailyWithdrawal; // sum of all withdrawals during given day\n }\n\n struct Snapshot {\n uint24 nextSlot; // next slot to from the queue\n uint32 txCount; // number of successful pool interactions since launch at the time of the snapshot\n uint88 cumTvl; // cumulative sum of tvl over txCount interactions (granularity of 1e9)\n }\n\n struct UserStats {\n uint16 day; // last update day number\n uint72 dailyDeposit; // sum of user deposits during given day\n uint8 tier; // user limits tier, 0 being the default tier\n uint72 dailyDirectDeposit; // sum of user direct deposits during given day\n }\n\n struct Limits {\n uint256 tvlCap;\n uint256 tvl;\n uint256 dailyDepositCap;\n uint256 dailyDepositCapUsage;\n uint256 dailyWithdrawalCap;\n uint256 dailyWithdrawalCapUsage;\n uint256 dailyUserDepositCap;\n uint256 dailyUserDepositCapUsage;\n uint256 depositCap;\n uint8 tier;\n uint256 dailyUserDirectDepositCap;\n uint256 dailyUserDirectDepositCapUsage;\n uint256 directDepositCap;\n }\n\n Slot0 private slot0;\n Slot1 private slot1;\n mapping(uint256 => Tier) private tiers; // pool limits and usage per tier\n mapping(uint256 => Snapshot) private snapshots; // single linked list of hourly snapshots\n mapping(address => UserStats) private userStats;\n\n event UpdateLimits(uint8 indexed tier, TierLimits limits);\n event UpdateTier(address user, uint8 tier);\n\n /**\n * @dev Returns currently configured limits and remaining quotas for the given user as of the current block.\n * @param _user user for which to retrieve limits.\n * @return limits (denominated in zkBOB units = 1e-9 BOB)\n */\n function getLimitsFor(address _user) external view returns (Limits memory) {\n Slot1 memory s1 = slot1;\n UserStats memory us = userStats[_user];\n Tier storage t = tiers[uint256(us.tier)];\n TierLimits memory tl = t.limits;\n TierStats memory ts = t.stats;\n uint24 curSlot = uint24(block.timestamp / SLOT_DURATION);\n uint24 today = curSlot / uint24(DAY_SLOTS);\n return Limits({\n tvlCap: tl.tvlCap * PRECISION,\n tvl: s1.tvl,\n dailyDepositCap: tl.dailyDepositCap * PRECISION,\n dailyDepositCapUsage: (ts.day == today) ? ts.dailyDeposit : 0,\n dailyWithdrawalCap: tl.dailyWithdrawalCap * PRECISION,\n dailyWithdrawalCapUsage: (ts.day == today) ? ts.dailyWithdrawal : 0,\n dailyUserDepositCap: tl.dailyUserDepositCap * PRECISION,\n dailyUserDepositCapUsage: (us.day == today) ? us.dailyDeposit : 0,\n depositCap: tl.depositCap * PRECISION,\n tier: us.tier,\n dailyUserDirectDepositCap: tl.dailyUserDirectDepositCap * PRECISION,\n dailyUserDirectDepositCapUsage: (us.day == today) ? us.dailyDirectDeposit : 0,\n directDepositCap: tl.directDepositCap * PRECISION\n });\n }\n\n function _recordOperation(\n address _user,\n int256 _txAmount\n )\n internal\n returns (uint56 maxWeeklyAvgTvl, uint32 maxWeeklyTxCount, uint256 txCount)\n {\n Slot0 memory s0 = slot0;\n Slot1 memory s1 = slot1;\n uint24 curSlot = uint24(block.timestamp / SLOT_DURATION);\n txCount = uint256(s0.txCount);\n\n // for full correctness, next line should use \"while\" instead of \"if\"\n // however, in order to keep constant gas usage, \"if\" is being used\n // this can lead to a longer sliding window (> 1 week) in some cases,\n // but eventually it will converge back to the 1 week target\n if (s0.txCount > 0 && curSlot - s0.tailSlot > WEEK_SLOTS) {\n // if tail is more than 1 week behind, we move tail pointer to the next snapshot\n Snapshot memory sn = snapshots[s0.tailSlot];\n delete snapshots[s0.tailSlot];\n s0.tailSlot = sn.nextSlot;\n uint32 weeklyTxCount = s0.txCount - sn.txCount;\n if (weeklyTxCount > s0.maxWeeklyTxCount) {\n s0.maxWeeklyTxCount = weeklyTxCount;\n }\n uint56 avgTvl = uint56((s0.cumTvl - sn.cumTvl) / weeklyTxCount);\n if (avgTvl > s0.maxWeeklyAvgTvl) {\n s0.maxWeeklyAvgTvl = avgTvl;\n }\n }\n\n if (s0.headSlot < curSlot) {\n snapshots[s0.headSlot] = Snapshot(curSlot, s0.txCount, s0.cumTvl);\n s0.headSlot = curSlot;\n }\n\n // update head stats\n s0.cumTvl += s1.tvl / uint72(PRECISION);\n s0.txCount++;\n\n _processTVLChange(s1, _user, _txAmount);\n\n slot0 = s0;\n return (s0.maxWeeklyAvgTvl, s0.maxWeeklyTxCount, txCount);\n }\n\n function _processTVLChange(Slot1 memory s1, address _user, int256 _txAmount) internal {\n uint16 curDay = uint16(block.timestamp / SLOT_DURATION / DAY_SLOTS);\n\n if (_txAmount == 0) {\n return;\n }\n\n UserStats memory us = userStats[_user];\n Tier storage t = tiers[us.tier];\n TierLimits memory tl = t.limits;\n TierStats memory ts = t.stats;\n\n if (_txAmount > 0) {\n uint256 depositAmount = uint256(_txAmount);\n s1.tvl += uint72(depositAmount);\n\n // check all sorts of limits when processing a deposit\n require(depositAmount <= uint256(tl.depositCap) * PRECISION, \"ZkBobAccounting: single deposit cap exceeded\");\n require(uint256(s1.tvl) <= uint256(tl.tvlCap) * PRECISION, \"ZkBobAccounting: tvl cap exceeded\");\n\n if (curDay > us.day) {\n // user snapshot is outdated, day number and daily sum could be reset\n userStats[_user] =\n UserStats({day: curDay, dailyDeposit: uint72(depositAmount), tier: us.tier, dailyDirectDeposit: 0});\n } else {\n us.dailyDeposit += uint72(depositAmount);\n require(\n uint256(us.dailyDeposit) <= uint256(tl.dailyUserDepositCap) * PRECISION,\n \"ZkBobAccounting: daily user deposit cap exceeded\"\n );\n userStats[_user] = us;\n }\n\n if (curDay > ts.day) {\n // latest deposit was on an earlier day, reset daily withdrawal sum\n ts = TierStats({day: curDay, dailyDeposit: uint72(depositAmount), dailyWithdrawal: 0});\n } else {\n ts.dailyDeposit += uint72(depositAmount);\n require(\n uint256(ts.dailyDeposit) <= uint256(tl.dailyDepositCap) * PRECISION,\n \"ZkBobAccounting: daily deposit cap exceeded\"\n );\n }\n } else {\n uint256 withdrawAmount = uint256(-_txAmount);\n require(withdrawAmount <= type(uint32).max * PRECISION, \"ZkBobAccounting: withdrawal amount too large\");\n s1.tvl -= uint72(withdrawAmount);\n\n if (curDay > ts.day) {\n // latest withdrawal was on an earlier day, reset daily deposit sum\n ts = TierStats({day: curDay, dailyDeposit: 0, dailyWithdrawal: uint72(withdrawAmount)});\n } else {\n ts.dailyWithdrawal += uint72(withdrawAmount);\n require(\n uint256(ts.dailyWithdrawal) <= uint256(tl.dailyWithdrawalCap) * PRECISION,\n \"ZkBobAccounting: daily withdrawal cap exceeded\"\n );\n }\n }\n\n slot1 = s1;\n t.stats = ts;\n }\n\n function _checkDirectDepositLimits(address _user, uint256 _amount) internal {\n uint16 curDay = uint16(block.timestamp / SLOT_DURATION / DAY_SLOTS);\n\n UserStats memory us = userStats[_user];\n TierLimits memory tl = tiers[us.tier].limits;\n\n // check all sorts of limits when processing a deposit\n require(\n _amount <= uint256(tl.directDepositCap) * PRECISION, \"ZkBobAccounting: single direct deposit cap exceeded\"\n );\n\n if (curDay > us.day) {\n // user snapshot is outdated, day number and daily sum could be reset\n us = UserStats({day: curDay, dailyDeposit: 0, tier: us.tier, dailyDirectDeposit: uint72(_amount)});\n } else {\n us.dailyDirectDeposit += uint72(_amount);\n require(\n uint256(us.dailyDirectDeposit) <= uint256(tl.dailyUserDirectDepositCap) * PRECISION,\n \"ZkBobAccounting: daily user direct deposit cap exceeded\"\n );\n }\n userStats[_user] = us;\n }\n\n function _processDirectDepositBatch(uint256 _totalAmount) internal returns (uint256) {\n slot1.tvl += uint72(_totalAmount);\n return slot0.txCount++;\n }\n\n function _resetDailyLimits(uint8 _tier) internal {\n delete tiers[_tier].stats;\n }\n\n function _setLimits(\n uint8 _tier,\n uint256 _tvlCap,\n uint256 _dailyDepositCap,\n uint256 _dailyWithdrawalCap,\n uint256 _dailyUserDepositCap,\n uint256 _depositCap,\n uint256 _dailyUserDirectDepositCap,\n uint256 _directDepositCap\n )\n internal\n {\n require(_tier < 255, \"ZkBobAccounting: invalid limit tier\");\n require(_depositCap > 0, \"ZkBobAccounting: zero deposit cap\");\n require(_tvlCap <= type(uint56).max * PRECISION, \"ZkBobAccounting: tvl cap too large\");\n require(_dailyDepositCap <= type(uint32).max * PRECISION, \"ZkBobAccounting: daily deposit cap too large\");\n require(_dailyWithdrawalCap <= type(uint32).max * PRECISION, \"ZkBobAccounting: daily withdrawal cap too large\");\n require(_dailyUserDepositCap >= _depositCap, \"ZkBobAccounting: daily user deposit cap too low\");\n require(_dailyDepositCap >= _dailyUserDepositCap, \"ZkBobAccounting: daily deposit cap too low\");\n require(_tvlCap >= _dailyDepositCap, \"ZkBobAccounting: tvl cap too low\");\n require(_dailyWithdrawalCap > 0, \"ZkBobAccounting: zero daily withdrawal cap\");\n require(\n _dailyUserDirectDepositCap >= _directDepositCap, \"ZkBobAccounting: daily user direct deposit cap too low\"\n );\n TierLimits memory tl = TierLimits({\n tvlCap: uint56(_tvlCap / PRECISION),\n dailyDepositCap: uint32(_dailyDepositCap / PRECISION),\n dailyWithdrawalCap: uint32(_dailyWithdrawalCap / PRECISION),\n dailyUserDepositCap: uint32(_dailyUserDepositCap / PRECISION),\n depositCap: uint32(_depositCap / PRECISION),\n dailyUserDirectDepositCap: uint32(_dailyUserDirectDepositCap / PRECISION),\n directDepositCap: uint32(_directDepositCap / PRECISION)\n });\n tiers[_tier].limits = tl;\n emit UpdateLimits(_tier, tl);\n }\n\n function _setUsersTier(uint8 _tier, address[] memory _users) internal {\n require(\n _tier == 255 || tiers[uint256(_tier)].limits.tvlCap > 0, \"ZkBobAccounting: non-existing pool limits tier\"\n );\n for (uint256 i = 0; i < _users.length; i++) {\n address user = _users[i];\n userStats[user].tier = _tier;\n emit UpdateTier(user, _tier);\n }\n }\n\n function _txCount() internal view returns (uint256) {\n return slot0.txCount;\n }\n}\n" + }, + "abi": "[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"__pool_id\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"_token\",\"type\":\"address\"},{\"internalType\":\"contract ITransferVerifier\",\"name\":\"_transfer_verifier\",\"type\":\"address\"},{\"internalType\":\"contract ITreeVerifier\",\"name\":\"_tree_verifier\",\"type\":\"address\"},{\"internalType\":\"contract IBatchDepositVerifier\",\"name\":\"_batch_deposit_verifier\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_direct_deposit_queue\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"message\",\"type\":\"bytes\"}],\"name\":\"Message\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint8\",\"name\":\"tier\",\"type\":\"uint8\"},{\"components\":[{\"internalType\":\"uint56\",\"name\":\"tvlCap\",\"type\":\"uint56\"},{\"internalType\":\"uint32\",\"name\":\"dailyDepositCap\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"dailyWithdrawalCap\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"dailyUserDepositCap\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"depositCap\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"directDepositCap\",\"type\":\"uint32\"},{\"internalType\":\"uint32\",\"name\":\"dailyUserDirectDepositCap\",\"type\":\"uint32\"}],\"indexed\":false,\"internalType\":\"struct ZkBobAccounting.TierLimits\",\"name\":\"limits\",\"type\":\"tuple\"}],\"name\":\"UpdateLimits\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"manager\",\"type\":\"address\"}],\"name\":\"UpdateOperatorManager\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"user\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint8\",\"name\":\"tier\",\"type\":\"uint8\"}],\"name\":\"UpdateTier\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"seller\",\"type\":\"address\"}],\"name\":\"UpdateTokenSeller\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"fee\",\"type\":\"uint256\"}],\"name\":\"WithdrawFee\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"accumulatedFee\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"all_messages_hash\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_root_after\",\"type\":\"uint256\"},{\"internalType\":\"uint256[]\",\"name\":\"_indices\",\"type\":\"uint256[]\"},{\"internalType\":\"uint256\",\"name\":\"_out_commit\",\"type\":\"uint256\"},{\"internalType\":\"uint256[8]\",\"name\":\"_batch_deposit_proof\",\"type\":\"uint256[8]\"},{\"internalType\":\"uint256[8]\",\"name\":\"_tree_proof\",\"type\":\"uint256[8]\"}],\"name\":\"appendDirectDeposits\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"batch_deposit_verifier\",\"outputs\":[{\"internalType\":\"contract IBatchDepositVerifier\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"denominator\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"direct_deposit_queue\",\"outputs\":[{\"internalType\":\"contract IZkBobDirectDepositQueue\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_user\",\"type\":\"address\"}],\"name\":\"getLimitsFor\",\"outputs\":[{\"components\":[{\"internalType\":\"uint256\",\"name\":\"tvlCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"tvl\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"dailyDepositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"dailyDepositCapUsage\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"dailyWithdrawalCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"dailyWithdrawalCapUsage\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"dailyUserDepositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"dailyUserDepositCapUsage\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"depositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint8\",\"name\":\"tier\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"dailyUserDirectDepositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"dailyUserDirectDepositCapUsage\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"directDepositCap\",\"type\":\"uint256\"}],\"internalType\":\"struct ZkBobAccounting.Limits\",\"name\":\"\",\"type\":\"tuple\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_root\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_tvlCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_dailyDepositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_dailyWithdrawalCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_dailyUserDepositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_depositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_dailyUserDirectDepositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_directDepositCap\",\"type\":\"uint256\"}],\"name\":\"initialize\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"nullifiers\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"operatorManager\",\"outputs\":[{\"internalType\":\"contract IOperatorManager\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pool_id\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pool_index\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_sender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"recordDirectDeposit\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint8\",\"name\":\"_tier\",\"type\":\"uint8\"}],\"name\":\"resetDailyLimits\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"roots\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint8\",\"name\":\"_tier\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"_tvlCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_dailyDepositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_dailyWithdrawalCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_dailyUserDepositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_depositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_dailyUserDirectDepositCap\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_directDepositCap\",\"type\":\"uint256\"}],\"name\":\"setLimits\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contract IOperatorManager\",\"name\":\"_operatorManager\",\"type\":\"address\"}],\"name\":\"setOperatorManager\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_seller\",\"type\":\"address\"}],\"name\":\"setTokenSeller\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint8\",\"name\":\"_tier\",\"type\":\"uint8\"},{\"internalType\":\"address[]\",\"name\":\"_users\",\"type\":\"address[]\"}],\"name\":\"setUsersTier\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"token\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"tokenSeller\",\"outputs\":[{\"internalType\":\"contract ITokenSeller\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"transact\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"transfer_verifier\",\"outputs\":[{\"internalType\":\"contract ITransferVerifier\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"tree_verifier\",\"outputs\":[{\"internalType\":\"contract ITreeVerifier\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_operator\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_to\",\"type\":\"address\"}],\"name\":\"withdrawFee\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", + "constructorArguments": null, + "matchType": "PARTIAL", + "compilationArtifacts": null, + "creationInputArtifacts": null, + "deployedBytecodeArtifacts": null + } + ] +} \ No newline at end of file diff --git a/apps/explorer/lib/explorer/application.ex b/apps/explorer/lib/explorer/application.ex index 23c5f2548f..55fbd296a6 100644 --- a/apps/explorer/lib/explorer/application.ex +++ b/apps/explorer/lib/explorer/application.ex @@ -54,6 +54,9 @@ defmodule Explorer.Application do Supervisor.child_spec({Task.Supervisor, name: Explorer.MarketTaskSupervisor}, id: Explorer.MarketTaskSupervisor), Supervisor.child_spec({Task.Supervisor, name: Explorer.GenesisDataTaskSupervisor}, id: GenesisDataTaskSupervisor), Supervisor.child_spec({Task.Supervisor, name: Explorer.TaskSupervisor}, id: Explorer.TaskSupervisor), + Supervisor.child_spec({Task.Supervisor, name: Explorer.LookUpSmartContractSourcesTaskSupervisor}, + id: LookUpSmartContractSourcesTaskSupervisor + ), Explorer.SmartContract.SolcDownloader, Explorer.SmartContract.VyperDownloader, {Registry, keys: :duplicate, name: Registry.ChainEvents, id: Registry.ChainEvents}, @@ -138,9 +141,7 @@ defmodule Explorer.Application do end defp sc_microservice_configure(process) do - config = Application.get_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour, []) - - if config[:enabled] && config[:type] == "eth_bytecode_db" do + if Application.get_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour)[:eth_bytecode_db?] do process else [] diff --git a/apps/explorer/lib/explorer/chain/fetcher/look_up_smart_contract_sources_on_demand.ex b/apps/explorer/lib/explorer/chain/fetcher/look_up_smart_contract_sources_on_demand.ex index 32bf7bde62..1e6bd9e6eb 100644 --- a/apps/explorer/lib/explorer/chain/fetcher/look_up_smart_contract_sources_on_demand.ex +++ b/apps/explorer/lib/explorer/chain/fetcher/look_up_smart_contract_sources_on_demand.ex @@ -5,7 +5,6 @@ defmodule Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand do use GenServer - alias Explorer.Chain alias Explorer.Chain.{Address, Data, SmartContract} alias Explorer.Chain.Events.Publisher alias Explorer.SmartContract.EthBytecodeDBInterface @@ -16,10 +15,16 @@ defmodule Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand do @cache_name :smart_contracts_sources_fetching + @cooldown_timeout 500 + def trigger_fetch(nil, _) do :ignore end + def trigger_fetch(address, %SmartContract{partially_verified: true}) do + GenServer.cast(__MODULE__, {:fetch, address}) + end + def trigger_fetch(_address, %SmartContract{}) do :ignore end @@ -28,21 +33,20 @@ defmodule Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand do GenServer.cast(__MODULE__, {:fetch, address}) end - defp fetch_sources(address) do + defp fetch_sources(address, only_full?) do creation_tx_input = contract_creation_input(address.hash) - with {:ok, %{"sourceType" => type} = source} <- + with {:ok, %{"sourceType" => type, "matchType" => match_type} = source} <- %{} |> prepare_bytecode_for_microservice(creation_tx_input, Data.to_string(address.contract_code)) - |> EthBytecodeDBInterface.search_contract(), + |> EthBytecodeDBInterface.search_contract(address.hash), + :ok <- check_match_type(match_type, only_full?), {:ok, _} <- process_contract_source(type, source, address.hash) do Publisher.broadcast(%{smart_contract_was_verified: [address.hash]}, :on_demand) else _ -> false end - - :ets.insert(@cache_name, {to_string(address.hash), DateTime.utc_now()}) end def start_link(_) do @@ -50,35 +54,61 @@ defmodule Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand do end @impl true - def init(opts) do + def init(_) do :ets.new(@cache_name, [ :set, :named_table, :public ]) - {:ok, opts} + {:ok, + %{ + current_concurrency: 0, + max_concurrency: + Application.get_env(:explorer, Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand)[:max_concurrency] + }} end @impl true - def handle_cast({:fetch, address}, state) do - if need_to_fetch_sources?(address) && check_interval(to_string(address.hash)) do - fetch_sources(address) - end + def handle_cast({:fetch, address}, %{current_concurrency: counter, max_concurrency: max_concurrency} = state) + when counter < max_concurrency do + handle_fetch_request(address, state) + end + + @impl true + def handle_cast({:fetch, _address} = request, %{current_concurrency: _counter} = state) do + Process.send_after(self(), request, @cooldown_timeout) {:noreply, state} end - defp need_to_fetch_sources?(%Address{smart_contract: nil}), do: true + @impl true + def handle_info({:fetch, address}, %{current_concurrency: counter, max_concurrency: max_concurrency} = state) + when counter < max_concurrency do + handle_fetch_request(address, state) + end - defp need_to_fetch_sources?(%Address{hash: hash}) do - case Chain.address_hash_to_one_smart_contract(hash) do - nil -> - true + @impl true + def handle_info({:fetch, _address} = request, state) do + Process.send_after(self(), request, @cooldown_timeout) + {:noreply, state} + end - _ -> - false - end + @impl true + def handle_info({ref, _answer}, %{current_concurrency: counter} = state) do + Process.demonitor(ref, [:flush]) + {:noreply, %{state | current_concurrency: counter - 1}} + end + + @impl true + def handle_info({:DOWN, _ref, :process, _pid, _reason}, %{current_concurrency: counter} = state) do + {:noreply, %{state | current_concurrency: counter - 1}} + end + + defp partially_verified?(%Address{smart_contract: nil}), do: nil + + defp partially_verified?(%Address{hash: hash}) do + SmartContract.select_partially_verified_by_address_hash(hash) end defp check_interval(address_string) do @@ -101,7 +131,7 @@ defmodule Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand do end def process_contract_source("VYPER", source, address_hash) do - VyperPublisher.process_rust_verifier_response(source, address_hash, true, true) + VyperPublisher.process_rust_verifier_response(source, address_hash, true, true, true) end def process_contract_source("YUL", source, address_hash) do @@ -109,4 +139,29 @@ defmodule Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand do end def process_contract_source(_, _source, _address_hash), do: false + + defp check_match_type("PARTIAL", true), do: :full_match_required + defp check_match_type(_, _), do: :ok + + defp handle_fetch_request(address, %{current_concurrency: counter} = state) do + need_to_check_and_partially_verified? = + check_interval(to_lowercase_string(address.hash)) && partially_verified?(address) + + diff = + if is_nil(need_to_check_and_partially_verified?) || need_to_check_and_partially_verified? do + Task.Supervisor.async_nolink(Explorer.GenesisDataTaskSupervisor, fn -> + fetch_sources(address, need_to_check_and_partially_verified?) + end) + + :ets.insert(@cache_name, {to_lowercase_string(address.hash), DateTime.utc_now()}) + + 1 + else + 0 + end + + {:noreply, %{state | current_concurrency: counter + diff}} + end + + defp to_lowercase_string(hash), do: hash |> to_string() |> String.downcase() end diff --git a/apps/explorer/lib/explorer/chain/smart_contract.ex b/apps/explorer/lib/explorer/chain/smart_contract.ex index adb743d347..18590460e6 100644 --- a/apps/explorer/lib/explorer/chain/smart_contract.ex +++ b/apps/explorer/lib/explorer/chain/smart_contract.ex @@ -953,4 +953,16 @@ defmodule Explorer.Chain.SmartContract do end defp abi_decode_address_output(_), do: nil + + @spec select_partially_verified_by_address_hash(binary() | Hash.t(), keyword) :: boolean() | nil + def select_partially_verified_by_address_hash(address_hash, options \\ []) do + query = + from( + smart_contract in __MODULE__, + where: smart_contract.address_hash == ^address_hash, + select: smart_contract.partially_verified + ) + + Chain.select_repo(options).one(query) + end end diff --git a/apps/explorer/lib/explorer/smart_contract/eth_bytecode_db_interface.ex b/apps/explorer/lib/explorer/smart_contract/eth_bytecode_db_interface.ex index 51656f7668..b4ffab0832 100644 --- a/apps/explorer/lib/explorer/smart_contract/eth_bytecode_db_interface.ex +++ b/apps/explorer/lib/explorer/smart_contract/eth_bytecode_db_interface.ex @@ -3,8 +3,30 @@ defmodule Explorer.SmartContract.EthBytecodeDBInterface do Adapter for interaction with https://github.com/blockscout/blockscout-rs/tree/main/eth-bytecode-db """ - def search_contract(%{"bytecode" => _, "bytecodeType" => _} = body) do - http_post_request(bytecode_search_sources_url(), body) + def search_contract(%{"bytecode" => _, "bytecodeType" => _} = body, address_hash) do + if chain_id = Application.get_env(:block_scout_web, :chain_id) do + http_post_request( + bytecode_search_all_sources_url(), + Map.merge(body, %{ + "chain" => to_string(chain_id), + "address" => to_string(address_hash) + }) + ) + else + http_post_request(bytecode_search_sources_url(), body) + end + end + + def process_verifier_response(%{"sourcifySources" => [src | _]}) do + {:ok, Map.put(src, "sourcify?", true)} + end + + def process_verifier_response(%{"ethBytecodeDbSources" => [src | _]}) do + {:ok, src} + end + + def process_verifier_response(%{"ethBytecodeDbSources" => [], "sourcifySources" => []}) do + {:error, :no_matched_sources} end def process_verifier_response(%{"sources" => [src | _]}) do @@ -15,7 +37,23 @@ defmodule Explorer.SmartContract.EthBytecodeDBInterface do {:ok, nil} end - def bytecode_search_sources_url, do: "#{base_api_url()}" <> "/bytecodes/sources:search" + def bytecode_search_sources_url do + # workaround because of https://github.com/PSPDFKit-labs/bypass/issues/122 + if Mix.env() == :test do + "#{base_api_url()}" <> "/bytecodes/sources_search" + else + "#{base_api_url()}" <> "/bytecodes/sources:search" + end + end + + def bytecode_search_all_sources_url do + # workaround because of https://github.com/PSPDFKit-labs/bypass/issues/122 + if Mix.env() == :test do + "#{base_api_url()}" <> "/bytecodes/sources_search_all" + else + "#{base_api_url()}" <> "/bytecodes/sources:search-all" + end + end use Explorer.SmartContract.RustVerifierInterfaceBehaviour end diff --git a/apps/explorer/lib/explorer/smart_contract/helper.ex b/apps/explorer/lib/explorer/smart_contract/helper.ex index 047f80a3e7..c73ea123b9 100644 --- a/apps/explorer/lib/explorer/smart_contract/helper.ex +++ b/apps/explorer/lib/explorer/smart_contract/helper.ex @@ -115,11 +115,17 @@ defmodule Explorer.SmartContract.Helper do end def cast_libraries(map) do - map - |> Map.values() - |> Enum.reduce(%{}, fn map, acc -> Map.merge(acc, map) end) + map |> Map.values() |> List.first() |> cast_libraries(map) end + def cast_libraries(value, map) when is_map(value), + do: + map + |> Map.values() + |> Enum.reduce(%{}, fn map, acc -> Map.merge(acc, map) end) + + def cast_libraries(_value, map), do: map + def contract_creation_input(address_hash) do case Chain.smart_contract_creation_tx_bytecode(address_hash) do %{init: init, created_contract_code: _created_contract_code} -> diff --git a/apps/explorer/lib/explorer/smart_contract/rust_verifier_interface_behaviour.ex b/apps/explorer/lib/explorer/smart_contract/rust_verifier_interface_behaviour.ex index b96f7eca34..799fd7bd0e 100644 --- a/apps/explorer/lib/explorer/smart_contract/rust_verifier_interface_behaviour.ex +++ b/apps/explorer/lib/explorer/smart_contract/rust_verifier_interface_behaviour.ex @@ -9,7 +9,7 @@ defmodule Explorer.SmartContract.RustVerifierInterfaceBehaviour do alias HTTPoison.Response require Logger - @post_timeout :timer.seconds(120) + @post_timeout :timer.minutes(5) @request_error_msg "Error while sending request to verification microservice" def verify_multi_part( diff --git a/apps/explorer/lib/explorer/smart_contract/solidity/publish_helper.ex b/apps/explorer/lib/explorer/smart_contract/solidity/publish_helper.ex index dfa4dfb120..fa53ae8681 100644 --- a/apps/explorer/lib/explorer/smart_contract/solidity/publish_helper.ex +++ b/apps/explorer/lib/explorer/smart_contract/solidity/publish_helper.ex @@ -4,9 +4,9 @@ defmodule Explorer.SmartContract.Solidity.PublishHelper do """ alias Ecto.Changeset - alias Explorer.Chain + alias Explorer.Chain.{Address, SmartContract} alias Explorer.Chain.Events.Publisher, as: EventsPublisher - alias Explorer.Chain.SmartContract + alias Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand alias Explorer.SmartContract.Solidity.Publisher alias Explorer.ThirdPartyIntegrations.Sourcify @@ -148,26 +148,25 @@ defmodule Explorer.SmartContract.Solidity.PublishHelper do end def check_and_verify(address_hash_string) do - if Chain.smart_contract_fully_verified?(address_hash_string) do - {:ok, :already_fully_verified} + if Application.get_env(:explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour)[:eth_bytecode_db?] do + LookUpSmartContractSourcesOnDemand.trigger_fetch(%Address{hash: address_hash_string}, nil) else - check_and_verify_inner(address_hash_string) - end - end - - defp check_and_verify_inner(address_hash_string) do - if Application.get_env(:explorer, Explorer.ThirdPartyIntegrations.Sourcify)[:enabled] do - if Chain.smart_contract_verified?(address_hash_string) do - check_by_address_in_sourcify_if_contract_verified(address_hash_string) + if Application.get_env(:explorer, Explorer.ThirdPartyIntegrations.Sourcify)[:enabled] do + {:error, :sourcify_disabled} else - check_by_address_in_sourcify_else(address_hash_string) + check_by_address_in_sourcify( + SmartContract.select_partially_verified_by_address_hash(address_hash_string), + address_hash_string + ) end - else - {:error, :sourcify_disabled} end end - defp check_by_address_in_sourcify_if_contract_verified(address_hash_string) do + defp check_by_address_in_sourcify(false, _address_hash_string) do + {:ok, :already_fully_verified} + end + + defp check_by_address_in_sourcify(true, address_hash_string) do case Sourcify.check_by_address(address_hash_string) do {:ok, _verified_status} -> get_metadata_and_publish(address_hash_string, nil) @@ -177,7 +176,7 @@ defmodule Explorer.SmartContract.Solidity.PublishHelper do end end - defp check_by_address_in_sourcify_else(address_hash_string) do + defp check_by_address_in_sourcify(nil, address_hash_string) do case Sourcify.check_by_address_any(address_hash_string) do {:ok, "full", metadata} -> process_metadata_and_publish(address_hash_string, metadata, false, false) diff --git a/apps/explorer/lib/explorer/smart_contract/solidity/publisher.ex b/apps/explorer/lib/explorer/smart_contract/solidity/publisher.ex index 0457661981..cee27ad6c9 100644 --- a/apps/explorer/lib/explorer/smart_contract/solidity/publisher.ex +++ b/apps/explorer/lib/explorer/smart_contract/solidity/publisher.ex @@ -145,7 +145,7 @@ defmodule Explorer.SmartContract.Solidity.Publisher do "sourceFiles" => sources, "compilerSettings" => compiler_settings_string, "matchType" => match_type - }, + } = source, address_hash, is_standard_json?, save_file_path?, @@ -177,6 +177,7 @@ defmodule Explorer.SmartContract.Solidity.Publisher do |> Map.put("compiler_settings", if(is_standard_json?, do: compiler_settings)) |> Map.put("partially_verified", match_type == "PARTIAL") |> Map.put("verified_via_eth_bytecode_db", automatically_verified?) + |> Map.put("verified_via_sourcify", source["sourcify?"]) publish_smart_contract(address_hash, prepared_params, Jason.decode!(abi_string || "null")) end diff --git a/apps/explorer/test/explorer/chain_test.exs b/apps/explorer/test/explorer/chain_test.exs index b7472db712..83821fea4a 100644 --- a/apps/explorer/test/explorer/chain_test.exs +++ b/apps/explorer/test/explorer/chain_test.exs @@ -4242,14 +4242,18 @@ defmodule Explorer.ChainTest do assert sc_before_call.partially_verified == Map.get(valid_attrs, :partially_verified) assert {:ok, %SmartContract{}} = - Chain.update_smart_contract(%{address_hash: address.hash, partially_verified: false}) + Chain.update_smart_contract(%{ + address_hash: address.hash, + partially_verified: false, + contract_source_code: "new code" + }) sc_after_call = Repo.get_by(SmartContract, address_hash: address.hash) assert sc_after_call.name == Map.get(valid_attrs, :name) assert sc_after_call.partially_verified == false assert sc_after_call.compiler_version == Map.get(valid_attrs, :compiler_version) assert sc_after_call.optimization == Map.get(valid_attrs, :optimization) - assert sc_after_call.contract_source_code == Map.get(valid_attrs, :contract_source_code) + assert sc_after_call.contract_source_code == "new code" end test "check nothing changed", %{valid_attrs: valid_attrs, address: address} do diff --git a/config/runtime.exs b/config/runtime.exs index a80e8b88a3..17ab3d507f 100644 --- a/config/runtime.exs +++ b/config/runtime.exs @@ -359,11 +359,15 @@ config :explorer, Explorer.ThirdPartyIntegrations.Sourcify, chain_id: System.get_env("CHAIN_ID"), repo_url: System.get_env("SOURCIFY_REPO_URL") || "https://repo.sourcify.dev/contracts" +enabled? = ConfigHelper.parse_bool_env_var("MICROSERVICE_SC_VERIFIER_ENABLED") +# or "eth_bytecode_db" +type = System.get_env("MICROSERVICE_SC_VERIFIER_TYPE", "sc_verifier") + config :explorer, Explorer.SmartContract.RustVerifierInterfaceBehaviour, service_url: System.get_env("MICROSERVICE_SC_VERIFIER_URL") || "https://eth-bytecode-db.services.blockscout.com/", - enabled: ConfigHelper.parse_bool_env_var("MICROSERVICE_SC_VERIFIER_ENABLED"), - # or "eth_bytecode_db" - type: System.get_env("MICROSERVICE_SC_VERIFIER_TYPE", "eth_bytecode_db") + enabled: enabled?, + type: type, + eth_bytecode_db?: enabled? && type == "eth_bytecode_db" config :explorer, Explorer.Visualize.Sol2uml, service_url: System.get_env("MICROSERVICE_VISUALIZE_SOL2UML_URL"), @@ -407,7 +411,8 @@ config :explorer, Explorer.Chain.Cache.TransactionActionTokensData, max_cache_size: ConfigHelper.parse_integer_env_var("INDEXER_TX_ACTIONS_MAX_TOKEN_CACHE_SIZE", 100_000) config :explorer, Explorer.Chain.Fetcher.LookUpSmartContractSourcesOnDemand, - fetch_interval: ConfigHelper.parse_time_env_var("MICROSERVICE_ETH_BYTECODE_DB_INTERVAL_BETWEEN_LOOKUPS", "10m") + fetch_interval: ConfigHelper.parse_time_env_var("MICROSERVICE_ETH_BYTECODE_DB_INTERVAL_BETWEEN_LOOKUPS", "10m"), + max_concurrency: ConfigHelper.parse_integer_env_var("MICROSERVICE_ETH_BYTECODE_DB_MAX_LOOKUPS_CONCURRENCY", 10) config :explorer, Explorer.Chain.Cache.MinMissingBlockNumber, enabled: !ConfigHelper.parse_bool_env_var("DISABLE_INDEXER") diff --git a/docker-compose/envs/common-blockscout.env b/docker-compose/envs/common-blockscout.env index 38a1361972..c20e65a313 100644 --- a/docker-compose/envs/common-blockscout.env +++ b/docker-compose/envs/common-blockscout.env @@ -203,6 +203,7 @@ MICROSERVICE_SC_VERIFIER_ENABLED=true MICROSERVICE_SC_VERIFIER_URL=https://eth-bytecode-db.services.blockscout.com/ MICROSERVICE_SC_VERIFIER_TYPE=eth_bytecode_db MICROSERVICE_ETH_BYTECODE_DB_INTERVAL_BETWEEN_LOOKUPS=10m +MICROSERVICE_ETH_BYTECODE_DB_MAX_LOOKUPS_CONCURRENCY=10 MICROSERVICE_VISUALIZE_SOL2UML_ENABLED=true MICROSERVICE_VISUALIZE_SOL2UML_URL=http://visualizer:8050/ MICROSERVICE_SIG_PROVIDER_ENABLED=true