Skip to content

Commit

Permalink
Bugfixes and adding tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mikewcasale committed Aug 27, 2023
1 parent b10a5fb commit 9f2a606
Show file tree
Hide file tree
Showing 11 changed files with 204 additions and 107 deletions.
14 changes: 14 additions & 0 deletions fastlane_bot/data/event_test_data.json
Original file line number Diff line number Diff line change
Expand Up @@ -218,5 +218,19 @@
"newFeePPM": 3000
},
"event": "TradingFeePPMUpdated"
},
"bancor_v2_event": {
"args": {
"_token1": "0xB2607CB158bc222DD687e4D794c607B5ce983Ce2",
"_token2": "0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0",
"_rateN": 701296523896722535,
"_rateD": 124447579392500555356},
"event": "TokenRateUpdate",
"logIndex": 106,
"transactionIndex": 22,
"transactionHash": "0x5b03ac11612de4b57824bcec404cdbbe96265425c073b3ac3abfa9b9edf8dd1e",
"address": "0xADd45B18153382D69AB5A13c44d1782B8f3aDEEc",
"blockHash": "0x45f34d791644169219b806ebdf60341fb5e62e4ed49e9da225e34d82e17f1f8b",
"blockNumber": 18005932
}
}
12 changes: 10 additions & 2 deletions fastlane_bot/events/exchanges/bancor_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,15 @@ def get_fee(self, address: str, contract: Contract) -> Tuple[str, float]:
return fee, fee_float

def get_tkn0(self, address: str, contract: Contract, event: Any) -> str:
return contract.functions.reserveTokens().call()[0]
return (
event["args"]["_token1"]
if event
else contract.functions.reserveTokens().call()[0]
)

def get_tkn1(self, address: str, contract: Contract, event: Any) -> str:
return contract.functions.reserveTokens().call()[1]
return (
event["args"]["_token2"]
if event
else contract.functions.reserveTokens().call()[1]
)
4 changes: 2 additions & 2 deletions fastlane_bot/events/exchanges/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ class Exchange(ABC):
Base class for exchanges
"""

__VERSION__ = "0.0.1"
__DATE__ = "2023-07-03"
__VERSION__ = "0.0.2"
__DATE__ = "2023-08-27"

pools: Dict[str, Pool] = field(default_factory=dict)

Expand Down
2 changes: 1 addition & 1 deletion fastlane_bot/events/managers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,7 @@ def get_key_and_value(
"""
if ex_name == "carbon_v1":
return "cid", event["args"]["id"]
if ex_name in {"uniswap_v2", "sushiswap_v2", "uniswap_v3"}:
if ex_name in {"uniswap_v2", "sushiswap_v2", "uniswap_v3", "bancor_v2"}:
return "address", addr
if ex_name == "bancor_v3":
value = (
Expand Down
5 changes: 0 additions & 5 deletions fastlane_bot/events/managers/pools.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,11 +365,6 @@ def get_or_init_pool(self, pool_info: Dict[str, Any]) -> Pool:

pool = self.exchanges[pool_info["exchange_name"]].get_pool(key)

if pool_info["exchange_name"] == "bancor_v2":
print(f'pool_info["exchange_name"]: {pool_info["exchange_name"]}')
print(f"key: {key}")
print(f"pool: {pool}")

if not pool:
self.add_pool_to_exchange(pool_info)
key = self.pool_key_from_info(pool_info)
Expand Down
31 changes: 18 additions & 13 deletions fastlane_bot/events/pools/bancor_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,30 +50,32 @@ def event_matches_format(cls, event: Dict[str, Any]) -> bool:
def update_from_event(
self, event_args: Dict[str, Any], data: Dict[str, Any]
) -> Dict[str, Any]:
"""
See base class.
"""
tkn0 = self.state["tkn0_address"]
tkn1 = self.state["tkn1_address"]

event_args = event_args["args"]

"""
**** IMPORTANT ****
Bancor V2 pools emit 3 events per trade. Only one of them contains the new token balances we want.
Bancor V2 pools emit 3 events per trade. Only one of them contains the new token balances we want.
The one we want is the one where _token1 and _token2 match the token addresses of the pool.
"""

if event_args["_token1"] == tkn0 and event_args["_token2"] == tkn1:
data["tkn0_balance"] = event_args["_rateN"]
data["tkn1_balance"] = event_args["_rateD"]
if "tkn0_address" not in self.state:
self.state["tkn0_address"] = event_args["args"]["_token1"]
self.state["tkn1_address"] = event_args["args"]["_token2"]

if (
self.state["tkn0_address"] == event_args["args"]["_token1"]
and self.state["tkn1_address"] == event_args["args"]["_token2"]
):
data["tkn0_balance"] = event_args["args"]["_rateN"]
data["tkn1_balance"] = event_args["args"]["_rateD"]
else:
data["tkn0_balance"] = self.state["tkn0_balance"]
data["tkn1_balance"] = self.state["tkn0_balance"]
data["tkn1_balance"] = self.state["tkn1_balance"]

for key, value in data.items():
self.state[key] = value

if "anchor" not in self.state:
self.state["anchor"] = event_args["address"]

data["anchor"] = self.state["anchor"]
data["cid"] = self.state["cid"]
data["fee"] = self.state["fee"]
Expand All @@ -86,6 +88,7 @@ def update_from_contract(self, contract: Contract) -> Dict[str, Any]:
See base class.
"""
reserve0, reserve1 = contract.caller.reserveBalances()
tkn0_address, tkn1_address = contract.caller.reserveTokens()
fee = contract.caller.conversionFee()

params = {
Expand All @@ -96,6 +99,8 @@ def update_from_contract(self, contract: Contract) -> Dict[str, Any]:
"anchor": contract.caller.anchor(),
"tkn0_balance": reserve0,
"tkn1_balance": reserve1,
"tkn0_address": tkn0_address,
"tkn1_address": tkn1_address,
}
for key, value in params.items():
self.state[key] = value
Expand Down
4 changes: 3 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
@click.option("--n_jobs", default=-1, help="Number of parallel jobs to run")
@click.option(
"--exchanges",
default="carbon_v1,bancor_v3,uniswap_v3,uniswap_v2,sushiswap_v2",
default="carbon_v1,bancor_v3,uniswap_v3,uniswap_v2,sushiswap_v2,bancor_v2",
help="Comma separated external exchanges. Note that carbon_v1 and bancor_v3 must be included.",
)
@click.option(
Expand Down Expand Up @@ -395,6 +395,8 @@ def run(
mgr.cfg.logger.info("Timeout hit... stopping bot")
break

break

except Exception as e:
mgr.cfg.logger.error(f"Error in main loop: {e}")
time.sleep(polling_interval)
Expand Down
89 changes: 57 additions & 32 deletions resources/NBTest/NBTest_033_Pools.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
"execution_count": 1,
"id": "6580a545",
"metadata": {
"is_executing": true
"ExecuteTime": {
"end_time": "2023-08-27T13:30:38.970677Z",
"start_time": "2023-08-27T13:30:35.991735Z"
}
},
"outputs": [
{
Expand All @@ -19,6 +22,7 @@
"SushiswapV2Pool v0.0.1 (2023-07-03)\n",
"CarbonV1Pool v0.0.1 (2023-07-03)\n",
"BancorV3Pool v0.0.1 (2023-07-03)\n",
"BancorV2Pool v0.0.1 (2023-07-03)\n",
"imported m, np, pd, plt, os, sys, decimal; defined iseq, raises, require\n",
"Version = 3-b2.2 [requirements >= 3.0 is met]\n"
]
Expand All @@ -30,7 +34,7 @@
"import pytest\n",
"\n",
"from fastlane_bot import Bot\n",
"from fastlane_bot.events.pools import SushiswapV2Pool, UniswapV2Pool, UniswapV3Pool, BancorV3Pool, CarbonV1Pool\n",
"from fastlane_bot.events.pools import SushiswapV2Pool, UniswapV2Pool, UniswapV3Pool, BancorV3Pool, CarbonV1Pool, BancorV2Pool\n",
"from fastlane_bot.tools.cpc import ConstantProductCurve as CPC\n",
"\n",
"print(\"{0.__name__} v{0.__VERSION__} ({0.__DATE__})\".format(CPC))\n",
Expand All @@ -40,6 +44,7 @@
"print(\"{0.__name__} v{0.__VERSION__} ({0.__DATE__})\".format(SushiswapV2Pool))\n",
"print(\"{0.__name__} v{0.__VERSION__} ({0.__DATE__})\".format(CarbonV1Pool))\n",
"print(\"{0.__name__} v{0.__VERSION__} ({0.__DATE__})\".format(BancorV3Pool))\n",
"print(\"{0.__name__} v{0.__VERSION__} ({0.__DATE__})\".format(BancorV2Pool))\n",
"from fastlane_bot.testing import *\n",
"\n",
"#plt.style.use('seaborn-dark')\n",
Expand All @@ -54,8 +59,8 @@
"id": "14b3c378",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-03T21:13:38.642898Z",
"start_time": "2023-07-03T21:13:38.640819Z"
"end_time": "2023-08-27T13:30:38.982396Z",
"start_time": "2023-08-27T13:30:38.970002Z"
}
},
"outputs": [],
Expand All @@ -78,8 +83,8 @@
"id": "4bf9ea77",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-03T21:13:38.646156Z",
"start_time": "2023-07-03T21:13:38.643969Z"
"end_time": "2023-08-27T13:30:38.982538Z",
"start_time": "2023-08-27T13:30:38.973390Z"
}
},
"outputs": [],
Expand All @@ -89,6 +94,35 @@
"assert (uniswap_v2_pool.state['tkn0_balance'] == setup_data['uniswap_v2_event']['args']['reserve0'])"
]
},
{
"cell_type": "markdown",
"source": [
"## test_bancor_v2_pool"
],
"metadata": {
"collapsed": false
},
"id": "5e07f1229048cd9c"
},
{
"cell_type": "code",
"execution_count": 4,
"outputs": [],
"source": [
"bancor_v2_pool = BancorV2Pool()\n",
"bancor_v2_pool.update_from_event(setup_data['bancor_v2_event'], {'cid': '0x', 'fee': '0.000', 'fee_float': 0.0, 'exchange_name': 'bancor_v2'})\n",
"assert (bancor_v2_pool.state['tkn0_balance'] == setup_data['bancor_v2_event']['args']['_rateN'])\n",
"assert (bancor_v2_pool.state['tkn1_balance'] == setup_data['bancor_v2_event']['args']['_rateD'])"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-08-27T13:30:38.982584Z",
"start_time": "2023-08-27T13:30:38.975758Z"
}
},
"id": "4dfe57c17c271eec"
},
{
"cell_type": "markdown",
"id": "498dcb11",
Expand All @@ -99,12 +133,12 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 5,
"id": "9d4692f5",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-03T21:13:38.649098Z",
"start_time": "2023-07-03T21:13:38.647462Z"
"end_time": "2023-08-27T13:30:38.982619Z",
"start_time": "2023-08-27T13:30:38.977834Z"
}
},
"outputs": [],
Expand All @@ -124,12 +158,12 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 6,
"id": "cb1ac3fd",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-03T21:13:38.653324Z",
"start_time": "2023-07-03T21:13:38.651523Z"
"end_time": "2023-08-27T13:30:38.983082Z",
"start_time": "2023-08-27T13:30:38.981232Z"
}
},
"outputs": [],
Expand All @@ -150,29 +184,20 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 7,
"id": "d69d49a3",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-03T21:13:38.758091Z",
"start_time": "2023-07-03T21:13:38.655671Z"
"end_time": "2023-08-27T13:30:38.986906Z",
"start_time": "2023-08-27T13:30:38.984635Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"{'cid': '0x',\n",
" 'fee': '0.000',\n",
" 'fee_float': 0.0,\n",
" 'exchange_name': 'bancor_v3',\n",
" 'tkn0_balance': 2981332708522538339515032,\n",
" 'tkn1_balance': 2981332708522538339515032,\n",
" 'tkn0_symbol': 'tkn0',\n",
" 'tkn1_symbol': 'tkn1'}"
]
"text/plain": "{'cid': '0x',\n 'fee': '0.000',\n 'fee_float': 0.0,\n 'exchange_name': 'bancor_v3',\n 'tkn0_balance': 2981332708522538339515032,\n 'tkn1_balance': 2981332708522538339515032,\n 'tkn0_symbol': 'tkn0',\n 'tkn1_symbol': 'tkn1'}"
},
"execution_count": 6,
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
Expand All @@ -192,12 +217,12 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 8,
"id": "4e331537",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-03T21:13:38.758551Z",
"start_time": "2023-07-03T21:13:38.661171Z"
"end_time": "2023-08-27T13:30:39.015113Z",
"start_time": "2023-08-27T13:30:38.986781Z"
}
},
"outputs": [],
Expand Down Expand Up @@ -233,12 +258,12 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 9,
"id": "6a9b1034",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-03T21:13:38.758986Z",
"start_time": "2023-07-03T21:13:38.666351Z"
"end_time": "2023-08-27T13:30:39.015295Z",
"start_time": "2023-08-27T13:30:38.993472Z"
}
},
"outputs": [],
Expand Down
14 changes: 11 additions & 3 deletions resources/NBTest/NBTest_033_Pools.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,20 @@
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.13.1
# jupytext_version: 1.14.7
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---

# + is_executing=true
# +
import json

import pytest

from fastlane_bot import Bot
from fastlane_bot.events.pools import SushiswapV2Pool, UniswapV2Pool, UniswapV3Pool, BancorV3Pool, CarbonV1Pool
from fastlane_bot.events.pools import SushiswapV2Pool, UniswapV2Pool, UniswapV3Pool, BancorV3Pool, CarbonV1Pool, BancorV2Pool
from fastlane_bot.tools.cpc import ConstantProductCurve as CPC

print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(CPC))
Expand All @@ -29,6 +29,7 @@
print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(SushiswapV2Pool))
print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(CarbonV1Pool))
print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(BancorV3Pool))
print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(BancorV2Pool))
from fastlane_bot.testing import *

#plt.style.use('seaborn-dark')
Expand All @@ -46,6 +47,13 @@
uniswap_v2_pool.update_from_event(setup_data['uniswap_v2_event'], {'cid': '0x', 'fee': '0.000', 'fee_float': 0.0, 'exchange_name': 'sushiswap_v2', 'reserve0': setup_data['uniswap_v2_event']['args']['reserve0'], 'reserve1': setup_data['uniswap_v2_event']['args']['reserve1'], 'tkn0_symbol': 'tkn0', 'tkn1_symbol': 'tkn1'})
assert (uniswap_v2_pool.state['tkn0_balance'] == setup_data['uniswap_v2_event']['args']['reserve0'])

# ## test_bancor_v2_pool

bancor_v2_pool = BancorV2Pool()
bancor_v2_pool.update_from_event(setup_data['bancor_v2_event'], {'cid': '0x', 'fee': '0.000', 'fee_float': 0.0, 'exchange_name': 'bancor_v2'})
assert (bancor_v2_pool.state['tkn0_balance'] == setup_data['bancor_v2_event']['args']['_rateN'])
assert (bancor_v2_pool.state['tkn1_balance'] == setup_data['bancor_v2_event']['args']['_rateD'])

# ## test_sushiswap_v2_pool

sushiswap_v2_pool = SushiswapV2Pool()
Expand Down
Loading

0 comments on commit 9f2a606

Please sign in to comment.