-
Notifications
You must be signed in to change notification settings - Fork 32
/
swap.ts
229 lines (198 loc) · 6.12 KB
/
swap.ts
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import { Asset } from "@chain-registry/types";
import { BigNumber } from "bignumber.js";
import { CoinDenom, Trade, PrettyPair } from "./types";
import { symbolToOsmoDenom } from "./utils";
import Long from "long";
import { SwapAmountInRoute } from "osmojs/dist/codegen/osmosis/poolmanager/v1beta1/swap_route";
import { Pool } from "osmojs/dist/codegen/osmosis/gamm/pool-models/balancer/balancerPool";
import { Coin } from "osmojs/dist/codegen/cosmos/base/v1beta1/coin";
export const routesThroughPools = ({
denom,
trade,
pairs,
}: {
denom: CoinDenom;
trade: Trade;
pairs: PrettyPair[];
}): SwapAmountInRoute[] => {
const sellPool = pairs.find(
(pair) =>
(pair.baseAddress == trade.sell.denom && pair.quoteAddress == denom) ||
(pair.quoteAddress == trade.sell.denom && pair.baseAddress == denom)
);
const buyPool = pairs.find(
(pair) =>
(pair.baseAddress == denom && pair.quoteAddress == trade.buy.denom) ||
(pair.quoteAddress == denom && pair.baseAddress == trade.buy.denom)
);
if (sellPool && buyPool) {
const routes = [
{
poolId: BigInt(sellPool.poolId),
tokenOutDenom: denom,
},
{
poolId: BigInt(buyPool.poolId),
tokenOutDenom: trade.buy.denom,
},
];
return routes;
}
return [];
};
export const getRoutesForTrade = (
assets: Asset[],
{
trade,
pairs,
}: {
trade: Trade;
pairs: PrettyPair[];
}
): SwapAmountInRoute[] => {
const directPool = pairs.find(
(pair) =>
(pair.baseAddress == trade.sell.denom &&
pair.quoteAddress == trade.buy.denom) ||
(pair.quoteAddress == trade.sell.denom &&
pair.baseAddress == trade.buy.denom)
);
if (directPool) {
return [
{
poolId: BigInt(directPool.poolId),
tokenOutDenom: trade.buy.denom,
},
];
}
const osmoRoutes = routesThroughPools({
denom: "uosmo",
trade,
pairs,
});
if (osmoRoutes.length === 2) return osmoRoutes;
const atomRoutes = routesThroughPools({
denom: symbolToOsmoDenom(assets, "ATOM"),
trade,
pairs,
});
if (atomRoutes.length === 2) return atomRoutes;
return [];
};
export const calcAmountWithSlippage = (
amount: string,
slippage: number | string
) => {
const remainingPercentage = new BigNumber(100).minus(slippage).div(100);
return new BigNumber(amount).multipliedBy(remainingPercentage).toString();
};
const one = new BigNumber(1);
const getPoolAsset = (pool: Pool, denom: string) => {
const poolAsset = pool.poolAssets.find(
(asset) => asset?.token && asset.token.denom === denom
);
if (!poolAsset) {
throw new Error(
`Pool ${pool.id} doesn't have the pool asset for ${denom}`
);
}
return { denom, weight: poolAsset.weight, amount: poolAsset.token!.amount };
};
export const calcSpotPrice = (
tokenBalanceIn: BigNumber,
tokenWeightIn: BigNumber,
tokenBalanceOut: BigNumber,
tokenWeightOut: BigNumber,
swapFee: BigNumber
): BigNumber => {
const number = tokenBalanceIn.div(tokenWeightIn);
const denom = tokenBalanceOut.div(tokenWeightOut);
const scale = one.div(one.minus(swapFee));
return number.div(denom).multipliedBy(scale);
};
export const calcOutGivenIn = (
tokenBalanceIn: BigNumber,
tokenWeightIn: BigNumber,
tokenBalanceOut: BigNumber,
tokenWeightOut: BigNumber,
tokenAmountIn: BigNumber,
swapFee: BigNumber
): BigNumber => {
const weightRatio = tokenWeightIn.div(tokenWeightOut);
let adjustedIn = one.minus(swapFee);
adjustedIn = tokenAmountIn.multipliedBy(adjustedIn);
const y = tokenBalanceIn.div(tokenBalanceIn.plus(adjustedIn));
const foo = y.pow(weightRatio);
const bar = one.minus(foo);
return tokenBalanceOut.multipliedBy(bar);
};
export const calcInGivenOut = (
tokenBalanceIn: BigNumber,
tokenWeightIn: BigNumber,
tokenBalanceOut: BigNumber,
tokenWeightOut: BigNumber,
tokenAmountOut: BigNumber,
swapFee: BigNumber
): BigNumber => {
const weightRatio = tokenWeightOut.div(tokenWeightIn);
const diff = tokenBalanceOut.minus(tokenAmountOut);
const y = tokenBalanceOut.div(diff);
let foo = y.pow(weightRatio);
foo = foo.minus(one);
const tokenAmountIn = one.minus(swapFee);
return tokenBalanceIn.multipliedBy(foo).div(tokenAmountIn);
};
export const calcPriceImpactGivenIn = (
tokenIn: Coin,
tokenOutDenom: string,
pool: Pool
) => {
const inPoolAsset = getPoolAsset(pool, tokenIn.denom);
const outPoolAsset = getPoolAsset(pool, tokenOutDenom);
const swapFee = new BigNumber(pool.poolParams?.swapFee || 0).shiftedBy(-18);
const beforeSpotPriceInOverOut = calcSpotPrice(
new BigNumber(inPoolAsset.amount),
new BigNumber(inPoolAsset.weight),
new BigNumber(outPoolAsset.amount),
new BigNumber(outPoolAsset.weight),
swapFee
);
const tokenOutAmount = calcOutGivenIn(
new BigNumber(inPoolAsset.amount),
new BigNumber(inPoolAsset.weight),
new BigNumber(outPoolAsset.amount),
new BigNumber(outPoolAsset.weight),
new BigNumber(tokenIn.amount),
swapFee
).decimalPlaces(0);
const effectivePrice = new BigNumber(tokenIn.amount).div(tokenOutAmount);
const priceImpact = effectivePrice.div(beforeSpotPriceInOverOut).minus(one);
return priceImpact.toString();
};
export const calcPriceImpactGivenOut = (
tokenOut: Coin,
tokenInDenom: string,
pool: Pool
) => {
const inPoolAsset = getPoolAsset(pool, tokenInDenom);
const outPoolAsset = getPoolAsset(pool, tokenOut.denom);
const swapFee = new BigNumber(pool.poolParams?.swapFee || 0).shiftedBy(-18);
const beforeSpotPriceInOverOut = calcSpotPrice(
new BigNumber(inPoolAsset.amount),
new BigNumber(inPoolAsset.weight),
new BigNumber(outPoolAsset.amount),
new BigNumber(outPoolAsset.weight),
swapFee
);
const tokenInAmount = calcInGivenOut(
new BigNumber(inPoolAsset.amount),
new BigNumber(inPoolAsset.weight),
new BigNumber(outPoolAsset.amount),
new BigNumber(outPoolAsset.weight),
new BigNumber(tokenOut.amount),
swapFee
).decimalPlaces(0);
const effectivePrice = new BigNumber(tokenInAmount).div(tokenOut.amount);
const priceImpact = effectivePrice.div(beforeSpotPriceInOverOut).minus(one);
return priceImpact.toString();
};