Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bots/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ async def handle_mints(log):

# You can use generic `ContractContainer.EventType`s, to get matching logs from any contract
# NOTE: This will match based on `event_id := keccak(event.selector)`, so any matching will work
@bot.on_(Token.Approval, spender=ROUTER)
# NOTE: You can filter on logs from multiple addresses using `from_addresses=`
@bot.on_(Token.Approval, from_addresses=["YFI", "WBTC", "USDT"])
# Any handler function can be async too
async def exec_event2(log: ContractLog):
token = Token.at(log.contract_address)
Expand Down
4 changes: 2 additions & 2 deletions bots/latency-test.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@
from silverback import SilverbackBot

# NOTE: By default, assume this is a normal EOA (only 21k base gas required)
GAS_LIMIT = int(os.environ.get("GAS_LIMIT", 21_000))
MAX_EIP1559_BLOCK_DEPTH = int(os.environ.get("MAX_EIP1559_BLOCK_DEPTH", 3))
GAS_LIMIT = int(os.environ.get("GAS_LIMIT", "21000"))
MAX_EIP1559_BLOCK_DEPTH = int(os.environ.get("MAX_EIP1559_BLOCK_DEPTH", "3"))
PRIORITY_FEE = os.environ.get("PRIORITY_FEE", "0 gwei")

bot = SilverbackBot()
Expand Down
12 changes: 6 additions & 6 deletions docs/userguides/advanced.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ def update_last_hash(blk):
Here is a call sequence of how this function might get called in a reorg scenario:

```py
update_last_hash(blk1) # .hash: abc
update_last_hash(blk2) # .hash: def
update_last_hash(blk3) # .hash: ghi
update_last_hash(blk1) # .hash: abc
update_last_hash(blk2) # .hash: def
update_last_hash(blk3) # .hash: ghi
# Reorg happens! `blk2` (.hash: def) and onwards has changed
update_last_hash(blk2) # .hash: jkl, replaced .hash: def
update_last_hash(blk3) # .hash: mno, replaced .hash: ghi
update_last_hash(blk2) # .hash: jkl, replaced .hash: def
update_last_hash(blk3) # .hash: mno, replaced .hash: ghi
```

Our handling is safe because we just want whatever the last valid block's hash was.
Expand Down Expand Up @@ -131,6 +131,7 @@ def handle_on_worker_startup(state):
# Connect to DB, set initial state, etc
...


@bot.on_worker_shutdown()
def handle_on_worker_shutdown(state):
# cleanup resources, close connections cleanly, etc
Expand Down Expand Up @@ -171,7 +172,6 @@ async def store_token(log, context: Annotated[Context, TaskiqDepends()]):
@bot.on_worker_shutdown()
async def handle_on_worker_shutdown(state):
await state.db.__aexit__()

```

```{important}
Expand Down
25 changes: 11 additions & 14 deletions docs/userguides/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ bot = SilverbackBot()


@bot.on_(chain.blocks)
def handle_new_block(block):
... # Define your logic here
def handle_new_block(block): ... # Define your logic here
```

Inside of `handle_new_block` you can define any logic that you need to handle each new `block` created by the network.
Expand Down Expand Up @@ -101,8 +100,7 @@ TOKEN = Contract("<token address>")


@bot.on_(TOKEN.Transfer)
def handle_token_transfer(log):
... # Define your logic here
def handle_token_transfer(log): ... # Define your logic here
```

Inside of `handle_token_transfer` you can define any logic that you need to handle each new `Transfer` log emitted by `TOKEN`.
Expand All @@ -126,20 +124,19 @@ For example, if you only want to trigger on `Transfer` logs that represent a "bu

```python
from ape.utils import ZERO_ADDRESS

...


@bot.on_(USDC.Transfer, to=ZERO_ADDRESS)
def handle_burn(log):
... # Define your logic here
def handle_burn(log): ... # Define your logic here
```

In case an event parameter has the name of a Python keyword, we also support filtering by dict:

```python
@bot.on_(USDC.Transfer, filter_args={"from": ZERO_ADDRESS})
def handle_burn(log):
... # Define your logic here
def handle_burn(log): ... # Define your logic here
```

```{warning}
Expand All @@ -158,8 +155,7 @@ You can do that easily with the `@bot.cron` task decorator:

```python
@bot.cron("0 * * * *")
def every_hour(time):
... # Define your logic here
def every_hour(time): ... # Define your logic here
```

```{important}
Expand Down Expand Up @@ -202,10 +198,12 @@ along with the `block_time` handler which also generates a matching metric of th
async def handlerA(log):
return dict(block_time=log.timestamp)


@bot.cron("* * * * *")
async def handlerB(time):
return {"block_time": int(time.timestamp())}


@bot.on_(chain.blocks)
async def block_time(block):
return block.timestamp
Expand All @@ -229,8 +227,7 @@ You can then define a "metric callback" that is triggered whenever a new measure

```python
@bot.on_metric("current_price")
async def on_current_price(current_price: float):
... # Do something with the price
async def on_current_price(current_price: float): ... # Do something with the price
```

This can be particularly handy for definining conditions that trigger whenever a metric has been measured conditionally.
Expand Down Expand Up @@ -419,10 +416,10 @@ You can use this in your bot to enable a "test execution" mode, something like t
@bot.on_metric("metric-name", gt=THRESHOLD)
def execute_trade(metric):
if bot.signer:
... # Execute a transaction via `sender=bot.signer`
... # Execute a transaction via `sender=bot.signer`

else:
... # simulate what the transaction *would* have done
... # simulate what the transaction *would* have done
```

```{warning}
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ requires-python = ">=3.10,<4"
dependencies = [
"apepay>=0.3.5,<1", # For payments
"click", # Use same version as eth-ape
"eth-ape>=0.8.38,<1", # Bumps lower pin on web3py
"eth-ape>=0.8.52,<1", # Bumps lower pin on web3py
"ethpm-types>=0.6.10", # lower pin only, `eth-ape` governs upper pin
"eth-pydantic-types", # Use same version as eth-ape
"exceptiongroup; python_version < '3.11'", # Used with TaskGroup
Expand Down
2 changes: 1 addition & 1 deletion silverback/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ def __getattr__(name: str):


__all__ = [
"StateSnapshot",
"CircuitBreaker",
"SilverbackBot",
"SilverbackException",
"StateSnapshot",
]
11 changes: 8 additions & 3 deletions silverback/_build_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,17 @@ def build_container_images(
):
if (
not use_docker
and (result := subprocess.run(["podman", "--version"], capture_output=True)).returncode == 0
and (
result := subprocess.run(["podman", "--version"], capture_output=True, check=False)
).returncode
== 0
):
click.echo(f"Using {result.stdout.decode()}")
builder_name = "podman"

elif (result := subprocess.run(["docker", "--version"], capture_output=True)).returncode == 0:
elif (
result := subprocess.run(["docker", "--version"], capture_output=True, check=False)
).returncode == 0:
click.echo(f"Using {result.stdout.decode()}")
builder_name = "docker"

Expand Down Expand Up @@ -205,4 +210,4 @@ def build_container_images(

if push:
for tag in built_tags:
subprocess.run([builder_name, "push", tag])
subprocess.run([builder_name, "push", tag], check=True)
8 changes: 4 additions & 4 deletions silverback/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ def login(auth: "Auth"):

state = secrets.token_urlsafe()
# NOTE: Should verify state, but doesn't (need it for auth though)
auth.authorize(scope=["profile"], extras_params=dict(state=state))
auth.authorize(scope=["profile"], extras_params={"state": state})
userinfo = auth.current_user()
# TODO: Refactor once migration is completed
username = (
Expand Down Expand Up @@ -748,7 +748,7 @@ def create_payment_stream(

assert token_amount # mypy happy

click.echo(yaml.safe_dump(dict(configuration=configuration.settings_display_dict())))
click.echo(yaml.safe_dump({"configuration": configuration.settings_display_dict()}))
click.echo(f"duration: {stream_time}")
click.echo(f"payment: {token_amount / (10 ** token.decimals())} {token.symbol()}\n")

Expand Down Expand Up @@ -1293,7 +1293,7 @@ def list_bots(cluster: "ClusterClient"):
"""List all bots in a CLUSTER by network (Regardless of status)"""

if bots := list(cluster.bots.values()):
groups: dict[str, dict[str, list["Bot"]]] = defaultdict(lambda: defaultdict(list))
groups: dict[str, dict[str, list[Bot]]] = defaultdict(lambda: defaultdict(list))
for bot in bots:
groups[bot.ecosystem][bot.network].append(bot)

Expand Down Expand Up @@ -1417,7 +1417,7 @@ def update_bot(

if clear_environment or (environment and bot.environment != list(environment)):
variable_groups = cluster.variable_groups
env: dict[str, dict[str, list[str]]] = dict(old={}, new={})
env: dict[str, dict[str, list[str]]] = {"old": {}, "new": {}}

for vg_name in bot.environment:
if vg := variable_groups.get(vg_name):
Expand Down
23 changes: 13 additions & 10 deletions silverback/_click_ext.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fnmatch
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from functools import update_wrapper
from pathlib import Path
from traceback import TracebackException
Expand Down Expand Up @@ -89,13 +89,16 @@ def timedelta_callback(
timestamp = None

if timestamp:
if timestamp <= (now := datetime.now()):
now = datetime.now(timezone.utc)
if timestamp.tzinfo is None:
timestamp = timestamp.replace(tzinfo=timezone.utc)
if timestamp <= now:
raise click.BadParameter("Must be a time in the future.", ctx=ctx, param=param)
return timestamp - now

elif " " in timestamp_or_str:
units_value = {}
for time_units in map(lambda s: s.strip(), timestamp_or_str.split(",")):
for time_units in (s.strip() for s in timestamp_or_str.split(",")):
time, units = time_units.split(" ")
if not units.endswith("s"):
units += "s"
Expand Down Expand Up @@ -171,9 +174,9 @@ def __init__(self, *args, section=None, **kwargs):
self.sections = kwargs.pop("sections", {})
commands = {}

for section, command_list in self.sections.items():
for section_name, command_list in self.sections.items():
for cmd in command_list:
cmd.section = section
cmd.section = section_name
commands[cmd.name] = cmd

super().__init__(*args, commands=commands, **kwargs)
Expand Down Expand Up @@ -203,7 +206,7 @@ def new_decorator(f):
return new_decorator

def format_commands(self, ctx, formatter):
for section, cmds in self.sections.items():
for section in self.sections:
rows = []
for subcommand in self.list_commands(ctx):
cmd = self.get_command(ctx, subcommand)
Expand Down Expand Up @@ -310,7 +313,7 @@ def get_platform_client(ctx: click.Context, *args, **kwargs):

ctx.obj["platform"] = PlatformClient(
base_url=profile.host,
cookies=dict(session=auth.access_token_info()["access_token"]),
cookies={"session": auth.access_token_info()["access_token"]},
)

if expose_value:
Expand All @@ -328,7 +331,7 @@ def add_cluster_client(f):
def inject_cluster(ctx, param, value: str | None):
ctx.obj = ctx.obj or {}
if not (profile := ctx.obj.get("profile")):
raise AssertionError("Shouldn't happen, fix cli")
raise TypeError("Shouldn't happen, fix cli")

elif isinstance(profile, ClusterProfile):
return value # Ignore processing this for cluster clients
Expand Down Expand Up @@ -384,11 +387,11 @@ def get_cluster_client(ctx: click.Context, *args, **kwargs):
)

elif isinstance(profile, PlatformProfile):
platform: "PlatformClient" = ctx.obj["platform"]
platform: PlatformClient = ctx.obj["platform"]
kwargs["cluster"] = platform.get_cluster_client(*ctx.obj["cluster_path"])

else:
raise AssertionError("Profile not set, something wrong")
raise TypeError("Profile not set, something wrong")

return ctx.invoke(f, *args, **kwargs)

Expand Down
Loading
Loading