Skip to content

Commit

Permalink
refactor(example): update comments and data structure used in bot
Browse files Browse the repository at this point in the history
  • Loading branch information
fubuloubu committed Sep 23, 2024
1 parent 27fc975 commit 5066f11
Showing 1 changed file with 20 additions and 17 deletions.
37 changes: 20 additions & 17 deletions bots/example.py
Original file line number Diff line number Diff line change
@@ -1,47 +1,50 @@
import os
from datetime import timedelta
from collections import defaultdict

from ape_ethereum import multicall
from ape.types import AddressType
from silverback import SilverbackApp

from apepay import StreamManager
from apepay import Stream, StreamManager

app = SilverbackApp()
# NOTE: You should use one bot per-supported network
# NOTE: This bot assumes you use a new bot per deployment
# NOTE: This bot assumes you use a new bot per ApePay deployment
sm = StreamManager(os.environ["APEPAY_CONTRACT_ADDRESS"])

# NOTE: You would probably want to index this by network and deployment,
# if you were operating on multiple networks or deployments
db = []
# NOTE: You would probably want to index your db by network and deployment address,
# if you were operating on multiple networks and/or deployments (for easy lookup)
db: defaultdict[AddressType, list[Stream]] = defaultdict(list)
# TODO: Migrate to `app.state.db` when feature becomes available


@app.on_startup()
async def load_db(_):
for stream in sm.active_streams():
db.append(stream)
while len(db[stream.creator]) < stream.stream_id:
db[stream.creator].append(None) # Fill with empty values
assert stream.stream_id == len(db[stream.creator])
db[stream.creator].append(stream)


@sm.on_stream_created(app)
async def grant_product(stream):
db.append(stream)
assert stream.stream_id == len(db[stream.creator])
db[stream.creator].append(stream)
print(f"provisioning product for {stream.creator}")
return stream.time_left


@sm.on_stream_funded(app)
async def update_product_funding(stream):
# NOTE: properties of stream have changed, you may not need to handle this
# but typically you would want to update `stream.time_left` in record
db.remove(
next(s for s in db if s.stream_id == stream.stream_id and s.creator == stream.creator)
)
db.append(stream)
# NOTE: properties of stream have changed, you may not need to handle this, but typically you
# would want to update `stream.time_left` in db for use in user Stream life notifications
db[stream.creator].pop(stream.stream_id)
db[stream.creator].insert(stream.stream_id, stream)
return stream.time_left


@sm.on_stream_cancelled(app)
async def revoke_product(stream):
print(f"unprovisioning product for {stream.creator}")
db.remove(stream)
db[stream.creator].pop(stream.stream_id)
db[stream.creator].insert(stream.stream_id, None)
return stream.time_left

0 comments on commit 5066f11

Please sign in to comment.