Skip to content

Commit

Permalink
fix zapper
Browse files Browse the repository at this point in the history
  • Loading branch information
vuonghuuhung committed Sep 27, 2024
1 parent 646d1f6 commit 47ab38b
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 31 deletions.
2 changes: 1 addition & 1 deletion packages/oraiswap-v3/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@oraichain/oraiswap-v3",
"version": "0.1.19",
"version": "0.1.19-beta.1",
"main": "build/index.js",
"files": [
"build/"
Expand Down
5 changes: 3 additions & 2 deletions packages/oraiswap-v3/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ export const populateMessageZapIn = (
message.poolKey = poolKey;
message.tickLowerIndex = lowerTick;
message.tickUpperIndex = upperTick;
message.currentSqrtPrice = sqrtPrice.toString();
message.currentSqrtPrice = sqrtPrice;

if (buildZapInMessageOptions) {
if (buildZapInMessageOptions.isTokenX) {
Expand Down Expand Up @@ -567,7 +567,8 @@ export const calculateMinimumLiquidity = (
const res = buildZapInMessageOptions.isTokenX
? getLiquidityByX(BigInt(actualAmountXReceived.returnAmount), lowerTick, upperTick, sqrtPrice, true)
: getLiquidityByY(BigInt(actualAmountYReceived.returnAmount), lowerTick, upperTick, sqrtPrice, true);
message.minimumLiquidity = res.l ? (BigInt(res.l) * BigInt(100 - slippage)) / 100n : 0n;
const slippageMultiplier = BigInt(Math.floor((100 - slippage) * 1000));
message.minimumLiquidity = res.l ? (BigInt(res.l) * slippageMultiplier) / 100_000n : 0n;
return;
}

Expand Down
42 changes: 26 additions & 16 deletions packages/oraiswap-v3/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ import {
MULTICALL_CONTRACT,
oraichainTokens,
ORAIX_CONTRACT,
OSMO,
OSMOSIS_ORAICHAIN_DENOM,
TokenItemType,
USDT_CONTRACT,
USDT_CONTRACT
} from "@oraichain/oraidex-common";
import { ZapConsumer } from "./zap-consumer";
import { CosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { extractAddress, parsePoolKey } from "./helpers";
import { getTickAtSqrtPrice } from "./wasm/oraiswap_v3_wasm";

async function main() {
const zapper = new ZapConsumer({
Expand All @@ -20,30 +23,37 @@ async function main() {
deviation: 0,
smartRouteConfig: {
swapOptions: {
protocols: ["OraidexV3"],
protocols: ["OraidexV3"]
}
},
}
});

const tokenIn = oraichainTokens.find((t) => t.name === "USDT") as TokenItemType;
const pool = `${USDT_CONTRACT}-${KWT_CONTRACT}-100000000-1`;
const tokenIn = oraichainTokens.find((t) => t.name === "ORAI") as TokenItemType;
const pool = `${OSMOSIS_ORAICHAIN_DENOM}-orai-${(0.3 / 100) * 10 ** 12}-100`;
const poolKey = parsePoolKey(pool);
const poolInfo = await zapper.handler.getPool(poolKey);

// for (let i = 0; i < 10; i++) {
// const poolInfo = await zapper.handler.getPool(poolKey);
// console.log("poolInfo", poolInfo);
// }

const tickSpacing = poolKey.fee_tier.tick_spacing;
const currentTick = (await zapper.handler.getPool(poolKey)).pool.current_tick_index;

// console.log(getTickAtSqrtPrice(314557996917228655710133n, 10));

console.time("processZapInPositionLiquidity");
const res = await zapper.processZapInPositionLiquidity({
pool: poolInfo,
tokenIn: tokenIn as TokenItemType,
amountIn: (10 ** tokenIn.decimals).toString(),
lowerTick: currentTick - tickSpacing * 3,
upperTick: currentTick + tickSpacing * 3,
tokenX: oraichainTokens.find((t) => extractAddress(t) === poolKey.token_x) as TokenItemType,
tokenY: oraichainTokens.find((t) => extractAddress(t) === poolKey.token_y) as TokenItemType,
});
// const res = await zapper.processZapInPositionLiquidity({
// pool: poolInfo,
// tokenIn: tokenIn as TokenItemType,
// amountIn: (10 ** tokenIn.decimals).toString(),
// lowerTick: currentTick - tickSpacing * 3,
// upperTick: currentTick + tickSpacing * 3,
// tokenX: oraichainTokens.find((t) => extractAddress(t) === poolKey.token_x) as TokenItemType,
// tokenY: oraichainTokens.find((t) => extractAddress(t) === poolKey.token_y) as TokenItemType,
// });
console.timeEnd("processZapInPositionLiquidity");
console.dir(res, { depth: null });
// console.dir(res, { depth: null });
}

main().catch(console.error);
2 changes: 1 addition & 1 deletion packages/oraiswap-v3/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ export type ZapInLiquidityResponse = {
tickUpperIndex: number;
minimumLiquidity?: Liquidity;
currentTick: number;
currentSqrtPrice: string;
currentSqrtPrice: SqrtPrice;
};

export type ZapOutLiquidityResponse = {
Expand Down
22 changes: 15 additions & 7 deletions packages/oraiswap-v3/src/zap-consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export class ZapConsumer {
* @returns result of the swap
*/
private async simulateSwapOffChain(poolKey: PoolKey, pool: Pool, route: ActionRoute): Promise<CalculateSwapResult> {
const isXToY = route.tokenOut === poolKey.token_x ? false : true;
const isXToY = route.tokenOut !== poolKey.token_x;
const tickMap = await this._handler.getFullTickmap(poolKey);
const liquidityTicks = await this._handler.getAllLiquidityTicks(poolKey, tickMap);
const liquidityChanges = liquidityTicks.map((tick) => ({
Expand Down Expand Up @@ -269,7 +269,7 @@ export class ZapConsumer {
if (pool.current_tick_index < upperTick && pool.current_tick_index >= lowerTick) {
message.status = ZapInResult.OutRangeHasRouteThroughSelfMayBecomeInRange;
message.currentTick = pool.current_tick_index;
message.currentSqrtPrice = pool.sqrt_price;
message.currentSqrtPrice = BigInt(pool.sqrt_price);
return message;
} else {
message.status = ZapInResult.OutRangeHasRouteThroughSelf;
Expand All @@ -287,7 +287,7 @@ export class ZapConsumer {
* @returns result of the zap in operation
*/
public async processZapInPositionLiquidity(params: {
pool: PoolWithPoolKey;
poolKey: PoolKey;
tokenIn: TokenItemType;
amountIn: string;
lowerTick: number;
Expand All @@ -298,7 +298,8 @@ export class ZapConsumer {
}): Promise<ZapInLiquidityResponse> {
try {
// take params
const { pool, tokenIn, amountIn, lowerTick, upperTick, tokenX, tokenY, slippage = 1 } = params;
const { poolKey, tokenIn, amountIn, lowerTick, upperTick, tokenX, tokenY, slippage = 1 } = params;
const pool = await this._handler.getPool(poolKey);

// init message response
const zapInResult: ZapInLiquidityResponse = {} as ZapInLiquidityResponse;
Expand Down Expand Up @@ -326,7 +327,7 @@ export class ZapConsumer {
}

pool.pool.current_tick_index = zapInSingleSideResult.currentTick;
pool.pool.sqrt_price = zapInSingleSideResult.currentSqrtPrice;
pool.pool.sqrt_price = zapInSingleSideResult.currentSqrtPrice.toString();
zapInResult.status = zapInSingleSideResult.status;
}

Expand Down Expand Up @@ -521,14 +522,21 @@ export class ZapConsumer {
const pool = await this._handler.getPool(position.pool_key);
const { amountX, amountY } = calculateRewardAmounts(pool, position, zapFee);

const tokenX = oraichainTokens.find((t) => extractAddress(t) === pool.pool_key.token_x) as TokenItemType;
const tokenY = oraichainTokens.find((t) => extractAddress(t) === pool.pool_key.token_y) as TokenItemType;

if (!tokenX || !tokenY) {
throw new Error("Token X or Token Y not found in oraichainTokens.");
}

const [xRouteInfo, yRouteInfo] = await this.findZapRoutes([
{
sourceAsset: oraichainTokens.find((t) => extractAddress(t) === pool.pool_key.token_x) as TokenItemType,
sourceAsset: tokenX,
destAsset: tokenOut,
amount: amountX
},
{
sourceAsset: oraichainTokens.find((t) => extractAddress(t) === pool.pool_key.token_y) as TokenItemType,
sourceAsset: tokenY,
destAsset: tokenOut,
amount: amountY
}
Expand Down
12 changes: 8 additions & 4 deletions packages/oraiswap-v3/tests/wasm-bindgen.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,11 @@ describe("wasm bind gen tests", () => {
expect(res).toMatchObject(output);
});

it.each<[string, string, boolean]>([["orai1zyvk3n9r8sax4xvqph97pxuhduqqsqwq6dwzj2", "orai", false]])(
it.each<[string, string, boolean]>([
["orai1zyvk3n9r8sax4xvqph97pxuhduqqsqwq6dwzj2", "orai", false],
["orai1zyvk3n9r8sax4xvqph97pxuhduqqsqwq6dwzj2", "factory/abc/ton", false],
["orai", "orai1zyvk3n9r8sax4xvqph97pxuhduqqsqwq6dwzj2", true]
])(
"isTokenX",
(tokenX, tokenY, expected) => {
const res = isTokenX(tokenX, tokenY);
Expand Down Expand Up @@ -490,7 +494,7 @@ describe("wasm bind gen tests", () => {
it.each<
[
{
x: bigint;
y: bigint;
lower_tick: number;
upper_tick: number;
current_sqrt_price: bigint;
Expand All @@ -504,7 +508,7 @@ describe("wasm bind gen tests", () => {
>([
[
{
x: 1000000n,
y: 1000000n,
lower_tick: -10,
upper_tick: 10,
current_sqrt_price: 10n ** 24n,
Expand All @@ -517,7 +521,7 @@ describe("wasm bind gen tests", () => {
]
])("getLiquidityByY", (input, output) => {
const res = getLiquidityByY(
input.x,
input.y,
input.lower_tick,
input.upper_tick,
input.current_sqrt_price,
Expand Down

0 comments on commit 47ab38b

Please sign in to comment.