diff --git a/README.md b/README.md index 369b476ca2..55d957988b 100644 --- a/README.md +++ b/README.md @@ -32,12 +32,12 @@ Finally, you can execute Hyperdrive trades in a simulated blockchain environment ```python import datetime from fixedpointmath import FixedPoint -from agent0 import ILocalHyperdrive, ILocalChain +from agent0 import LocalHyperdrive, LocalChain # Initialize -chain = ILocalChain() -interactive_hyperdrive = ILocalHyperdrive(chain) -hyperdrive_agent0 = interactive_hyperdrive.init_agent(base=FixedPoint(100_000)) +chain = LocalChain() +hyperdrive = LocalHyperdrive(chain) +hyperdrive_agent0 = hyperdrive.init_agent(base=FixedPoint(100_000)) # Run trades chain.advance_time(datetime.timedelta(weeks=1)) @@ -48,7 +48,7 @@ close_event = hyperdrive_agent0.close_long( ) # Analyze -pool_state = interactive_hyperdrive.get_pool_state(coerce_float=True) +pool_state = hyperdrive.get_pool_state(coerce_float=True) pool_state.plot(x="block_number", y="longs_outstanding", kind="line") ``` diff --git a/examples/interactive_hyperdrive_forking_example.py b/examples/interactive_hyperdrive_forking_example.py index 6fa4436b38..47c3039ae4 100644 --- a/examples/interactive_hyperdrive_forking_example.py +++ b/examples/interactive_hyperdrive_forking_example.py @@ -9,7 +9,7 @@ from fixedpointmath import FixedPoint -from agent0 import IHyperdrive, ILocalChain, PolicyZoo +from agent0 import Hyperdrive, LocalChain, PolicyZoo from agent0.core.base.make_key import make_private_key # %% @@ -23,19 +23,19 @@ # %% # Launch a local anvil chain forked from the rpc uri. -chain = ILocalChain(fork_uri=rpc_uri, fork_block_number=fork_block_number) +chain = LocalChain(fork_uri=rpc_uri, fork_block_number=fork_block_number) -hyperdrive_address = IHyperdrive.get_hyperdrive_addresses_from_registry(registry_address, chain)["sdai_14_day"] +hyperdrive_address = Hyperdrive.get_hyperdrive_addresses_from_registry(registry_address, chain)["sdai_14_day"] -# Note that we use IHyperdrive here instead of ILocalHyperdrive, -# as ILocalHyperdrive deploys a new pool, whereas we want to connect to an existing pool +# Note that we use Hyperdrive here instead of LocalHyperdrive, +# as LocalHyperdrive deploys a new pool, whereas we want to connect to an existing pool # on the forked local chain. -# TODO this prevents us from using data tools provided by ILocalHyperdrive, ideally we can -# load a ILocalHyperdrive from an IHyperdrive object that connects to an existing pool and populates +# TODO this prevents us from using data tools provided by LocalHyperdrive, ideally we can +# load a LocalHyperdrive from an Hyperdrive object that connects to an existing pool and populates # the database. This is blocked by needing an archive node, the fix here would be to # (1) use event data instead, and (2) build historical data from event data. -hyperdrive_config = IHyperdrive.Config() -hyperdrive_pool = IHyperdrive(chain, hyperdrive_address, hyperdrive_config) +hyperdrive_config = Hyperdrive.Config() +hyperdrive_pool = Hyperdrive(chain, hyperdrive_address, hyperdrive_config) # %% diff --git a/examples/interactive_local_hyperdrive_advanced_example.py b/examples/interactive_local_hyperdrive_advanced_example.py index 03e23df12f..9aca8bd161 100644 --- a/examples/interactive_local_hyperdrive_advanced_example.py +++ b/examples/interactive_local_hyperdrive_advanced_example.py @@ -6,17 +6,17 @@ from fixedpointmath import FixedPoint -from agent0 import ILocalChain, ILocalHyperdrive, PolicyZoo +from agent0 import LocalChain, LocalHyperdrive, PolicyZoo # %% # Parameters for local chain initialization, defines defaults in constructor -local_chain_config = ILocalChain.Config() +local_chain_config = LocalChain.Config() # Launches a local chain in a subprocess # This also launches a local postgres docker container for data under the hood, attached to the chain. # Each hyperdrive pool will have it's own database within this container # NOTE: LocalChain is a subclass of Chain # TODO can also implement functionality such as save/load state here -chain = ILocalChain(local_chain_config) +chain = LocalChain(local_chain_config) # Can connect to a specific existing chain # existing_chain = Chain("http://localhost:8545") @@ -25,9 +25,9 @@ # An "admin" user (as provided by the Chain object) is launched/funded here for deploying hyperdrive # Parameters for pool initialization. If empty, defaults to default values, allows for custom values if needed -initial_pool_config = ILocalHyperdrive.Config() +initial_pool_config = LocalHyperdrive.Config() # Launches 2 pools on the same local chain -interactive_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) +interactive_hyperdrive = LocalHyperdrive(chain, initial_pool_config) # %% # Generate funded trading agents from the interactive object diff --git a/examples/interactive_local_hyperdrive_example.py b/examples/interactive_local_hyperdrive_example.py index 2ffc09f7c9..c0d72dc0e0 100644 --- a/examples/interactive_local_hyperdrive_example.py +++ b/examples/interactive_local_hyperdrive_example.py @@ -8,16 +8,16 @@ from fixedpointmath import FixedPoint -from agent0 import ILocalChain, ILocalHyperdrive +from agent0 import LocalChain, LocalHyperdrive # %% # Parameters for local chain initialization, defines defaults in constructor -local_chain_config = ILocalChain.Config() +local_chain_config = LocalChain.Config() # Launches a local chain in a subprocess # This also launches a local postgres docker container for data under the hood, attached to the chain. # Each hyperdrive pool will have it's own database within this container # NOTE: LocalChain is a subclass of Chain -chain = ILocalChain(local_chain_config) +chain = LocalChain(local_chain_config) # Can connect to a specific existing chain # existing_chain = Chain("http://localhost:8545") @@ -26,18 +26,18 @@ # An "admin" user (as provided by the Chain object) is launched/funded here for deploying hyperdrive # Parameters for pool initialization. If empty, defaults to default values, allows for custom values if needed -initial_pool_config = ILocalHyperdrive.Config() +initial_pool_config = LocalHyperdrive.Config() # Launches 2 pools on the same local chain -interactive_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) -interactive_hyperdrive_2 = ILocalHyperdrive(chain, initial_pool_config) +hyperdrive = LocalHyperdrive(chain, initial_pool_config) +hyperdrive_2 = LocalHyperdrive(chain, initial_pool_config) # %% # Generate funded trading agents from the interactive object # Names are reflected on output data frames and plots later -hyperdrive_agent0 = interactive_hyperdrive.init_agent(base=FixedPoint(100000), eth=FixedPoint(100), name="alice") -hyperdrive_agent1 = interactive_hyperdrive_2.init_agent(base=FixedPoint(100000), eth=FixedPoint(100), name="bob") +hyperdrive_agent0 = hyperdrive.init_agent(base=FixedPoint(100000), eth=FixedPoint(100), name="alice") +hyperdrive_agent1 = hyperdrive_2.init_agent(base=FixedPoint(100000), eth=FixedPoint(100), name="bob") # Omission of name defaults to wallet address -hyperdrive_agent2 = interactive_hyperdrive.init_agent(base=FixedPoint(100000)) +hyperdrive_agent2 = hyperdrive.init_agent(base=FixedPoint(100000)) # Add funds to an agent hyperdrive_agent0.add_funds(base=FixedPoint(100000), eth=FixedPoint(100)) @@ -93,18 +93,18 @@ # %% # Get data from database under the hood -pool_config = interactive_hyperdrive.get_pool_config() +pool_config = hyperdrive.get_pool_config() # The underlying data is in Decimal format, which is lossless. We don't care about precision # here, and pandas need a numerical float for plotting, so we coerce decimals to floats here -pool_state = interactive_hyperdrive.get_pool_state(coerce_float=True) +pool_state = hyperdrive.get_pool_state(coerce_float=True) # TODO checkpoint info doesn't play nice with advancing time. # This is because we don't create checkpoints when we advance time. -checkpoint_info = interactive_hyperdrive.get_checkpoint_info() +checkpoint_info = hyperdrive.get_checkpoint_info() -current_wallet = interactive_hyperdrive.get_current_wallet() -ticker = interactive_hyperdrive.get_ticker() -wallet_positions = interactive_hyperdrive.get_wallet_positions() -total_wallet_pnl_over_time = interactive_hyperdrive.get_total_wallet_pnl_over_time(coerce_float=True) +current_wallet = hyperdrive.get_current_wallet() +ticker = hyperdrive.get_ticker() +wallet_positions = hyperdrive.get_wallet_positions() +total_wallet_pnl_over_time = hyperdrive.get_total_wallet_pnl_over_time(coerce_float=True) # %% print(pool_state) diff --git a/examples/interactive_remote_hyperdrive_example.py b/examples/interactive_remote_hyperdrive_example.py index e93fe7996a..a6d3026159 100644 --- a/examples/interactive_remote_hyperdrive_example.py +++ b/examples/interactive_remote_hyperdrive_example.py @@ -9,13 +9,13 @@ from fixedpointmath import FixedPoint -from agent0 import IChain, IHyperdrive, PolicyZoo +from agent0 import Chain, Hyperdrive, PolicyZoo from agent0.core.base.make_key import make_private_key # %% # Set the rpc_uri to the chain, e.g., to sepolia testnet rpc_uri = "http://uri.to.sepolia.testnet" -chain = IChain(rpc_uri) +chain = Chain(rpc_uri) # Set the address of the hyperdrive pool # hyperdrive_address = "0x0000000000000000000000000000000000000000" @@ -24,9 +24,9 @@ # This is the registry address deployed on sepolia. registry_address = "0xba5156E697d39a03EDA824C19f375383F6b759EA" -hyperdrive_address = IHyperdrive.get_hyperdrive_addresses_from_registry(registry_address, chain)["sdai_14_day"] -hyperdrive_config = IHyperdrive.Config() -hyperdrive_pool = IHyperdrive(chain, hyperdrive_address, hyperdrive_config) +hyperdrive_address = Hyperdrive.get_hyperdrive_addresses_from_registry(registry_address, chain)["sdai_14_day"] +hyperdrive_config = Hyperdrive.Config() +hyperdrive_pool = Hyperdrive(chain, hyperdrive_address, hyperdrive_config) # %% diff --git a/examples/tutorial.ipynb b/examples/tutorial.ipynb index f71b457fc5..bec75cc9fc 100644 --- a/examples/tutorial.ipynb +++ b/examples/tutorial.ipynb @@ -38,11 +38,11 @@ "source": [ "import datetime\n", "from fixedpointmath import FixedPoint\n", - "from agent0 import ILocalHyperdrive, ILocalChain\n", + "from agent0 import LocalHyperdrive, LocalChain\n", "\n", - "chain = ILocalChain()\n", - "interactive_hyperdrive = ILocalHyperdrive(chain)\n", - "hyperdrive_agent0 = interactive_hyperdrive.init_agent(base=FixedPoint(100_000))" + "chain = LocalChain()\n", + "hyperdrive = LocalHyperdrive(chain)\n", + "hyperdrive_agent0 = hyperdrive.init_agent(base=FixedPoint(100_000))" ] }, { @@ -81,7 +81,7 @@ { "data": { "text/plain": [ - "OpenLong(trader='0xfBAD8328499B0F402E2541d038406B12ef604C54', asset_id=452312848583266388373324160190187140051835877600158453279131187532623020656, maturity_time=1712358000, base_amount=FixedPoint(\"100.0\"), vault_share_amount=FixedPoint(\"99.999994292237768785\"), as_base=True, bond_amount=FixedPoint(\"100.094931446527329167\"))" + "OpenLong(trader='0x888Fe86DEBcceA6CE844B9b57340CA2e4045581a', asset_id=452312848583266388373324160190187140051835877600158453279131187532625774656, maturity_time=1715112000, base_amount=FixedPoint(\"100.0\"), vault_share_amount=FixedPoint(\"99.999994292237768785\"), as_base=True, bond_amount=FixedPoint(\"100.094931446527329167\"), __name__='OpenLong')" ] }, "execution_count": 3, @@ -163,7 +163,7 @@ " " ], "text/plain": [ - "" + "" ] }, "metadata": {}, @@ -171,7 +171,7 @@ } ], "source": [ - "dashboard = interactive_hyperdrive.get_dashboard_iframe()\n", + "dashboard = hyperdrive.get_dashboard_iframe()\n", "display(dashboard)" ] }, @@ -237,7 +237,7 @@ { "data": { "text/plain": [ - "[OpenShort(trader='0xd916eB77507B14f99Ea32974EaC6b2216EAC336f', asset_id=904625697166532776746648320380374280103671755200316906558262375063533769712, maturity_time=1712444400, base_amount=FixedPoint(\"0.110312209275189716\"), vault_share_amount=FixedPoint(\"0.110297079098986197\"), as_base=True, base_proceeds=FixedPoint(\"112.770034371258485699\"), bond_amount=FixedPoint(\"112.879252612892491776\"))]" + "[OpenShort(trader='0x35DD4CBFD0c3D6bcBAFAC4fb70BEef0882A86Bb7', asset_id=904625697166532776746648320380374280103671755200316906558262375063536523712, maturity_time=1715198400, base_amount=FixedPoint(\"0.110312209275189716\"), vault_share_amount=FixedPoint(\"0.110297079098986197\"), as_base=True, base_proceeds=FixedPoint(\"112.770034371258485699\"), bond_amount=FixedPoint(\"112.879252612892491776\"), __name__='OpenShort')]" ] }, "execution_count": 7, @@ -246,7 +246,7 @@ } ], "source": [ - "random_agent = interactive_hyperdrive.init_agent(\n", + "random_agent = hyperdrive.init_agent(\n", " base=FixedPoint(1_000),\n", " policy=PolicyZoo.random,\n", " policy_config=PolicyZoo.random.Config(rng_seed=123),\n", @@ -310,7 +310,7 @@ " done_trading = False\n", " # If no longs in wallet, we check our fixed rate threshold and open the long if threshold reached.\n", " if len(wallet.longs) == 0:\n", - " if interface.calc_fixed_rate() > self.config.fixed_rate_threshold:\n", + " if interface.calc_spot_rate() > self.config.fixed_rate_threshold:\n", " return [open_long_trade(self.config.open_long_amount)], done_trading\n", " # If there are longs in the wallet, we check for maturity and close them if maturity reached.\n", " else:\n", @@ -344,7 +344,7 @@ "metadata": {}, "outputs": [], "source": [ - "policy_agent = interactive_hyperdrive.init_agent(\n", + "policy_agent = hyperdrive.init_agent(\n", " base=FixedPoint(1_000_000),\n", " policy=OpenLongPolicy,\n", " policy_config=OpenLongPolicy.Config(\n", @@ -397,73 +397,73 @@ " \n", " 0\n", " 20\n", - " 2024-03-29 23:02:15\n", + " 2024-04-30 20:23:38\n", " 0.049999999999999996\n", " \n", " \n", " 1\n", " 21\n", - " 2024-03-29 23:02:27\n", + " 2024-04-30 20:23:50\n", " 0.049999999999999996\n", " \n", " \n", " 2\n", " 22\n", - " 2024-03-29 23:02:39\n", + " 2024-04-30 20:24:02\n", " 0.049999999999999996\n", " \n", " \n", " 3\n", " 23\n", - " 2024-03-29 23:02:51\n", + " 2024-04-30 20:24:14\n", " 0.049999939182615754\n", " \n", " \n", " 4\n", " 24\n", - " 2024-03-29 23:03:03\n", + " 2024-04-30 20:24:26\n", " 0.049999999941576964\n", " \n", " \n", " 5\n", " 25\n", - " 2024-03-29 23:03:15\n", + " 2024-04-30 20:24:38\n", " 0.049999999941576964\n", " \n", " \n", " 6\n", " 73\n", - " 2024-03-30 23:03:27\n", + " 2024-05-01 20:24:50\n", " 0.049999999941576964\n", " \n", " \n", " 7\n", " 74\n", - " 2024-03-30 23:03:39\n", + " 2024-05-01 20:25:02\n", " 0.050000052064751971\n", " \n", " \n", " 8\n", " 75\n", - " 2024-03-30 23:03:51\n", + " 2024-05-01 20:25:14\n", " 0.050000052064751971\n", " \n", " \n", " 9\n", " 76\n", - " 2024-03-30 23:04:03\n", + " 2024-05-01 20:25:26\n", " 0.050000052064751971\n", " \n", " \n", " 10\n", " 77\n", - " 2024-03-30 23:04:15\n", + " 2024-05-01 20:25:38\n", " 0.050000120641985167\n", " \n", " \n", " 11\n", " 78\n", - " 2024-03-30 23:04:27\n", + " 2024-05-01 20:25:50\n", " 0.050000120641985167\n", " \n", " \n", @@ -472,18 +472,18 @@ ], "text/plain": [ " block_number timestamp fixed_rate\n", - "0 20 2024-03-29 23:02:15 0.049999999999999996\n", - "1 21 2024-03-29 23:02:27 0.049999999999999996\n", - "2 22 2024-03-29 23:02:39 0.049999999999999996\n", - "3 23 2024-03-29 23:02:51 0.049999939182615754\n", - "4 24 2024-03-29 23:03:03 0.049999999941576964\n", - "5 25 2024-03-29 23:03:15 0.049999999941576964\n", - "6 73 2024-03-30 23:03:27 0.049999999941576964\n", - "7 74 2024-03-30 23:03:39 0.050000052064751971\n", - "8 75 2024-03-30 23:03:51 0.050000052064751971\n", - "9 76 2024-03-30 23:04:03 0.050000052064751971\n", - "10 77 2024-03-30 23:04:15 0.050000120641985167\n", - "11 78 2024-03-30 23:04:27 0.050000120641985167" + "0 20 2024-04-30 20:23:38 0.049999999999999996\n", + "1 21 2024-04-30 20:23:50 0.049999999999999996\n", + "2 22 2024-04-30 20:24:02 0.049999999999999996\n", + "3 23 2024-04-30 20:24:14 0.049999939182615754\n", + "4 24 2024-04-30 20:24:26 0.049999999941576964\n", + "5 25 2024-04-30 20:24:38 0.049999999941576964\n", + "6 73 2024-05-01 20:24:50 0.049999999941576964\n", + "7 74 2024-05-01 20:25:02 0.050000052064751971\n", + "8 75 2024-05-01 20:25:14 0.050000052064751971\n", + "9 76 2024-05-01 20:25:26 0.050000052064751971\n", + "10 77 2024-05-01 20:25:38 0.050000120641985167\n", + "11 78 2024-05-01 20:25:50 0.050000120641985167" ] }, "execution_count": 11, @@ -492,7 +492,7 @@ } ], "source": [ - "interactive_hyperdrive.get_pool_state()[[\"block_number\", \"timestamp\", \"fixed_rate\"]]" + "hyperdrive.get_pool_state()[[\"block_number\", \"timestamp\", \"fixed_rate\"]]" ] }, { @@ -565,85 +565,85 @@ " \n", " 0\n", " 20\n", - " 2024-03-29 23:02:15\n", + " 2024-04-30 20:23:38\n", " 0.049999999999999996\n", " \n", " \n", " 1\n", " 21\n", - " 2024-03-29 23:02:27\n", + " 2024-04-30 20:23:50\n", " 0.049999999999999996\n", " \n", " \n", " 2\n", " 22\n", - " 2024-03-29 23:02:39\n", + " 2024-04-30 20:24:02\n", " 0.049999999999999996\n", " \n", " \n", " 3\n", " 23\n", - " 2024-03-29 23:02:51\n", + " 2024-04-30 20:24:14\n", " 0.049999939182615754\n", " \n", " \n", " 4\n", " 24\n", - " 2024-03-29 23:03:03\n", + " 2024-04-30 20:24:26\n", " 0.049999999941576964\n", " \n", " \n", " 5\n", " 25\n", - " 2024-03-29 23:03:15\n", + " 2024-04-30 20:24:38\n", " 0.049999999941576964\n", " \n", " \n", " 6\n", " 73\n", - " 2024-03-30 23:03:27\n", + " 2024-05-01 20:24:50\n", " 0.049999999941576964\n", " \n", " \n", " 7\n", " 74\n", - " 2024-03-30 23:03:39\n", + " 2024-05-01 20:25:02\n", " 0.050000052064751971\n", " \n", " \n", " 8\n", " 75\n", - " 2024-03-30 23:03:51\n", + " 2024-05-01 20:25:14\n", " 0.050000052064751971\n", " \n", " \n", " 9\n", " 76\n", - " 2024-03-30 23:04:03\n", + " 2024-05-01 20:25:26\n", " 0.050000052064751971\n", " \n", " \n", " 10\n", " 77\n", - " 2024-03-30 23:04:15\n", + " 2024-05-01 20:25:38\n", " 0.050000120641985167\n", " \n", " \n", " 11\n", " 78\n", - " 2024-03-30 23:04:27\n", + " 2024-05-01 20:25:50\n", " 0.050000120641985167\n", " \n", " \n", " 12\n", " 79\n", - " 2024-03-30 23:04:39\n", + " 2024-05-01 20:26:02\n", " 0.050000120641985167\n", " \n", " \n", " 13\n", " 80\n", - " 2024-03-30 23:04:51\n", + " 2024-05-01 20:26:14\n", " 0.063106209172254943\n", " \n", " \n", @@ -652,20 +652,20 @@ ], "text/plain": [ " block_number timestamp fixed_rate\n", - "0 20 2024-03-29 23:02:15 0.049999999999999996\n", - "1 21 2024-03-29 23:02:27 0.049999999999999996\n", - "2 22 2024-03-29 23:02:39 0.049999999999999996\n", - "3 23 2024-03-29 23:02:51 0.049999939182615754\n", - "4 24 2024-03-29 23:03:03 0.049999999941576964\n", - "5 25 2024-03-29 23:03:15 0.049999999941576964\n", - "6 73 2024-03-30 23:03:27 0.049999999941576964\n", - "7 74 2024-03-30 23:03:39 0.050000052064751971\n", - "8 75 2024-03-30 23:03:51 0.050000052064751971\n", - "9 76 2024-03-30 23:04:03 0.050000052064751971\n", - "10 77 2024-03-30 23:04:15 0.050000120641985167\n", - "11 78 2024-03-30 23:04:27 0.050000120641985167\n", - "12 79 2024-03-30 23:04:39 0.050000120641985167\n", - "13 80 2024-03-30 23:04:51 0.063106209172254943" + "0 20 2024-04-30 20:23:38 0.049999999999999996\n", + "1 21 2024-04-30 20:23:50 0.049999999999999996\n", + "2 22 2024-04-30 20:24:02 0.049999999999999996\n", + "3 23 2024-04-30 20:24:14 0.049999939182615754\n", + "4 24 2024-04-30 20:24:26 0.049999999941576964\n", + "5 25 2024-04-30 20:24:38 0.049999999941576964\n", + "6 73 2024-05-01 20:24:50 0.049999999941576964\n", + "7 74 2024-05-01 20:25:02 0.050000052064751971\n", + "8 75 2024-05-01 20:25:14 0.050000052064751971\n", + "9 76 2024-05-01 20:25:26 0.050000052064751971\n", + "10 77 2024-05-01 20:25:38 0.050000120641985167\n", + "11 78 2024-05-01 20:25:50 0.050000120641985167\n", + "12 79 2024-05-01 20:26:02 0.050000120641985167\n", + "13 80 2024-05-01 20:26:14 0.063106209172254943" ] }, "execution_count": 13, @@ -675,7 +675,7 @@ ], "source": [ "policy_agent.open_short(bonds=FixedPoint(20_000_000))\n", - "interactive_hyperdrive.get_pool_state()[[\"block_number\", \"timestamp\", \"fixed_rate\"]]" + "hyperdrive.get_pool_state()[[\"block_number\", \"timestamp\", \"fixed_rate\"]]" ] }, { @@ -694,7 +694,7 @@ { "data": { "text/plain": [ - "[OpenLong(trader='0x6BfCbaC0038fEDdc5c416F0B654B592153255298', asset_id=452312848583266388373324160190187140051835877600158453279131187532623107056, maturity_time=1712444400, base_amount=FixedPoint(\"100000.0\"), vault_share_amount=FixedPoint(\"99986.276614078975487391\"), as_base=True, bond_amount=FixedPoint(\"100119.747042597919407309\"))]" + "[OpenLong(trader='0xA503fD85129E41E0A31e0C607658971e977fA7f7', asset_id=452312848583266388373324160190187140051835877600158453279131187532625861056, maturity_time=1715198400, base_amount=FixedPoint(\"100000.0\"), vault_share_amount=FixedPoint(\"99986.276614078975487391\"), as_base=True, bond_amount=FixedPoint(\"100119.747042597919407309\"), __name__='OpenLong')]" ] }, "execution_count": 14, @@ -714,8 +714,8 @@ "\n", "Along with a fully managed simulator, interactive hyperdrive also provides an interface for connecting to any existing remote chain and deployed hyperdrive pool. We can use this interface to make trades or execute any policy on the deployed hyperdrive pool.\n", "\n", - "In this tutorial, we'll use the Anvil node and Hyperdrive pool being hosted by the `ILocalChain`\n", - "and `ILocalHyperdrive` objects, but we can simply replace the corresponding configurations with any valid RPC and contract addresses.\n" + "In this tutorial, we'll use the Anvil node and Hyperdrive pool being hosted by the `LocalChain`\n", + "and `LocalHyperdrive` objects, but we can simply replace the corresponding configurations with any valid RPC and contract addresses.\n" ] }, { @@ -724,20 +724,20 @@ "metadata": {}, "outputs": [], "source": [ - "from agent0 import IChain, IHyperdrive\n", + "from agent0 import Chain, Hyperdrive\n", "\n", "# Get the RPC address and the hyperdrive contract addresses to connect to from the managed\n", "# interactive hyperdrive objects.\n", "rpc_uri = chain.rpc_uri\n", - "hyperdrive_address = interactive_hyperdrive.get_hyperdrive_address()\n", + "hyperdrive_address = hyperdrive.get_hyperdrive_address()\n", "\n", "# We can specify other parameters as such.\n", "# rpc_uri = \"\"\n", "# hyperdrive_address = \"0x\"\n", "\n", "# Connect to the remote chain and hyperdrive objects.\n", - "remote_chain = IChain(rpc_uri)\n", - "remote_hyperdrive = IHyperdrive(remote_chain, hyperdrive_address)" + "remote_chain = Chain(rpc_uri)\n", + "remote_hyperdrive = Hyperdrive(remote_chain, hyperdrive_address)" ] }, { @@ -802,7 +802,7 @@ { "data": { "text/plain": [ - "OpenShort(trader='0xC561F5185577dc38a68C09bdf81829dE8fCbDA34', asset_id=904625697166532776746648320380374280103671755200316906558262375063533769712, maturity_time=1712444400, base_amount=FixedPoint(\"0.24586616185096029\"), vault_share_amount=FixedPoint(\"0.245832406657190211\"), as_base=True, base_proceeds=FixedPoint(\"199.756098771479606786\"), bond_amount=FixedPoint(\"200.0\"))" + "OpenShort(trader='0x88d61CAc63D7057Bb73d02b022D6c87ecbc1d4Eb', asset_id=904625697166532776746648320380374280103671755200316906558262375063536523712, maturity_time=1715198400, base_amount=FixedPoint(\"0.24586616185096029\"), vault_share_amount=FixedPoint(\"0.245832406657190211\"), as_base=True, base_proceeds=FixedPoint(\"199.756098771479606786\"), bond_amount=FixedPoint(\"200.0\"), __name__='OpenShort')" ] }, "execution_count": 17, @@ -822,7 +822,7 @@ { "data": { "text/plain": [ - "[OpenLong(trader='0xC561F5185577dc38a68C09bdf81829dE8fCbDA34', asset_id=452312848583266388373324160190187140051835877600158453279131187532623107056, maturity_time=1712444400, base_amount=FixedPoint(\"100000.0\"), vault_share_amount=FixedPoint(\"99986.269004773767680122\"), as_base=True, bond_amount=FixedPoint(\"100119.612148284479444947\"))]" + "[OpenLong(trader='0x88d61CAc63D7057Bb73d02b022D6c87ecbc1d4Eb', asset_id=452312848583266388373324160190187140051835877600158453279131187532625861056, maturity_time=1715198400, base_amount=FixedPoint(\"100000.0\"), vault_share_amount=FixedPoint(\"99986.269004773767680122\"), as_base=True, bond_amount=FixedPoint(\"100119.612148284479444947\"), __name__='OpenLong')]" ] }, "execution_count": 18, @@ -850,7 +850,7 @@ { "data": { "text/plain": [ - "HyperdriveWallet(address=HexBytes('0xc561f5185577dc38a68c09bdf81829de8fcbda34'), balance=Quantity(amount=FixedPoint(\"899999.75413383814903971\"), unit=), lp_tokens=FixedPoint(\"0.0\"), withdraw_shares=FixedPoint(\"0.0\"), longs={1712444400: Long(balance=FixedPoint(\"100119.612148284479444947\"), maturity_time=1712444400)}, shorts={1712444400: Short(balance=FixedPoint(\"200.0\"), maturity_time=1712444400)})" + "HyperdriveWallet(address=HexBytes('0x88d61cac63d7057bb73d02b022d6c87ecbc1d4eb'), balance=Quantity(amount=FixedPoint(\"899999.75413383814903971\"), unit=), lp_tokens=FixedPoint(\"0.0\"), withdraw_shares=FixedPoint(\"0.0\"), longs={1715198400: Long(balance=FixedPoint(\"100119.612148284479444947\"), maturity_time=1715198400)}, shorts={1715198400: Short(balance=FixedPoint(\"200.0\"), maturity_time=1715198400)})" ] }, "execution_count": 19, diff --git a/scripts/checkpoint_bot.py b/scripts/checkpoint_bot.py index 689388cf8a..6c37a1e98a 100644 --- a/scripts/checkpoint_bot.py +++ b/scripts/checkpoint_bot.py @@ -13,7 +13,7 @@ from eth_account.account import Account from fixedpointmath import FixedPoint -from agent0.core.base import EthAgent +from agent0.core.base import PolicyAgent from agent0.core.base.config import EnvironmentConfig from agent0.ethpy import EthConfig, build_eth_config from agent0.ethpy.base import initialize_web3_with_http_provider, set_anvil_account_balance, smart_contract_transact @@ -120,12 +120,12 @@ def main(argv: Sequence[str] | None = None) -> None: # Fund the checkpoint sender with some ETH. if parsed_args.fund: balance = FixedPoint(100).scaled_value - sender = EthAgent(Account().create("CHECKPOINT_BOT")) + sender = PolicyAgent(Account().create("CHECKPOINT_BOT")) set_anvil_account_balance(web3, sender.address, balance) logging.info("Successfully funded the sender=%s.", sender.address) else: private_key = os.getenv("CHECKPOINT_BOT_KEY") - sender = EthAgent(Account().from_key(private_key)) + sender = PolicyAgent(Account().from_key(private_key)) # Get the Hyperdrive contract. # TODO replace this with the hyperdrive interface diff --git a/scripts/fund_agents_from_user_key.py b/scripts/fund_agents_from_user_key.py index 22387ee93e..eeb782da6f 100644 --- a/scripts/fund_agents_from_user_key.py +++ b/scripts/fund_agents_from_user_key.py @@ -8,7 +8,7 @@ from eth_account.account import Account from agent0.core import build_account_config_from_env -from agent0.core.hyperdrive import HyperdriveAgent +from agent0.core.hyperdrive import HyperdrivePolicyAgent from agent0.core.hyperdrive.utilities.run_bots import async_fund_agents from agent0.ethpy import build_eth_config from agent0.ethpy.hyperdrive import HyperdriveReadInterface, get_hyperdrive_addresses_from_artifacts @@ -55,7 +55,7 @@ hyperdrive_address = get_hyperdrive_addresses_from_artifacts( os.path.join(eth_config.artifacts_uri, "addresses.json") )["erc4626_hyperdrive"] - user_account = HyperdriveAgent(Account().from_key(account_key_config.USER_KEY)) + user_account = HyperdrivePolicyAgent(Account().from_key(account_key_config.USER_KEY)) interface = HyperdriveReadInterface(eth_config, hyperdrive_address, read_retry_count=5) diff --git a/scripts/get_all_events.py b/scripts/get_all_events.py index 7bea915cd5..c4b516dbf0 100644 --- a/scripts/get_all_events.py +++ b/scripts/get_all_events.py @@ -4,18 +4,18 @@ from fixedpointmath import FixedPoint from agent0.chainsync.db.hyperdrive import get_transactions -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.core.hyperdrive.policies import PolicyZoo # This is meant to be a standalone script, no need for global upper_case naming style # pylint: disable=invalid-name -local_chain_config = ILocalChain.Config() -chain = ILocalChain(local_chain_config) -initial_pool_config = ILocalHyperdrive.Config() -interactive_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) -interactive_hyperdrive2 = ILocalHyperdrive(chain, initial_pool_config) -interactive_hyperdrive3 = ILocalHyperdrive(chain, initial_pool_config) +local_chain_config = LocalChain.Config() +chain = LocalChain(local_chain_config) +initial_pool_config = LocalHyperdrive.Config() +interactive_hyperdrive = LocalHyperdrive(chain, initial_pool_config) +interactive_hyperdrive2 = LocalHyperdrive(chain, initial_pool_config) +interactive_hyperdrive3 = LocalHyperdrive(chain, initial_pool_config) # %% # Generate funded trading agents from the interactive object diff --git a/scripts/local_fuzz_bots.py b/scripts/local_fuzz_bots.py index 12c20884d0..50129dd3a7 100644 --- a/scripts/local_fuzz_bots.py +++ b/scripts/local_fuzz_bots.py @@ -6,7 +6,7 @@ import numpy as np -from agent0 import ILocalChain, ILocalHyperdrive +from agent0 import LocalChain, LocalHyperdrive from agent0.hyperfuzz.system_fuzz import generate_fuzz_hyperdrive_config, run_fuzz_bots from agent0.hyperlogs import setup_logging from agent0.hyperlogs.rollbar_utilities import initialize_rollbar @@ -24,17 +24,17 @@ def main() -> None: rng_seed = random.randint(0, 10000000) rng = np.random.default_rng(rng_seed) - local_chain_config = ILocalChain.Config(chain_port=11111, db_port=22222, block_timestamp_interval=12) + local_chain_config = LocalChain.Config(chain_port=11111, db_port=22222, block_timestamp_interval=12) while True: # Build interactive local hyperdrive # TODO can likely reuse some of these resources # instead, we start from scratch every time. - chain = ILocalChain(local_chain_config) + chain = LocalChain(local_chain_config) # Fuzz over config values hyperdrive_config = generate_fuzz_hyperdrive_config(rng, log_to_rollbar, rng_seed) - hyperdrive_pool = ILocalHyperdrive(chain, hyperdrive_config) + hyperdrive_pool = LocalHyperdrive(chain, hyperdrive_config) # TODO submit multiple transactions per block run_fuzz_bots( diff --git a/scripts/remote_fuzz_bot_invariant_checks.py b/scripts/remote_fuzz_bot_invariant_checks.py index 7d173ce06b..ceb5359aa0 100644 --- a/scripts/remote_fuzz_bot_invariant_checks.py +++ b/scripts/remote_fuzz_bot_invariant_checks.py @@ -11,7 +11,7 @@ from web3 import Web3 -from agent0 import IHyperdrive +from agent0 import Hyperdrive from agent0.core.base.config import EnvironmentConfig from agent0.ethpy import build_eth_config from agent0.ethpy.hyperdrive import HyperdriveReadInterface @@ -104,7 +104,7 @@ def setup_fuzz(argv: Sequence[str] | None) -> tuple[Args, HyperdriveReadInterfac # Setup hyperdrive interface if parsed_args.pool_addr == "": - hyperdrive_addresses = IHyperdrive.get_hyperdrive_addresses_from_artifacts(eth_config.artifacts_uri) + hyperdrive_addresses = Hyperdrive.get_hyperdrive_addresses_from_artifacts(eth_config.artifacts_uri) if parsed_args.pool not in hyperdrive_addresses: raise ValueError( f"Pool {parsed_args.pool} not recognized. Available options are {list(hyperdrive_addresses.keys())}" diff --git a/scripts/remote_fuzz_bots.py b/scripts/remote_fuzz_bots.py index cb0af23c14..fa024ef5de 100644 --- a/scripts/remote_fuzz_bots.py +++ b/scripts/remote_fuzz_bots.py @@ -10,7 +10,7 @@ from web3.types import RPCEndpoint -from agent0 import IChain, IHyperdrive +from agent0 import Chain, Hyperdrive from agent0.ethpy import build_eth_config from agent0.hyperfuzz.system_fuzz import run_fuzz_bots from agent0.hyperlogs import setup_logging @@ -34,7 +34,7 @@ def main(argv: Sequence[str] | None = None) -> None: # Get config and addresses eth_config = build_eth_config() - hyperdrive_addresses = IHyperdrive.get_hyperdrive_addresses_from_artifacts(eth_config.artifacts_uri) + hyperdrive_addresses = Hyperdrive.get_hyperdrive_addresses_from_artifacts(eth_config.artifacts_uri) if parsed_args.pool not in hyperdrive_addresses: raise ValueError( f"Pool {parsed_args.pool} not recognized. Available options are {list(hyperdrive_addresses.keys())}" @@ -49,9 +49,9 @@ def main(argv: Sequence[str] | None = None) -> None: rng_seed = random.randint(0, 10000000) # Connect to the chain - chain = IChain(eth_config.rpc_uri) + chain = Chain(eth_config.rpc_uri) - hyperdrive_config = IHyperdrive.Config( + hyperdrive_config = Hyperdrive.Config( preview_before_trade=True, rng_seed=rng_seed, log_to_rollbar=log_to_rollbar, @@ -59,7 +59,7 @@ def main(argv: Sequence[str] | None = None) -> None: crash_log_level=logging.CRITICAL, crash_report_additional_info={"rng_seed": rng_seed}, ) - hyperdrive_pool = IHyperdrive(chain, hyperdrive_address, hyperdrive_config) + hyperdrive_pool = Hyperdrive(chain, hyperdrive_address, hyperdrive_config) try: run_fuzz_bots( diff --git a/scripts/run_unit_fuzz.py b/scripts/run_unit_fuzz.py index 5e03c69926..5a3214333e 100644 --- a/scripts/run_unit_fuzz.py +++ b/scripts/run_unit_fuzz.py @@ -6,7 +6,7 @@ import sys from typing import NamedTuple, Sequence -from agent0.core.hyperdrive.interactive import ILocalChain +from agent0.core.hyperdrive.interactive import LocalChain from agent0.hyperfuzz import FuzzAssertionException from agent0.hyperfuzz.unit_fuzz import ( fuzz_long_short_maturity_values, @@ -36,7 +36,7 @@ def main(argv: Sequence[str] | None = None): while True: try: print("Running long short maturity test") - chain_config = ILocalChain.Config(db_port=5434, chain_port=10001) + chain_config = LocalChain.Config(db_port=5434, chain_port=10001) long_maturity_vals_epsilon = 1e-14 short_maturity_vals_epsilon = 1e-9 fuzz_long_short_maturity_values( @@ -51,7 +51,7 @@ def main(argv: Sequence[str] | None = None): try: print("Running path independence test") - chain_config = ILocalChain.Config(db_port=5435, chain_port=10002) + chain_config = LocalChain.Config(db_port=5435, chain_port=10002) lp_share_price_epsilon = 1e-14 effective_share_reserves_epsilon = 1e-4 present_value_epsilon = 1e-4 @@ -69,7 +69,7 @@ def main(argv: Sequence[str] | None = None): try: print("Running fuzz profit test") - chain_config = ILocalChain.Config(db_port=5436, chain_port=10003) + chain_config = LocalChain.Config(db_port=5436, chain_port=10003) fuzz_profit_check(chain_config) except FuzzAssertionException: pass @@ -78,7 +78,7 @@ def main(argv: Sequence[str] | None = None): try: print("Running fuzz present value test") - chain_config = ILocalChain.Config(db_port=5437, chain_port=10004) + chain_config = LocalChain.Config(db_port=5437, chain_port=10004) present_value_epsilon = 0.01 fuzz_present_value(test_epsilon=present_value_epsilon, chain_config=chain_config) except FuzzAssertionException: diff --git a/scripts/testnet_checkpoint_bots.py b/scripts/testnet_checkpoint_bots.py index ebdafc5b97..670692aef1 100644 --- a/scripts/testnet_checkpoint_bots.py +++ b/scripts/testnet_checkpoint_bots.py @@ -15,8 +15,8 @@ from eth_account.account import Account from eth_typing import ChecksumAddress -from agent0 import IChain, IHyperdrive -from agent0.core.base import EthAgent +from agent0 import Chain, Hyperdrive +from agent0.core.base import PolicyAgent from agent0.ethpy.base import smart_contract_transact from agent0.ethpy.hyperdrive import get_hyperdrive_pool_config from agent0.hyperfuzz.system_fuzz.run_fuzz_bots import _async_runner @@ -53,9 +53,9 @@ def does_checkpoint_exist(hyperdrive_contract: IHyperdriveContract, checkpoint_t def run_checkpoint_bot( - chain: IChain, + chain: Chain, pool_address: ChecksumAddress, - sender: EthAgent, + sender: PolicyAgent, block_time: int = 1, block_timestamp_interval: int = 1, check_checkpoint: bool = False, @@ -66,11 +66,11 @@ def run_checkpoint_bot( Arguments --------- - chain: IChain + chain: Chain The chain object. pool_address: ChecksumAddress The pool address. - sender: EthAgent + sender: PolicyAgent The sender of the transaction. block_time: int The block time in seconds. @@ -206,18 +206,18 @@ def main(argv: Sequence[str] | None = None) -> None: ) # Initialize - chain = IChain(parsed_args.rpc_uri) + chain = Chain(parsed_args.rpc_uri) # We calculate how many blocks we should wait before checking for a new pool pool_check_num_blocks = parsed_args.pool_check_sleep_time // 12 private_key = os.getenv("CHECKPOINT_BOT_KEY") - sender = EthAgent(Account().from_key(private_key)) + sender = PolicyAgent(Account().from_key(private_key)) while True: logging.info("Checking for new pools...") # Reset hyperdrive objs - deployed_pools = IHyperdrive.get_hyperdrive_addresses_from_registry(parsed_args.registry_addr, chain) + deployed_pools = Hyperdrive.get_hyperdrive_addresses_from_registry(parsed_args.registry_addr, chain) logging.info("Running for all pools...") diff --git a/scripts/testnet_fuzz_bot_invariant_checks.py b/scripts/testnet_fuzz_bot_invariant_checks.py index dc3589bd57..882c3af5f8 100644 --- a/scripts/testnet_fuzz_bot_invariant_checks.py +++ b/scripts/testnet_fuzz_bot_invariant_checks.py @@ -17,7 +17,7 @@ import time from typing import NamedTuple, Sequence -from agent0 import IChain, IHyperdrive +from agent0 import Chain, Hyperdrive from agent0.hyperfuzz.system_fuzz.invariant_checks import run_invariant_checks from agent0.hyperlogs import setup_logging from agent0.hyperlogs.rollbar_utilities import initialize_rollbar @@ -33,7 +33,7 @@ def main(argv: Sequence[str] | None = None) -> None: """ parsed_args = parse_arguments(argv) - chain = IChain(parsed_args.rpc_uri) + chain = Chain(parsed_args.rpc_uri) # We use the logical name if we don't specify pool addr, otherwise we use the pool addr rollbar_environment_name = "testnet_fuzz_bot_invariant_check" @@ -48,7 +48,7 @@ def main(argv: Sequence[str] | None = None) -> None: last_executed_block_number = -pool_check_num_blocks - 1 # no matter what we will run the check the first time last_pool_check_block_number = 0 - hyperdrive_objs: dict[str, IHyperdrive] = {} + hyperdrive_objs: dict[str, Hyperdrive] = {} # Run the loop forever while True: @@ -61,12 +61,12 @@ def main(argv: Sequence[str] | None = None) -> None: if latest_block_number > last_pool_check_block_number + pool_check_num_blocks: logging.info("Checking for new pools...") # Reset hyperdrive objs - hyperdrive_objs: dict[str, IHyperdrive] = {} + hyperdrive_objs: dict[str, Hyperdrive] = {} # First iteration, get list of deployed pools - deployed_pools = IHyperdrive.get_hyperdrive_addresses_from_registry(parsed_args.registry_addr, chain) + deployed_pools = Hyperdrive.get_hyperdrive_addresses_from_registry(parsed_args.registry_addr, chain) for name, addr in deployed_pools.items(): logging.info("Adding pool %s", name) - hyperdrive_objs[name] = IHyperdrive(chain, addr) + hyperdrive_objs[name] = Hyperdrive(chain, addr) last_pool_check_block_number = latest_block_number if not latest_block_number > last_executed_block_number: diff --git a/src/agent0/__init__.py b/src/agent0/__init__.py index b0510758d8..773bf4e00c 100644 --- a/src/agent0/__init__.py +++ b/src/agent0/__init__.py @@ -9,5 +9,5 @@ redeem_withdraw_shares_trade, remove_liquidity_trade, ) -from agent0.core.hyperdrive.interactive import IChain, IHyperdrive, ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import Chain, Hyperdrive, LocalChain, LocalHyperdrive from agent0.core.hyperdrive.policies import HyperdriveBasePolicy, PolicyZoo diff --git a/src/agent0/core/base/__init__.py b/src/agent0/core/base/__init__.py index 4960ab055a..1866b08587 100644 --- a/src/agent0/core/base/__init__.py +++ b/src/agent0/core/base/__init__.py @@ -1,4 +1,4 @@ """The agent0 base module exports some types here.""" -from .agent import BaseMarketAction, EthAgent, EthWallet, EthWalletDeltas +from .agent import BaseMarketAction, EthWallet, EthWalletDeltas, PolicyAgent from .types import WEI, Freezable, MarketType, Quantity, TokenType, Trade diff --git a/src/agent0/core/base/agent/__init__.py b/src/agent0/core/base/agent/__init__.py index a31dde57f4..7a2853862b 100644 --- a/src/agent0/core/base/agent/__init__.py +++ b/src/agent0/core/base/agent/__init__.py @@ -1,5 +1,5 @@ """Base implementation of agents.""" -from .eth_agent import EthAgent from .eth_wallet import EthWallet, EthWalletDeltas from .market_actions import BaseMarketAction +from .policy_agent import PolicyAgent diff --git a/src/agent0/core/base/agent/eth_agent.py b/src/agent0/core/base/agent/policy_agent.py similarity index 89% rename from src/agent0/core/base/agent/eth_agent.py rename to src/agent0/core/base/agent/policy_agent.py index 27ca7c6486..0df2a76bec 100644 --- a/src/agent0/core/base/agent/eth_agent.py +++ b/src/agent0/core/base/agent/policy_agent.py @@ -20,7 +20,7 @@ MarketAction = TypeVar("MarketAction") -class EthAgent(LocalAccount, Generic[Policy, MarketInterface, MarketAction]): +class PolicyAgent(LocalAccount, Generic[Policy, MarketInterface, MarketAction]): r"""Enact policies on smart contracts and tracks wallet state""" def __init__(self, account: LocalAccount, initial_budget: FixedPoint | None = None, policy: Policy | None = None): @@ -43,18 +43,18 @@ def __init__(self, account: LocalAccount, initial_budget: FixedPoint | None = No .. code-block:: python >>> from eth_account.account import Account - >>> from agent0.core.base import EthAgent - >>> agent = EthAgent(Account().create("CHECKPOINT_BOT")) + >>> from agent0.core.base import PolicyAgent + >>> agent = PolicyAgent(Account().create("CHECKPOINT_BOT")) Alternatively, you can also use the Account api to provide a pre-generated key: .. code-block:: python >>> from eth_account.account import Account - >>> from agent0.core.base import EthAgent - >>> agent = EthAgent(Account().from_key(agent_private_key)) + >>> from agent0.core.base import PolicyAgent + >>> agent = PolicyAgent(Account().from_key(agent_private_key)) - The EthAgent has the same properties as a Web3 LocalAgent. + The PolicyAgent has the same properties as a Web3 LocalAgent. For example, you can get public and private keys as well as the address: .. code-block:: python diff --git a/src/agent0/core/hyperdrive/__init__.py b/src/agent0/core/hyperdrive/__init__.py index 54ccb2af14..a04df4ce63 100644 --- a/src/agent0/core/hyperdrive/__init__.py +++ b/src/agent0/core/hyperdrive/__init__.py @@ -2,8 +2,8 @@ from .agent import ( HyperdriveActionType, - HyperdriveAgent, HyperdriveMarketAction, + HyperdrivePolicyAgent, HyperdriveWallet, HyperdriveWalletDeltas, Long, diff --git a/src/agent0/core/hyperdrive/agent/__init__.py b/src/agent0/core/hyperdrive/agent/__init__.py index 07ee9f93f5..4639127a59 100644 --- a/src/agent0/core/hyperdrive/agent/__init__.py +++ b/src/agent0/core/hyperdrive/agent/__init__.py @@ -12,6 +12,6 @@ redeem_withdraw_shares_trade, remove_liquidity_trade, ) -from .hyperdrive_agent import HyperdriveAgent +from .hyperdrive_policy_agent import HyperdrivePolicyAgent from .hyperdrive_wallet import HyperdriveWallet, HyperdriveWalletDeltas, Long, Short from .trade_result import TradeResult, TradeStatus diff --git a/src/agent0/core/hyperdrive/agent/hyperdrive_agent.py b/src/agent0/core/hyperdrive/agent/hyperdrive_policy_agent.py similarity index 97% rename from src/agent0/core/hyperdrive/agent/hyperdrive_agent.py rename to src/agent0/core/hyperdrive/agent/hyperdrive_policy_agent.py index 29def6d8ef..d4ebfc5b7e 100644 --- a/src/agent0/core/hyperdrive/agent/hyperdrive_agent.py +++ b/src/agent0/core/hyperdrive/agent/hyperdrive_policy_agent.py @@ -7,7 +7,7 @@ from fixedpointmath import FixedPoint -from agent0.core.base import EthAgent, MarketType +from agent0.core.base import MarketType, PolicyAgent from agent0.core.base.policies import BasePolicy from agent0.ethpy.hyperdrive.interface import HyperdriveReadInterface @@ -29,7 +29,7 @@ Policy = TypeVar("Policy", bound=BasePolicy) -class HyperdriveAgent(EthAgent[Policy, HyperdriveReadInterface, HyperdriveMarketAction]): +class HyperdrivePolicyAgent(PolicyAgent[Policy, HyperdriveReadInterface, HyperdriveMarketAction]): r"""Enact policies on smart contracts and tracks wallet state .. todo:: diff --git a/src/agent0/core/hyperdrive/agent/trade_result.py b/src/agent0/core/hyperdrive/agent/trade_result.py index f69d3a7b03..5b9e5288b1 100644 --- a/src/agent0/core/hyperdrive/agent/trade_result.py +++ b/src/agent0/core/hyperdrive/agent/trade_result.py @@ -13,7 +13,7 @@ from agent0.core.base import Trade from .hyperdrive_actions import HyperdriveMarketAction - from .hyperdrive_agent import HyperdriveAgent + from .hyperdrive_policy_agent import HyperdrivePolicyAgent class TradeStatus(Enum): @@ -32,7 +32,7 @@ class TradeResult: status: TradeStatus """The status of the trade.""" - agent: HyperdriveAgent | None = None + agent: HyperdrivePolicyAgent | None = None """The agent that was executing the trade.""" trade_object: Trade[HyperdriveMarketAction] | None = None """The trade object for the trade.""" diff --git a/src/agent0/core/hyperdrive/crash_report/crash_report.py b/src/agent0/core/hyperdrive/crash_report/crash_report.py index 54d4840479..dd739d6f1e 100644 --- a/src/agent0/core/hyperdrive/crash_report/crash_report.py +++ b/src/agent0/core/hyperdrive/crash_report/crash_report.py @@ -25,7 +25,7 @@ if TYPE_CHECKING: from agent0.core.base import Trade - from agent0.core.hyperdrive import HyperdriveAgent, HyperdriveMarketAction + from agent0.core.hyperdrive import HyperdriveMarketAction, HyperdrivePolicyAgent from agent0.ethpy.hyperdrive import HyperdriveReadInterface @@ -54,7 +54,7 @@ def setup_hyperdrive_crash_report_logging(log_format_string: str | None = None) def build_crash_trade_result( exception: Exception, interface: HyperdriveReadInterface, - agent: HyperdriveAgent | None = None, + agent: HyperdrivePolicyAgent | None = None, trade_object: Trade[HyperdriveMarketAction] | None = None, additional_info: dict[str, Any] | None = None, pool_state: PoolState | None = None, @@ -67,10 +67,10 @@ def build_crash_trade_result( The exception that was thrown interface: HyperdriveReadInterface An interface for Hyperdrive with contracts deployed on any chain with an RPC url. - agent: HyperdriveAgent | None, optional. + agent: HyperdrivePolicyAgent | None, optional. Object containing a wallet address and Agent for determining trades. If None, won't report the agent. trade_object: Trade[HyperdriveMarketAction] | None, optional - A trade provided by a HyperdriveAgent. If None, won't report the trade object. + A trade provided by a HyperdrivePolicyAgent. If None, won't report the trade object. additional_info: dict[str, Any] | None, optional Additional information used for crash reporting, optional pool_state: PoolState | None, optional @@ -405,7 +405,7 @@ def _hyperdrive_trade_obj_to_dict(trade_obj: Trade[HyperdriveMarketAction] | Non } -def _hyperdrive_agent_to_dict(agent: HyperdriveAgent | None): +def _hyperdrive_agent_to_dict(agent: HyperdrivePolicyAgent | None): if agent is None: return {} return {"address": agent.checksum_address, "policy": agent.policy.name} diff --git a/src/agent0/core/hyperdrive/interactive/__init__.py b/src/agent0/core/hyperdrive/interactive/__init__.py index 5267bb2378..96b696e2eb 100644 --- a/src/agent0/core/hyperdrive/interactive/__init__.py +++ b/src/agent0/core/hyperdrive/interactive/__init__.py @@ -1,6 +1,6 @@ """Interactive hyperdrive""" -from .i_chain import IChain -from .i_hyperdrive import IHyperdrive -from .i_local_chain import ILocalChain -from .i_local_hyperdrive import ILocalHyperdrive +from .chain import Chain +from .hyperdrive import Hyperdrive +from .local_chain import LocalChain +from .local_hyperdrive import LocalHyperdrive diff --git a/src/agent0/core/hyperdrive/interactive/i_chain.py b/src/agent0/core/hyperdrive/interactive/chain.py similarity index 99% rename from src/agent0/core/hyperdrive/interactive/i_chain.py rename to src/agent0/core/hyperdrive/interactive/chain.py index 7fa58a1201..cfad3025d0 100644 --- a/src/agent0/core/hyperdrive/interactive/i_chain.py +++ b/src/agent0/core/hyperdrive/interactive/chain.py @@ -7,7 +7,7 @@ from agent0.ethpy.base import initialize_web3_with_http_provider -class IChain: +class Chain: """A class that represents a ethereum node.""" def __init__(self, rpc_uri: str): diff --git a/src/agent0/core/hyperdrive/interactive/econ_tests.py b/src/agent0/core/hyperdrive/interactive/econ_tests.py index 993951debc..46451d7052 100644 --- a/src/agent0/core/hyperdrive/interactive/econ_tests.py +++ b/src/agent0/core/hyperdrive/interactive/econ_tests.py @@ -3,24 +3,24 @@ import pytest from fixedpointmath import FixedPoint -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive YEAR_IN_SECONDS = 31_536_000 @pytest.mark.anvil -def test_symmetry(chain: ILocalChain): +def test_symmetry(chain: LocalChain): """Does in equal out? One may be under the impression swaps between x and y have the same result, irrespective of direction. We set the number of bonds in and out to 100k and see if the resulting shares_in and shares_out differ.""" - interactive_config = ILocalHyperdrive.Config( + interactive_config = LocalHyperdrive.Config( position_duration=YEAR_IN_SECONDS, # 1 year term governance_lp_fee=FixedPoint(0.1), curve_fee=FixedPoint(0.01), flat_fee=FixedPoint(0), ) - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) interface = interactive_hyperdrive.interface shares_out = interface.calc_shares_out_given_bonds_in_down(FixedPoint(100_000)) shares_in = interface.calc_shares_in_given_bonds_out_down(FixedPoint(100_000)) diff --git a/src/agent0/core/hyperdrive/interactive/exec/execute_agent_trades.py b/src/agent0/core/hyperdrive/interactive/exec/execute_agent_trades.py index 2b77c11ba4..828882b969 100644 --- a/src/agent0/core/hyperdrive/interactive/exec/execute_agent_trades.py +++ b/src/agent0/core/hyperdrive/interactive/exec/execute_agent_trades.py @@ -31,12 +31,12 @@ from agent0.ethpy.hyperdrive import HyperdriveReadInterface, HyperdriveReadWriteInterface, ReceiptBreakdown if TYPE_CHECKING: - from agent0.core.hyperdrive import HyperdriveAgent + from agent0.core.hyperdrive import HyperdrivePolicyAgent async def async_execute_agent_trades( interface: HyperdriveReadWriteInterface, - agent: HyperdriveAgent, + agent: HyperdrivePolicyAgent, liquidate: bool, randomize_liquidation: bool = False, interactive_mode: bool = False, @@ -53,8 +53,8 @@ async def async_execute_agent_trades( --------- interface: HyperdriveReadWriteInterface The Hyperdrive API interface object. - agent: HyperdriveAgent - The HyperdriveAgent that is conducting the trade. + agent: HyperdrivePolicyAgent + The HyperdrivePolicyAgent that is conducting the trade. liquidate: bool If set, will ignore all policy settings and liquidate all open positions. randomize_liquidation: bool, optional @@ -129,7 +129,7 @@ async def async_execute_agent_trades( async def async_execute_single_trade( interface: HyperdriveReadWriteInterface, - agent: HyperdriveAgent, + agent: HyperdrivePolicyAgent, trade_object: Trade[HyperdriveMarketAction], execute_policy_post_action: bool, ) -> TradeResult: @@ -143,8 +143,8 @@ async def async_execute_single_trade( --------- interface: HyperdriveReadWriteInterface The Hyperdrive API interface object. - agent: HyperdriveAgent - The HyperdriveAgent that is conducting the trade. + agent: HyperdrivePolicyAgent + The HyperdrivePolicyAgent that is conducting the trade. trade_object: Trade[HyperdriveMarketAction] The trade to execute. execute_policy_post_action: bool @@ -192,7 +192,7 @@ def _handle_contract_call_to_trade_and_update_wallets( wallet_deltas_or_exception: list[tuple[HyperdriveWalletDeltas, ReceiptBreakdown] | BaseException], trades: list[Trade[HyperdriveMarketAction]], interface: HyperdriveReadInterface, - agent: HyperdriveAgent, + agent: HyperdrivePolicyAgent, ) -> list[TradeResult]: """Handle the results of executing trades. This function also updates the underlying agent's wallet. @@ -205,7 +205,7 @@ def _handle_contract_call_to_trade_and_update_wallets( The list of trades that were executed. interface: HyperdriveReadInterface The read interface for the market. - agent: HyperdriveAgent + agent: HyperdrivePolicyAgent The agent that executed the trades. Returns @@ -255,7 +255,7 @@ def _handle_contract_call_to_trade_and_update_wallets( async def _async_match_contract_call_to_trade( - agent: HyperdriveAgent, + agent: HyperdrivePolicyAgent, interface: HyperdriveReadWriteInterface, trade_envelope: Trade[HyperdriveMarketAction], nonce: Nonce, @@ -264,7 +264,7 @@ async def _async_match_contract_call_to_trade( Arguments --------- - agent: HyperdriveAgent + agent: HyperdrivePolicyAgent Object containing a wallet address and Agent for determining trades. interface: HyperdriveReadWriteInterface The Hyperdrive API interface object. diff --git a/src/agent0/core/hyperdrive/interactive/exec/set_max_approval.py b/src/agent0/core/hyperdrive/interactive/exec/set_max_approval.py index cbc78fb39f..3a71aa935a 100644 --- a/src/agent0/core/hyperdrive/interactive/exec/set_max_approval.py +++ b/src/agent0/core/hyperdrive/interactive/exec/set_max_approval.py @@ -8,18 +8,18 @@ from web3 import Web3 from web3.contract.contract import Contract -from agent0.core.hyperdrive import HyperdriveAgent +from agent0.core.hyperdrive import HyperdrivePolicyAgent from agent0.ethpy.base import smart_contract_transact def set_max_approval( - agent: HyperdriveAgent, web3: Web3, base_token_contract: Contract, hyperdrive_address: str + agent: HyperdrivePolicyAgent, web3: Web3, base_token_contract: Contract, hyperdrive_address: str ) -> None: """Establish max approval for the hyperdrive contract for the given agent. Arguments --------- - agent: HyperdriveAgent + agent: HyperdrivePolicyAgent A Hyperdrive agent to approve. web3: Web3 web3 provider object. diff --git a/src/agent0/core/hyperdrive/interactive/i_hyperdrive.py b/src/agent0/core/hyperdrive/interactive/hyperdrive.py similarity index 93% rename from src/agent0/core/hyperdrive/interactive/i_hyperdrive.py rename to src/agent0/core/hyperdrive/interactive/hyperdrive.py index cad8769d0c..60eb4301d9 100644 --- a/src/agent0/core/hyperdrive/interactive/i_hyperdrive.py +++ b/src/agent0/core/hyperdrive/interactive/hyperdrive.py @@ -17,7 +17,7 @@ from numpy.random._generator import Generator from web3 import Web3 -from agent0.core.hyperdrive import HyperdriveActionType, HyperdriveAgent, TradeResult, TradeStatus +from agent0.core.hyperdrive import HyperdriveActionType, HyperdrivePolicyAgent, TradeResult, TradeStatus from agent0.core.hyperdrive.agent import ( add_liquidity_trade, build_wallet_positions_from_chain, @@ -40,6 +40,7 @@ get_hyperdrive_addresses_from_registry, ) +from .chain import Chain from .event_types import ( AddLiquidity, CloseLong, @@ -50,8 +51,7 @@ RemoveLiquidity, ) from .exec import async_execute_agent_trades, async_execute_single_trade, set_max_approval -from .i_chain import IChain -from .i_hyperdrive_agent import IHyperdriveAgent +from .hyperdrive_agent import HyperdriveAgent # In order to support both scripts and jupyter notebooks with underlying async functions, # we use the nest_asyncio package so that we can execute asyncio.run within a running event loop. @@ -61,7 +61,7 @@ nest_asyncio.apply() -class IHyperdrive: +class Hyperdrive: """Interactive Hyperdrive class that supports connecting to an existing hyperdrive deployment.""" # Lots of config @@ -126,7 +126,7 @@ def get_hyperdrive_addresses_from_artifacts( def get_hyperdrive_addresses_from_registry( cls, registry_contract_addr: str, - chain: IChain, + chain: Chain, ) -> dict[str, ChecksumAddress]: """Gather deployed Hyperdrive pool addresses. @@ -134,8 +134,8 @@ def get_hyperdrive_addresses_from_registry( --------- registry_contract_addr: str The address of the Hyperdrive factory contract. - chain: IChain - The IChain object connected to a chain. + chain: Chain + The Chain object connected to a chain. Returns ------- @@ -147,7 +147,7 @@ def get_hyperdrive_addresses_from_registry( def __init__( self, - chain: IChain, + chain: Chain, hyperdrive_address: ChecksumAddress, config: Config | None = None, ): @@ -155,7 +155,7 @@ def __init__( Arguments --------- - chain: IChain + chain: Chain The chain to interact with hyperdrive_address: ChecksumAddress The address of the hyperdrive contract @@ -195,7 +195,7 @@ def init_agent( private_key: str, policy: Type[HyperdriveBasePolicy] | None = None, policy_config: HyperdriveBasePolicy.Config | None = None, - ) -> IHyperdriveAgent: + ) -> HyperdriveAgent: """Initialize an agent object given a private key. .. note:: @@ -212,13 +212,13 @@ def init_agent( Returns ------- - IHyperdriveAgent + HyperdriveAgent The agent object for a user to execute trades with. """ # If the underlying policy's rng isn't set, we use the one from interactive hyperdrive if policy_config is not None and policy_config.rng is None and policy_config.rng_seed is None: policy_config.rng = self.config.rng - out_agent = IHyperdriveAgent( + out_agent = HyperdriveAgent( pool=self, policy=policy, policy_config=policy_config, @@ -231,7 +231,7 @@ def _init_agent( policy: Type[HyperdriveBasePolicy] | None, policy_config: HyperdriveBasePolicy.Config | None, private_key: str, - ) -> HyperdriveAgent[HyperdriveBasePolicy]: + ) -> HyperdrivePolicyAgent[HyperdriveBasePolicy]: # Setting the budget to 0 here, we'll update the wallet from the chain if policy is None: if policy_config is None: @@ -242,7 +242,7 @@ def _init_agent( policy_config = policy.Config(rng=self.config.rng) policy_obj = policy(policy_config) - agent = HyperdriveAgent(Account().from_key(private_key), initial_budget=FixedPoint(0), policy=policy_obj) + agent = HyperdrivePolicyAgent(Account().from_key(private_key), initial_budget=FixedPoint(0), policy=policy_obj) # Add the public address to the chain object to avoid multiple objects # with the same underlying account @@ -251,7 +251,7 @@ def _init_agent( self._sync_wallet(agent) return agent - def _set_max_approval(self, agent: HyperdriveAgent) -> None: + def _set_max_approval(self, agent: HyperdrivePolicyAgent) -> None: # Establish max approval for the hyperdrive contract set_max_approval( agent, @@ -260,12 +260,16 @@ def _set_max_approval(self, agent: HyperdriveAgent) -> None: str(self.interface.hyperdrive_contract.address), ) - def _sync_wallet(self, agent: HyperdriveAgent) -> None: + def _sync_wallet(self, agent: HyperdrivePolicyAgent) -> None: # TODO add sync from db agent.wallet = build_wallet_positions_from_chain(agent, self.interface) def _add_funds( - self, agent: HyperdriveAgent, base: FixedPoint, eth: FixedPoint, signer_account: LocalAccount | None = None + self, + agent: HyperdrivePolicyAgent, + base: FixedPoint, + eth: FixedPoint, + signer_account: LocalAccount | None = None, ) -> None: # The signer of the mint transaction defaults to the agent itself, unless specified. if signer_account is None: @@ -290,7 +294,7 @@ def _add_funds( # Update the agent's wallet balance agent.wallet.balance.amount += base - def _open_long(self, agent: HyperdriveAgent, base: FixedPoint) -> OpenLong: + def _open_long(self, agent: HyperdrivePolicyAgent, base: FixedPoint) -> OpenLong: # Build trade object trade_object = open_long_trade(base) # TODO expose async here to the caller eventually @@ -302,7 +306,7 @@ def _open_long(self, agent: HyperdriveAgent, base: FixedPoint) -> OpenLong: tx_receipt = self._handle_trade_result(trade_result) return self._build_event_obj_from_tx_receipt(HyperdriveActionType.OPEN_LONG, tx_receipt) - def _close_long(self, agent: HyperdriveAgent, maturity_time: int, bonds: FixedPoint) -> CloseLong: + def _close_long(self, agent: HyperdrivePolicyAgent, maturity_time: int, bonds: FixedPoint) -> CloseLong: # Build trade object trade_object = close_long_trade(bonds, maturity_time) # TODO expose async here to the caller eventually @@ -314,7 +318,7 @@ def _close_long(self, agent: HyperdriveAgent, maturity_time: int, bonds: FixedPo tx_receipt = self._handle_trade_result(trade_result) return self._build_event_obj_from_tx_receipt(HyperdriveActionType.CLOSE_LONG, tx_receipt) - def _open_short(self, agent: HyperdriveAgent, bonds: FixedPoint) -> OpenShort: + def _open_short(self, agent: HyperdrivePolicyAgent, bonds: FixedPoint) -> OpenShort: trade_object = open_short_trade(bonds) # TODO expose async here to the caller eventually trade_result: TradeResult = asyncio.run( @@ -325,7 +329,7 @@ def _open_short(self, agent: HyperdriveAgent, bonds: FixedPoint) -> OpenShort: tx_receipt = self._handle_trade_result(trade_result) return self._build_event_obj_from_tx_receipt(HyperdriveActionType.OPEN_SHORT, tx_receipt) - def _close_short(self, agent: HyperdriveAgent, maturity_time: int, bonds: FixedPoint) -> CloseShort: + def _close_short(self, agent: HyperdrivePolicyAgent, maturity_time: int, bonds: FixedPoint) -> CloseShort: trade_object = close_short_trade(bonds, maturity_time) # TODO expose async here to the caller eventually trade_result: TradeResult = asyncio.run( @@ -336,7 +340,7 @@ def _close_short(self, agent: HyperdriveAgent, maturity_time: int, bonds: FixedP tx_receipt = self._handle_trade_result(trade_result) return self._build_event_obj_from_tx_receipt(HyperdriveActionType.CLOSE_SHORT, tx_receipt) - def _add_liquidity(self, agent: HyperdriveAgent, base: FixedPoint) -> AddLiquidity: + def _add_liquidity(self, agent: HyperdrivePolicyAgent, base: FixedPoint) -> AddLiquidity: trade_object = add_liquidity_trade(base) # TODO expose async here to the caller eventually trade_result: TradeResult = asyncio.run( @@ -347,7 +351,7 @@ def _add_liquidity(self, agent: HyperdriveAgent, base: FixedPoint) -> AddLiquidi tx_receipt = self._handle_trade_result(trade_result) return self._build_event_obj_from_tx_receipt(HyperdriveActionType.ADD_LIQUIDITY, tx_receipt) - def _remove_liquidity(self, agent: HyperdriveAgent, shares: FixedPoint) -> RemoveLiquidity: + def _remove_liquidity(self, agent: HyperdrivePolicyAgent, shares: FixedPoint) -> RemoveLiquidity: trade_object = remove_liquidity_trade(shares) # TODO expose async here to the caller eventually trade_result: TradeResult = asyncio.run( @@ -358,7 +362,7 @@ def _remove_liquidity(self, agent: HyperdriveAgent, shares: FixedPoint) -> Remov tx_receipt = self._handle_trade_result(trade_result) return self._build_event_obj_from_tx_receipt(HyperdriveActionType.REMOVE_LIQUIDITY, tx_receipt) - def _redeem_withdraw_share(self, agent: HyperdriveAgent, shares: FixedPoint) -> RedeemWithdrawalShares: + def _redeem_withdraw_share(self, agent: HyperdrivePolicyAgent, shares: FixedPoint) -> RedeemWithdrawalShares: trade_object = redeem_withdraw_shares_trade(shares) # TODO expose async here to the caller eventually trade_results: TradeResult = asyncio.run( @@ -370,7 +374,7 @@ def _redeem_withdraw_share(self, agent: HyperdriveAgent, shares: FixedPoint) -> return self._build_event_obj_from_tx_receipt(HyperdriveActionType.REDEEM_WITHDRAW_SHARE, tx_receipt) def _execute_policy_action( - self, agent: HyperdriveAgent + self, agent: HyperdrivePolicyAgent ) -> list[OpenLong | OpenShort | CloseLong | CloseShort | AddLiquidity | RemoveLiquidity | RedeemWithdrawalShares]: # Only allow executing agent policies if a policy was passed in the constructor # we check type instead of isinstance to explicitly check for the hyperdrive base class @@ -392,7 +396,7 @@ def _execute_policy_action( return out_events def _liquidate( - self, agent: HyperdriveAgent, randomize: bool + self, agent: HyperdrivePolicyAgent, randomize: bool ) -> list[CloseLong | CloseShort | RemoveLiquidity | RedeemWithdrawalShares]: trade_results: list[TradeResult] = asyncio.run( async_execute_agent_trades( diff --git a/src/agent0/core/hyperdrive/interactive/i_hyperdrive_agent.py b/src/agent0/core/hyperdrive/interactive/hyperdrive_agent.py similarity index 98% rename from src/agent0/core/hyperdrive/interactive/i_hyperdrive_agent.py rename to src/agent0/core/hyperdrive/interactive/hyperdrive_agent.py index 0811b8a48a..51ddd7da8f 100644 --- a/src/agent0/core/hyperdrive/interactive/i_hyperdrive_agent.py +++ b/src/agent0/core/hyperdrive/interactive/hyperdrive_agent.py @@ -23,14 +23,14 @@ RedeemWithdrawalShares, RemoveLiquidity, ) - from .i_hyperdrive import IHyperdrive + from .hyperdrive import Hyperdrive # We keep this class bare bones, while we want the logic functions in InteractiveHyperdrive to be private # Hence, we call protected class methods in this class. # pylint: disable=protected-access -class IHyperdriveAgent: +class HyperdriveAgent: """Interactive Hyperdrive Agent. This class is barebones with documentation, will just call the corresponding function in the interactive hyperdrive class to keep all logic in the same place. Adding these @@ -39,7 +39,7 @@ class IHyperdriveAgent: def __init__( self, - pool: IHyperdrive, + pool: Hyperdrive, policy: Type[HyperdriveBasePolicy] | None, policy_config: HyperdriveBasePolicy.Config | None, private_key: str, diff --git a/src/agent0/core/hyperdrive/interactive/i_hyperdrive_test.py b/src/agent0/core/hyperdrive/interactive/hyperdrive_test.py similarity index 87% rename from src/agent0/core/hyperdrive/interactive/i_hyperdrive_test.py rename to src/agent0/core/hyperdrive/interactive/hyperdrive_test.py index 25ba35251b..228bdec79c 100644 --- a/src/agent0/core/hyperdrive/interactive/i_hyperdrive_test.py +++ b/src/agent0/core/hyperdrive/interactive/hyperdrive_test.py @@ -7,10 +7,10 @@ from agent0.core.hyperdrive import HyperdriveWallet from agent0.ethpy.hyperdrive import AssetIdPrefix, HyperdriveReadInterface, encode_asset_id -from .i_chain import IChain -from .i_hyperdrive import IHyperdrive -from .i_local_chain import ILocalChain -from .i_local_hyperdrive import ILocalHyperdrive +from .chain import Chain +from .hyperdrive import Hyperdrive +from .local_chain import LocalChain +from .local_hyperdrive import LocalHyperdrive # needed to pass in fixtures # pylint: disable=redefined-outer-name @@ -70,28 +70,28 @@ def _ensure_agent_wallet_is_correct(wallet: HyperdriveWallet, interface: Hyperdr # ruff: noqa: PLR0915 (too many statements) @pytest.mark.anvil @pytest.mark.parametrize("check_remote_chain", [True, False]) -def test_remote_funding_and_trades(chain: ILocalChain, check_remote_chain: bool): +def test_remote_funding_and_trades(chain: LocalChain, check_remote_chain: bool): """Deploy a local chain and point the remote interface to the local chain.""" # Parameters for pool initialization. If empty, defaults to default values, allows for custom values if needed # We explicitly set initial liquidity here to ensure we have withdrawal shares when trading - initial_pool_config = ILocalHyperdrive.Config( + initial_pool_config = LocalHyperdrive.Config( initial_liquidity=FixedPoint(1_000), initial_fixed_apr=FixedPoint("0.05"), position_duration=60 * 60 * 24 * 365, # 1 year ) # Launches a local hyperdrive pool # This deploys the pool - interactive_local_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) + interactive_local_hyperdrive = LocalHyperdrive(chain, initial_pool_config) # Gather relevant objects from the local hyperdrive hyperdrive_addresses = interactive_local_hyperdrive.get_hyperdrive_address() # Connect to the local chain using the remote hyperdrive interface if check_remote_chain: - remote_chain = IChain(chain.rpc_uri) - interactive_remote_hyperdrive = IHyperdrive(remote_chain, hyperdrive_addresses) + remote_chain = Chain(chain.rpc_uri) + interactive_remote_hyperdrive = Hyperdrive(remote_chain, hyperdrive_addresses) else: - interactive_remote_hyperdrive = IHyperdrive(chain, hyperdrive_addresses) + interactive_remote_hyperdrive = Hyperdrive(chain, hyperdrive_addresses) # Generate trading agents from the interactive object hyperdrive_agent0 = interactive_remote_hyperdrive.init_agent(private_key=make_private_key()) @@ -206,18 +206,18 @@ def test_remote_funding_and_trades(chain: ILocalChain, check_remote_chain: bool) @pytest.mark.anvil @pytest.mark.parametrize("check_remote_chain", [True, False]) -def test_multi_account_bookkeeping(chain: ILocalChain, check_remote_chain: bool): +def test_multi_account_bookkeeping(chain: LocalChain, check_remote_chain: bool): # Parameters for pool initialization. If empty, defaults to default values, allows for custom values if needed # We explicitly set initial liquidity here to ensure we have withdrawal shares when trading - initial_pool_config = ILocalHyperdrive.Config( + initial_pool_config = LocalHyperdrive.Config( initial_liquidity=FixedPoint(1_000), initial_fixed_apr=FixedPoint("0.05"), position_duration=60 * 60 * 24 * 365, # 1 year ) # Launches a local hyperdrive pool # This deploys the pool - interactive_local_hyperdrive_0 = ILocalHyperdrive(chain, initial_pool_config) - interactive_local_hyperdrive_1 = ILocalHyperdrive(chain, initial_pool_config) + interactive_local_hyperdrive_0 = LocalHyperdrive(chain, initial_pool_config) + interactive_local_hyperdrive_1 = LocalHyperdrive(chain, initial_pool_config) # Gather relevant objects from the local hyperdrive hyperdrive_addresses_0 = interactive_local_hyperdrive_0.get_hyperdrive_address() @@ -225,12 +225,12 @@ def test_multi_account_bookkeeping(chain: ILocalChain, check_remote_chain: bool) # Connect to the local chain using the remote hyperdrive interface if check_remote_chain: - remote_chain = IChain(chain.rpc_uri) - interactive_remote_hyperdrive_0 = IHyperdrive(remote_chain, hyperdrive_addresses_0) - interactive_remote_hyperdrive_1 = IHyperdrive(remote_chain, hyperdrive_addresses_1) + remote_chain = Chain(chain.rpc_uri) + interactive_remote_hyperdrive_0 = Hyperdrive(remote_chain, hyperdrive_addresses_0) + interactive_remote_hyperdrive_1 = Hyperdrive(remote_chain, hyperdrive_addresses_1) else: - interactive_remote_hyperdrive_0 = IHyperdrive(chain, hyperdrive_addresses_0) - interactive_remote_hyperdrive_1 = IHyperdrive(chain, hyperdrive_addresses_1) + interactive_remote_hyperdrive_0 = Hyperdrive(chain, hyperdrive_addresses_0) + interactive_remote_hyperdrive_1 = Hyperdrive(chain, hyperdrive_addresses_1) # Generate trading agents from the interactive object private_key = make_private_key() @@ -247,17 +247,17 @@ def test_multi_account_bookkeeping(chain: ILocalChain, check_remote_chain: bool) @pytest.mark.anvil @pytest.mark.parametrize("check_remote_chain", [True, False]) -def test_no_policy_call(chain: ILocalChain, check_remote_chain: bool): +def test_no_policy_call(chain: LocalChain, check_remote_chain: bool): """Deploy a local chain and point the remote interface to the local chain.""" - initial_pool_config = ILocalHyperdrive.Config() - interactive_local_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) + initial_pool_config = LocalHyperdrive.Config() + interactive_local_hyperdrive = LocalHyperdrive(chain, initial_pool_config) hyperdrive_addresses = interactive_local_hyperdrive.get_hyperdrive_address() # Connect to the local chain using the remote hyperdrive interface if check_remote_chain: - remote_chain = IChain(chain.rpc_uri) - interactive_remote_hyperdrive = IHyperdrive(remote_chain, hyperdrive_addresses) + remote_chain = Chain(chain.rpc_uri) + interactive_remote_hyperdrive = Hyperdrive(remote_chain, hyperdrive_addresses) else: - interactive_remote_hyperdrive = IHyperdrive(chain, hyperdrive_addresses) + interactive_remote_hyperdrive = Hyperdrive(chain, hyperdrive_addresses) # Create agent without policy passed in hyperdrive_agent = interactive_remote_hyperdrive.init_agent(private_key=make_private_key()) @@ -268,28 +268,28 @@ def test_no_policy_call(chain: ILocalChain, check_remote_chain: bool): @pytest.mark.anvil @pytest.mark.parametrize("check_remote_chain", [True, False]) -def test_sync_wallet_from_chain(chain: ILocalChain, check_remote_chain: bool): +def test_sync_wallet_from_chain(chain: LocalChain, check_remote_chain: bool): """Deploy a local chain and point the remote interface to the local chain.""" # Parameters for pool initialization. If empty, defaults to default values, allows for custom values if needed # We explicitly set initial liquidity here to ensure we have withdrawal shares when trading - initial_pool_config = ILocalHyperdrive.Config( + initial_pool_config = LocalHyperdrive.Config( initial_liquidity=FixedPoint(1_000), initial_fixed_apr=FixedPoint("0.05"), position_duration=60 * 60 * 24 * 365, # 1 year ) # Launches a local hyperdrive pool # This deploys the pool - interactive_local_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) + interactive_local_hyperdrive = LocalHyperdrive(chain, initial_pool_config) # Gather relevant objects from the local hyperdrive hyperdrive_addresses = interactive_local_hyperdrive.get_hyperdrive_address() # Connect to the local chain using the remote hyperdrive interface if check_remote_chain: - remote_chain = IChain(chain.rpc_uri) - interactive_remote_hyperdrive = IHyperdrive(remote_chain, hyperdrive_addresses) + remote_chain = Chain(chain.rpc_uri) + interactive_remote_hyperdrive = Hyperdrive(remote_chain, hyperdrive_addresses) else: - interactive_remote_hyperdrive = IHyperdrive(chain, hyperdrive_addresses) + interactive_remote_hyperdrive = Hyperdrive(chain, hyperdrive_addresses) # Generate trading agents from the interactive object using the same underlying wallet private_key = make_private_key() diff --git a/src/agent0/core/hyperdrive/interactive/i_local_chain.py b/src/agent0/core/hyperdrive/interactive/local_chain.py similarity index 98% rename from src/agent0/core/hyperdrive/interactive/i_local_chain.py rename to src/agent0/core/hyperdrive/interactive/local_chain.py index ad85ccde26..dc7d636c3f 100644 --- a/src/agent0/core/hyperdrive/interactive/i_local_chain.py +++ b/src/agent0/core/hyperdrive/interactive/local_chain.py @@ -21,15 +21,15 @@ from agent0.chainsync.db.hyperdrive.import_export_data import export_db_to_file, import_to_db from agent0.core.hyperdrive.crash_report import get_anvil_state_dump +from .chain import Chain from .event_types import CreateCheckpoint -from .i_chain import IChain if TYPE_CHECKING: - from .i_local_hyperdrive import ILocalHyperdrive + from .local_hyperdrive import LocalHyperdrive # pylint: disable=too-many-instance-attributes -class ILocalChain(IChain): +class LocalChain(Chain): """Launches a local anvil chain in a subprocess, along with a postgres container.""" # Pylint is complaining that `load_state` is an abstract method, so we need to overwrite here. @@ -123,7 +123,7 @@ def __init__(self, config: Config | None = None, fork_uri: str | None = None, fo self._snapshot_dir = config.snapshot_dir self._saved_snapshot_id: str self._has_saved_snapshot = False - self._deployed_hyperdrive_pools: list[ILocalHyperdrive] = [] + self._deployed_hyperdrive_pools: list[LocalHyperdrive] = [] self.experimental_data_threading = config.experimental_data_threading if config.block_timestamp_interval is not None: @@ -183,7 +183,7 @@ def _set_block_timestamp_interval(self, timestamp_interval: int) -> None: # pylint: disable=too-many-branches def advance_time( self, time_delta: int | timedelta, create_checkpoints: bool = True - ) -> dict[ILocalHyperdrive, list[CreateCheckpoint]]: + ) -> dict[LocalHyperdrive, list[CreateCheckpoint]]: """Advance time for this chain using the `evm_mine` RPC call. This function looks at the timestamp of the current block, then @@ -218,9 +218,7 @@ def advance_time( else: time_delta = int(time_delta) # convert int-like (e.g. np.int64) types to int - out_dict: dict[ILocalHyperdrive, list[CreateCheckpoint]] = { - pool: [] for pool in self._deployed_hyperdrive_pools - } + out_dict: dict[LocalHyperdrive, list[CreateCheckpoint]] = {pool: [] for pool in self._deployed_hyperdrive_pools} # Don't checkpoint when advancing time if `create_checkpoints` is false # or there are no deployed pools @@ -470,7 +468,7 @@ def _initialize_postgres_container( return postgres_config, container - def _add_deployed_pool_to_bookkeeping(self, pool: ILocalHyperdrive): + def _add_deployed_pool_to_bookkeeping(self, pool: LocalHyperdrive): if self._has_saved_snapshot: raise ValueError("Cannot add a new pool after saving a snapshot") self._deployed_hyperdrive_pools.append(pool) diff --git a/src/agent0/core/hyperdrive/interactive/i_local_hyperdrive.py b/src/agent0/core/hyperdrive/interactive/local_hyperdrive.py similarity index 96% rename from src/agent0/core/hyperdrive/interactive/i_local_hyperdrive.py rename to src/agent0/core/hyperdrive/interactive/local_hyperdrive.py index 0ae1cf651d..a2f2abe033 100644 --- a/src/agent0/core/hyperdrive/interactive/i_local_hyperdrive.py +++ b/src/agent0/core/hyperdrive/interactive/local_hyperdrive.py @@ -43,7 +43,7 @@ ) from agent0.chainsync.exec import acquire_data, data_analysis from agent0.core.base.make_key import make_private_key -from agent0.core.hyperdrive import HyperdriveAgent, TradeResult, TradeStatus +from agent0.core.hyperdrive import HyperdrivePolicyAgent, TradeResult, TradeStatus from agent0.core.hyperdrive.agent import build_wallet_positions_from_db from agent0.core.hyperdrive.crash_report import get_anvil_state_dump from agent0.core.hyperdrive.policies import HyperdriveBasePolicy @@ -67,21 +67,21 @@ RedeemWithdrawalShares, RemoveLiquidity, ) -from .i_hyperdrive import IHyperdrive -from .i_local_chain import ILocalChain -from .i_local_hyperdrive_agent import ILocalHyperdriveAgent +from .hyperdrive import Hyperdrive +from .local_chain import LocalChain +from .local_hyperdrive_agent import LocalHyperdriveAgent # Is very thorough module. # pylint: disable=too-many-lines -class ILocalHyperdrive(IHyperdrive): +class LocalHyperdrive(Hyperdrive): """Interactive Hyperdrive class that supports an interactive interface for running tests and experiments.""" # Lots of attributes in config # pylint: disable=too-many-instance-attributes @dataclass(kw_only=True) - class Config(IHyperdrive.Config): + class Config(Hyperdrive.Config): """The configuration for the local hyperdrive pool.""" # Environment variables @@ -209,7 +209,7 @@ def _fees(self) -> Fees: governanceZombie=self.governance_zombie_fee.scaled_value, ) - def __init__(self, chain: ILocalChain, config: Config | None = None): + def __init__(self, chain: LocalChain, config: Config | None = None): """Constructor for the interactive hyperdrive agent. Arguments @@ -272,14 +272,14 @@ def __init__(self, chain: ILocalChain, config: Config | None = None): self._run_blocking_data_pipeline() self.dashboard_subprocess: subprocess.Popen | None = None - self._pool_agents: list[ILocalHyperdriveAgent] = [] + self._pool_agents: list[LocalHyperdriveAgent] = [] def get_hyperdrive_address(self) -> ChecksumAddress: """Returns the hyperdrive addresses for this pool. Returns ------- - IHyperdrive.Addresses + ChecksumAddress The hyperdrive addresses for this pool """ # pylint: disable=protected-access @@ -447,7 +447,7 @@ def __eq__(self, other): other._deployed_hyperdrive.hyperdrive_contract.address, ) - def _deploy_hyperdrive(self, config: Config, chain: ILocalChain) -> DeployedHyperdrivePool: + def _deploy_hyperdrive(self, config: Config, chain: LocalChain) -> DeployedHyperdrivePool: # sanity check (also for type checking), should get set in __post_init__ factory_deploy_config = FactoryConfig( governance="", # will be determined in the deploy function @@ -555,7 +555,7 @@ def init_agent( base: FixedPoint | None = None, eth: FixedPoint | None = None, name: str | None = None, - ) -> ILocalHyperdriveAgent: + ) -> LocalHyperdriveAgent: """Initializes an agent with initial funding and a logical name. Arguments @@ -590,7 +590,7 @@ def init_agent( # If the underlying policy's rng isn't set, we use the one from interactive hyperdrive if policy_config is not None and policy_config.rng is None and policy_config.rng_seed is None: policy_config.rng = self.config.rng - out_agent = ILocalHyperdriveAgent( + out_agent = LocalHyperdriveAgent( base=base, eth=eth, name=name, @@ -1023,7 +1023,7 @@ def _init_local_agent( policy: Type[HyperdriveBasePolicy] | None, policy_config: HyperdriveBasePolicy.Config | None, private_key: str | None = None, - ) -> HyperdriveAgent: + ) -> HyperdrivePolicyAgent: # We overwrite the base init agents with different parameters # pylint: disable=arguments-differ # pylint: disable=too-many-arguments @@ -1040,7 +1040,9 @@ def _init_local_agent( policy_obj = policy(policy_config) # Setting the budget to 0 here, `_add_funds` will take care of updating the wallet - agent = HyperdriveAgent(Account().from_key(agent_private_key), initial_budget=FixedPoint(0), policy=policy_obj) + agent = HyperdrivePolicyAgent( + Account().from_key(agent_private_key), initial_budget=FixedPoint(0), policy=policy_obj + ) # Update wallet to agent's previous budget if private_key is not None: # address already existed agent.wallet.balance.amount = self.interface.get_eth_base_balances(agent)[1] @@ -1068,7 +1070,7 @@ def _init_local_agent( add_addr_to_username(name, [agent.address], self.db_session) return agent - def _sync_wallet(self, agent: HyperdriveAgent) -> None: + def _sync_wallet(self, agent: HyperdrivePolicyAgent) -> None: # TODO add sync from db super()._sync_wallet(agent) # Ensure db is up to date @@ -1076,7 +1078,11 @@ def _sync_wallet(self, agent: HyperdriveAgent) -> None: self._run_blocking_data_pipeline() def _add_funds( - self, agent: HyperdriveAgent, base: FixedPoint, eth: FixedPoint, signer_account: LocalAccount | None = None + self, + agent: HyperdrivePolicyAgent, + base: FixedPoint, + eth: FixedPoint, + signer_account: LocalAccount | None = None, ) -> None: # TODO this can be fixed by getting actual base values from the chain. if self.chain._has_saved_snapshot: # pylint: disable=protected-access @@ -1115,7 +1121,7 @@ def _handle_trade_result(self, trade_result: TradeResult) -> ReceiptBreakdown: return super()._handle_trade_result(trade_result) - def _open_long(self, agent: HyperdriveAgent, base: FixedPoint) -> OpenLong: + def _open_long(self, agent: HyperdrivePolicyAgent, base: FixedPoint) -> OpenLong: out = super()._open_long(agent, base) # Experimental changes runs data pipeline in thread # Turn that off here to run in slow, but won't crash mode @@ -1123,7 +1129,7 @@ def _open_long(self, agent: HyperdriveAgent, base: FixedPoint) -> OpenLong: self._run_blocking_data_pipeline() return out - def _close_long(self, agent: HyperdriveAgent, maturity_time: int, bonds: FixedPoint) -> CloseLong: + def _close_long(self, agent: HyperdrivePolicyAgent, maturity_time: int, bonds: FixedPoint) -> CloseLong: out = super()._close_long(agent, maturity_time, bonds) # Experimental changes runs data pipeline in thread # Turn that off here to run in slow, but won't crash mode @@ -1131,7 +1137,7 @@ def _close_long(self, agent: HyperdriveAgent, maturity_time: int, bonds: FixedPo self._run_blocking_data_pipeline() return out - def _open_short(self, agent: HyperdriveAgent, bonds: FixedPoint) -> OpenShort: + def _open_short(self, agent: HyperdrivePolicyAgent, bonds: FixedPoint) -> OpenShort: out = super()._open_short(agent, bonds) # Experimental changes runs data pipeline in thread # Turn that off here to run in slow, but won't crash mode @@ -1139,7 +1145,7 @@ def _open_short(self, agent: HyperdriveAgent, bonds: FixedPoint) -> OpenShort: self._run_blocking_data_pipeline() return out - def _close_short(self, agent: HyperdriveAgent, maturity_time: int, bonds: FixedPoint) -> CloseShort: + def _close_short(self, agent: HyperdrivePolicyAgent, maturity_time: int, bonds: FixedPoint) -> CloseShort: out = super()._close_short(agent, maturity_time, bonds) # Experimental changes runs data pipeline in thread # Turn that off here to run in slow, but won't crash mode @@ -1147,7 +1153,7 @@ def _close_short(self, agent: HyperdriveAgent, maturity_time: int, bonds: FixedP self._run_blocking_data_pipeline() return out - def _add_liquidity(self, agent: HyperdriveAgent, base: FixedPoint) -> AddLiquidity: + def _add_liquidity(self, agent: HyperdrivePolicyAgent, base: FixedPoint) -> AddLiquidity: out = super()._add_liquidity(agent, base) # Experimental changes runs data pipeline in thread # Turn that off here to run in slow, but won't crash mode @@ -1155,7 +1161,7 @@ def _add_liquidity(self, agent: HyperdriveAgent, base: FixedPoint) -> AddLiquidi self._run_blocking_data_pipeline() return out - def _remove_liquidity(self, agent: HyperdriveAgent, shares: FixedPoint) -> RemoveLiquidity: + def _remove_liquidity(self, agent: HyperdrivePolicyAgent, shares: FixedPoint) -> RemoveLiquidity: out = super()._remove_liquidity(agent, shares) # Experimental changes runs data pipeline in thread # Turn that off here to run in slow, but won't crash mode @@ -1163,7 +1169,7 @@ def _remove_liquidity(self, agent: HyperdriveAgent, shares: FixedPoint) -> Remov self._run_blocking_data_pipeline() return out - def _redeem_withdraw_share(self, agent: HyperdriveAgent, shares: FixedPoint) -> RedeemWithdrawalShares: + def _redeem_withdraw_share(self, agent: HyperdrivePolicyAgent, shares: FixedPoint) -> RedeemWithdrawalShares: out = super()._redeem_withdraw_share(agent, shares) # Experimental changes runs data pipeline in thread # Turn that off here to run in slow, but won't crash mode @@ -1172,7 +1178,7 @@ def _redeem_withdraw_share(self, agent: HyperdriveAgent, shares: FixedPoint) -> return out def _execute_policy_action( - self, agent: HyperdriveAgent + self, agent: HyperdrivePolicyAgent ) -> list[OpenLong | OpenShort | CloseLong | CloseShort | AddLiquidity | RemoveLiquidity | RedeemWithdrawalShares]: out = super()._execute_policy_action(agent) # Experimental changes runs data pipeline in thread @@ -1182,7 +1188,7 @@ def _execute_policy_action( return out def _liquidate( - self, agent: HyperdriveAgent, randomize: bool + self, agent: HyperdrivePolicyAgent, randomize: bool ) -> list[CloseLong | CloseShort | RemoveLiquidity | RedeemWithdrawalShares]: out = super()._liquidate(agent, randomize) # Experimental changes runs data pipeline in thread diff --git a/src/agent0/core/hyperdrive/interactive/i_local_hyperdrive_agent.py b/src/agent0/core/hyperdrive/interactive/local_hyperdrive_agent.py similarity index 91% rename from src/agent0/core/hyperdrive/interactive/i_local_hyperdrive_agent.py rename to src/agent0/core/hyperdrive/interactive/local_hyperdrive_agent.py index 2d008b4e10..af47f56179 100644 --- a/src/agent0/core/hyperdrive/interactive/i_local_hyperdrive_agent.py +++ b/src/agent0/core/hyperdrive/interactive/local_hyperdrive_agent.py @@ -6,17 +6,17 @@ from fixedpointmath import FixedPoint -from .i_hyperdrive_agent import IHyperdriveAgent +from .hyperdrive_agent import HyperdriveAgent if TYPE_CHECKING: from typing import Type from agent0.core.hyperdrive.policies import HyperdriveBasePolicy - from .i_local_hyperdrive import ILocalHyperdrive + from .local_hyperdrive import LocalHyperdrive -class ILocalHyperdriveAgent(IHyperdriveAgent): +class LocalHyperdriveAgent(HyperdriveAgent): """Interactive Local Hyperdrive Agent. This class is barebones with documentation, will just call the corresponding function @@ -29,7 +29,7 @@ def __init__( base: FixedPoint, eth: FixedPoint, name: str | None, - pool: ILocalHyperdrive, + pool: LocalHyperdrive, policy: Type[HyperdriveBasePolicy] | None, policy_config: HyperdriveBasePolicy.Config | None, private_key: str | None = None, diff --git a/src/agent0/core/hyperdrive/interactive/i_local_hyperdrive_test.py b/src/agent0/core/hyperdrive/interactive/local_hyperdrive_test.py similarity index 90% rename from src/agent0/core/hyperdrive/interactive/i_local_hyperdrive_test.py rename to src/agent0/core/hyperdrive/interactive/local_hyperdrive_test.py index 03b4a60cf0..614f1c4cae 100644 --- a/src/agent0/core/hyperdrive/interactive/i_local_hyperdrive_test.py +++ b/src/agent0/core/hyperdrive/interactive/local_hyperdrive_test.py @@ -14,8 +14,8 @@ from agent0.core.hyperdrive.policies import HyperdriveBasePolicy, PolicyZoo from agent0.ethpy.hyperdrive import BASE_TOKEN_SYMBOL, AssetIdPrefix, HyperdriveReadInterface, encode_asset_id -from .i_local_chain import ILocalChain -from .i_local_hyperdrive import ILocalHyperdrive +from .local_chain import LocalChain +from .local_hyperdrive import LocalHyperdrive YEAR_IN_SECONDS = 31_536_000 @@ -27,7 +27,7 @@ @pytest.mark.anvil -def _ensure_db_wallet_matches_agent_wallet(interactive_hyperdrive: ILocalHyperdrive, agent_wallet: HyperdriveWallet): +def _ensure_db_wallet_matches_agent_wallet(interactive_hyperdrive: LocalHyperdrive, agent_wallet: HyperdriveWallet): # NOTE this function is assuming only one agent is making trades # Test against db @@ -77,18 +77,18 @@ def _ensure_db_wallet_matches_agent_wallet(interactive_hyperdrive: ILocalHyperdr # pylint: disable=too-many-statements # ruff: noqa: PLR0915 (too many statements) @pytest.mark.anvil -def test_funding_and_trades(chain: ILocalChain): +def test_funding_and_trades(chain: LocalChain): """Deploy 2 pools, 3 agents, and test funding and each trade type.""" # Parameters for pool initialization. If empty, defaults to default values, allows for custom values if needed # We explicitly set initial liquidity here to ensure we have withdrawal shares when trading - initial_pool_config = ILocalHyperdrive.Config( + initial_pool_config = LocalHyperdrive.Config( initial_liquidity=FixedPoint(1_000), initial_fixed_apr=FixedPoint("0.05"), position_duration=60 * 60 * 24 * 365, # 1 year ) # Launches 2 pools on the same local chain - interactive_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) - interactive_hyperdrive_2 = ILocalHyperdrive(chain, initial_pool_config) + interactive_hyperdrive = LocalHyperdrive(chain, initial_pool_config) + interactive_hyperdrive_2 = LocalHyperdrive(chain, initial_pool_config) # Generate funded trading agents from the interactive object # Names are reflected on output data frames and plots later @@ -189,12 +189,12 @@ def test_funding_and_trades(chain: ILocalChain): @pytest.mark.anvil -def test_block_timestamp_interval(chain: ILocalChain): +def test_block_timestamp_interval(chain: LocalChain): """Ensure block timestamp interval is set correctly.""" # The chain in the test fixture defaults to 12 seconds # We need the underlying hyperdrive interface here to test time - interactive_hyperdrive = ILocalHyperdrive(chain) + interactive_hyperdrive = LocalHyperdrive(chain) hyperdrive_interface = interactive_hyperdrive.interface hyperdrive_agent0 = interactive_hyperdrive.init_agent(base=FixedPoint(1_111_111), eth=FixedPoint(111), name="alice") @@ -209,10 +209,10 @@ def test_block_timestamp_interval(chain: ILocalChain): @pytest.mark.anvil -def test_advance_time(chain: ILocalChain): +def test_advance_time(chain: LocalChain): """Advance time by 3600 seconds then 1 week.""" # We need the underlying hyperdrive interface here to test time - interactive_hyperdrive = ILocalHyperdrive(chain) + interactive_hyperdrive = LocalHyperdrive(chain) hyperdrive_interface = interactive_hyperdrive.interface current_time_1 = hyperdrive_interface.get_block_timestamp(hyperdrive_interface.get_current_block()) @@ -228,15 +228,15 @@ def test_advance_time(chain: ILocalChain): @pytest.mark.anvil -def test_advance_time_with_checkpoints(chain: ILocalChain): +def test_advance_time_with_checkpoints(chain: LocalChain): """Checkpoint creation with advance time.""" # Since advancing time with checkpoints can be off by a block, we set block timestamp interval here # to be 1 to avoid advancing extra time chain._set_block_timestamp_interval(1) # pylint: disable=protected-access # We need the underlying hyperdrive interface here to test time - config = ILocalHyperdrive.Config(checkpoint_duration=3600) - interactive_hyperdrive = ILocalHyperdrive(chain, config) + config = LocalHyperdrive.Config(checkpoint_duration=3600) + interactive_hyperdrive = LocalHyperdrive(chain, config) hyperdrive_interface = interactive_hyperdrive.interface # TODO there is a non-determininstic element here, the first advance time for 600 seconds @@ -287,11 +287,11 @@ def test_advance_time_with_checkpoints(chain: ILocalChain): @pytest.mark.anvil -def test_save_load_snapshot(chain: ILocalChain): +def test_save_load_snapshot(chain: LocalChain): """Save and load snapshot.""" # Parameters for pool initialization. If empty, defaults to default values, allows for custom values if needed - initial_pool_config = ILocalHyperdrive.Config() - interactive_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) + initial_pool_config = LocalHyperdrive.Config() + interactive_hyperdrive = LocalHyperdrive(chain, initial_pool_config) hyperdrive_interface = interactive_hyperdrive.interface # Generate funded trading agents from the interactive object @@ -442,11 +442,11 @@ def test_save_load_snapshot(chain: ILocalChain): @pytest.mark.anvil -def test_set_variable_rate(chain: ILocalChain): +def test_set_variable_rate(chain: LocalChain): """Set the variable rate.""" # We need the underlying hyperdrive interface here to test time - config = ILocalHyperdrive.Config(initial_variable_rate=FixedPoint("0.05")) - interactive_hyperdrive = ILocalHyperdrive(chain, config) + config = LocalHyperdrive.Config(initial_variable_rate=FixedPoint("0.05")) + interactive_hyperdrive = LocalHyperdrive(chain, config) # Make a trade to mine the block on this variable rate so it shows up in the data pipeline _ = interactive_hyperdrive.init_agent() @@ -463,12 +463,12 @@ def test_set_variable_rate(chain: ILocalChain): @pytest.mark.anvil -def test_access_deployer_account(chain: ILocalChain): +def test_access_deployer_account(chain: LocalChain): """Access the deployer account.""" - config = ILocalHyperdrive.Config( + config = LocalHyperdrive.Config( initial_liquidity=FixedPoint("100"), ) - interactive_hyperdrive = ILocalHyperdrive(chain, config) + interactive_hyperdrive = LocalHyperdrive(chain, config) privkey = chain.get_deployer_account_private_key() # anvil account 0 pubkey = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" larry = interactive_hyperdrive.init_agent(base=FixedPoint(100_000), name="larry", private_key=privkey) @@ -477,12 +477,12 @@ def test_access_deployer_account(chain: ILocalChain): @pytest.mark.anvil -def test_access_deployer_liquidity(chain: ILocalChain): +def test_access_deployer_liquidity(chain: LocalChain): """Remove liquidity from the deployer account.""" - config = ILocalHyperdrive.Config( + config = LocalHyperdrive.Config( initial_liquidity=FixedPoint(100), ) - interactive_hyperdrive = ILocalHyperdrive(chain, config) + interactive_hyperdrive = LocalHyperdrive(chain, config) privkey = chain.get_deployer_account_private_key() # anvil account 0 larry = interactive_hyperdrive.init_agent(base=FixedPoint(100_000), name="larry", private_key=privkey) assert ( @@ -499,12 +499,12 @@ def test_access_deployer_liquidity(chain: ILocalChain): @pytest.mark.anvil -def test_remove_deployer_liquidity(chain: ILocalChain): +def test_remove_deployer_liquidity(chain: LocalChain): """Remove liquidity from the deployer account.""" - config = ILocalHyperdrive.Config( + config = LocalHyperdrive.Config( initial_liquidity=FixedPoint(100), ) - interactive_hyperdrive = ILocalHyperdrive(chain, config) + interactive_hyperdrive = LocalHyperdrive(chain, config) privkey = chain.get_deployer_account_private_key() # anvil account 0 larry = interactive_hyperdrive.init_agent(base=FixedPoint(100_000), name="larry", private_key=privkey) larry.remove_liquidity(shares=larry.wallet.lp_tokens) @@ -521,17 +521,17 @@ def test_remove_deployer_liquidity(chain: ILocalChain): @pytest.mark.anvil -def test_get_config_no_transactions(chain: ILocalChain): +def test_get_config_no_transactions(chain: LocalChain): """Get pool config before executing any transactions.""" - interactive_hyperdrive = ILocalHyperdrive(chain) + interactive_hyperdrive = LocalHyperdrive(chain) pool_config = interactive_hyperdrive.get_pool_config() assert isinstance(pool_config, Series) @pytest.mark.anvil -def test_get_config_with_transactions(chain: ILocalChain): +def test_get_config_with_transactions(chain: LocalChain): """Get pool config after executing one transaction.""" - interactive_hyperdrive = ILocalHyperdrive(chain) + interactive_hyperdrive = LocalHyperdrive(chain) agent0 = interactive_hyperdrive.init_agent(base=FixedPoint(100_000), eth=FixedPoint(100), name="alice") agent0.open_long(base=FixedPoint(11_111)) pool_config = interactive_hyperdrive.get_pool_config() @@ -539,9 +539,9 @@ def test_get_config_with_transactions(chain: ILocalChain): @pytest.mark.anvil -def test_liquidate(chain: ILocalChain): +def test_liquidate(chain: LocalChain): """Test liquidation.""" - interactive_hyperdrive = ILocalHyperdrive(chain) + interactive_hyperdrive = LocalHyperdrive(chain) alice = interactive_hyperdrive.init_agent(base=FixedPoint(10_000), name="alice") alice.open_long(base=FixedPoint(100)) alice.open_short(bonds=FixedPoint(100)) @@ -554,11 +554,11 @@ def test_liquidate(chain: ILocalChain): @pytest.mark.anvil -def test_random_liquidate(chain: ILocalChain): +def test_random_liquidate(chain: LocalChain): """Test random liquidation.""" # Explicitly setting a random seed to remove randomness in the test - interactive_config = ILocalHyperdrive.Config(rng_seed=1234) - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_config = LocalHyperdrive.Config(rng_seed=1234) + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) alice = interactive_hyperdrive.init_agent(base=FixedPoint(10_000), name="alice") # We run the same trades 5 times, and ensure there's at least one difference @@ -598,18 +598,18 @@ def test_random_liquidate(chain: ILocalChain): @pytest.mark.anvil -def test_share_price_compounding_quincunx(chain: ILocalChain): +def test_share_price_compounding_quincunx(chain: LocalChain): """Share price when compounding by quincunx (one fifth of a year) should increase by more than the APR.""" # setup initial_variable_rate = FixedPoint("0.045") - interactive_config = ILocalHyperdrive.Config( + interactive_config = LocalHyperdrive.Config( position_duration=YEAR_IN_SECONDS, # 1 year term governance_lp_fee=FixedPoint(0), curve_fee=FixedPoint(0), flat_fee=FixedPoint(0), initial_variable_rate=initial_variable_rate, ) - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) hyperdrive_interface = interactive_hyperdrive.interface logging.info(f"Variable rate: {hyperdrive_interface.current_pool_state.variable_rate}") logging.info(f"Starting share price: {hyperdrive_interface.current_pool_state.pool_info.lp_share_price}") @@ -628,18 +628,18 @@ def test_share_price_compounding_quincunx(chain: ILocalChain): @pytest.mark.anvil -def test_share_price_compounding_annus(chain: ILocalChain): +def test_share_price_compounding_annus(chain: LocalChain): """Share price when compounding by annus (one year) should increase by exactly the APR (no compounding).""" # setup initial_variable_rate = FixedPoint("0.045") - interactive_config = ILocalHyperdrive.Config( + interactive_config = LocalHyperdrive.Config( position_duration=YEAR_IN_SECONDS, # 1 year term governance_lp_fee=FixedPoint(0), curve_fee=FixedPoint(0), flat_fee=FixedPoint(0), initial_variable_rate=initial_variable_rate, ) - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) hyperdrive_interface = interactive_hyperdrive.interface logging.info(f"Variable rate: {hyperdrive_interface.current_pool_state.variable_rate}") logging.info(f"Starting share price: {hyperdrive_interface.current_pool_state.pool_info.lp_share_price}") @@ -650,10 +650,10 @@ def test_share_price_compounding_annus(chain: ILocalChain): @pytest.mark.anvil -def test_policy_config_forgotten(chain: ILocalChain): +def test_policy_config_forgotten(chain: LocalChain): """The policy config is not passed in.""" - interactive_config = ILocalHyperdrive.Config() - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_config = LocalHyperdrive.Config() + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) alice = interactive_hyperdrive.init_agent( base=FixedPoint(10_000), name="alice", @@ -663,10 +663,10 @@ def test_policy_config_forgotten(chain: ILocalChain): @pytest.mark.anvil -def test_policy_config_none_rng(chain: ILocalChain): +def test_policy_config_none_rng(chain: LocalChain): """The policy config has rng set to None.""" - interactive_config = ILocalHyperdrive.Config() - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_config = LocalHyperdrive.Config() + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) agent_policy = PolicyZoo.random.Config() agent_policy.rng = None alice = interactive_hyperdrive.init_agent( @@ -679,7 +679,7 @@ def test_policy_config_none_rng(chain: ILocalChain): @pytest.mark.anvil -def test_snapshot_policy_state(chain: ILocalChain): +def test_snapshot_policy_state(chain: LocalChain): """Tests proper saving/loading of policy state during snapshotting.""" # Define dummy class for deep state copy @@ -707,7 +707,7 @@ def action( return [], False # Initialize agent with sub policy - interactive_hyperdrive = ILocalHyperdrive(chain) + interactive_hyperdrive = LocalHyperdrive(chain) agent = interactive_hyperdrive.init_agent(policy=_SubPolicy) # Snapshot state chain.save_snapshot() @@ -740,10 +740,10 @@ def action( @pytest.mark.anvil -def test_load_rng_on_snapshot(chain: ILocalChain): +def test_load_rng_on_snapshot(chain: LocalChain): """The policy config has rng set to None.""" - load_rng_hyperdrive = ILocalHyperdrive(chain, ILocalHyperdrive.Config(load_rng_on_snapshot=True)) - non_load_rng_hyperdrive = ILocalHyperdrive(chain, ILocalHyperdrive.Config(load_rng_on_snapshot=False)) + load_rng_hyperdrive = LocalHyperdrive(chain, LocalHyperdrive.Config(load_rng_on_snapshot=True)) + non_load_rng_hyperdrive = LocalHyperdrive(chain, LocalHyperdrive.Config(load_rng_on_snapshot=False)) agent_policy = PolicyZoo.random.Config() agent_policy.rng = None @@ -777,14 +777,14 @@ def test_load_rng_on_snapshot(chain: ILocalChain): assert not np.array_equal(bob_random_before_snap, bob_random_after_snap) -def test_hyperdrive_read_interface_standardized_variable_rate(chain: ILocalChain): +def test_hyperdrive_read_interface_standardized_variable_rate(chain: LocalChain): # TODO this is testing the underlying standardized_variable_rate call in # the hyperdrive interface. Ideally, this would live in `read_interface_test.py`, # but we need a local chain for advancing time for testing. Move this test # to `read_interface_test` once we start using interactive hyperdrive for all tests. - hyperdrive_config = ILocalHyperdrive.Config(checkpoint_duration=86400) # checkpoint duration of 1 day - interactive_hyperdrive = ILocalHyperdrive(chain, hyperdrive_config) + hyperdrive_config = LocalHyperdrive.Config(checkpoint_duration=86400) # checkpoint duration of 1 day + interactive_hyperdrive = LocalHyperdrive(chain, hyperdrive_config) hyperdrive_interface = interactive_hyperdrive.interface mock_variable_rate = hyperdrive_interface.get_variable_rate() @@ -803,9 +803,9 @@ def test_hyperdrive_read_interface_standardized_variable_rate(chain: ILocalChain @pytest.mark.anvil @pytest.mark.parametrize("time_stretch", [0.01, 0.1, 0.5, 1, 10, 100]) -def test_deploy_nonstandard_timestretch(chain: ILocalChain, time_stretch: float): +def test_deploy_nonstandard_timestretch(chain: LocalChain, time_stretch: float): """Deplopy with nonstandard timestretch parameters.""" - initial_pool_config = ILocalHyperdrive.Config( + initial_pool_config = LocalHyperdrive.Config( initial_liquidity=FixedPoint(10_000_000), position_duration=60 * 60 * 24 * 365, # 1 year factory_min_fixed_apr=FixedPoint(0.001), @@ -815,5 +815,5 @@ def test_deploy_nonstandard_timestretch(chain: ILocalChain, time_stretch: float) initial_fixed_apr=FixedPoint(time_stretch), initial_time_stretch_apr=FixedPoint(time_stretch), ) - interactive_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) + interactive_hyperdrive = LocalHyperdrive(chain, initial_pool_config) assert isinstance(interactive_hyperdrive.interface.current_pool_state.pool_config.time_stretch, FixedPoint) diff --git a/src/agent0/core/hyperdrive/policies/lpandarb_test.py b/src/agent0/core/hyperdrive/policies/lpandarb_test.py index 4a929706a0..144a998373 100644 --- a/src/agent0/core/hyperdrive/policies/lpandarb_test.py +++ b/src/agent0/core/hyperdrive/policies/lpandarb_test.py @@ -7,9 +7,9 @@ import pytest from fixedpointmath import FixedPoint -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.core.hyperdrive.interactive.event_types import AddLiquidity, CloseLong, CloseShort, OpenLong, OpenShort -from agent0.core.hyperdrive.interactive.i_local_hyperdrive_agent import ILocalHyperdriveAgent +from agent0.core.hyperdrive.interactive.local_hyperdrive_agent import LocalHyperdriveAgent from agent0.core.hyperdrive.policies import PolicyZoo # avoid unnecessary warning from using fixtures defined in outer scope @@ -26,7 +26,7 @@ @pytest.fixture(scope="function") -def interactive_hyperdrive(chain: ILocalChain) -> ILocalHyperdrive: +def interactive_hyperdrive(chain: LocalChain) -> LocalHyperdrive: """Create interactive hyperdrive. Arguments @@ -39,15 +39,15 @@ def interactive_hyperdrive(chain: ILocalChain) -> ILocalHyperdrive: InteractiveHyperdrive Interactive hyperdrive. """ - interactive_config = ILocalHyperdrive.Config( + interactive_config = LocalHyperdrive.Config( position_duration=YEAR_IN_SECONDS, # 1 year term initial_fixed_apr=FixedPoint("0.05"), ) - return ILocalHyperdrive(chain, interactive_config) + return LocalHyperdrive(chain, interactive_config) @pytest.fixture(scope="function") -def arbitrage_andy(interactive_hyperdrive) -> ILocalHyperdriveAgent: +def arbitrage_andy(interactive_hyperdrive) -> LocalHyperdriveAgent: """Create Arbitrage Andy interactive hyperdrive agent used to arbitrage the fixed rate to the variable rate. Arguments @@ -63,7 +63,7 @@ def arbitrage_andy(interactive_hyperdrive) -> ILocalHyperdriveAgent: return create_arbitrage_andy(interactive_hyperdrive) -def create_arbitrage_andy(interactive_hyperdrive) -> ILocalHyperdriveAgent: +def create_arbitrage_andy(interactive_hyperdrive) -> LocalHyperdriveAgent: """Create Arbitrage Andy interactive hyperdrive agent used to arbitrage the fixed rate to the variable rate. Arguments @@ -87,7 +87,7 @@ def create_arbitrage_andy(interactive_hyperdrive) -> ILocalHyperdriveAgent: @pytest.fixture(scope="function") -def manual_agent(interactive_hyperdrive) -> ILocalHyperdriveAgent: +def manual_agent(interactive_hyperdrive) -> LocalHyperdriveAgent: """Create manual interactive hyperdrive agent used to manually move markets. Arguments @@ -106,10 +106,10 @@ def manual_agent(interactive_hyperdrive) -> ILocalHyperdriveAgent: @pytest.mark.anvil @pytest.mark.parametrize("trade_amount", TRADE_AMOUNTS) def test_open_long( - interactive_hyperdrive: ILocalHyperdrive, + interactive_hyperdrive: LocalHyperdrive, trade_amount: float, - arbitrage_andy: ILocalHyperdriveAgent, - manual_agent: ILocalHyperdriveAgent, + arbitrage_andy: LocalHyperdriveAgent, + manual_agent: LocalHyperdriveAgent, ): """Open a long to hit the target rate.""" # change the fixed rate @@ -135,10 +135,10 @@ def test_open_long( @pytest.mark.anvil @pytest.mark.parametrize("trade_amount", TRADE_AMOUNTS) def test_open_short( - interactive_hyperdrive: ILocalHyperdrive, + interactive_hyperdrive: LocalHyperdrive, trade_amount: float, - arbitrage_andy: ILocalHyperdriveAgent, - manual_agent: ILocalHyperdriveAgent, + arbitrage_andy: LocalHyperdriveAgent, + manual_agent: LocalHyperdriveAgent, ): """Open a short to hit the target rate.""" # change the fixed rate @@ -165,10 +165,10 @@ def test_open_short( @pytest.mark.anvil @pytest.mark.parametrize("trade_amount", [0.003, 10]) def test_close_long( - interactive_hyperdrive: ILocalHyperdrive, + interactive_hyperdrive: LocalHyperdrive, trade_amount: float, - arbitrage_andy: ILocalHyperdriveAgent, - manual_agent: ILocalHyperdriveAgent, + arbitrage_andy: LocalHyperdriveAgent, + manual_agent: LocalHyperdriveAgent, ): """Close a long to hit the target rate.""" # report starting fixed rate @@ -261,7 +261,7 @@ def test_close_long( @pytest.mark.anvil -def test_already_at_target(interactive_hyperdrive: ILocalHyperdrive, arbitrage_andy: ILocalHyperdriveAgent): +def test_already_at_target(interactive_hyperdrive: LocalHyperdrive, arbitrage_andy: LocalHyperdriveAgent): """Already at target, do nothing.""" # report starting fixed rate logging.info("starting fixed rate is %s", interactive_hyperdrive.interface.calc_spot_rate()) @@ -281,7 +281,7 @@ def test_already_at_target(interactive_hyperdrive: ILocalHyperdrive, arbitrage_a @pytest.mark.anvil -def test_reduce_long(interactive_hyperdrive: ILocalHyperdrive, arbitrage_andy: ILocalHyperdriveAgent): +def test_reduce_long(interactive_hyperdrive: LocalHyperdrive, arbitrage_andy: LocalHyperdriveAgent): """Reduce a long position.""" # give Andy a long event = arbitrage_andy.open_long(base=FixedPoint(10)) @@ -297,7 +297,7 @@ def test_reduce_long(interactive_hyperdrive: ILocalHyperdrive, arbitrage_andy: I @pytest.mark.anvil -def test_reduce_short(interactive_hyperdrive: ILocalHyperdrive, arbitrage_andy: ILocalHyperdriveAgent): +def test_reduce_short(interactive_hyperdrive: LocalHyperdrive, arbitrage_andy: LocalHyperdriveAgent): """Reduce a short position.""" logging.info("starting fixed rate is %s", interactive_hyperdrive.interface.calc_spot_rate()) @@ -317,7 +317,7 @@ def test_reduce_short(interactive_hyperdrive: ILocalHyperdrive, arbitrage_andy: @pytest.mark.anvil -def test_safe_long_trading(interactive_hyperdrive: ILocalHyperdrive, manual_agent: ILocalHyperdriveAgent): +def test_safe_long_trading(interactive_hyperdrive: LocalHyperdrive, manual_agent: LocalHyperdriveAgent): """Test that the agent doesn't overextend itself.""" # setup larry_base = FixedPoint(1e4) @@ -339,7 +339,7 @@ def test_safe_long_trading(interactive_hyperdrive: ILocalHyperdrive, manual_agen @pytest.mark.anvil -def test_safe_short_trading(interactive_hyperdrive: ILocalHyperdrive, manual_agent: ILocalHyperdriveAgent): +def test_safe_short_trading(interactive_hyperdrive: LocalHyperdrive, manual_agent: LocalHyperdriveAgent): """Test that the agent doesn't overextend itself.""" # setup larry_base = FixedPoint(1e4) diff --git a/src/agent0/core/hyperdrive/policies/random_hold_test.py b/src/agent0/core/hyperdrive/policies/random_hold_test.py index 05d1899e9a..9e3da8db56 100644 --- a/src/agent0/core/hyperdrive/policies/random_hold_test.py +++ b/src/agent0/core/hyperdrive/policies/random_hold_test.py @@ -5,7 +5,7 @@ import pytest from fixedpointmath import FixedPoint -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.core.hyperdrive.interactive.event_types import CloseLong, CloseShort from agent0.core.hyperdrive.policies import PolicyZoo @@ -13,16 +13,16 @@ @pytest.mark.anvil -def test_random_hold_policy(chain: ILocalChain): +def test_random_hold_policy(chain: LocalChain): # Parameters for pool initialization. If empty, defaults to default values, allows for custom values if needed # We explicitly set initial liquidity here to ensure we have withdrawal shares when trading - initial_pool_config = ILocalHyperdrive.Config( + initial_pool_config = LocalHyperdrive.Config( initial_liquidity=FixedPoint(1_000), initial_fixed_apr=FixedPoint("0.05"), position_duration=60 * 60 * 24 * 7, # 1 week checkpoint_duration=60 * 60 * 24, # 1 day ) - interactive_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) + interactive_hyperdrive = LocalHyperdrive(chain, initial_pool_config) random_hold_agent = interactive_hyperdrive.init_agent( base=FixedPoint(1_111_111), eth=FixedPoint(111), diff --git a/src/agent0/core/hyperdrive/policies/random_test.py b/src/agent0/core/hyperdrive/policies/random_test.py index 467a37cac6..839a4ef801 100644 --- a/src/agent0/core/hyperdrive/policies/random_test.py +++ b/src/agent0/core/hyperdrive/policies/random_test.py @@ -6,7 +6,7 @@ from fixedpointmath import FixedPoint from agent0.core.hyperdrive import HyperdriveActionType -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.core.hyperdrive.interactive.event_types import ( AddLiquidity, CloseLong, @@ -20,14 +20,14 @@ @pytest.mark.anvil -def test_random_policy(chain: ILocalChain): - initial_pool_config = ILocalHyperdrive.Config( +def test_random_policy(chain: LocalChain): + initial_pool_config = LocalHyperdrive.Config( initial_liquidity=FixedPoint(1_000), initial_fixed_apr=FixedPoint("0.05"), position_duration=60 * 60 * 24 * 7, # 1 week checkpoint_duration=60 * 60 * 24, # 1 day ) - interactive_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) + interactive_hyperdrive = LocalHyperdrive(chain, initial_pool_config) random_agent = interactive_hyperdrive.init_agent( base=FixedPoint(1_000_000), @@ -44,14 +44,14 @@ def test_random_policy(chain: ILocalChain): @pytest.mark.anvil -def test_random_policy_trades(chain: ILocalChain): - initial_pool_config = ILocalHyperdrive.Config( +def test_random_policy_trades(chain: LocalChain): + initial_pool_config = LocalHyperdrive.Config( initial_liquidity=FixedPoint(1_000), initial_fixed_apr=FixedPoint("0.05"), position_duration=60 * 60 * 24 * 7, # 1 week checkpoint_duration=60 * 60 * 24, # 1 day ) - interactive_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) + interactive_hyperdrive = LocalHyperdrive(chain, initial_pool_config) random_agent = interactive_hyperdrive.init_agent( base=FixedPoint(1_000_000), diff --git a/src/agent0/core/hyperdrive/policies/simple_lp_test.py b/src/agent0/core/hyperdrive/policies/simple_lp_test.py index 75a138b759..b23e9ec50e 100644 --- a/src/agent0/core/hyperdrive/policies/simple_lp_test.py +++ b/src/agent0/core/hyperdrive/policies/simple_lp_test.py @@ -7,17 +7,17 @@ import pytest from fixedpointmath import FixedPoint, isclose -from agent0 import ILocalChain, ILocalHyperdrive, PolicyZoo +from agent0 import LocalChain, LocalHyperdrive, PolicyZoo from agent0.core.hyperdrive.interactive.event_types import AddLiquidity, RemoveLiquidity # pylint: disable=too-many-locals @pytest.mark.anvil -def test_simple_lp_policy(chain: ILocalChain): +def test_simple_lp_policy(chain: LocalChain): # Parameters for pool initialization. If empty, defaults to default values, allows for custom values if needed # We explicitly set initial liquidity here to ensure we have withdrawal shares when trading - initial_pool_config = ILocalHyperdrive.Config( + initial_pool_config = LocalHyperdrive.Config( initial_liquidity=FixedPoint("100"), initial_variable_rate=FixedPoint("0.01"), initial_fixed_apr=FixedPoint("0.05"), @@ -30,7 +30,7 @@ def test_simple_lp_policy(chain: ILocalChain): # This test requires the non-policy actions to be passed into the policy's post trade stage. always_execute_policy_post_action=True, ) - interactive_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) + interactive_hyperdrive = LocalHyperdrive(chain, initial_pool_config) # Deploy LP agent & add base liquidity pnl_target = FixedPoint("8.0") diff --git a/src/agent0/core/hyperdrive/utilities/predict_trade_test.py b/src/agent0/core/hyperdrive/utilities/predict_trade_test.py index 19445c994a..5cb962cd6a 100644 --- a/src/agent0/core/hyperdrive/utilities/predict_trade_test.py +++ b/src/agent0/core/hyperdrive/utilities/predict_trade_test.py @@ -26,7 +26,7 @@ from fixedpointmath import FixedPoint from tabulate import tabulate -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.core.hyperdrive.interactive.event_types import OpenLong, OpenShort from agent0.core.hyperdrive.utilities.predict import TradeDeltas, predict_long, predict_short @@ -77,7 +77,7 @@ def _log_event( ) -def test_prediction_example(chain: ILocalChain): +def test_prediction_example(chain: LocalChain): """Demonstrate the simplest case of a prediction. Output: @@ -93,13 +93,13 @@ def test_prediction_example(chain: ILocalChain): | governance | 0.00475964 | 0.00499762 | 0.00475964 | +------------+--------------+---------------+--------------+ """ - interactive_config = ILocalHyperdrive.Config( + interactive_config = LocalHyperdrive.Config( position_duration=YEAR_IN_SECONDS, # 1 year term governance_lp_fee=FixedPoint(0.1), curve_fee=FixedPoint(0.01), flat_fee=FixedPoint(0), ) - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) agent = interactive_hyperdrive.init_agent(base=FixedPoint(1e9)) base_needed = FixedPoint(100) delta = predict_long(hyperdrive_interface=interactive_hyperdrive.interface, base=base_needed) @@ -108,15 +108,15 @@ def test_prediction_example(chain: ILocalChain): _log_table(delta) -def test_open_long_bonds(chain: ILocalChain): +def test_open_long_bonds(chain: LocalChain): """Demonstrate abililty to open long with bonds as input.""" - interactive_config = ILocalHyperdrive.Config( + interactive_config = LocalHyperdrive.Config( position_duration=YEAR_IN_SECONDS, # 1 year term governance_lp_fee=FixedPoint(0.1), curve_fee=FixedPoint(0.01), flat_fee=FixedPoint(0), ) - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) agent = interactive_hyperdrive.init_agent(base=FixedPoint(1e9)) bonds_needed = FixedPoint(100) @@ -125,15 +125,15 @@ def test_open_long_bonds(chain: ILocalChain): _log_event("long ", "bonds", bonds_needed, event[0] if isinstance(event, list) else event) -def test_open_short_base(chain: ILocalChain): +def test_open_short_base(chain: LocalChain): """Demonstrate abililty to open short with base as input.""" - interactive_config = ILocalHyperdrive.Config( + interactive_config = LocalHyperdrive.Config( position_duration=YEAR_IN_SECONDS, # 1 year term governance_lp_fee=FixedPoint(0.1), curve_fee=FixedPoint(0.01), flat_fee=FixedPoint(0), ) - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) agent = interactive_hyperdrive.init_agent(base=FixedPoint(1e9)) base_needed = FixedPoint(100) @@ -144,16 +144,16 @@ def test_open_short_base(chain: ILocalChain): @pytest.mark.anvil -def test_predict_open_long_bonds(chain: ILocalChain): +def test_predict_open_long_bonds(chain: LocalChain): """Predict outcome of an open long, for a given amount of bonds.""" # setup - interactive_config = ILocalHyperdrive.Config( + interactive_config = LocalHyperdrive.Config( position_duration=YEAR_IN_SECONDS, # 1 year term governance_lp_fee=FixedPoint(0.1), curve_fee=FixedPoint(0.01), flat_fee=FixedPoint(0), ) - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) hyperdrive_interface = interactive_hyperdrive.interface agent = interactive_hyperdrive.init_agent(base=FixedPoint(1e9)) pool_state = deepcopy(hyperdrive_interface.current_pool_state) @@ -215,16 +215,16 @@ def test_predict_open_long_bonds(chain: ILocalChain): @pytest.mark.anvil -def test_predict_open_long_base(chain: ILocalChain): +def test_predict_open_long_base(chain: LocalChain): """Predict outcome of an open long, for a given amount of base.""" # setup - interactive_config = ILocalHyperdrive.Config( + interactive_config = LocalHyperdrive.Config( position_duration=YEAR_IN_SECONDS, # 1 year term governance_lp_fee=FixedPoint(0), curve_fee=FixedPoint(0.01), flat_fee=FixedPoint(0), ) - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) hyperdrive_interface = interactive_hyperdrive.interface agent = interactive_hyperdrive.init_agent(base=FixedPoint(1e9)) @@ -275,15 +275,15 @@ def test_predict_open_long_base(chain: ILocalChain): @pytest.mark.anvil -def test_predict_open_short_bonds(chain: ILocalChain): +def test_predict_open_short_bonds(chain: LocalChain): """Predict outcome of an open short, for a given amount of bonds.""" - interactive_config = ILocalHyperdrive.Config( + interactive_config = LocalHyperdrive.Config( position_duration=YEAR_IN_SECONDS, # 1 year term governance_lp_fee=FixedPoint(0.1), curve_fee=FixedPoint(0.01), flat_fee=FixedPoint(0), ) - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) hyperdrive_interface = interactive_hyperdrive.interface agent = interactive_hyperdrive.init_agent(base=FixedPoint(1e9)) @@ -337,15 +337,15 @@ def test_predict_open_short_bonds(chain: ILocalChain): @pytest.mark.anvil -def test_predict_open_short_base(chain: ILocalChain): +def test_predict_open_short_base(chain: LocalChain): """Predict outcome of an open short, for a given amount of base.""" - interactive_config = ILocalHyperdrive.Config( + interactive_config = LocalHyperdrive.Config( position_duration=YEAR_IN_SECONDS, # 1 year term governance_lp_fee=FixedPoint(0.1), curve_fee=FixedPoint(0.01), flat_fee=FixedPoint(0), ) - interactive_hyperdrive = ILocalHyperdrive(chain, interactive_config) + interactive_hyperdrive = LocalHyperdrive(chain, interactive_config) hyperdrive_interface = interactive_hyperdrive.interface agent = interactive_hyperdrive.init_agent(base=FixedPoint(1e9)) diff --git a/src/agent0/core/hyperdrive/utilities/run_bots/create_and_fund_user_account.py b/src/agent0/core/hyperdrive/utilities/run_bots/create_and_fund_user_account.py index 911766d81c..b6d4650517 100644 --- a/src/agent0/core/hyperdrive/utilities/run_bots/create_and_fund_user_account.py +++ b/src/agent0/core/hyperdrive/utilities/run_bots/create_and_fund_user_account.py @@ -8,7 +8,7 @@ from agent0.core import AccountKeyConfig from agent0.core.base.make_key import make_private_key -from agent0.core.hyperdrive import HyperdriveAgent +from agent0.core.hyperdrive import HyperdrivePolicyAgent from agent0.ethpy.base import set_anvil_account_balance, smart_contract_transact from agent0.ethpy.hyperdrive import HyperdriveReadInterface @@ -22,7 +22,7 @@ def create_and_fund_user_account( account_key_config: AccountKeyConfig, interface: HyperdriveReadInterface, -) -> HyperdriveAgent: +) -> HyperdrivePolicyAgent: """Helper function for funding a fake user account. .. note:: @@ -38,7 +38,7 @@ def create_and_fund_user_account( Returns ------- - HyperdriveAgent + HyperdrivePolicyAgent An agent that corresponds to the fake "user" """ # generate fake user account @@ -47,26 +47,26 @@ def create_and_fund_user_account( return user_account -def _create_user_account() -> HyperdriveAgent: - """Create a fake HyperdriveAgent. +def _create_user_account() -> HyperdrivePolicyAgent: + """Create a fake HyperdrivePolicyAgent. .. note:: This function will soon be deprecated in favor of the IHyperdrive workflow Returns ------- - HyperdriveAgent + HyperdrivePolicyAgent The fake user. """ user_private_key = make_private_key(extra_entropy="FAKE USER") # argument value can be any str - user_account = HyperdriveAgent(Account().from_key(user_private_key)) + user_account = HyperdrivePolicyAgent(Account().from_key(user_private_key)) return user_account def _fund_user_account( web3: Web3, account_key_config: AccountKeyConfig, - user_account: HyperdriveAgent, + user_account: HyperdrivePolicyAgent, base_token_contract: ERC20MintableContract, ) -> tuple[RPCResponse, TxReceipt]: """Fund a user account. @@ -81,7 +81,7 @@ def _fund_user_account( account_key_config: AccountKeyConfig Configuration linking to the env file for storing private keys and initial budgets. Defines the agents to be funded. - user_account: HyperdriveAgent + user_account: HyperdrivePolicyAgent Object containing a wallet address and Agent for determining trades base_token_contract: ERC20MintableContract The deployed ERC20 base token contract. diff --git a/src/agent0/core/hyperdrive/utilities/run_bots/execute_multi_agent_trades.py b/src/agent0/core/hyperdrive/utilities/run_bots/execute_multi_agent_trades.py index 6a61216149..14f2155640 100644 --- a/src/agent0/core/hyperdrive/utilities/run_bots/execute_multi_agent_trades.py +++ b/src/agent0/core/hyperdrive/utilities/run_bots/execute_multi_agent_trades.py @@ -31,12 +31,12 @@ from agent0.ethpy.hyperdrive import HyperdriveReadWriteInterface, ReceiptBreakdown if TYPE_CHECKING: - from agent0.core.hyperdrive import HyperdriveAgent + from agent0.core.hyperdrive import HyperdrivePolicyAgent async def async_execute_multi_agent_trades( interface: HyperdriveReadWriteInterface, - agents: list[HyperdriveAgent], + agents: list[HyperdrivePolicyAgent], liquidate: bool, randomize_liquidation: bool = False, interactive_mode: bool = False, @@ -50,8 +50,8 @@ async def async_execute_multi_agent_trades( --------- interface: HyperdriveReadWriteInterface The Hyperdrive API interface object. - agents: list[HyperdriveAgent] - A list of HyperdriveAgent that are conducting the trades. + agents: list[HyperdrivePolicyAgent] + A list of HyperdrivePolicyAgent that are conducting the trades. liquidate: bool If set, will ignore all policy settings and liquidate all open positions. randomize_liquidation: bool @@ -92,7 +92,7 @@ async def async_execute_multi_agent_trades( async def _async_execute_single_agent_trade( - agent: HyperdriveAgent, + agent: HyperdrivePolicyAgent, interface: HyperdriveReadWriteInterface, liquidate: bool, randomize_liquidation: bool, @@ -107,8 +107,8 @@ async def _async_execute_single_agent_trade( Arguments --------- - agent: HyperdriveAgent - The HyperdriveAgent that is conducting the trade + agent: HyperdrivePolicyAgent + The HyperdrivePolicyAgent that is conducting the trade interface: HyperdriveReadWriteInterface The Hyperdrive API interface object liquidate: bool @@ -205,7 +205,7 @@ async def _async_execute_single_agent_trade( async def _async_match_contract_call_to_trade( - agent: HyperdriveAgent, + agent: HyperdrivePolicyAgent, interface: HyperdriveReadWriteInterface, trade_envelope: Trade[HyperdriveMarketAction], nonce: Nonce, @@ -217,7 +217,7 @@ async def _async_match_contract_call_to_trade( Arguments --------- - agent: HyperdriveAgent + agent: HyperdrivePolicyAgent Object containing a wallet address and Agent for determining trades. interface: HyperdriveReadWriteInterface The Hyperdrive API interface object. diff --git a/src/agent0/core/hyperdrive/utilities/run_bots/fund_agents.py b/src/agent0/core/hyperdrive/utilities/run_bots/fund_agents.py index b56df3d021..27d55848ab 100644 --- a/src/agent0/core/hyperdrive/utilities/run_bots/fund_agents.py +++ b/src/agent0/core/hyperdrive/utilities/run_bots/fund_agents.py @@ -10,7 +10,7 @@ from agent0.core import AccountKeyConfig from agent0.core.base.make_key import make_private_key -from agent0.core.hyperdrive import HyperdriveAgent +from agent0.core.hyperdrive import HyperdrivePolicyAgent from agent0.ethpy.base import ( async_eth_transfer, async_smart_contract_transact, @@ -41,7 +41,7 @@ def async_fund_agents_with_fake_user( """ # Generate fake user account user_private_key = make_private_key(extra_entropy="FAKE USER") # argument value can be any str - user_account = HyperdriveAgent(Account().from_key(user_private_key)) + user_account = HyperdrivePolicyAgent(Account().from_key(user_private_key)) # Fund the user with Eth eth_balance = sum((int(budget) for budget in account_key_config.AGENT_ETH_BUDGETS)) * 2 # double for good measure _ = set_anvil_account_balance(interface.web3, user_account.address, eth_balance) @@ -60,7 +60,7 @@ def async_fund_agents_with_fake_user( async def async_fund_agents( interface: HyperdriveReadInterface, - user_account: HyperdriveAgent, + user_account: HyperdrivePolicyAgent, account_key_config: AccountKeyConfig, ) -> None: """Fund agents using passed in configs. @@ -69,8 +69,8 @@ async def async_fund_agents( --------- interface: HyperdriveReadInterface An Hyperdrive interface object for accessing the base token contract. - user_account: HyperdriveAgent - The HyperdriveAgent corresponding to the user account to fund the agents. + user_account: HyperdrivePolicyAgent + The HyperdrivePolicyAgent corresponding to the user account to fund the agents. account_key_config: AccountKeyConfig Configuration linking to the env file for storing private keys and initial budgets. Defines the agents to be funded. @@ -85,7 +85,8 @@ async def async_fund_agents( # Prepare accounts and eth budgets # Sanity check for zip function agent_accounts = [ - HyperdriveAgent(Account().from_key(agent_private_key)) for agent_private_key in account_key_config.AGENT_KEYS + HyperdrivePolicyAgent(Account().from_key(agent_private_key)) + for agent_private_key in account_key_config.AGENT_KEYS ] accounts_left = list(zip(agent_accounts, account_key_config.AGENT_ETH_BUDGETS)) for attempt in range(FUND_RETRY_COUNT): @@ -180,7 +181,7 @@ async def async_fund_agents( def _check_user_balances( interface: HyperdriveReadInterface, - user_account: HyperdriveAgent, + user_account: HyperdrivePolicyAgent, account_key_config: AccountKeyConfig, ) -> None: """Check the user eth and base balances to ensure there is enough for funding agents. @@ -189,8 +190,8 @@ def _check_user_balances( --------- interface: HyperdriveReadInterface An Hyperdrive interface object for accessing the base token contract. - user_account: HyperdriveAgent - The HyperdriveAgent corresponding to the user account to fund the agents. + user_account: HyperdrivePolicyAgent + The HyperdrivePolicyAgent corresponding to the user account to fund the agents. account_key_config: AccountKeyConfig Configuration linking to the env file for storing private keys and initial budgets. Defines the agents to be funded. diff --git a/src/agent0/core/hyperdrive/utilities/run_bots/get_agent_accounts.py b/src/agent0/core/hyperdrive/utilities/run_bots/get_agent_accounts.py index 820a6dcec8..8f58d28382 100644 --- a/src/agent0/core/hyperdrive/utilities/run_bots/get_agent_accounts.py +++ b/src/agent0/core/hyperdrive/utilities/run_bots/get_agent_accounts.py @@ -13,7 +13,7 @@ from agent0.core import AccountKeyConfig from agent0.core.base.config import AgentConfig -from agent0.core.hyperdrive import HyperdriveAgent +from agent0.core.hyperdrive import HyperdrivePolicyAgent from agent0.ethpy.base import async_smart_contract_transact, get_account_balance from agent0.ethpy.hyperdrive import HyperdriveReadInterface @@ -25,7 +25,7 @@ def get_agent_accounts( agent_config: list[AgentConfig], account_key_config: AccountKeyConfig, global_rng: Generator, -) -> list[HyperdriveAgent]: +) -> list[HyperdrivePolicyAgent]: """Get agents according to provided config, provide eth, base token and approve hyperdrive. Arguments @@ -46,7 +46,7 @@ def get_agent_accounts( """ # TODO: raise issue on failure by looking at `rpc_response`, `tx_receipt` returned from function # Do this for `set_anvil_account_balance`, `smart_contract_transact(mint)`, `smart_contract_transact(approve)` - agents: list[HyperdriveAgent] = [] + agents: list[HyperdrivePolicyAgent] = [] num_agents_so_far: list[int] = [] # maintains the total number of agents for each agent type agent_base_budgets = [int(budget) for budget in account_key_config.AGENT_BASE_BUDGETS] @@ -66,7 +66,7 @@ def get_agent_accounts( if agent_info.policy_config.rng_seed is None and agent_info.policy_config.rng is None: agent_info.policy_config.rng = global_rng.spawn(1)[0] - eth_agent = HyperdriveAgent( + eth_agent = HyperdrivePolicyAgent( Account().from_key(account_key_config.AGENT_KEYS[agent_count]), initial_budget=agent_budget, policy=agent_info.policy(agent_info.policy_config), @@ -86,12 +86,12 @@ def get_agent_accounts( return agents -async def _set_max_approval(agents: list[HyperdriveAgent], interface: HyperdriveReadInterface) -> None: +async def _set_max_approval(agents: list[HyperdrivePolicyAgent], interface: HyperdriveReadInterface) -> None: """Establish max approval for the hyperdrive contract for all agents async Arguments --------- - agents: list[HyperdriveAgent] + agents: list[HyperdrivePolicyAgent] List of agents """ agents_left = list(agents) diff --git a/src/agent0/core/hyperdrive/utilities/run_bots/run_agents.py b/src/agent0/core/hyperdrive/utilities/run_bots/run_agents.py index dbde397dfd..13b377adc9 100644 --- a/src/agent0/core/hyperdrive/utilities/run_bots/run_agents.py +++ b/src/agent0/core/hyperdrive/utilities/run_bots/run_agents.py @@ -25,7 +25,7 @@ if TYPE_CHECKING: from agent0.core import AccountKeyConfig from agent0.core.base.config import AgentConfig, EnvironmentConfig - from agent0.core.hyperdrive import HyperdriveAgent + from agent0.core.hyperdrive import HyperdrivePolicyAgent from agent0.ethpy import EthConfig START_LATENCY = 1 @@ -108,7 +108,7 @@ def _setup_agents( hyperdrive_address: ChecksumAddress | None = None, load_wallet_state: bool = True, liquidate: bool = False, -) -> tuple[HyperdriveReadWriteInterface, list[HyperdriveAgent], EthConfig, ChecksumAddress]: +) -> tuple[HyperdriveReadWriteInterface, list[HyperdrivePolicyAgent], EthConfig, ChecksumAddress]: """Entrypoint to setup agents for automated trading. .. note:: @@ -137,10 +137,10 @@ def _setup_agents( Returns ------- - tuple[HyperdriveReadWriteInterface, list[HyperdriveAgent], EthConfig, ChecksumAddress] + tuple[HyperdriveReadWriteInterface, list[HyperdrivePolicyAgent], EthConfig, ChecksumAddress] A tuple containing: - The Hyperdrive interface API object - - A list of HyperdriveAgent objects that contain a wallet address and Agent for determining trades + - A list of HyperdrivePolicyAgent objects that contain a wallet address and Agent for determining trades - The eth_config with defaults assigned. - The contract_addresses with defaults assigned. """ @@ -216,7 +216,7 @@ def _run_agents( environment_config: EnvironmentConfig, account_key_config: AccountKeyConfig, interface: HyperdriveReadWriteInterface, - agent_accounts: list[HyperdriveAgent], + agent_accounts: list[HyperdrivePolicyAgent], liquidate: bool = False, minimum_avg_agent_base: FixedPoint | None = None, ): @@ -233,8 +233,8 @@ def _run_agents( Dataclass containing configuration options for the agent account, including keys and budgets. interface: HyperdriveReadWriteInterface An interface for Hyperdrive with contracts deployed on any chain with an RPC url. - agent_accounts: list[HyperdriveAgent] - A list of HyperdriveAgent that are conducting the trades + agent_accounts: list[HyperdrivePolicyAgent] + A list of HyperdrivePolicyAgent that are conducting the trades liquidate: bool, optional If set, will ignore all policy settings and liquidate all open positions. Defaults to False. diff --git a/src/agent0/core/hyperdrive/utilities/run_bots/setup_experiment.py b/src/agent0/core/hyperdrive/utilities/run_bots/setup_experiment.py index 8a5f5d8acf..c774a5c6d1 100644 --- a/src/agent0/core/hyperdrive/utilities/run_bots/setup_experiment.py +++ b/src/agent0/core/hyperdrive/utilities/run_bots/setup_experiment.py @@ -16,7 +16,7 @@ from agent0.core import AccountKeyConfig from agent0.core.base.config import AgentConfig, EnvironmentConfig -from agent0.core.hyperdrive import HyperdriveAgent +from agent0.core.hyperdrive import HyperdrivePolicyAgent from agent0.core.hyperdrive.crash_report import setup_hyperdrive_crash_report_logging from agent0.ethpy.base import async_smart_contract_transact, get_account_balance from agent0.ethpy.hyperdrive import HyperdriveReadInterface @@ -32,7 +32,7 @@ def setup_experiment( agent_config: list[AgentConfig], account_key_config: AccountKeyConfig, interface: HyperdriveReadInterface, -) -> list[HyperdriveAgent]: +) -> list[HyperdrivePolicyAgent]: """Get agents according to provided config, provide eth, base token and approve hyperdrive. .. note:: @@ -51,8 +51,8 @@ def setup_experiment( Returns ------- - list[HyperdriveAgent] - A list of HyperdriveAgent objects that contain a wallet address and Agent for determining trades + list[HyperdrivePolicyAgent] + A list of HyperdrivePolicyAgent objects that contain a wallet address and Agent for determining trades """ # this is the global rng object that generates child rng objects for each agent # random number generator should be used everywhere so that the experiment is repeatable @@ -88,7 +88,7 @@ def _get_agent_accounts( base_token_contract: Contract, hyperdrive_address: str, global_rng: Generator, -) -> list[HyperdriveAgent]: +) -> list[HyperdrivePolicyAgent]: """Get agents according to provided config, provide eth, base token and approve hyperdrive. .. note:: @@ -116,7 +116,7 @@ def _get_agent_accounts( """ # TODO: raise issue on failure by looking at `rpc_response`, `tx_receipt` returned from function # Do this for `set_anvil_account_balance`, `smart_contract_transact(mint)`, `smart_contract_transact(approve)` - agents: list[HyperdriveAgent] = [] + agents: list[HyperdrivePolicyAgent] = [] num_agents_so_far: list[int] = [] # maintains the total number of agents for each agent type agent_base_budgets = [int(budget) for budget in account_key_config.AGENT_BASE_BUDGETS] @@ -136,7 +136,7 @@ def _get_agent_accounts( if agent_info.policy_config.rng_seed is None and agent_info.policy_config.rng is None: agent_info.policy_config.rng = global_rng.spawn(1)[0] - eth_agent = HyperdriveAgent( + eth_agent = HyperdrivePolicyAgent( Account().from_key(account_key_config.AGENT_KEYS[agent_count]), initial_budget=agent_budget, policy=agent_info.policy(agent_info.policy_config), @@ -157,7 +157,7 @@ def _get_agent_accounts( async def _set_max_approval( - agents: list[HyperdriveAgent], web3: Web3, base_token_contract: Contract, hyperdrive_address: str + agents: list[HyperdrivePolicyAgent], web3: Web3, base_token_contract: Contract, hyperdrive_address: str ) -> None: """Establish max approval for the hyperdrive contract for all agents async @@ -166,7 +166,7 @@ async def _set_max_approval( Arguments --------- - agents: list[HyperdriveAgent] + agents: list[HyperdrivePolicyAgent] List of agents web3: Web3 web3 provider object diff --git a/src/agent0/core/hyperdrive/utilities/run_bots/trade_loop.py b/src/agent0/core/hyperdrive/utilities/run_bots/trade_loop.py index 63689d9d7a..a2a8f5279c 100644 --- a/src/agent0/core/hyperdrive/utilities/run_bots/trade_loop.py +++ b/src/agent0/core/hyperdrive/utilities/run_bots/trade_loop.py @@ -6,7 +6,7 @@ import logging from datetime import datetime -from agent0.core.hyperdrive import HyperdriveAgent, TradeResult, TradeStatus +from agent0.core.hyperdrive import HyperdrivePolicyAgent, TradeResult, TradeStatus from agent0.core.hyperdrive.crash_report import get_anvil_state_dump, log_hyperdrive_crash_report from agent0.core.hyperdrive.interactive.exec import check_for_new_block from agent0.core.test_utils import assert_never @@ -19,7 +19,7 @@ # pylint: disable=too-many-arguments def trade_if_new_block( interface: HyperdriveReadWriteInterface, - agent_accounts: list[HyperdriveAgent], + agent_accounts: list[HyperdrivePolicyAgent], halt_on_errors: bool, halt_on_slippage: bool, crash_report_to_file: bool, @@ -38,8 +38,8 @@ def trade_if_new_block( --------- interface: HyperdriveReadWriteInterface The Hyperdrive API interface object. - agent_accounts: list[HyperdriveAgent]] - A list of HyperdriveAgent objects that contain a wallet address and Agent for determining trades. + agent_accounts: list[HyperdrivePolicyAgent]] + A list of HyperdrivePolicyAgent objects that contain a wallet address and Agent for determining trades. halt_on_errors: bool If true, raise an exception if a trade reverts. Otherwise, log a warning and move on. diff --git a/src/agent0/core/test_fixtures/chain.py b/src/agent0/core/test_fixtures/chain.py index 472dd648f3..0fc0e04a8c 100644 --- a/src/agent0/core/test_fixtures/chain.py +++ b/src/agent0/core/test_fixtures/chain.py @@ -9,11 +9,11 @@ import pytest from docker.errors import DockerException -from agent0.core.hyperdrive.interactive import ILocalChain +from agent0.core.hyperdrive.interactive import LocalChain @pytest.fixture -def chain() -> Iterator[ILocalChain]: +def chain() -> Iterator[LocalChain]: """Local chain connected to a local database hosted in docker. Yield @@ -44,7 +44,7 @@ def chain() -> Iterator[ILocalChain]: else: raise exc - local_chain_config = ILocalChain.Config() - _chain = ILocalChain(local_chain_config) + local_chain_config = LocalChain.Config() + _chain = LocalChain(local_chain_config) yield _chain _chain.cleanup() diff --git a/src/agent0/ethpy/base/transactions_test.py b/src/agent0/ethpy/base/transactions_test.py index bf1c008d31..9e2e314bf2 100644 --- a/src/agent0/ethpy/base/transactions_test.py +++ b/src/agent0/ethpy/base/transactions_test.py @@ -3,18 +3,18 @@ import pytest from fixedpointmath import FixedPoint -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.core.hyperdrive.policies import PolicyZoo from agent0.ethpy.base.transactions import build_transaction @pytest.mark.anvil -def test_gas_price_base_multiple_explicit(chain: ILocalChain): +def test_gas_price_base_multiple_explicit(chain: LocalChain): """Set the gas price base multiple explicitly.""" # set up config, hyperdrive, interface, web3, and agent base_fee_multiple = 100 - config = ILocalHyperdrive.Config() - hyperdrive = ILocalHyperdrive(chain, config) + config = LocalHyperdrive.Config() + hyperdrive = LocalHyperdrive(chain, config) interface = hyperdrive.interface web3 = interface.web3 agent = hyperdrive.init_agent(eth=FixedPoint(1)) @@ -52,12 +52,12 @@ def test_gas_price_base_multiple_explicit(chain: ILocalChain): @pytest.mark.anvil -def test_gas_price_priority_multiple_explicit(chain: ILocalChain): +def test_gas_price_priority_multiple_explicit(chain: LocalChain): """Set the gas price priority multiple explicitly.""" # set up config, hyperdrive, interface, web3, and agent priority_fee_multiple = 100 - config = ILocalHyperdrive.Config() - hyperdrive = ILocalHyperdrive(chain, config) + config = LocalHyperdrive.Config() + hyperdrive = LocalHyperdrive(chain, config) interface = hyperdrive.interface web3 = interface.web3 agent = hyperdrive.init_agent(eth=FixedPoint(1)) @@ -89,12 +89,12 @@ def test_gas_price_priority_multiple_explicit(chain: ILocalChain): @pytest.mark.anvil -def test_gas_price_base_multiple_policy(chain: ILocalChain): +def test_gas_price_base_multiple_policy(chain: LocalChain): """Set the gas price base multiple through an agent policy.""" # set up config, hyperdrive, interface, web3, and agent base_fee_multiple = 100 - config = ILocalHyperdrive.Config() - hyperdrive = ILocalHyperdrive(chain, config) + config = LocalHyperdrive.Config() + hyperdrive = LocalHyperdrive(chain, config) interface = hyperdrive.interface regular_agent = hyperdrive.init_agent( @@ -116,12 +116,12 @@ def test_gas_price_base_multiple_policy(chain: ILocalChain): @pytest.mark.anvil -def test_gas_price_priority_multiple_policy(chain: ILocalChain): +def test_gas_price_priority_multiple_policy(chain: LocalChain): """Set the gas price priority multiple through an agent policy.""" # set up config, hyperdrive, interface, web3, and agent priority_fee_multiple = 100 - config = ILocalHyperdrive.Config() - hyperdrive = ILocalHyperdrive(chain, config) + config = LocalHyperdrive.Config() + hyperdrive = LocalHyperdrive(chain, config) interface = hyperdrive.interface regular_agent = hyperdrive.init_agent( diff --git a/src/agent0/hyperfuzz/system_fuzz/run_fuzz_bots.py b/src/agent0/hyperfuzz/system_fuzz/run_fuzz_bots.py index 2e29646f83..5f84d5319e 100644 --- a/src/agent0/hyperfuzz/system_fuzz/run_fuzz_bots.py +++ b/src/agent0/hyperfuzz/system_fuzz/run_fuzz_bots.py @@ -9,9 +9,9 @@ from fixedpointmath import FixedPoint from numpy.random._generator import Generator -from agent0 import IHyperdrive, ILocalChain, ILocalHyperdrive, PolicyZoo +from agent0 import Hyperdrive, LocalChain, LocalHyperdrive, PolicyZoo from agent0.core.base.make_key import make_private_key -from agent0.core.hyperdrive.interactive.i_hyperdrive_agent import IHyperdriveAgent +from agent0.core.hyperdrive.interactive.hyperdrive_agent import HyperdriveAgent from agent0.hyperfuzz.system_fuzz.invariant_checks import run_invariant_checks ONE_HOUR_IN_SECONDS = 60 * 60 @@ -41,7 +41,7 @@ FEE_RANGE: tuple[float, float] = (0.0001, 0.2) -def generate_fuzz_hyperdrive_config(rng: Generator, log_to_rollbar: bool, rng_seed: int) -> ILocalHyperdrive.Config: +def generate_fuzz_hyperdrive_config(rng: Generator, log_to_rollbar: bool, rng_seed: int) -> LocalHyperdrive.Config: """Fuzz over hyperdrive config. Arguments @@ -55,7 +55,7 @@ def generate_fuzz_hyperdrive_config(rng: Generator, log_to_rollbar: bool, rng_se Returns ------- - ILocalHyperdrive.Config + LocalHyperdrive.Config Fuzzed hyperdrive config. """ # Position duration must be a multiple of checkpoint duration @@ -83,7 +83,7 @@ def generate_fuzz_hyperdrive_config(rng: Generator, log_to_rollbar: bool, rng_se # Generate flat fee in terms of APR flat_fee = FixedPoint(rng.uniform(*FEE_RANGE) * (position_duration / ONE_YEAR_IN_SECONDS)) - return ILocalHyperdrive.Config( + return LocalHyperdrive.Config( preview_before_trade=True, rng=rng, log_to_rollbar=log_to_rollbar, @@ -161,7 +161,7 @@ async def _async_runner( def run_fuzz_bots( - hyperdrive_pool: IHyperdrive, + hyperdrive_pool: Hyperdrive, check_invariance: bool, num_random_agents: int | None = None, num_random_hold_agents: int | None = None, @@ -182,7 +182,7 @@ def run_fuzz_bots( Arguments --------- - hyperdrive_pool: IHyperdrive + hyperdrive_pool: Hyperdrive The hyperdrive pool to run the bots on. check_invariance: bool If True, will run invariance checks after each set of trades. @@ -239,10 +239,10 @@ def run_fuzz_bots( minimum_avg_agent_base = base_budget_per_bot / FixedPoint(10) # Initialize agents - agents: list[IHyperdriveAgent] = [] + agents: list[HyperdriveAgent] = [] for _ in range(num_random_agents): # Initialize & fund agent using a random private key - agent: IHyperdriveAgent = hyperdrive_pool.init_agent( + agent: HyperdriveAgent = hyperdrive_pool.init_agent( private_key=make_private_key(), policy=PolicyZoo.random, policy_config=PolicyZoo.random.Config( @@ -255,7 +255,7 @@ def run_fuzz_bots( agents.append(agent) for _ in range(num_random_hold_agents): - agent: IHyperdriveAgent = hyperdrive_pool.init_agent( + agent: HyperdriveAgent = hyperdrive_pool.init_agent( private_key=make_private_key(), policy=PolicyZoo.random_hold, policy_config=PolicyZoo.random_hold.Config( @@ -354,8 +354,8 @@ def run_fuzz_bots( if random_advance_time: # We only allow random advance time if the chain connected to the pool is a - # ILocalChain object - if isinstance(hyperdrive_pool.chain, ILocalChain): + # LocalChain object + if isinstance(hyperdrive_pool.chain, LocalChain): # RNG should always exist, config's post_init should always # initialize an rng object assert hyperdrive_pool.config.rng is not None @@ -363,14 +363,14 @@ def run_fuzz_bots( random_time = int(hyperdrive_pool.config.rng.integers(*ADVANCE_TIME_SECONDS_RANGE)) hyperdrive_pool.chain.advance_time(random_time, create_checkpoints=True) else: - raise ValueError("Random advance time only allowed for pools deployed on ILocalChain") + raise ValueError("Random advance time only allowed for pools deployed on LocalChain") if random_variable_rate: - if isinstance(hyperdrive_pool, ILocalHyperdrive): + if isinstance(hyperdrive_pool, LocalHyperdrive): # RNG should always exist, config's post_init should always # initialize an rng object assert hyperdrive_pool.config.rng is not None random_rate = FixedPoint(hyperdrive_pool.config.rng.uniform(*VARIABLE_RATE_RANGE)) hyperdrive_pool.set_variable_rate(random_rate) else: - raise ValueError("Random variable rate only allowed for ILocalHyperdrive pools") + raise ValueError("Random variable rate only allowed for LocalHyperdrive pools") diff --git a/src/agent0/hyperfuzz/unit_fuzz/fuzz_long_short_maturity_values.py b/src/agent0/hyperfuzz/unit_fuzz/fuzz_long_short_maturity_values.py index 833260a7bc..4c4697794f 100644 --- a/src/agent0/hyperfuzz/unit_fuzz/fuzz_long_short_maturity_values.py +++ b/src/agent0/hyperfuzz/unit_fuzz/fuzz_long_short_maturity_values.py @@ -28,7 +28,7 @@ from fixedpointmath import FixedPoint, isclose from agent0.core.hyperdrive.crash_report import build_crash_trade_result, log_hyperdrive_crash_report -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.core.hyperdrive.interactive.event_types import CloseLong, CloseShort, OpenLong, OpenShort from agent0.hyperfuzz import FuzzAssertionException from agent0.hypertypes.fixedpoint_types import CheckpointFP @@ -56,7 +56,7 @@ def fuzz_long_short_maturity_values( num_trades: int, long_maturity_vals_epsilon: float, short_maturity_vals_epsilon: float, - chain_config: ILocalChain.Config | None = None, + chain_config: LocalChain.Config | None = None, log_to_stdout: bool = False, ): """Does fuzzy invariant checks on closing longs and shorts past maturity. @@ -194,7 +194,7 @@ class Args(NamedTuple): num_trades: int long_maturity_vals_epsilon: float short_maturity_vals_epsilon: float - chain_config: ILocalChain.Config + chain_config: LocalChain.Config log_to_stdout: bool @@ -216,7 +216,7 @@ def namespace_to_args(namespace: argparse.Namespace) -> Args: num_trades=namespace.num_trades, long_maturity_vals_epsilon=namespace.long_maturity_vals_epsilon, short_maturity_vals_epsilon=namespace.short_maturity_vals_epsilon, - chain_config=ILocalChain.Config(chain_port=namespace.chain_port), + chain_config=LocalChain.Config(chain_port=namespace.chain_port), log_to_stdout=namespace.log_to_stdout, ) @@ -279,7 +279,7 @@ def invariant_check( maturity_checkpoint: CheckpointFP, long_maturity_vals_epsilon: float, short_maturity_vals_epsilon: float, - interactive_hyperdrive: ILocalHyperdrive, + interactive_hyperdrive: LocalHyperdrive, ) -> None: """Check the pool state invariants and throws an assertion exception if fails. diff --git a/src/agent0/hyperfuzz/unit_fuzz/fuzz_path_independence.py b/src/agent0/hyperfuzz/unit_fuzz/fuzz_path_independence.py index 9ab4d47992..aa6a530fec 100644 --- a/src/agent0/hyperfuzz/unit_fuzz/fuzz_path_independence.py +++ b/src/agent0/hyperfuzz/unit_fuzz/fuzz_path_independence.py @@ -43,7 +43,7 @@ from fixedpointmath import FixedPoint, isclose from agent0.core.hyperdrive.crash_report import build_crash_trade_result, log_hyperdrive_crash_report -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.ethpy.base.errors import ContractCallException from agent0.hyperfuzz import FuzzAssertionException from agent0.hyperlogs import ExtendedJSONEncoder @@ -71,7 +71,7 @@ def fuzz_path_independence( lp_share_price_epsilon: float, effective_share_reserves_epsilon: float, present_value_epsilon: float, - chain_config: ILocalChain.Config, + chain_config: LocalChain.Config, log_to_stdout: bool = False, ): """Does fuzzy invariant checks for opening and closing longs and shorts. @@ -299,7 +299,7 @@ class Args(NamedTuple): lp_share_price_epsilon: float effective_share_reserves_epsilon: float present_value_epsilon: float - chain_config: ILocalChain.Config + chain_config: LocalChain.Config log_to_stdout: bool @@ -322,7 +322,7 @@ def namespace_to_args(namespace: argparse.Namespace) -> Args: lp_share_price_epsilon=namespace.lp_share_price_epsilon, effective_share_reserves_epsilon=namespace.effective_share_reserves_epsilon, present_value_epsilon=namespace.present_value_epsilon, - chain_config=ILocalChain.Config(chain_port=namespace.chain_port), + chain_config=LocalChain.Config(chain_port=namespace.chain_port), log_to_stdout=namespace.log_to_stdout, ) @@ -392,7 +392,7 @@ def parse_arguments(argv: Sequence[str] | None = None) -> Args: def invariant_check( check_data: dict[str, Any], check_epsilon: dict[str, Any], - interactive_hyperdrive: ILocalHyperdrive, + interactive_hyperdrive: LocalHyperdrive, ) -> None: """Check the pool state invariants and throws an assertion exception if fails. diff --git a/src/agent0/hyperfuzz/unit_fuzz/fuzz_present_value.py b/src/agent0/hyperfuzz/unit_fuzz/fuzz_present_value.py index a23c5a8e0e..8312f05bd3 100644 --- a/src/agent0/hyperfuzz/unit_fuzz/fuzz_present_value.py +++ b/src/agent0/hyperfuzz/unit_fuzz/fuzz_present_value.py @@ -29,7 +29,7 @@ from agent0.core.hyperdrive import HyperdriveActionType from agent0.core.hyperdrive.crash_report import build_crash_trade_result, log_hyperdrive_crash_report -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.hyperfuzz import FuzzAssertionException from .helpers import setup_fuzz @@ -54,7 +54,7 @@ def main(argv: Sequence[str] | None = None): def fuzz_present_value( test_epsilon: float, - chain_config: ILocalChain.Config, + chain_config: LocalChain.Config, log_to_stdout: bool = False, ): """Does fuzzy invariant checks for opening and closing longs and shorts. @@ -202,7 +202,7 @@ class Args(NamedTuple): """Command line arguments for the invariant checker.""" test_epsilon: float - chain_config: ILocalChain.Config + chain_config: LocalChain.Config log_to_stdout: bool @@ -221,7 +221,7 @@ def namespace_to_args(namespace: argparse.Namespace) -> Args: """ return Args( test_epsilon=namespace.test_epsilon, - chain_config=ILocalChain.Config(chain_port=namespace.chain_port), + chain_config=LocalChain.Config(chain_port=namespace.chain_port), log_to_stdout=namespace.log_to_stdout, ) @@ -267,7 +267,7 @@ def parse_arguments(argv: Sequence[str] | None = None) -> Args: def invariant_check( check_data: dict[str, Any], test_epsilon: float, - interactive_hyperdrive: ILocalHyperdrive, + interactive_hyperdrive: LocalHyperdrive, ) -> None: """Check the pool state invariants and throws an assertion exception if fails. diff --git a/src/agent0/hyperfuzz/unit_fuzz/fuzz_profit_check.py b/src/agent0/hyperfuzz/unit_fuzz/fuzz_profit_check.py index c0dd48b316..ccb572b7ed 100644 --- a/src/agent0/hyperfuzz/unit_fuzz/fuzz_profit_check.py +++ b/src/agent0/hyperfuzz/unit_fuzz/fuzz_profit_check.py @@ -33,7 +33,7 @@ from fixedpointmath import FixedPoint from agent0.core.hyperdrive.crash_report import build_crash_trade_result, log_hyperdrive_crash_report -from agent0.core.hyperdrive.interactive import ILocalChain +from agent0.core.hyperdrive.interactive import LocalChain from agent0.hyperfuzz import FuzzAssertionException from .helpers import advance_time_after_checkpoint, advance_time_before_checkpoint, setup_fuzz @@ -53,7 +53,7 @@ def main(argv: Sequence[str] | None = None): fuzz_profit_check(*parsed_args) -def fuzz_profit_check(chain_config: ILocalChain.Config | None = None, log_to_stdout: bool = False): +def fuzz_profit_check(chain_config: LocalChain.Config | None = None, log_to_stdout: bool = False): """Fuzzes invariant checks for profit from long and short positions. Parameters @@ -223,7 +223,7 @@ def fuzz_profit_check(chain_config: ILocalChain.Config | None = None, log_to_std class Args(NamedTuple): """Command line arguments for the invariant checker.""" - chain_config: ILocalChain.Config + chain_config: LocalChain.Config log_to_stdout: bool @@ -241,7 +241,7 @@ def namespace_to_args(namespace: argparse.Namespace) -> Args: Formatted arguments """ return Args( - chain_config=ILocalChain.Config(chain_port=namespace.chain_port), + chain_config=LocalChain.Config(chain_port=namespace.chain_port), log_to_stdout=namespace.log_to_stdout, ) diff --git a/src/agent0/hyperfuzz/unit_fuzz/helpers/advance_time.py b/src/agent0/hyperfuzz/unit_fuzz/helpers/advance_time.py index dce39c7cfe..70368860a4 100644 --- a/src/agent0/hyperfuzz/unit_fuzz/helpers/advance_time.py +++ b/src/agent0/hyperfuzz/unit_fuzz/helpers/advance_time.py @@ -2,12 +2,10 @@ from numpy.random._generator import Generator -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive -def advance_time_before_checkpoint( - chain: ILocalChain, rng: Generator, interactive_hyperdrive: ILocalHyperdrive -) -> None: +def advance_time_before_checkpoint(chain: LocalChain, rng: Generator, interactive_hyperdrive: LocalHyperdrive) -> None: """Advance time on the chain a random amount that is less than the next checkpoint time. Arguments @@ -41,7 +39,7 @@ def advance_time_before_checkpoint( assert len(checkpoint_info[interactive_hyperdrive]) == 0, "Checkpoint was created when it should not have been." -def advance_time_after_checkpoint(chain: ILocalChain, interactive_hyperdrive: ILocalHyperdrive) -> None: +def advance_time_after_checkpoint(chain: LocalChain, interactive_hyperdrive: LocalHyperdrive) -> None: """Advance time on the chain to the next checkpoint boundary plus some buffer. Arguments diff --git a/src/agent0/hyperfuzz/unit_fuzz/helpers/close_random_trades.py b/src/agent0/hyperfuzz/unit_fuzz/helpers/close_random_trades.py index 09e1e31e8f..750aa8c46b 100644 --- a/src/agent0/hyperfuzz/unit_fuzz/helpers/close_random_trades.py +++ b/src/agent0/hyperfuzz/unit_fuzz/helpers/close_random_trades.py @@ -5,13 +5,13 @@ from numpy.random._generator import Generator from agent0.core.hyperdrive.interactive.event_types import OpenLong, OpenShort -from agent0.core.hyperdrive.interactive.i_local_hyperdrive_agent import ILocalHyperdriveAgent +from agent0.core.hyperdrive.interactive.local_hyperdrive_agent import LocalHyperdriveAgent def permute_trade_events( - trade_events: list[tuple[ILocalHyperdriveAgent, OpenLong | OpenShort]], + trade_events: list[tuple[LocalHyperdriveAgent, OpenLong | OpenShort]], rng: Generator, -) -> list[tuple[ILocalHyperdriveAgent, OpenLong | OpenShort]]: +) -> list[tuple[LocalHyperdriveAgent, OpenLong | OpenShort]]: """Given a list of trade events, returns the list in random order. Arguments @@ -33,7 +33,7 @@ def permute_trade_events( def close_trades( - trade_events: list[tuple[ILocalHyperdriveAgent, OpenLong | OpenShort]], + trade_events: list[tuple[LocalHyperdriveAgent, OpenLong | OpenShort]], ) -> None: """Close trades provided. diff --git a/src/agent0/hyperfuzz/unit_fuzz/helpers/execute_random_trades.py b/src/agent0/hyperfuzz/unit_fuzz/helpers/execute_random_trades.py index 4945392afe..15219d1815 100644 --- a/src/agent0/hyperfuzz/unit_fuzz/helpers/execute_random_trades.py +++ b/src/agent0/hyperfuzz/unit_fuzz/helpers/execute_random_trades.py @@ -9,18 +9,18 @@ from numpy.random._generator import Generator from agent0.core.hyperdrive import HyperdriveActionType -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.core.hyperdrive.interactive.event_types import OpenLong, OpenShort -from agent0.core.hyperdrive.interactive.i_local_hyperdrive_agent import ILocalHyperdriveAgent +from agent0.core.hyperdrive.interactive.local_hyperdrive_agent import LocalHyperdriveAgent def execute_random_trades( num_trades: int, - chain: ILocalChain, + chain: LocalChain, rng: Generator, - interactive_hyperdrive: ILocalHyperdrive, + interactive_hyperdrive: LocalHyperdrive, advance_time: bool = False, -) -> list[tuple[ILocalHyperdriveAgent, OpenLong | OpenShort]]: +) -> list[tuple[LocalHyperdriveAgent, OpenLong | OpenShort]]: """Conduct some trades specified by the trade list. If advance time is true, the sum of all time passed between all trades will be between 0 and the position duration. @@ -59,7 +59,7 @@ def execute_random_trades( # Generate a list of trades available_actions = np.array([HyperdriveActionType.OPEN_LONG, HyperdriveActionType.OPEN_SHORT]) # Do the trades - trade_events: list[tuple[ILocalHyperdriveAgent, OpenLong | OpenShort]] = [] + trade_events: list[tuple[LocalHyperdriveAgent, OpenLong | OpenShort]] = [] for trade_index, trade_type in enumerate([rng.choice(available_actions, size=1)[0] for _ in range(num_trades)]): trade_amount = _get_open_trade_amount(trade_type, rng, interactive_hyperdrive) # the short trade amount is technically bonds, but we know that will be less than the required base @@ -79,7 +79,7 @@ def execute_random_trades( def _get_open_trade_amount( trade_type: HyperdriveActionType, rng: Generator, - interactive_hyperdrive: ILocalHyperdrive, + interactive_hyperdrive: LocalHyperdrive, max_budget: FixedPoint = FixedPoint("1e9"), percent_max: FixedPoint = FixedPoint("0.75"), ) -> FixedPoint: @@ -122,18 +122,18 @@ def _get_open_trade_amount( @overload def _execute_trade( - trade_type: Literal[HyperdriveActionType.OPEN_LONG], trade_amount: FixedPoint, agent: ILocalHyperdriveAgent + trade_type: Literal[HyperdriveActionType.OPEN_LONG], trade_amount: FixedPoint, agent: LocalHyperdriveAgent ) -> OpenLong: ... @overload def _execute_trade( - trade_type: Literal[HyperdriveActionType.OPEN_SHORT], trade_amount: FixedPoint, agent: ILocalHyperdriveAgent + trade_type: Literal[HyperdriveActionType.OPEN_SHORT], trade_amount: FixedPoint, agent: LocalHyperdriveAgent ) -> OpenShort: ... def _execute_trade( - trade_type: HyperdriveActionType, trade_amount: FixedPoint, agent: ILocalHyperdriveAgent + trade_type: HyperdriveActionType, trade_amount: FixedPoint, agent: LocalHyperdriveAgent ) -> OpenLong | OpenShort: """Execute a trade given the type, amount, and agent. diff --git a/src/agent0/hyperfuzz/unit_fuzz/helpers/setup_fuzz.py b/src/agent0/hyperfuzz/unit_fuzz/helpers/setup_fuzz.py index 6c3dc587c9..75d5974f7d 100644 --- a/src/agent0/hyperfuzz/unit_fuzz/helpers/setup_fuzz.py +++ b/src/agent0/hyperfuzz/unit_fuzz/helpers/setup_fuzz.py @@ -8,13 +8,13 @@ from fixedpointmath import FixedPoint from numpy.random._generator import Generator -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.hyperlogs import setup_logging def setup_fuzz( log_filename: str, - chain_config: ILocalChain.Config | None = None, + chain_config: LocalChain.Config | None = None, log_to_stdout: bool = False, log_to_rollbar: bool = True, crash_log_level: int | None = None, @@ -24,7 +24,7 @@ def setup_fuzz( governance_lp_fee: FixedPoint | None = None, governance_zombie_fee: FixedPoint | None = None, var_interest: FixedPoint | None = None, -) -> tuple[ILocalChain, int, Generator, ILocalHyperdrive]: +) -> tuple[LocalChain, int, Generator, LocalHyperdrive]: """Setup the fuzz experiment. Arguments @@ -77,8 +77,8 @@ def setup_fuzz( ) # Setup local chain - config = chain_config if chain_config else ILocalChain.Config() - chain = ILocalChain(config=config) + config = chain_config if chain_config else LocalChain.Config() + chain = LocalChain(config=config) random_seed = np.random.randint( low=1, high=99999999 ) # No seed, we want this to be random every time it is executed @@ -94,7 +94,7 @@ def setup_fuzz( "fuzz_test_name": fuzz_test_name, } - initial_pool_config = ILocalHyperdrive.Config( + initial_pool_config = LocalHyperdrive.Config( preview_before_trade=True, checkpoint_duration=60 * 60 * 24, # 1 day # TODO calc_max_short doesn't work with a week position duration, setting to 30 days @@ -120,6 +120,6 @@ def setup_fuzz( if var_interest is not None: initial_pool_config.initial_variable_rate = var_interest - interactive_hyperdrive = ILocalHyperdrive(chain, initial_pool_config) + interactive_hyperdrive = LocalHyperdrive(chain, initial_pool_config) return chain, random_seed, rng, interactive_hyperdrive diff --git a/src/agent0/traiderdaive/gym_environments/full_hyperdrive_env.py b/src/agent0/traiderdaive/gym_environments/full_hyperdrive_env.py index df3c3794b7..51b42d9fe2 100644 --- a/src/agent0/traiderdaive/gym_environments/full_hyperdrive_env.py +++ b/src/agent0/traiderdaive/gym_environments/full_hyperdrive_env.py @@ -15,7 +15,7 @@ from gymnasium import spaces from scipy.special import expit -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.core.hyperdrive.policies import PolicyZoo # Global suppression of warnings, TODO fix @@ -79,12 +79,12 @@ def __init__( self.eval_mode = gym_config.eval_mode self.sample_actions = gym_config.sample_actions if self.eval_mode: - local_chain_config = ILocalChain.Config(block_timestamp_interval=12, db_port=5434, chain_port=10001) + local_chain_config = LocalChain.Config(block_timestamp_interval=12, db_port=5434, chain_port=10001) else: - local_chain_config = ILocalChain.Config(block_timestamp_interval=12, db_port=5435, chain_port=10002) - initial_pool_config = ILocalHyperdrive.Config() - self.chain = ILocalChain(local_chain_config) - self.interactive_hyperdrive = ILocalHyperdrive(self.chain, initial_pool_config) + local_chain_config = LocalChain.Config(block_timestamp_interval=12, db_port=5435, chain_port=10002) + initial_pool_config = LocalHyperdrive.Config() + self.chain = LocalChain(local_chain_config) + self.interactive_hyperdrive = LocalHyperdrive(self.chain, initial_pool_config) # TODO set seed self.rng = np.random.default_rng() diff --git a/src/agent0/traiderdaive/gym_environments/simple_hyperdrive_env.py b/src/agent0/traiderdaive/gym_environments/simple_hyperdrive_env.py index 57be71fc56..ea8e2e9249 100644 --- a/src/agent0/traiderdaive/gym_environments/simple_hyperdrive_env.py +++ b/src/agent0/traiderdaive/gym_environments/simple_hyperdrive_env.py @@ -12,7 +12,7 @@ from fixedpointmath import FixedPoint from gymnasium import spaces -from agent0.core.hyperdrive.interactive import ILocalChain, ILocalHyperdrive +from agent0.core.hyperdrive.interactive import LocalChain, LocalHyperdrive from agent0.core.hyperdrive.policies import PolicyZoo # Global suppression of warnings, TODO fix @@ -89,10 +89,10 @@ def __init__( ): """Initializes the environment""" # TODO parameterize these in the gym config - local_chain_config = ILocalChain.Config(block_timestamp_interval=3600) - self.chain = ILocalChain(local_chain_config) - initial_pool_config = ILocalHyperdrive.Config() - self.interactive_hyperdrive = ILocalHyperdrive(self.chain, initial_pool_config) + local_chain_config = LocalChain.Config(block_timestamp_interval=3600) + self.chain = LocalChain(local_chain_config) + initial_pool_config = LocalHyperdrive.Config() + self.interactive_hyperdrive = LocalHyperdrive(self.chain, initial_pool_config) # Define the rl bot self.rl_bot = self.interactive_hyperdrive.init_agent(base=gym_config.rl_agent_budget, name="rl_bot")