Skip to content

Commit

Permalink
Exposing gas limit to chain config and using the parameter for create…
Browse files Browse the repository at this point in the history
… checkpoint in advance time (#1498)
  • Loading branch information
Sheng Lundquist authored May 29, 2024
1 parent ad8623e commit d0dd965
Show file tree
Hide file tree
Showing 11 changed files with 62 additions and 23 deletions.
1 change: 1 addition & 0 deletions scripts/local_fuzz_bots.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def main(argv: Sequence[str] | None = None) -> None:
rng=rng,
crash_log_level=logging.CRITICAL,
crash_report_additional_info={"rng_seed": rng_seed},
gas_limit=int(1e6), # Plenty of gas limit for transactions
)

while True:
Expand Down
7 changes: 4 additions & 3 deletions scripts/run_unit_fuzz.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import argparse
import sys
import traceback
from typing import NamedTuple, Sequence

from agent0.core.hyperdrive.interactive import LocalChain
Expand Down Expand Up @@ -52,7 +53,7 @@ def main(argv: Sequence[str] | None = None):
# We catch other exceptions here, for some reason rollbar needs to be continuously running in order
# to log.
except Exception: # pylint: disable=broad-except
print("Unexpected error:", sys.exc_info()[0])
print("Unexpected error:\n", traceback.print_exc())

try:
print("Running path independence test")
Expand Down Expand Up @@ -89,7 +90,7 @@ def main(argv: Sequence[str] | None = None):
except FuzzAssertionException:
pass
except Exception: # pylint: disable=broad-except
print("Unexpected error:", sys.exc_info()[0])
print("Unexpected error:\n", traceback.print_exc())

try:
print("Running fuzz present value test")
Expand All @@ -104,7 +105,7 @@ def main(argv: Sequence[str] | None = None):
except FuzzAssertionException:
pass
except Exception: # pylint: disable=broad-except
print("Unexpected error:", sys.exc_info()[0])
print("Unexpected error:\n", traceback.print_exc())

num_checks += 1
if parsed_args.number_of_runs > 0 and num_checks >= parsed_args.number_of_runs:
Expand Down
2 changes: 2 additions & 0 deletions src/agent0/core/base/policies/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ class Config(Freezable):
"""The base fee multiple for transactions. Defaults to None."""
priority_fee_multiple: float | None = None
"""The priority fee multiple for transactions. Defaults to None."""
gas_limit: int | None = None
"""Maximum gas to spend per trade."""

def __init__(self, policy_config: Config):
"""Initialize the policy.
Expand Down
37 changes: 33 additions & 4 deletions src/agent0/core/hyperdrive/interactive/chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import atexit
import logging
import os
from dataclasses import dataclass
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, Type

Expand Down Expand Up @@ -106,6 +106,14 @@ class Config:
The experiment's stateful random number generator. Defaults to creating a generator from
the provided random seed if not set.
"""
gas_limit: int | None = None
"""
The maximum gas to use when executing transactions. This gas limit controls
any transactions that are executed on the chain.
NOTE: the policies `gas_limit` overwrites this value if it is set.
"""
# TODO we only use gas_limit currently for policy trades and `create_checkpoint` in advance time,
# need to propagate this to other trades

def __post_init__(self):
"""Create the random number generator if not set."""
Expand Down Expand Up @@ -297,6 +305,28 @@ def block_time(self) -> Timestamp:
# Agent functions
################

def _handle_policy_config(
self,
policy: Type[HyperdriveBasePolicy] | None = None,
policy_config: HyperdriveBasePolicy.Config | None = None,
) -> HyperdriveBasePolicy.Config | None:
if policy is None:
return None
return_policy_config = None
# Policy config might be frozen, we create a new one while setting these variables
if policy_config is not None:
policy_dict = asdict(policy_config)
# If the underlying policy's rng isn't set, we use the one from the chain object
if policy_config.rng is None and policy_config.rng_seed is None:
policy_dict["rng"] = self.config.rng
# If the underlying policy's `gas_limit` isn't set, we use the one from the chain object
if policy_config.gas_limit is None:
policy_dict["gas_limit"] = self.config.gas_limit
return_policy_config = policy.Config(**policy_dict)
else:
return_policy_config = policy.Config(rng=self.config.rng, gas_limit=self.config.gas_limit)
return return_policy_config

def init_agent(
self,
private_key: str,
Expand Down Expand Up @@ -330,9 +360,8 @@ def init_agent(
"""
# pylint: disable=too-many-arguments

# 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
policy_config = self._handle_policy_config(policy, policy_config)

out_agent = HyperdriveAgent(
name=name,
chain=self,
Expand Down
8 changes: 4 additions & 4 deletions src/agent0/core/hyperdrive/interactive/hyperdrive_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ def __init__(
self._active_policy: HyperdriveBasePolicy | None = None

if policy is not None:
if policy_config is None:
policy_config = policy.Config(rng=self.chain.config.rng)
# Policy config gets set in `init_agent` and `set_active_policy` if passed in
assert policy_config is not None
self._active_policy = policy(policy_config)

self.account: LocalAccount = Account().from_key(private_key)
Expand Down Expand Up @@ -234,8 +234,8 @@ def set_active(
self._active_pool = pool

if policy is not None:
if policy_config is None:
policy_config = policy.Config(rng=self.chain.config.rng)
policy_config = self.chain._handle_policy_config(policy, policy_config)
assert policy_config is not None
self._active_policy = policy(policy_config)

################
Expand Down
11 changes: 6 additions & 5 deletions src/agent0/core/hyperdrive/interactive/local_chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ def advance_time(
for pool in self._deployed_hyperdrive_pools:
# Create checkpoint handles making a checkpoint at the right time
checkpoint_event = pool._create_checkpoint( # pylint: disable=protected-access
check_if_exists=True,
check_if_exists=True, gas_limit=self.config.gas_limit
)
if checkpoint_event is not None:
out_dict[pool].append(checkpoint_event)
Expand All @@ -307,7 +307,9 @@ def advance_time(
time_before_checkpoints = self._web3.eth.get_block("latest").get("timestamp")
assert time_before_checkpoints is not None
for pool in self._deployed_hyperdrive_pools:
checkpoint_event = pool._create_checkpoint() # pylint: disable=protected-access
checkpoint_event = pool._create_checkpoint(
gas_limit=self.config.gas_limit
) # pylint: disable=protected-access
# These checkpoints should never fail
assert checkpoint_event is not None
# Add checkpoint event to the output
Expand Down Expand Up @@ -611,9 +613,7 @@ def init_agent(
if eth is None:
eth = FixedPoint(0)

# If the underlying policy's rng isn't set, we use the one from the chain object
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
policy_config = self._handle_policy_config(policy, policy_config)

out_agent = LocalHyperdriveAgent(
base=base,
Expand Down Expand Up @@ -749,3 +749,4 @@ def run_dashboard(self, blocking: bool = False) -> None:
input("Press any key to kill dashboard server.")
self.dashboard_subprocess.kill()
self.dashboard_subprocess = None
self.dashboard_subprocess = None
4 changes: 2 additions & 2 deletions src/agent0/core/hyperdrive/interactive/local_hyperdrive.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ def set_variable_rate(self, variable_rate: FixedPoint) -> None:
self._run_blocking_data_pipeline()

def _create_checkpoint(
self, checkpoint_time: int | None = None, check_if_exists: bool = True
self, checkpoint_time: int | None = None, check_if_exists: bool = True, gas_limit: int | None = None
) -> CreateCheckpoint | None:
"""Internal function without safeguard checks for creating a checkpoint.
Creating checkpoints is called by the chain's `advance_time`.
Expand All @@ -348,7 +348,7 @@ def _create_checkpoint(

try:
tx_receipt = self.interface.create_checkpoint(
self.chain.get_deployer_account(), checkpoint_time=checkpoint_time
self.chain.get_deployer_account(), checkpoint_time=checkpoint_time, gas_limit=gas_limit
)
except AssertionError as exc:
# Adding additional context to the "Transaction receipt has no logs" error
Expand Down
2 changes: 0 additions & 2 deletions src/agent0/core/hyperdrive/policies/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,6 @@ class Config(HyperdriveBasePolicy.Config):
"""The probability of this bot to make a trade on an action call."""
randomly_ignore_slippage_tolerance: bool = False
"""If we randomly ignore slippage tolerance."""
gas_limit: int | None = None
"""Maximum gas to spend per trade."""
allowable_actions: list[HyperdriveActionType] = field(
default_factory=lambda: [
HyperdriveActionType.OPEN_LONG,
Expand Down
2 changes: 2 additions & 0 deletions src/agent0/ethpy/hyperdrive/interface/_contract_calls.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ def _create_checkpoint(
sender: LocalAccount,
block_number: BlockNumber | None = None,
checkpoint_time: int | None = None,
gas_limit: int | None = None,
) -> ReceiptBreakdown:
"""See API for documentation."""
if checkpoint_time is None:
Expand All @@ -138,6 +139,7 @@ def _create_checkpoint(
read_retry_count=interface.read_retry_count,
write_retry_count=interface.write_retry_count,
timeout=interface.txn_receipt_timeout,
txn_options_gas=gas_limit,
)
trade_result = parse_logs(tx_receipt, interface.hyperdrive_contract, "createCheckpoint")
return trade_result
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ def get_read_interface(self) -> HyperdriveReadInterface:
)

def create_checkpoint(
self, sender: LocalAccount, block_number: BlockNumber | None = None, checkpoint_time: int | None = None
self,
sender: LocalAccount,
block_number: BlockNumber | None = None,
checkpoint_time: int | None = None,
gas_limit: int | None = None,
) -> ReceiptBreakdown:
"""Create a Hyperdrive checkpoint.
Expand All @@ -102,6 +106,8 @@ def create_checkpoint(
Defaults to the current block number.
checkpoint_time: int, optional
The checkpoint time to use. Defaults to the corresponding checkpoint for the provided block_number
gas_limit: int | None, optional
The maximum amount of gas used by the transaction.
Returns
-------
Expand All @@ -113,6 +119,7 @@ def create_checkpoint(
sender=sender,
block_number=block_number,
checkpoint_time=checkpoint_time,
gas_limit=gas_limit,
)

def set_variable_rate(self, sender: LocalAccount, new_rate: FixedPoint) -> None:
Expand Down
2 changes: 0 additions & 2 deletions src/agent0/hyperfuzz/system_fuzz/run_local_fuzz_bots.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,6 @@ def run_local_fuzz_bots(
slippage_tolerance=slippage_tolerance,
trade_chance=FixedPoint("0.8"),
randomly_ignore_slippage_tolerance=True,
gas_limit=int(1e6), # Plenty of gas limit for transactions
),
)
agents.append(agent)
Expand All @@ -295,7 +294,6 @@ def run_local_fuzz_bots(
trade_chance=FixedPoint("0.8"),
randomly_ignore_slippage_tolerance=True,
max_open_positions=2_000,
gas_limit=int(1e6), # Plenty of gas limit for transactions
),
)
agents.append(agent)
Expand Down

0 comments on commit d0dd965

Please sign in to comment.