@gmx-io/sdk 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +31 -5
  2. package/build/src/configs/batch.d.ts +2 -3
  3. package/build/src/configs/chains.d.ts +2 -1
  4. package/build/src/configs/chains.js +3 -2
  5. package/build/src/configs/markets.js +56 -0
  6. package/build/src/configs/tokens.js +88 -0
  7. package/build/src/modules/accounts/accounts.spec.js +1 -0
  8. package/build/src/modules/markets/index.js +1 -1
  9. package/build/src/modules/markets/markets.spec.js +1 -0
  10. package/build/src/modules/markets/query-builders.js +1 -1
  11. package/build/src/modules/orders/orders.spec.js +1 -0
  12. package/build/src/modules/positions/positions.d.ts +2 -2
  13. package/build/src/modules/positions/positions.js +4 -4
  14. package/build/src/modules/positions/positions.spec.js +2 -1
  15. package/build/src/modules/tokens/tokens.spec.js +1 -0
  16. package/build/src/modules/trades/trades.spec.js +1 -0
  17. package/build/src/prebuilt/hashedKinkModelMarketRatesKeys.json +64 -0
  18. package/build/src/prebuilt/hashedMarketConfigKeys.json +400 -0
  19. package/build/src/prebuilt/hashedMarketValuesKeys.json +120 -0
  20. package/build/src/utils/__tests__/LruCache.spec.js +1 -0
  21. package/build/src/utils/__tests__/bigmath.spec.js +1 -0
  22. package/build/src/utils/__tests__/fees.spec.d.ts +1 -0
  23. package/build/src/utils/__tests__/fees.spec.js +62 -0
  24. package/build/src/utils/__tests__/hash.spec.js +1 -0
  25. package/build/src/utils/__tests__/markets.spec.js +1 -0
  26. package/build/src/utils/__tests__/numbers.spec.js +27 -2
  27. package/build/src/utils/__tests__/objects.spec.js +1 -0
  28. package/build/src/utils/__tests__/positions.spec.js +13 -12
  29. package/build/src/utils/__tests__/prices.spec.js +1 -0
  30. package/build/src/utils/__tests__/referrals.spec.js +1 -0
  31. package/build/src/utils/__tests__/subgraph.spec.js +1 -0
  32. package/build/src/utils/__tests__/tokens.spec.js +1 -0
  33. package/build/src/utils/__tests__/trade.spec.js +1 -0
  34. package/build/src/utils/common.d.ts +6 -1
  35. package/build/src/utils/common.js +9 -1
  36. package/build/src/utils/fees/executionFee.d.ts +33 -0
  37. package/build/src/utils/fees/executionFee.js +46 -0
  38. package/build/src/utils/fees/executionFee.spec.js +1 -1
  39. package/build/src/utils/fees/index.d.ts +1 -1
  40. package/build/src/utils/fees/index.js +17 -10
  41. package/build/src/utils/multicall.js +4 -3
  42. package/build/src/utils/numbers.d.ts +2 -0
  43. package/build/src/utils/numbers.js +28 -0
  44. package/build/src/utils/testUtil.d.ts +14310 -322
  45. package/build/tsconfig.tsbuildinfo +1 -1
  46. package/package.json +6 -29
@@ -0,0 +1,62 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { USD_DECIMALS } from "../../configs/factors";
3
+ import { getFundingFactorPerPeriod } from "../fees";
4
+ import { numberToBigint } from "../numbers";
5
+ const dollar = 10n ** BigInt(USD_DECIMALS);
6
+ const eightMillion = 8000000n;
7
+ const tenMillion = 10000000n;
8
+ function toFactor(percent) {
9
+ const value = parseFloat(percent.replace("%", ""));
10
+ return numberToBigint(value, 30 - 2);
11
+ }
12
+ const second = 1;
13
+ describe("getFundingFactorPerPeriod", () => {
14
+ it("works when short pay, shorts OI bigger", () => {
15
+ const marketInfo = {
16
+ fundingFactorPerSecond: toFactor("50%"),
17
+ longsPayShorts: false,
18
+ longInterestUsd: eightMillion * dollar,
19
+ shortInterestUsd: tenMillion * dollar,
20
+ };
21
+ const forLongs = getFundingFactorPerPeriod(marketInfo, true, second);
22
+ expect(forLongs.toString()).toBe(toFactor("62.5%").toString());
23
+ const forShorts = getFundingFactorPerPeriod(marketInfo, false, second);
24
+ expect(forShorts.toString()).toBe(toFactor("-50%").toString());
25
+ });
26
+ it("works when short pay, longs OI bigger", () => {
27
+ const marketInfo = {
28
+ fundingFactorPerSecond: toFactor("50%"),
29
+ longsPayShorts: false,
30
+ longInterestUsd: tenMillion * dollar,
31
+ shortInterestUsd: eightMillion * dollar,
32
+ };
33
+ const forLongs = getFundingFactorPerPeriod(marketInfo, true, second);
34
+ expect(forLongs.toString()).toBe(toFactor("50%").toString());
35
+ const forShorts = getFundingFactorPerPeriod(marketInfo, false, second);
36
+ expect(forShorts.toString()).toBe(toFactor("-62.5%").toString());
37
+ });
38
+ it("works when long pay, shorts OI bigger", () => {
39
+ const marketInfo = {
40
+ fundingFactorPerSecond: toFactor("50%"),
41
+ longsPayShorts: true,
42
+ longInterestUsd: eightMillion * dollar,
43
+ shortInterestUsd: tenMillion * dollar,
44
+ };
45
+ const forLongs = getFundingFactorPerPeriod(marketInfo, true, second);
46
+ expect(forLongs.toString()).toBe(toFactor("-62.5%").toString());
47
+ const forShorts = getFundingFactorPerPeriod(marketInfo, false, second);
48
+ expect(forShorts.toString()).toBe(toFactor("50%").toString());
49
+ });
50
+ it("works when long pay, longs OI bigger", () => {
51
+ const marketInfo = {
52
+ fundingFactorPerSecond: toFactor("50%"),
53
+ longsPayShorts: true,
54
+ longInterestUsd: tenMillion * dollar,
55
+ shortInterestUsd: eightMillion * dollar,
56
+ };
57
+ const forLongs = getFundingFactorPerPeriod(marketInfo, true, second);
58
+ expect(forLongs.toString()).toBe(toFactor("-50%").toString());
59
+ const forShorts = getFundingFactorPerPeriod(marketInfo, false, second);
60
+ expect(forShorts.toString()).toBe(toFactor("62.5%").toString());
61
+ });
62
+ });
@@ -1,5 +1,6 @@
1
1
  import { hashData, hashString, hashDataMap } from "../hash";
2
2
  import { LRUCache } from "../LruCache";
3
+ import { describe, expect, it } from "vitest";
3
4
  describe("hashData", () => {
4
5
  it("returns a valid hash and caches it", () => {
5
6
  const inputTypes = ["uint256", "string"];
@@ -1,3 +1,4 @@
1
+ import { describe, expect, it } from "vitest";
1
2
  import { getMarketFullName, getMarketIndexName, getMarketPoolName, getContractMarketPrices, getTokenPoolType, getPoolUsdWithoutPnl, getCappedPoolPnl, getMaxLeverageByMinCollateralFactor, getMaxAllowedLeverageByMinCollateralFactor, getOppositeCollateral, getAvailableUsdLiquidityForCollateral, getReservedUsd, getMarketDivisor, getMarketPnl, getOpenInterestUsd, getOpenInterestInTokens, getPriceForPnl, } from "../markets";
2
3
  import { TOKENS } from "../../configs/tokens";
3
4
  import { ARBITRUM } from "../../configs/chains";
@@ -1,5 +1,6 @@
1
- import { PRECISION, BN_ZERO, BN_ONE, BN_NEGATIVE_ONE, expandDecimals, basisPointsToFloat, getBasisPoints, roundUpMagnitudeDivision, applyFactor, } from "../numbers";
1
+ import { describe, expect, it } from "vitest";
2
2
  import { BASIS_POINTS_DIVISOR_BIGINT } from "../../configs/factors";
3
+ import { BN_NEGATIVE_ONE, BN_ONE, BN_ZERO, PRECISION, applyFactor, basisPointsToFloat, bigintToNumber, expandDecimals, getBasisPoints, numberToBigint, roundUpMagnitudeDivision, } from "../numbers";
3
4
  describe("numbers utils", () => {
4
5
  it("constants", () => {
5
6
  // Just to confirm they exist and have no unexpected changes
@@ -30,7 +31,7 @@ describe("numbers utils", () => {
30
31
  expect(getBasisPoints(2n, 1n)).toBe(2n * BASIS_POINTS_DIVISOR_BIGINT);
31
32
  expect(getBasisPoints(1n, 2n)).toBe(5000n);
32
33
  });
33
- it.only("rounds up if remainder != 0 and shouldRoundUp=true", () => {
34
+ it("rounds up if remainder != 0 and shouldRoundUp=true", () => {
34
35
  expect(getBasisPoints(7n, 3n, true)).toBe(23334n);
35
36
  });
36
37
  it("returns same result if remainder=0, even if shouldRoundUp=true", () => {
@@ -53,4 +54,28 @@ describe("numbers utils", () => {
53
54
  expect(applyFactor(value, factor)).toBe(20000n);
54
55
  });
55
56
  });
57
+ it("bigintToNumber", () => {
58
+ expect(bigintToNumber(0n, 30)).toEqual(0);
59
+ expect(bigintToNumber(1n, 30)).toEqual(1e-30);
60
+ expect(bigintToNumber(PRECISION, 30)).toEqual(1);
61
+ expect(bigintToNumber(PRECISION * 100n, 30)).toEqual(100);
62
+ expect(bigintToNumber(PRECISION * 2n, 30)).toEqual(2);
63
+ expect(bigintToNumber(PRECISION / 2n, 30)).toEqual(0.5);
64
+ expect(bigintToNumber(1123456n, 6)).toEqual(1.123456);
65
+ expect(bigintToNumber(-1123456n, 6)).toEqual(-1.123456);
66
+ });
67
+ it("numberToBigint", () => {
68
+ expect(numberToBigint(0, 30)).toEqual(0n);
69
+ expect(numberToBigint(1e-30, 30)).toEqual(1n);
70
+ expect(numberToBigint(-1e-30, 30)).toEqual(-1n);
71
+ expect(numberToBigint(1, 30)).toEqual(PRECISION);
72
+ expect(numberToBigint(100, 30)).toEqual(PRECISION * 100n);
73
+ expect(numberToBigint(2, 30)).toEqual(PRECISION * 2n);
74
+ expect(numberToBigint(0.5, 30)).toEqual(PRECISION / 2n);
75
+ expect(numberToBigint(-0.5, 30)).toEqual(-PRECISION / 2n);
76
+ expect(numberToBigint(1.1234567, 6)).toEqual(1123456n);
77
+ expect(numberToBigint(1.12345678, 6)).toEqual(1123456n);
78
+ expect(numberToBigint(1.123456789, 6)).toEqual(1123456n);
79
+ expect(numberToBigint(-1.123456789, 6)).toEqual(-1123456n);
80
+ });
56
81
  });
@@ -1,3 +1,4 @@
1
+ import { describe, expect, it } from "vitest";
1
2
  import { setByKey, updateByKey, getByKey } from "../objects";
2
3
  describe("setByKey", () => {
3
4
  it("should set a key in an object", () => {
@@ -1,22 +1,23 @@
1
+ import { describe, expect, it, vi, beforeEach } from "vitest";
1
2
  import { bigMath } from "../bigmath";
2
3
  import { getPositionFee, getPriceImpactForPosition } from "../fees";
3
4
  import { getCappedPoolPnl, getMarketPnl, getPoolUsdWithoutPnl } from "../markets";
4
5
  import { getEntryPrice, getLeverage, getLiquidationPrice, getPositionKey, getPositionNetValue, getPositionPendingFeesUsd, getPositionPnlUsd, getPositionValueUsd, parsePositionKey, } from "../positions";
5
6
  import { convertToUsd, getIsEquivalentTokens } from "../tokens";
6
- jest.mock("../markets", () => ({
7
- ...jest.requireActual("../markets"),
8
- getMarketPnl: jest.fn(),
9
- getPoolUsdWithoutPnl: jest.fn(),
10
- getCappedPoolPnl: jest.fn(),
7
+ vi.mock("../markets", () => ({
8
+ ...vi.importActual("../markets"),
9
+ getMarketPnl: vi.fn(),
10
+ getPoolUsdWithoutPnl: vi.fn(),
11
+ getCappedPoolPnl: vi.fn(),
11
12
  }));
12
- jest.mock("../tokens", () => ({
13
- ...jest.requireActual("../tokens"),
14
- convertToUsd: jest.fn(),
15
- getIsEquivalentTokens: jest.fn(),
13
+ vi.mock("../tokens", () => ({
14
+ ...vi.importActual("../tokens"),
15
+ convertToUsd: vi.fn(),
16
+ getIsEquivalentTokens: vi.fn(),
16
17
  }));
17
- jest.mock("../fees", () => ({
18
- getPositionFee: jest.fn(),
19
- getPriceImpactForPosition: jest.fn(),
18
+ vi.mock("../fees", () => ({
19
+ getPositionFee: vi.fn(),
20
+ getPriceImpactForPosition: vi.fn(),
20
21
  }));
21
22
  describe("getPositionKey", () => {
22
23
  it("returns key in expected format", () => {
@@ -1,3 +1,4 @@
1
+ import { describe, expect, it } from "vitest";
1
2
  import { getMarkPrice, getShouldUseMaxPrice, getTriggerThresholdType } from "../prices";
2
3
  import { OrderType } from "../../types/orders";
3
4
  import { TriggerThresholdType } from "../../types/trade";
@@ -1,3 +1,4 @@
1
+ import { describe, expect, it } from "vitest";
1
2
  import { decodeReferralCode, encodeReferralCode, MAX_REFERRAL_CODE_LENGTH } from "../referrals";
2
3
  import { zeroHash } from "viem";
3
4
  describe("utils/referrals", () => {
@@ -1,3 +1,4 @@
1
+ import { describe, expect, it } from "vitest";
1
2
  import { buildFiltersBody } from "../subgraph";
2
3
  describe("buildFiltersBody", () => {
3
4
  it("should return empty object if no filters", () => {
@@ -1,3 +1,4 @@
1
+ import { describe, expect, it } from "vitest";
1
2
  import { parseContractPrice, convertToContractPrice, convertToContractTokenPrices, convertToTokenAmount, convertToUsd, getMidPrice, getIsEquivalentTokens, getTokenData, getTokensRatioByAmounts, } from "../tokens";
2
3
  import { expandDecimals, PRECISION } from "../numbers";
3
4
  import { TOKENS } from "../../configs/tokens";
@@ -1,3 +1,4 @@
1
+ import { describe, expect, it } from "vitest";
1
2
  import { applySlippageToMinOut, applySlippageToPrice } from "../trade";
2
3
  describe("applySlippageToPrice", () => {
3
4
  it("applies positive slippage if getShouldUseMaxPrice is true", () => {
@@ -1,2 +1,7 @@
1
- export declare const sleep: (ms: number) => Promise<unknown>;
1
+ declare global {
2
+ interface AbortSignal {
3
+ addEventListener(type: "abort", listener: () => void): void;
4
+ }
5
+ }
6
+ export declare const sleep: (ms: number, abortSignal?: AbortSignal) => Promise<unknown>;
2
7
  export declare const TIMEZONE_OFFSET_SEC: number;
@@ -1,2 +1,10 @@
1
- export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1
+ export const sleep = (ms, abortSignal) => new Promise((resolve) => {
2
+ const timeout = setTimeout(resolve, ms);
3
+ if (abortSignal) {
4
+ abortSignal.addEventListener("abort", () => {
5
+ clearTimeout(timeout);
6
+ resolve(undefined);
7
+ });
8
+ }
9
+ });
2
10
  export const TIMEZONE_OFFSET_SEC = -new Date().getTimezoneOffset() * 60;
@@ -21,3 +21,36 @@ export declare function estimateExecuteSwapOrderGasLimit(gasLimits: GasLimitsCon
21
21
  swapsCount: number;
22
22
  callbackGasLimit?: bigint;
23
23
  }): bigint;
24
+ /**
25
+ * Only GM deposits. Do not confuse with increase with zero delta size.
26
+ *
27
+ * Copy from contract: `estimateExecuteDepositGasLimit`
28
+ */
29
+ export declare function estimateExecuteDepositGasLimit(gasLimits: GasLimitsConfig, deposit: {
30
+ longTokenSwapsCount?: number;
31
+ shortTokenSwapsCount?: number;
32
+ callbackGasLimit?: bigint;
33
+ }): bigint;
34
+ export declare function estimateExecuteGlvDepositGasLimit(gasLimits: GasLimitsConfig, { marketsCount, isMarketTokenDeposit, }: {
35
+ isMarketTokenDeposit: any;
36
+ marketsCount: bigint;
37
+ initialLongTokenAmount: bigint;
38
+ initialShortTokenAmount: bigint;
39
+ }): bigint;
40
+ export declare function estimateExecuteGlvWithdrawalGasLimit(gasLimits: GasLimitsConfig, { marketsCount, }: {
41
+ marketsCount: bigint;
42
+ }): bigint;
43
+ /**
44
+ * Only GM withdrawals. Do not confuse with decrease with zero delta size.
45
+ *
46
+ * Copy from contract: `estimateExecuteWithdrawalGasLimit`
47
+ */
48
+ export declare function estimateExecuteWithdrawalGasLimit(gasLimits: GasLimitsConfig, withdrawal: {
49
+ callbackGasLimit?: bigint;
50
+ }): bigint;
51
+ /**
52
+ * Copy from contract: `estimateExecuteShiftGasLimit`
53
+ */
54
+ export declare function estimateExecuteShiftGasLimit(gasLimits: GasLimitsConfig, shift: {
55
+ callbackGasLimit?: bigint;
56
+ }): bigint;
@@ -51,3 +51,49 @@ export function estimateExecuteSwapOrderGasLimit(gasLimits, order) {
51
51
  const swapsCount = BigInt(order.swapsCount);
52
52
  return gasLimits.swapOrder + gasPerSwap * swapsCount + (order.callbackGasLimit ?? 0n);
53
53
  }
54
+ /**
55
+ * Only GM deposits. Do not confuse with increase with zero delta size.
56
+ *
57
+ * Copy from contract: `estimateExecuteDepositGasLimit`
58
+ */
59
+ export function estimateExecuteDepositGasLimit(gasLimits, deposit) {
60
+ const gasPerSwap = gasLimits.singleSwap;
61
+ const swapsCount = BigInt((deposit.longTokenSwapsCount ?? 0) + (deposit.shortTokenSwapsCount ?? 0));
62
+ const gasForSwaps = swapsCount * gasPerSwap;
63
+ return gasLimits.depositToken + (deposit.callbackGasLimit ?? 0n) + gasForSwaps;
64
+ }
65
+ export function estimateExecuteGlvDepositGasLimit(gasLimits, { marketsCount, isMarketTokenDeposit, }) {
66
+ const gasPerGlvPerMarket = gasLimits.glvPerMarketGasLimit;
67
+ const gasForGlvMarkets = gasPerGlvPerMarket * marketsCount;
68
+ const glvDepositGasLimit = gasLimits.glvDepositGasLimit;
69
+ const gasLimit = glvDepositGasLimit + gasForGlvMarkets;
70
+ if (isMarketTokenDeposit) {
71
+ return gasLimit;
72
+ }
73
+ return gasLimit + gasLimits.depositToken;
74
+ }
75
+ export function estimateExecuteGlvWithdrawalGasLimit(gasLimits, { marketsCount, }) {
76
+ const gasPerGlvPerMarket = gasLimits.glvPerMarketGasLimit;
77
+ const gasForGlvMarkets = gasPerGlvPerMarket * marketsCount;
78
+ const glvWithdrawalGasLimit = gasLimits.glvWithdrawalGasLimit;
79
+ const gasLimit = glvWithdrawalGasLimit + gasForGlvMarkets;
80
+ return gasLimit + gasLimits.withdrawalMultiToken;
81
+ }
82
+ /**
83
+ * Only GM withdrawals. Do not confuse with decrease with zero delta size.
84
+ *
85
+ * Copy from contract: `estimateExecuteWithdrawalGasLimit`
86
+ */
87
+ export function estimateExecuteWithdrawalGasLimit(gasLimits, withdrawal) {
88
+ // Swap is not used but supported in the contract.
89
+ // const gasPerSwap = gasLimits.singleSwap;
90
+ // const swapsCount = 0n;
91
+ // const gasForSwaps = swapsCount * gasPerSwap;
92
+ return gasLimits.withdrawalMultiToken + (withdrawal.callbackGasLimit ?? 0n);
93
+ }
94
+ /**
95
+ * Copy from contract: `estimateExecuteShiftGasLimit`
96
+ */
97
+ export function estimateExecuteShiftGasLimit(gasLimits, shift) {
98
+ return gasLimits.shift + (shift.callbackGasLimit ?? 0n);
99
+ }
@@ -1,8 +1,8 @@
1
+ import { describe, expect, it } from "vitest";
1
2
  import { NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
2
3
  import { getExecutionFee } from "./executionFee";
3
4
  import { expandDecimals } from "../numbers";
4
5
  import { ARBITRUM } from "../../configs/chains";
5
- const serializeBigInt = (e) => JSON.stringify(e, (t, e) => (typeof e === "bigint" ? e.toString() : e), 2);
6
6
  describe("getExecutionFee", () => {
7
7
  const chainId = ARBITRUM;
8
8
  const gasLimits = {
@@ -1,9 +1,9 @@
1
1
  import { FeeItem } from "../../types/fees";
2
2
  import { MarketInfo } from "../../types/markets";
3
3
  import { SwapStats } from "../../types/trade";
4
- export * from "./priceImpact";
5
4
  export * from "./estimateOraclePriceCount";
6
5
  export * from "./executionFee";
6
+ export * from "./priceImpact";
7
7
  export declare function getSwapFee(marketInfo: MarketInfo, swapAmount: bigint, forPositiveImpact: boolean): bigint;
8
8
  export declare function getPositionFee(marketInfo: MarketInfo, sizeDeltaUsd: bigint, forPositiveImpact: boolean, referralInfo: {
9
9
  totalRebateFactor: bigint;
@@ -1,9 +1,9 @@
1
1
  import { HIGH_PRICE_IMPACT_BPS } from "../../configs/factors";
2
2
  import { bigMath } from "../bigmath";
3
3
  import { applyFactor, getBasisPoints, PRECISION } from "../numbers";
4
- export * from "./priceImpact";
5
4
  export * from "./estimateOraclePriceCount";
6
5
  export * from "./executionFee";
6
+ export * from "./priceImpact";
7
7
  export function getSwapFee(marketInfo, swapAmount, forPositiveImpact) {
8
8
  const factor = forPositiveImpact
9
9
  ? marketInfo.swapFeeFactorForPositiveImpact
@@ -31,18 +31,25 @@ export function getPositionFee(marketInfo, sizeDeltaUsd, forPositiveImpact, refe
31
31
  }
32
32
  export function getFundingFactorPerPeriod(marketInfo, isLong, periodInSeconds) {
33
33
  const { fundingFactorPerSecond, longsPayShorts, longInterestUsd, shortInterestUsd } = marketInfo;
34
- const isLargerSide = isLong ? longsPayShorts : !longsPayShorts;
35
- let factorPerSecond;
36
- if (isLargerSide) {
37
- factorPerSecond = fundingFactorPerSecond * -1n;
34
+ const largerInterestUsd = bigMath.max(longInterestUsd, shortInterestUsd);
35
+ const payingInterestUsd = longsPayShorts ? longInterestUsd : shortInterestUsd;
36
+ const receivingInterestUsd = longsPayShorts ? shortInterestUsd : longInterestUsd;
37
+ let fundingForPayingSide = 0n;
38
+ if (payingInterestUsd !== 0n) {
39
+ fundingForPayingSide = bigMath.mulDiv(fundingFactorPerSecond, largerInterestUsd, payingInterestUsd);
40
+ }
41
+ let fundingForReceivingSide = 0n;
42
+ if (receivingInterestUsd !== 0n) {
43
+ fundingForReceivingSide = bigMath.mulDiv(fundingForPayingSide, payingInterestUsd, receivingInterestUsd);
44
+ }
45
+ if ((longsPayShorts && isLong) || (!longsPayShorts && !isLong)) {
46
+ // paying side
47
+ return fundingForPayingSide * BigInt(periodInSeconds) * -1n;
38
48
  }
39
49
  else {
40
- const largerInterestUsd = longsPayShorts ? longInterestUsd : shortInterestUsd;
41
- const smallerInterestUsd = longsPayShorts ? shortInterestUsd : longInterestUsd;
42
- const ratio = smallerInterestUsd > 0 ? bigMath.mulDiv(largerInterestUsd, PRECISION, smallerInterestUsd) : 0n;
43
- factorPerSecond = applyFactor(ratio, fundingFactorPerSecond);
50
+ // receiving side
51
+ return fundingForReceivingSide * BigInt(periodInSeconds);
44
52
  }
45
- return factorPerSecond * BigInt(periodInSeconds);
46
53
  }
47
54
  export function getFundingFeeRateUsd(marketInfo, isLong, sizeInUsd, periodInSeconds) {
48
55
  const factor = getFundingFactorPerPeriod(marketInfo, isLong, periodInSeconds);
@@ -52,8 +52,6 @@ export class Multicall {
52
52
  });
53
53
  });
54
54
  });
55
- // const providerUrl = rpcUrl;
56
- // const rpcProviderName = getProviderNameFromUrl(providerUrl);
57
55
  const processResponse = (response) => {
58
56
  const multicallResult = {
59
57
  success: true,
@@ -94,14 +92,17 @@ export class Multicall {
94
92
  });
95
93
  return multicallResult;
96
94
  };
95
+ const timeoutController = new AbortController();
97
96
  const result = await Promise.race([
98
97
  client.multicall({ contracts: encodedPayload }),
99
- sleep(maxTimeout).then(() => Promise.reject(new Error("multicall timeout"))),
98
+ sleep(maxTimeout, timeoutController.signal).then(() => Promise.reject(new Error("multicall timeout"))),
100
99
  ])
101
100
  .then((response) => {
101
+ timeoutController.abort();
102
102
  return processResponse(response);
103
103
  })
104
104
  .catch((_viemError) => {
105
+ timeoutController.abort();
105
106
  const e = new Error(_viemError.message.slice(0, 150));
106
107
  /* eslint-disable-next-line */
107
108
  console.error(e);
@@ -7,3 +7,5 @@ export declare function basisPointsToFloat(basisPoints: bigint): bigint;
7
7
  export declare function getBasisPoints(numerator: bigint, denominator: bigint, shouldRoundUp?: boolean): bigint;
8
8
  export declare function roundUpMagnitudeDivision(a: bigint, b: bigint): bigint;
9
9
  export declare function applyFactor(value: bigint, factor: bigint): bigint;
10
+ export declare function numberToBigint(value: number, decimals: number): bigint;
11
+ export declare function bigintToNumber(value: bigint, decimals: number): number;
@@ -28,3 +28,31 @@ export function roundUpMagnitudeDivision(a, b) {
28
28
  export function applyFactor(value, factor) {
29
29
  return (value * factor) / PRECISION;
30
30
  }
31
+ export function numberToBigint(value, decimals) {
32
+ const negative = value < 0;
33
+ if (negative)
34
+ value *= -1;
35
+ const int = Math.trunc(value);
36
+ let frac = value - int;
37
+ let res = BigInt(int);
38
+ for (let i = 0; i < decimals; i++) {
39
+ res *= 10n;
40
+ if (frac !== 0) {
41
+ frac *= 10;
42
+ const fracInt = Math.trunc(frac);
43
+ res += BigInt(fracInt);
44
+ frac -= fracInt;
45
+ }
46
+ }
47
+ return negative ? -res : res;
48
+ }
49
+ export function bigintToNumber(value, decimals) {
50
+ const negative = value < 0;
51
+ if (negative)
52
+ value *= -1n;
53
+ const precision = 10n ** BigInt(decimals);
54
+ const int = value / precision;
55
+ const frac = value % precision;
56
+ const num = parseFloat(`${int}.${frac.toString().padStart(decimals, "0")}`);
57
+ return negative ? -num : num;
58
+ }