StableMath.py

All functions in this class are static methods and can be called without instantiation.

calculate_invariant

Computes the invariant given the current balances, using the Newton-Raphson approximation.

def calculate_invariant(amplificationParameter: Decimal, balances: list) -> Decimal:
        
        bal_sum = 0
        for bal in balances:
            bal_sum += bal
        num_tokens = len(balances)
        if(bal_sum==0):
            return 0
        prevInvariant = 0
        invariant = bal_sum
        ampTimesTotal = amplificationParameter*num_tokens
        for i in range(255):
            P_D = num_tokens*balances[0]
            for j in range(1, num_tokens):
                P_D = ceil(((P_D*balances[j])*num_tokens)/invariant)
            prevInvariant = invariant

            invariant = ceil(((num_tokens*invariant)*invariant + (ampTimesTotal*bal_sum)*P_D) / ((num_tokens + 1)*invariant + (ampTimesTotal - 1)*P_D))
            if(invariant > prevInvariant):
                if(invariant - prevInvariant <= 1):
                    break
            elif(prevInvariant - invariant <= 1):
                break
        return Decimal(invariant)

calc_out_given_in

Computes how many tokens can be taken out of a pool if tokenAmountIn are sent, given the current balances.

A - amount of tokens (in and out) B - token balance in the pool (for "token in" and "token out") W - weights of these tokens inside the pool (for "token in" and "token out") - a

calc_in_given_out

This formula is used for the calculation of how many tokens "in" you need to send to the pool to receive the desired number of tokens "out" back.

calc_bpt_in_given_exact_tokens_out

calc_bpt_out_given_exact_tokens_in

calc_tokens_in_given_exact_bpt_out

calc_tokens_out_given_exact_bpt_in

get_token_balance_given_invariant_and_all_other_balances

Last updated

Was this helpful?