-
Notifications
You must be signed in to change notification settings - Fork 44
/
calc_out_amt_given_in.go
73 lines (64 loc) · 2.39 KB
/
calc_out_amt_given_in.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package types
import (
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// CalcOutAmtGivenIn calculates tokens to be swapped out given the provided
// amount and fee deducted, using solveConstantFunctionInvariant.
func (p Pool) CalcOutAmtGivenIn(
ctx sdk.Context,
oracle OracleKeeper,
snapshot *Pool,
tokensIn sdk.Coins,
tokenOutDenom string,
swapFee sdk.Dec,
accountedPool AccountedPoolKeeper,
) (sdk.Coin, error) {
tokenIn, poolAssetIn, poolAssetOut, err := p.parsePoolAssets(tokensIn, tokenOutDenom)
if err != nil {
return sdk.Coin{}, err
}
tokenAmountInAfterFee := sdk.NewDecFromInt(tokenIn.Amount).Mul(sdk.OneDec().Sub(swapFee))
poolTokenInBalance := sdk.NewDecFromInt(poolAssetIn.Token.Amount)
// accounted pool balance
acountedPoolAssetInAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetIn.Token.Denom)
if acountedPoolAssetInAmt.IsPositive() {
poolTokenInBalance = sdk.NewDecFromInt(acountedPoolAssetInAmt)
}
poolTokenOutBalance := sdk.NewDecFromInt(poolAssetOut.Token.Amount)
// accounted pool balance
acountedPoolAssetOutAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetOut.Token.Denom)
if acountedPoolAssetOutAmt.IsPositive() {
poolTokenOutBalance = sdk.NewDecFromInt(acountedPoolAssetOutAmt)
}
poolPostSwapInBalance := poolTokenInBalance.Add(tokenAmountInAfterFee)
outWeight := sdk.NewDecFromInt(poolAssetOut.Weight)
inWeight := sdk.NewDecFromInt(poolAssetIn.Weight)
if p.PoolParams.UseOracle {
_, poolAssetIn, poolAssetOut, err := snapshot.parsePoolAssets(tokensIn, tokenOutDenom)
oracleWeights, err := OraclePoolNormalizedWeights(ctx, oracle, []PoolAsset{poolAssetIn, poolAssetOut})
if err != nil {
return sdk.Coin{}, err
}
inWeight = oracleWeights[0].Weight
outWeight = oracleWeights[1].Weight
}
// deduct swapfee on the tokensIn
// delta balanceOut is positive(tokens inside the pool decreases)
tokenAmountOut, err := solveConstantFunctionInvariant(
poolTokenInBalance,
poolPostSwapInBalance,
inWeight,
poolTokenOutBalance,
outWeight,
)
if err != nil {
return sdk.Coin{}, err
}
// We ignore the decimal component, as we round down the token amount out.
tokenAmountOutInt := tokenAmountOut.TruncateInt()
if !tokenAmountOutInt.IsPositive() {
return sdk.Coin{}, errorsmod.Wrapf(ErrInvalidMathApprox, "token amount must be positive")
}
return sdk.NewCoin(tokenOutDenom, tokenAmountOutInt), nil
}