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
4 changes: 2 additions & 2 deletions .github/workflows/common_check.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ jobs:
fail-fast: false
matrix:
python-version: ["3.11",]
poetry-version: ["1.3.2"]
os: [ubuntu-20.04,]
poetry-version: ["2.0.1"]
os: [ubuntu-24.04,]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
Expand Down
28 changes: 16 additions & 12 deletions balpy/balancerv2cad/notebooks/BalancerV2.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
}
],
"source": [
"#optional -f show the full list of installed files\n",
"# optional -f show the full list of installed files\n",
"%pip show balancerv2cad "
]
},
Expand All @@ -82,7 +82,6 @@
"metadata": {},
"outputs": [],
"source": [
"from decimal import Decimal\n",
"from balancerv2cad.WeightedPool import WeightedPool"
]
},
Expand Down Expand Up @@ -157,12 +156,9 @@
"source": [
"bp.join_pool(\n",
" # First argument populates \"balances\" as a dict with key-value pair 'token' is a string and 'value' as an integer\n",
" {'a':100,\n",
" 'b':100},\n",
" \n",
" {\"a\": 100, \"b\": 100},\n",
" # First argument populates \"weights\" as a dict with key-value pair 'token' is a string and 'value' as float\n",
" {'a':0.5,\n",
" 'b':0.5}\n",
" {\"a\": 0.5, \"b\": 0.5},\n",
")"
]
},
Expand All @@ -181,8 +177,12 @@
}
],
"source": [
"print(\"Balance of 'a': {}. Balance of 'b': {}\".format(bp._balances['a'], bp._balances['b']))\n",
"print(\"Weight of 'a': {}. Weight of 'b': {}\".format(bp._weights['a'], bp._weights['b']))"
"print(\n",
" \"Balance of 'a': {}. Balance of 'b': {}\".format(\n",
" bp._balances[\"a\"], bp._balances[\"b\"]\n",
" )\n",
")\n",
"print(\"Weight of 'a': {}. Weight of 'b': {}\".format(bp._weights[\"a\"], bp._weights[\"b\"]))"
]
},
{
Expand Down Expand Up @@ -239,9 +239,13 @@
}
],
"source": [
"bp.swap('b', 'a', 1, given_in=False)\n",
"print(\"Balance of 'a': {}. Balance of 'b': {}\".format(bp._balances['a'], bp._balances['b']))\n",
"print(\"Weight of 'a': {}. Weight of 'b': {}\".format(bp._weights['a'], bp._weights['b']))"
"bp.swap(\"b\", \"a\", 1, given_in=False)\n",
"print(\n",
" \"Balance of 'a': {}. Balance of 'b': {}\".format(\n",
" bp._balances[\"a\"], bp._balances[\"b\"]\n",
" )\n",
")\n",
"print(\"Weight of 'a': {}. Weight of 'b': {}\".format(bp._weights[\"a\"], bp._weights[\"b\"]))"
]
},
{
Expand Down
6 changes: 2 additions & 4 deletions balpy/balancerv2cad/scripts/project_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Define functions as project "scripts" and run them via the
pyproject.toml
"""

import subprocess as sp
import sys

Expand All @@ -18,10 +19,7 @@ def stub_gen() -> None:
out_file = f"src/{ks.__package__}-stubs"
path = str(ks.BASE_DIR / "src" / f"{ks.__package__}")
try:
sp.run(
f"stubgen -p {ks.__package__} -o {out_file}",
check=True,
shell=True)
sp.run(f"stubgen -p {ks.__package__} -o {out_file}", check=True, shell=True)
sp.run(f"mypy {path}", check=True, shell=True)
except sp.CalledProcessError as error:
print(f"{error}")
Expand Down
25 changes: 8 additions & 17 deletions balpy/balancerv2cad/src/balancerv2cad/StableMath.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ class BalancerMathResult:
class StableMath:
# -------------------------------------
@staticmethod
def calculateInvariant(amplificationParameter: Decimal,
balances: list) -> Decimal:
def calculateInvariant(amplificationParameter: Decimal, balances: list) -> Decimal:
# /**********************************************************************************************
# // invariant //
# // D = invariant D^(n+1) //
Expand All @@ -44,8 +43,7 @@ def calculateInvariant(amplificationParameter: Decimal,
prevInvariant = invariant

invariant = ceil(
((num_tokens * invariant) * invariant +
(ampTimesTotal * bal_sum) * P_D)
((num_tokens * invariant) * invariant + (ampTimesTotal * bal_sum) * P_D)
/ ((num_tokens + 1) * invariant + (ampTimesTotal - 1) * P_D)
)
if invariant > prevInvariant:
Expand Down Expand Up @@ -101,8 +99,7 @@ def calcBptInGivenExactTokensOut(
)
)

swapFeeExcess = mulUp(
swapFee, Decimal(tokenBalancePercentageExcess))
swapFeeExcess = mulUp(swapFee, Decimal(tokenBalancePercentageExcess))
amountOutBeforeFee = Decimal(
divUp(amountsOut[i], complement(swapFeeExcess))
)
Expand Down Expand Up @@ -142,8 +139,7 @@ def calcBptOutGivenExactTokensIn(
for i in range(len(balances)):
currentWeight = divDown(Decimal(balances[i]), Decimal(sumBalances))
tokenBalanceRatiosWithoutFee.append(
balances[i] + divDown(Decimal(amountsIn[i]),
Decimal(balances[i]))
balances[i] + divDown(Decimal(amountsIn[i]), Decimal(balances[i]))
)
weightedBalanceRatio = weightedBalanceRatio + mulDown(
tokenBalanceRatiosWithoutFee[i], currentWeight
Expand Down Expand Up @@ -203,15 +199,12 @@ def calcDueTokenProtocolSwapFeeAmount(
)

if balances[tokenIndex] > finalBalanceFeeToken:
accumulatedTokenSwapFees = balances[tokenIndex] - \
finalBalanceFeeToken
accumulatedTokenSwapFees = balances[tokenIndex] - finalBalanceFeeToken
else:
accumulatedTokenSwapFees = 0

return divDown(
mulDown(
accumulatedTokenSwapFees,
Decimal(protocolSwapFeePercentage))
mulDown(accumulatedTokenSwapFees, Decimal(protocolSwapFeePercentage))
)

@staticmethod
Expand All @@ -234,8 +227,7 @@ def calcInGivenOut(
# // P = product of final balances but x //
# **************************************************************************************************************/
getcontext().prec = 28
invariant = StableMath.calculateInvariant(
amplificationParameter, balances)
invariant = StableMath.calculateInvariant(amplificationParameter, balances)
balances[tokenIndexOut] = balances[tokenIndexOut] - tokenAmountOut

finalBalanceIn = StableMath.getTokenBalanceGivenInvariantAndAllOtherBalances(
Expand Down Expand Up @@ -266,8 +258,7 @@ def calcOutGivenIn(
# // P = product of final balances but y //
# **************************************************************************************************************/
print("Context", "OUTGIVENIN")
invariant = StableMath.calculateInvariant(
amplificationParameter, balances)
invariant = StableMath.calculateInvariant(amplificationParameter, balances)
print("Invariant", invariant)
balances[tokenIndexIn] = balances[tokenIndexIn] + tokenAmountIn
finalBalanceOut = StableMath.getTokenBalanceGivenInvariantAndAllOtherBalances(
Expand Down
37 changes: 11 additions & 26 deletions balpy/balancerv2cad/src/balancerv2cad/WeightedMath.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@

class WeightedMath:
@staticmethod
def calculate_invariant(
normalized_weights: List[Decimal], balances: List[Decimal]):
def calculate_invariant(normalized_weights: List[Decimal], balances: List[Decimal]):
# /**********************************************************************************************
# // invariant _____ //
# // wi = weight index i | | wi //
Expand Down Expand Up @@ -118,11 +117,9 @@ def calc_bpt_out_given_exact_tokens_in(
else:
amount_in_without_fee = amounts_in[i]

balance_ratio = divDown(
(balances[i] + amount_in_without_fee), balances[i])
balance_ratio = divDown((balances[i] + amount_in_without_fee), balances[i])
invariant_ratio = mulDown(
invariant_ratio, (powDown(
balance_ratio, normalized_weights[i]))
invariant_ratio, (powDown(balance_ratio, normalized_weights[i]))
)

if invariant_ratio >= 1:
Expand All @@ -147,21 +144,16 @@ def calc_token_in_given_exact_bpt_out(
# // w = weight //
# ******************************************************************************************/

invariant_ratio = divUp(
(bpt_total_supply + bpt_amount_out),
bpt_total_supply)
invariant_ratio = divUp((bpt_total_supply + bpt_amount_out), bpt_total_supply)
sys.stdout.write(f"invariant ratio {invariant_ratio}")
balance_ratio = powUp(
invariant_ratio, (divUp(
Decimal(1), normalized_weight)))
balance_ratio = powUp(invariant_ratio, (divUp(Decimal(1), normalized_weight)))
sys.stdout.write(f"normalized weight {normalized_weight}")
amount_in_without_fee = mulUp(balance, (balance_ratio - Decimal(1)))
taxable_percentage = complement(normalized_weight)
taxable_amount = mulUp(amount_in_without_fee, taxable_percentage)
non_taxable_amount = amount_in_without_fee - taxable_amount
sys.stdout.write(f" swap fee {swap_fee}")
return non_taxable_amount + \
(divUp(taxable_amount, complement(swap_fee)))
return non_taxable_amount + (divUp(taxable_amount, complement(swap_fee)))

@staticmethod
def calc_bpt_in_given_exact_tokens_out(
Expand Down Expand Up @@ -197,11 +189,9 @@ def calc_bpt_in_given_exact_tokens_out(
)
else:
amount_out_with_fee = amounts_out[i]
balance_ratio = divUp(
(balances[i] - amount_out_with_fee), balances[i])
balance_ratio = divUp((balances[i] - amount_out_with_fee), balances[i])
invariant_ratio = mulDown(
invariant_ratio, (powDown(
balance_ratio, normalized_weights[i]))
invariant_ratio, (powDown(balance_ratio, normalized_weights[i]))
)
return mulUp(bpt_total_supply, complement(invariant_ratio))

Expand All @@ -222,19 +212,14 @@ def calc_token_out_given_exact_bpt_in(
# // w = weight //
# *****************************************************************************************/

invariant_ratio = divUp(
(bpt_total_supply - bpt_amount_in),
bpt_total_supply)
balance_ratio = powUp(
invariant_ratio, (divDown(
Decimal(1), normalized_weight)))
invariant_ratio = divUp((bpt_total_supply - bpt_amount_in), bpt_total_supply)
balance_ratio = powUp(invariant_ratio, (divDown(Decimal(1), normalized_weight)))
amount_out_without_fee = mulDown(balance, complement(balance_ratio))
taxable_percentage = complement(normalized_weight)
taxable_amount = mulUp(amount_out_without_fee, taxable_percentage)
non_taxable_amount = amount_out_without_fee - taxable_amount

return non_taxable_amount + \
mulDown(taxable_amount, complement(swap_fee))
return non_taxable_amount + mulDown(taxable_amount, complement(swap_fee))

@staticmethod
def calc_tokens_out_given_exact_bpt_in(
Expand Down
2 changes: 1 addition & 1 deletion balpy/balancerv2cad/src/balancerv2cad/WeightedPool.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def set_swap_fee(self, amount: Decimal):
self._swap_fee = amount

def set_weights(self, weights: dict):
if not weights.keys() in self._weights:
if weights.keys() not in self._weights:
raise Exception("WEIGHT TICKER NOT FOUND, JOIN POOL FIRST")
for key, amount in weights.items():
if isinstance(amount, int) or isinstance(amount, float):
Expand Down
3 changes: 1 addition & 2 deletions balpy/balancerv2cad/src/balancerv2cad/logger/pkg_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ def __load_configuration(self) -> None:
sys.exit(1)

@staticmethod
def get_logger(name: Literal["production"]
= DEFAULT_LOGGER_NAME) -> logging.Logger:
def get_logger(name: Literal["production"] = DEFAULT_LOGGER_NAME) -> logging.Logger:
"""
Return a logger by name.
Only logger names that are defined in the config
Expand Down
4 changes: 1 addition & 3 deletions balpy/balancerv2cad/src/balancerv2cad/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ def run() -> None:
ks.__version__,
)
except KeyError as error:
logger.error(
"Could not find %s in .env file. Please consult the README",
error)
logger.error("Could not find %s in .env file. Please consult the README", error)
logger.info("Testing for %s@%s", ks.__package__, ks.__version__)
logger.debug("Testing for %s@%s", ks.__package__, ks.__version__)
logger.warning("Testing for %s@%s", ks.__package__, ks.__version__)
Expand Down
6 changes: 2 additions & 4 deletions balpy/balancerv2cad/tests/unit-test/test_WeightedMath.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,7 @@ def test_in_given_out_extreme_weights(weightedmath_test):
expected = Decimal(0.107419197916188066)
assert expectEqualWithError(result, expected)

def test_calc_due_token_protocol_swap_fee_amount_two_tokens(
weightedmath_test):
def test_calc_due_token_protocol_swap_fee_amount_two_tokens(weightedmath_test):
# Returns protocl swap fees
normalized_weights = [Decimal(0.3), Decimal(0.7)]
balances = [Decimal(10), Decimal(11)]
Expand Down Expand Up @@ -208,8 +207,7 @@ def test_calc_due_token_protocol_swap_fee_amount_two_tokens(
expected = Decimal(0.439148057504926669190)
assert expectEqualWithError(result, expected)

def test_calc_due_token_protocol_swap_fee_amount_three_tokens(
weightedmath_test):
def test_calc_due_token_protocol_swap_fee_amount_three_tokens(weightedmath_test):
normalized_weights = [Decimal(0.3), Decimal(0.2), Decimal(0.5)]
balances = [Decimal(10), Decimal(11), Decimal(12)]
last_invariant = Decimal(10)
Expand Down
Loading