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
5 changes: 0 additions & 5 deletions balpy/balancerv2cad/src/balancerv2cad/StableMath.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,10 @@ class BalancerMathResult:


class StableMath:

# -------------------------------------
@staticmethod
def calculateInvariant(amplificationParameter: Decimal,
balances: list) -> Decimal:

# /**********************************************************************************************
# // invariant //
# // D = invariant D^(n+1) //
Expand Down Expand Up @@ -224,7 +222,6 @@ def calcInGivenOut(
tokenIndexOut: int,
tokenAmountOut: Decimal,
) -> Decimal:

# /**************************************************************************************************************
# // inGivenOut token x for y - polynomial equation to solve //
# // ax = amount in to calculate //
Expand Down Expand Up @@ -257,7 +254,6 @@ def calcOutGivenIn(
tokenIndexOut: int,
tokenAmountIn: Decimal,
) -> Decimal:

# /**************************************************************************************************************
# // outGivenIn token x for y - polynomial equation to solve //
# // ay = amount out to calculate //
Expand Down Expand Up @@ -340,7 +336,6 @@ def calcTokenInGivenExactBptOut(
def calcTokensOutGivenExactBptIn(
balances: list, bptAmountIn: Decimal, bptTotalSupply: Decimal
) -> list:

# /**********************************************************************************************
# // exactBPTInForTokensOut //
# // (per token) //
Expand Down
9 changes: 0 additions & 9 deletions balpy/balancerv2cad/src/balancerv2cad/WeightedMath.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ class WeightedMath:
@staticmethod
def calculate_invariant(
normalized_weights: List[Decimal], balances: List[Decimal]):

# /**********************************************************************************************
# // invariant _____ //
# // wi = weight index i | | wi //
Expand All @@ -40,7 +39,6 @@ def calc_out_given_in(
weight_out: Decimal,
amount_in: Decimal,
) -> Decimal:

# /**********************************************************************************************
# // outGivenIn //
# // aO = amountOut //
Expand Down Expand Up @@ -69,7 +67,6 @@ def calc_in_given_out(
weight_out: Decimal,
amount_out: Decimal,
):

# /**********************************************************************************************
# // inGivenOut //
# // aO = amount_out //
Expand All @@ -95,7 +92,6 @@ def calc_bpt_out_given_exact_tokens_in(
bptTotalSupply: Decimal,
swap_fee: Decimal,
):

balance_ratios_with_fee = [None] * len(amounts_in)
invariant_ratio_with_fees = 0
for i in range(len(balances)):
Expand Down Expand Up @@ -142,7 +138,6 @@ def calc_token_in_given_exact_bpt_out(
bpt_total_supply: Decimal,
swap_fee: Decimal,
) -> Decimal:

# /******************************************************************************************
# // tokenInForExactBPTOut //
# // a = amountIn //
Expand Down Expand Up @@ -176,7 +171,6 @@ def calc_bpt_in_given_exact_tokens_out(
bpt_total_supply: Decimal,
swap_fee: Decimal,
) -> Decimal:

balance_ratios_without_fee = [Decimal(0)] * len(amounts_out)
invariant_ratio_without_fees = Decimal(0)
for i in range(len(balances)):
Expand Down Expand Up @@ -219,7 +213,6 @@ def calc_token_out_given_exact_bpt_in(
bpt_total_supply: Decimal,
swap_fee: Decimal,
) -> Decimal:

# /*****************************************************************************************
# // exactBPTInForTokenOut //
# // a = amountOut //
Expand Down Expand Up @@ -247,7 +240,6 @@ def calc_token_out_given_exact_bpt_in(
def calc_tokens_out_given_exact_bpt_in(
balances: List[Decimal], bpt_amount_in: Decimal, total_bpt: Decimal
) -> List:

# /**********************************************************************************************
# // exactBPTInForTokensOut //
# // (per token) //
Expand All @@ -271,7 +263,6 @@ def calc_due_token_protocol_swap_fee_amount(
current_invariant: Decimal,
protocol_swap_fee_percentage: Decimal,
) -> Decimal:

# /*********************************************************************************
# /* protocol_swap_fee_percentage * balanceToken * ( 1 - (previous_invariant / current_invariant) ^ (1 / weightToken))
# *********************************************************************************/
Expand Down
2 changes: 0 additions & 2 deletions balpy/balancerv2cad/src/balancerv2cad/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ def mulUp(a: Decimal, b: Decimal) -> Decimal:

def divUp(a: Decimal, b: Decimal) -> Decimal:
if a * b == 0:

return Decimal(0)
else:
getcontext().prec = 28
Expand All @@ -31,7 +30,6 @@ def divDown(a: Decimal, b: Decimal) -> Decimal:


def complement(a: Decimal) -> Decimal:

return Decimal(1 - a) if a < 1 else Decimal(0)


Expand Down
1 change: 0 additions & 1 deletion balpy/balancerv2cad/tests/unit-test/test_StableMath.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,6 @@ def test_calcTokensOutGivenExactBptIn(stablemath_test):

# TODO give critical results
def test_getTokenBalanceGivenInvariantAndAllOtherBalances(stablemath_test):

# assert StableMath.getTokenBalanceGivenInvariantAndAllOtherBalances(22, [2,3,4,20], 1, 2) == 0.002573235526125192

# self.assertAlmostEqual(
Expand Down
74 changes: 37 additions & 37 deletions balpy/balpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@
from web3.middleware import geth_poa_middleware

from .enums.types import Chain, SwapType

# balpy modules
from . import balancerErrors as be
from .enums.stablePoolJoinExitKind import StablePhantomPoolJoinKind
from .enums.types import Chain, SwapType
from .enums.weightedPoolJoinExitKind import WeightedPoolExitKind, WeightedPoolJoinKind
from .graph.graph import BALANCER_API_ENDPOINT, DEFAULT_SWAP_OPTIONS, TheGraph

BALANCER_API_ENDPOINT = "https://api-v3.balancer.fi/"

class Suppressor(object):
def __enter__(self):
Expand Down Expand Up @@ -163,7 +163,7 @@ class balpy(object):
"id": 8453,
"blockExplorerUrl": "basescan.org",
"balFrontend": "app.balancer.fi/#/base",
}
},
}

apiEndpoint = BALANCER_API_ENDPOINT
Expand Down Expand Up @@ -335,7 +335,6 @@ def __init__(
usingCustomConfig = customConfigFile is not None
customConfig = None
if usingCustomConfig:

# load custom config file if it exists, quit if not
if not os.path.isfile(customConfigFile):
self.ERROR(
Expand Down Expand Up @@ -432,6 +431,10 @@ def __init__(
print()
print("==============================================================")

self.graph = TheGraph(
network, customUrl=BALANCER_API_ENDPOINT, usingJsonEndpoint=True
)

# ======================
# ====Color Printing====
# ======================
Expand Down Expand Up @@ -582,7 +585,6 @@ def erc20GetContract(self, tokenAddress):

@cache
def erc20GetDecimals(self, tokenAddress):

# keep the manually maintained cache since the
# multicaller function can populate it too
if tokenAddress in self.decimals.keys():
Expand Down Expand Up @@ -1771,7 +1773,6 @@ def balJoinPoolInit(
gasEstimateOverride=-1,
gasPriceGweiOverride=-1,
):

if poolDescription["poolType"] in [
"AaveLinearPool", "ERC4626LinearPool"]:
slippageTolerancePercent = 1
Expand Down Expand Up @@ -1826,7 +1827,6 @@ def balLinearPoolInitJoin(
gasEstimateOverride=-1,
gasPriceGweiOverride=-1,
):

phantomBptAddress = self.balPooldIdToAddress(poolId)

batchSwap = {}
Expand Down Expand Up @@ -2414,7 +2414,6 @@ def balLoadArbitraryContract(self, address, abi):

@cache
def balPoolGetAbi(self, poolType):

if poolType == "HighAmpComposableStable":
poolType = "ComposableStable"

Expand Down Expand Up @@ -2968,7 +2967,6 @@ def balQueryBatchSwaps(self, originalSwapsDescription):
swapsDescription = copy.deepcopy(originalSwapsDescription)
vault = self.balLoadContract("Vault")
for swapDescription in swapsDescription:

# do deep copy to avoid modifying the swapDescription in place,
# breaking index remappings
deepCopySwapDescription = copy.deepcopy(swapDescription)
Expand Down Expand Up @@ -3048,15 +3046,10 @@ def balGetApiEndpointSor(self):
)

def balSorQuery(self, data):

query = data["sor"]

# scale amount based on input/output
token_for_decimals = query["orderKind"].lower() + "Token"
amount_scaled = self.erc20ScaleDecimalsWei(
query[token_for_decimals], query["amount"]
)
query["amount"] = int(amount_scaled)
query["orderKind"].lower() + "Token"

# get gas price if not provided
if "gasPrice" not in query.keys():
Expand All @@ -3068,28 +3061,31 @@ def balSorQuery(self, data):
# API gets grumpy when you send it numbers. Send everything as a string
for field in query:
query[field] = str(query[field])
# breakpoint()

response = requests.post(
self.balGetApiEndpointSor(),
headers={"Content-Type": "application/json"},
data=json.dumps(query),
response = self.graph.getSorGetSwapPaths(
chain=self.network,
swapAmount=query["amount"],
tokenIn=query["sellToken"],
tokenOut=query["buyToken"],
swapType=SwapType.EXACT_IN.value,
)

batch_swap = self.balSorResponseToBatchSwapFormat(
data, response.json())
batch_swap = self.balSorResponseToBatchSwapFormat(data, response)

batch_swap["returnAmount"] = response["returnAmount"]

return batch_swap

def _getSorGetSwapPaths(self,
chain: Chain,
swapAmount: float,
tokenIn: str,
tokenOut: str,
swapType: SwapType = SwapType.EXACT_IN,
swapOptions: dict = None,
queryBatchSwap: bool = True,
):
def _getSorGetSwapPaths(
self,
chain: Chain,
swapAmount: float,
tokenIn: str,
tokenOut: str,
swapType: SwapType = SwapType.EXACT_IN,
swapOptions: dict = None,
queryBatchSwap: bool = True,
):
"""
Calls the SOR api from the Balancer to get swap paths.
Args:
Expand All @@ -3102,7 +3098,7 @@ def _getSorGetSwapPaths(self,
queryBatchSwap (bool, optional): Whether to query batch swap. Defaults to True.
Returns:
dict: The response from the SOR.

"""
if not swapOptions:
swapOptions = DEFAULT_SWAP_OPTIONS
Expand Down Expand Up @@ -3134,7 +3130,7 @@ def _getSorGetSwapPaths(self,
assetInIndex,
poolId
}

returnAmount,
tokenInAmount,
tokenOutAmount,
Expand All @@ -3148,13 +3144,17 @@ def _getSorGetSwapPaths(self,
"swapAmount": swapAmount,
"tokenIn": tokenIn,
"tokenOut": tokenOut,
"swapType": swapType,
"swapType": swapType.value,
"queryBatchSwap": queryBatchSwap,
}

response = requests.post(BALANCER_API_ENDPOINT, json={"query": query_string, "variables": params})
response = requests.post(
BALANCER_API_ENDPOINT, json={
"query": query_string, "variables": params}
)

return response.json()["data"]["sorGetSwapPaths"]

return response.json()['data']['sorGetSwapPaths']
def balSorResponseToBatchSwapFormat(self, query, response):
sor = query["sor"]
del query["sor"]
Expand Down Expand Up @@ -3401,7 +3401,7 @@ def generateDeploymentsDocsTable(self):
contracts = ["Contracts", contractDashLine] + contracts
addresses = ["Addresses", addressDashLine] + addresses

for (c, a) in zip(contracts, addresses):
for c, a in zip(contracts, addresses):
cPadded = padWithSpaces(c, longestContractStringLength)
aPadded = padWithSpaces(a, longestAddressStringLength)
line = "| " + cPadded + " | " + aPadded + " |\n"
Expand Down
3 changes: 2 additions & 1 deletion balpy/enums/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from enum import Enum


class Chain(Enum):
MAINNET = "MAINNET"
GNOSIS = "GNOSIS"
Expand All @@ -13,4 +14,4 @@ class Chain(Enum):


class SwapType(Enum):
EXACT_IN = "EXACT_IN"
EXACT_IN = "EXACT_IN"
Loading