Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Balancer base code, part 1 #87

Merged
merged 8 commits into from
Aug 27, 2023
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
2 changes: 1 addition & 1 deletion fastlane_bot/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class VersionRequirementNotMetError(RuntimeError): pass

def _split_version_str(vstr):
"""splits version mumber string into tuple (int, int, int, ...)"""
m = _re.match("^([0-9\.]*)", vstr.strip())
m = _re.match(r"^([0-9\.]*)", vstr.strip())
if m is None:
raise ValueError("Invalid version number string", vstr)
vlst = tuple(int(x) for x in m.group(0).split("."))
Expand Down
40 changes: 25 additions & 15 deletions fastlane_bot/tests/nbtest/test_003_Serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,30 @@
def notest_optimizer_pickling():
# ------------------------------------------------------------

N=5
curves = [
CPC.from_xy(x=1, y=2000, pair="ETH/USDC"),
CPC.from_xy(x=1, y=2200, pair="ETH/USDC"),
CPC.from_xy(x=1, y=2400, pair="ETH/USDC"),
]
# note: the below is a bit icky as the same curve objects are added multiple times
CC = CPCContainer(curves*N)
O = CPCArbOptimizer(CC)
O.CC.asdf()
pass

O.pickle("delme")
O.pickle("delme", addts=False)
# +
# N=5
# curves = [
# CPC.from_xy(x=1, y=2000, pair="ETH/USDC"),
# CPC.from_xy(x=1, y=2200, pair="ETH/USDC"),
# CPC.from_xy(x=1, y=2400, pair="ETH/USDC"),
# ]

# CC = CPCContainer(curves*N)
# O = CPCArbOptimizer(CC)
# O.CC.asdf()

# !ls *.pickle
# +
# O.pickle("delme")
# O.pickle("delme", addts=False)

O.unpickle("delme")
# +


# +
# O.unpickle("delme")
# -


# ------------------------------------------------------------
Expand Down Expand Up @@ -92,6 +99,7 @@ def test_creating_curves():
'x': 100,
'x_act': 100,
'y_act': 100,
'alpha': 0.5,
'pair': 'TKNB/TKNQ',
'cid': "1",
'fee': 0,
Expand Down Expand Up @@ -278,7 +286,7 @@ def test_serializing_curves():

df = CC.asdf()
assert len(df) == 3
assert tuple(df.reset_index().columns) == ('cid', 'k', 'x', 'x_act', 'y_act',
assert tuple(df.reset_index().columns) == ('cid', 'k', 'x', 'x_act', 'y_act', 'alpha',
'pair', 'fee', 'descr', 'constr', 'params')
assert tuple(df["k"]) == (2000, 8040, 1970)
assert CPCContainer.from_df(df) == CC
Expand Down Expand Up @@ -395,4 +403,6 @@ def notest_saving_curves():






5 changes: 3 additions & 2 deletions fastlane_bot/tests/nbtest/test_037_Exchanges.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
mocked_contract.functions.token0.return_value.call.return_value = 'token0'
mocked_contract.functions.token1.return_value.call.return_value = 'token1'
mocked_contract.functions.fee.return_value.call.return_value = 3000
mocked_contract.functions.tradingFeePPM.return_value.call.return_value = 2000


# ------------------------------------------------------------
Expand Down Expand Up @@ -107,7 +108,7 @@ def test_test_carbon_v1_exchange_update():

carbon_v1_exchange = CarbonV1()
assert (carbon_v1_exchange.get_abi() == CARBON_CONTROLLER_ABI)
assert (carbon_v1_exchange.get_fee('', mocked_contract) == ('0.002', 0.002))
assert (carbon_v1_exchange.get_fee('', mocked_contract) == ('2000', 0.002))
assert (carbon_v1_exchange.get_tkn0('', mocked_contract, setup_data['carbon_v1_event_update']) == setup_data['carbon_v1_event_update']['args']['token0'])


Expand All @@ -121,7 +122,7 @@ def test_test_carbon_v1_exchange_create():

carbon_v1_exchange = CarbonV1()
assert (carbon_v1_exchange.get_abi() == CARBON_CONTROLLER_ABI)
assert (carbon_v1_exchange.get_fee('', mocked_contract) == ('0.002', 0.002))
assert (carbon_v1_exchange.get_fee('', mocked_contract) == ('2000', 0.002))
assert (carbon_v1_exchange.get_tkn0('', mocked_contract, setup_data['carbon_v1_event_create']) == setup_data['carbon_v1_event_create']['args']['token0'])


Expand Down
14 changes: 2 additions & 12 deletions fastlane_bot/tests/nbtest/test_038_TestBancorV3Mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,17 +196,7 @@ def init_bot(mgr: Manager) -> CarbonBot:
assert pool.cid in pool_cids, f"[test_bancor_v3] Validation missing pool.cid {pool.cid} in {pool_cids}"
optimal_arb = finder.get_optimal_arb_trade_amts(pool_cids, 'BNT-FF1C')
assert type(optimal_arb) == float, f"[test_bancor_v3] Optimal arb calculation type is {type(optimal_arb)} not float"
assert iseq(optimal_arb, 5003.2368760578265), f"[test_bancor_v3] Optimal arb calculation type is {optimal_arb}, expected 5003.2368760578265"










assert iseq(optimal_arb, 4051.1611717583105), f"[test_bancor_v3] Optimal arb calculation type is {optimal_arb}, expected 4051.1611717583105"

# ------------------------------------------------------------
# Test 038
Expand Down Expand Up @@ -282,7 +272,7 @@ def test_test_get_fee_safe():
)
ext_fee = finder.get_fee_safe(first_check_pools[1].fee)
assert type(ext_fee) == float, f"[test_bancor_v3] Testing external pool, fee type is {type(ext_fee)} not float"
assert iseq(ext_fee, 0.003), f"[test_bancor_v3] Testing external pool, fee amt is {ext_fee} not 0.003"
assert iseq(ext_fee, 0.0005), f"[test_bancor_v3] Testing external pool, fee amt is {ext_fee} not 0.0005"


# ------------------------------------------------------------
Expand Down
100 changes: 100 additions & 0 deletions fastlane_bot/tests/nbtest/test_048_RespectFlashloanTokensClickParam.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# ------------------------------------------------------------
# Auto generated test file `test_048_RespectFlashloanTokensClickParam.py`
# ------------------------------------------------------------
# source file = NBTest_048_RespectFlashloanTokensClickParam.py
# test id = 048
# test comment = RespectFlashloanTokensClickParam
# ------------------------------------------------------------



"""
This module contains the tests which ensure that the flashloan tokens click parameters are respected.
"""
from fastlane_bot import Bot
from fastlane_bot.tools.cpc import ConstantProductCurve as CPC
from fastlane_bot.events.exchanges import UniswapV2, UniswapV3, SushiswapV2, CarbonV1, BancorV3
import subprocess, os, sys
import pytest
print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(CPC))
print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(Bot))
print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(UniswapV2))
print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(UniswapV3))
print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(SushiswapV2))
print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(CarbonV1))
print("{0.__name__} v{0.__VERSION__} ({0.__DATE__})".format(BancorV3))
from fastlane_bot.testing import *
plt.rcParams['figure.figsize'] = [12,6]
from fastlane_bot import __VERSION__
require("3.0", __VERSION__)




def find_main_py():
# Start at the directory of the current script
cwd = os.path.abspath(os.path.join(os.getcwd()))

print(f"Searching for main.py in {cwd}")
while True:
# Check if main.py exists in the current directory
if "main.py" in os.listdir(cwd):
return cwd # Found the directory containing main.py
else:
# If not, go up one directory
new_cwd = os.path.dirname(cwd)

# If we're already at the root directory, stop searching
if new_cwd == cwd:
raise FileNotFoundError("Could not find main.py in any parent directory")

cwd = new_cwd


def run_command(arb_mode, expected_log_line):

# Find the correct path to main.py
main_script_path = find_main_py()
print(f"Found main.py in {main_script_path}")
main_script_path = main_script_path + "/main.py"

# Run the command
cmd = [
"python",
main_script_path,
f"--arb_mode={arb_mode}",
"--default_min_profit_bnt=60",
"--limit_bancor3_flashloan_tokens=False",
"--use_cached_events=True",
"--logging_path=fastlane_bot/data/",
"--timeout=1",
"--loglevel=DEBUG",
"--flashloan_tokens=BNT-FF1C,ETH-EEeE,ETH2X-FLI-USD",
]
subprocess.Popen(cmd)

# Wait for the expected log line to appear
found = False
result = subprocess.run(cmd, text=True, capture_output=True, check=True, timeout=7)

# Check if the expected log line is in the output
if expected_log_line in result.stderr or expected_log_line in result.stdout:
found = True

if not found:
pytest.fail("Expected log line was not found within 1 minute") # If we reach this point, the test has failed




# ------------------------------------------------------------
# Test 048
# File test_048_RespectFlashloanTokensClickParam.py
# Segment Test flashloan_tokens is Respected
# ------------------------------------------------------------
def test_test_flashloan_tokens_is_respected():
# ------------------------------------------------------------

expected_log_line = "Flashloan tokens are set as: ['BNT-FF1C', 'ETH-EEeE', 'ETH2X_FLI-USD']"
arb_mode = "multi"
run_command(arb_mode=arb_mode, expected_log_line=expected_log_line)
Loading
Loading