timelock-sdk 0.0.80 → 0.0.82

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.
package/dist/client.d.cts CHANGED
@@ -1,3 +1,3 @@
1
1
  import "./uniswapMathLens-CK8C7WOt.cjs";
2
- import { B as useOptionPnl, F as useOptionTimeline, H as useMaxPositionSize, I as useSetOperatorPerms, L as useUserOperators, P as OptionTimelineData, R as useExtendOption, V as useMintOption, a as batchGetAmountsFromLiquidity, at as useExerciseOption, c as useLiquidityBlocks, ct as useClosedUserOptions, d as usePriceAtTick, dt as useTimelockConfig, f as UniswapPoolData, h as useCurrentPrice, i as useVaultData, it as useMarketData, l as useBurnLiquidity, lt as TimelockMarketProvider, m as useCurrentTick, n as useLens, o as useMintLiquidity, ot as OptionData, p as usePoolData, r as useVaultTVL, s as LiquidityBlockData, st as useActiveUserOptions, t as useApproval, u as usePriceHistory, ut as useCurrentMarket, z as useOptionPremium } from "./client-D_t-2-g5.cjs";
3
- export { LiquidityBlockData, OptionData, OptionTimelineData, TimelockMarketProvider, UniswapPoolData, batchGetAmountsFromLiquidity, useActiveUserOptions, useApproval, useBurnLiquidity, useClosedUserOptions, useCurrentMarket, useCurrentPrice, useCurrentTick, useExerciseOption, useExtendOption, useLens, useLiquidityBlocks, useMarketData, useMaxPositionSize, useMintLiquidity, useMintOption, useOptionPnl, useOptionPremium, useOptionTimeline, usePoolData, usePriceAtTick, usePriceHistory, useSetOperatorPerms, useTimelockConfig, useUserOperators, useVaultData, useVaultTVL };
2
+ import { B as useOptionTimeline, F as useUserOperators, G as useMaxPositionSize, H as useOptionPremium, I as usePerpsOperator, L as useClosePerp, P as useSetOperatorPerms, R as useMintPerp, U as useOptionPnl, V as useExtendOption, W as useMintOption, a as batchGetAmountsFromLiquidity, c as useLiquidityBlocks, ct as useExerciseOption, d as usePriceAtTick, dt as useClosedUserOptions, f as UniswapPoolData, ft as TimelockProvider, h as useCurrentPrice, i as useVaultData, l as useBurnLiquidity, lt as OptionData, m as useCurrentTick, mt as useTimelockConfig, n as useLens, o as useMintLiquidity, p as usePoolData, pt as useCurrentMarket, r as useVaultTVL, s as LiquidityBlockData, st as useMarketData, t as useApproval, u as usePriceHistory, ut as useActiveUserOptions, z as OptionTimelineData } from "./client-GoHd57RL.cjs";
3
+ export { LiquidityBlockData, OptionData, OptionTimelineData, TimelockProvider, UniswapPoolData, batchGetAmountsFromLiquidity, useActiveUserOptions, useApproval, useBurnLiquidity, useClosePerp, useClosedUserOptions, useCurrentMarket, useCurrentPrice, useCurrentTick, useExerciseOption, useExtendOption, useLens, useLiquidityBlocks, useMarketData, useMaxPositionSize, useMintLiquidity, useMintOption, useMintPerp, useOptionPnl, useOptionPremium, useOptionTimeline, usePerpsOperator, usePoolData, usePriceAtTick, usePriceHistory, useSetOperatorPerms, useTimelockConfig, useUserOperators, useVaultData, useVaultTVL };
package/dist/client.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import "./uniswapMathLens-C54iWXpi.js";
2
- import { B as useOptionPnl, F as useOptionTimeline, H as useMaxPositionSize, I as useSetOperatorPerms, L as useUserOperators, P as OptionTimelineData, R as useExtendOption, V as useMintOption, a as batchGetAmountsFromLiquidity, at as useExerciseOption, c as useLiquidityBlocks, ct as useClosedUserOptions, d as usePriceAtTick, dt as useTimelockConfig, f as UniswapPoolData, h as useCurrentPrice, i as useVaultData, it as useMarketData, l as useBurnLiquidity, lt as TimelockMarketProvider, m as useCurrentTick, n as useLens, o as useMintLiquidity, ot as OptionData, p as usePoolData, r as useVaultTVL, s as LiquidityBlockData, st as useActiveUserOptions, t as useApproval, u as usePriceHistory, ut as useCurrentMarket, z as useOptionPremium } from "./client-euowNGgz.js";
3
- export { LiquidityBlockData, OptionData, OptionTimelineData, TimelockMarketProvider, UniswapPoolData, batchGetAmountsFromLiquidity, useActiveUserOptions, useApproval, useBurnLiquidity, useClosedUserOptions, useCurrentMarket, useCurrentPrice, useCurrentTick, useExerciseOption, useExtendOption, useLens, useLiquidityBlocks, useMarketData, useMaxPositionSize, useMintLiquidity, useMintOption, useOptionPnl, useOptionPremium, useOptionTimeline, usePoolData, usePriceAtTick, usePriceHistory, useSetOperatorPerms, useTimelockConfig, useUserOperators, useVaultData, useVaultTVL };
2
+ import { B as useOptionTimeline, F as useUserOperators, G as useMaxPositionSize, H as useOptionPremium, I as usePerpsOperator, L as useClosePerp, P as useSetOperatorPerms, R as useMintPerp, U as useOptionPnl, V as useExtendOption, W as useMintOption, a as batchGetAmountsFromLiquidity, c as useLiquidityBlocks, ct as useExerciseOption, d as usePriceAtTick, dt as useClosedUserOptions, f as UniswapPoolData, ft as TimelockProvider, h as useCurrentPrice, i as useVaultData, l as useBurnLiquidity, lt as OptionData, m as useCurrentTick, mt as useTimelockConfig, n as useLens, o as useMintLiquidity, p as usePoolData, pt as useCurrentMarket, r as useVaultTVL, s as LiquidityBlockData, st as useMarketData, t as useApproval, u as usePriceHistory, ut as useActiveUserOptions, z as OptionTimelineData } from "./client-BjjoSITU.js";
3
+ export { LiquidityBlockData, OptionData, OptionTimelineData, TimelockProvider, UniswapPoolData, batchGetAmountsFromLiquidity, useActiveUserOptions, useApproval, useBurnLiquidity, useClosePerp, useClosedUserOptions, useCurrentMarket, useCurrentPrice, useCurrentTick, useExerciseOption, useExtendOption, useLens, useLiquidityBlocks, useMarketData, useMaxPositionSize, useMintLiquidity, useMintOption, useMintPerp, useOptionPnl, useOptionPremium, useOptionTimeline, usePerpsOperator, usePoolData, usePriceAtTick, usePriceHistory, useSetOperatorPerms, useTimelockConfig, useUserOperators, useVaultData, useVaultTVL };
package/dist/client.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
 
4
4
  import { r as lensAbi, t as optionsMarketAbi } from "./optionsMarket-6PlyceXp.js";
5
- import { A as getErc20, D as token1ToToken0, E as token0ToToken1, F as uniswapMathLenses, M as getTimelockMarket, N as getUniswapMathLens, P as timelockLenses, d as wrapAmount, j as getTimelockLens, k as getPriceHistory, n as EMPTY_ARRAY, p as wrapPrice, t as getPayoutAtTick, v as getNearestValidStrikeTick, w as roundTickDown, y as getPriceAtTick } from "./optionUtils-CoIk8zAr.js";
5
+ import { A as getErc20, D as token1ToToken0, E as token0ToToken1, F as uniswapMathLenses, M as getTimelockMarket$1, N as getUniswapMathLens, P as timelockLenses, _ as getAmountsFromLiquidity, d as wrapAmount, j as getTimelockLens, k as getPriceHistory, n as EMPTY_ARRAY, p as wrapPrice, t as getPayoutAtTick, v as getNearestValidStrikeTick$1, w as roundTickDown, y as getPriceAtTick } from "./optionUtils-CoIk8zAr.js";
6
6
  import { n as uniswapV3PoolAbi, t as singleOwnerVaultAbi } from "./singleOwnerVault-BeJChjfJ.js";
7
7
  import { encodeAbiParameters, encodeFunctionData, erc20Abi, maxUint256, zeroAddress } from "viem";
8
8
  import React, { createContext, useContext, useMemo } from "react";
@@ -11,6 +11,8 @@ import { GraphQLClient, RequestOptions } from "graphql-request";
11
11
  import gql from "graphql-tag";
12
12
  import { waitForTransactionReceipt } from "viem/actions";
13
13
  import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
14
+ import { getNearestValidStrikeTick, getTimelockMarket } from "timelock-sdk";
15
+ import { useApproval as useApproval$1, useCurrentTick as useCurrentTick$1, useMarketData as useMarketData$1, usePoolData as usePoolData$1, useSetOperatorPerms as useSetOperatorPerms$1, useUserOperators as useUserOperators$1 } from "timelock-sdk/client";
14
16
 
15
17
  //#region src/generated/graphql.ts
16
18
  const UserOptionFieldsFragmentDoc = gql`
@@ -280,9 +282,9 @@ function getSdk(client, withWrapper = defaultWrapper) {
280
282
  }
281
283
 
282
284
  //#endregion
283
- //#region src/providers/TimelockMarketProvider.tsx
284
- const TimelockMarketContext = createContext(void 0);
285
- const TimelockMarketProvider = ({ children, marketData, envioGraphqlUrl }) => {
285
+ //#region src/providers/TimelockProvider.tsx
286
+ const TimelockContext = createContext(void 0);
287
+ const TimelockProvider = ({ children, marketData, envioGraphqlUrl, perpsOperatorUrl }) => {
286
288
  const chainId = useChainId();
287
289
  const lensAddr = timelockLenses[chainId];
288
290
  const uniswapMathLensAddr = uniswapMathLenses[chainId];
@@ -294,24 +296,26 @@ const TimelockMarketProvider = ({ children, marketData, envioGraphqlUrl }) => {
294
296
  lensAddr,
295
297
  uniswapMathLensAddr,
296
298
  envioGraphqlUrl,
297
- graphqlClient
299
+ graphqlClient,
300
+ perpsOperatorUrl
298
301
  }), [
299
302
  marketData,
300
303
  lensAddr,
301
304
  uniswapMathLensAddr,
302
305
  envioGraphqlUrl,
303
- graphqlClient
306
+ graphqlClient,
307
+ perpsOperatorUrl
304
308
  ]);
305
- return /* @__PURE__ */ React.createElement(TimelockMarketContext.Provider, { value: contextValue }, children);
309
+ return /* @__PURE__ */ React.createElement(TimelockContext.Provider, { value: contextValue }, children);
306
310
  };
307
311
  const useCurrentMarket = () => {
308
- const context = useContext(TimelockMarketContext);
309
- if (context === void 0) throw new Error("useCurrentMarket must be used within a TimelockMarketProvider");
312
+ const context = useContext(TimelockContext);
313
+ if (context === void 0) throw new Error("useCurrentMarket must be used within a TimelockProvider");
310
314
  return context.marketData;
311
315
  };
312
316
  const useTimelockConfig = () => {
313
- const context = useContext(TimelockMarketContext);
314
- if (context === void 0) throw new Error("useConfig must be used within a TimelockMarketProvider");
317
+ const context = useContext(TimelockContext);
318
+ if (context === void 0) throw new Error("useConfig must be used within a TimelockProvider");
315
319
  return context;
316
320
  };
317
321
 
@@ -326,7 +330,7 @@ const useLens = () => {
326
330
  };
327
331
 
328
332
  //#endregion
329
- //#region src/hooks/market/useMarketData.ts
333
+ //#region src/hooks/options/useMarketData.ts
330
334
  const useMarketData = (marketAddr) => {
331
335
  const { graphqlClient } = useTimelockConfig();
332
336
  const { timelockLens } = useLens();
@@ -376,7 +380,7 @@ const usePoolData = (poolAddr) => {
376
380
  };
377
381
 
378
382
  //#endregion
379
- //#region src/hooks/market/useExerciseOption.ts
383
+ //#region src/hooks/options/useExerciseOption.ts
380
384
  const swapper = "0xc396aa907F8De0c32460050B8Adbf047186C504d";
381
385
  const useExerciseOption = (marketAddr) => {
382
386
  const { vault, pool } = useMarketData(marketAddr);
@@ -414,7 +418,7 @@ const useExerciseOption = (marketAddr) => {
414
418
  };
415
419
 
416
420
  //#endregion
417
- //#region src/hooks/market/useMaxPositionSize.ts
421
+ //#region src/hooks/options/useMaxPositionSize.ts
418
422
  const useMaxPositionSize = (marketAddr, strikeTick, maxBorrowableRange = 100) => {
419
423
  const { timelockLens } = useLens();
420
424
  const { optionAssetDecimals } = useMarketData(marketAddr);
@@ -498,7 +502,7 @@ const useApproval = () => {
498
502
  };
499
503
 
500
504
  //#endregion
501
- //#region src/hooks/market/useMintOption.ts
505
+ //#region src/hooks/options/useMintOption.ts
502
506
  const useMintOption = (marketAddr) => {
503
507
  const { payoutAsset, vault, pool, optionAssetIsToken0 } = useMarketData(marketAddr);
504
508
  const { tickSpacing } = usePoolData(pool);
@@ -515,8 +519,8 @@ const useMintOption = (marketAddr) => {
515
519
  if (!timelockLens) throw new Error("Timelock lens not available");
516
520
  if (!vault || !payoutAsset || optionAssetIsToken0 === void 0) throw new Error("Market data not available");
517
521
  if (currentTick === void 0 || !tickSpacing) throw new Error("Pool data not available");
518
- strikeTick = getNearestValidStrikeTick(optionType, optionAssetIsToken0, tickSpacing, currentTick, strikeTick);
519
- const [premium, protocolFee] = await getTimelockMarket(marketAddr, client).read.calculatePremium([
522
+ strikeTick = getNearestValidStrikeTick$1(optionType, optionAssetIsToken0, tickSpacing, currentTick, strikeTick);
523
+ const [premium, protocolFee] = await getTimelockMarket$1(marketAddr, client).read.calculatePremium([
520
524
  optionType === "CALL" ? 0 : 1,
521
525
  amount,
522
526
  strikeTick,
@@ -546,7 +550,7 @@ const useMintOption = (marketAddr) => {
546
550
  };
547
551
 
548
552
  //#endregion
549
- //#region src/hooks/market/useOptionPnl.ts
553
+ //#region src/hooks/options/useOptionPnl.ts
550
554
  const useOptionPnl = (option) => {
551
555
  const { marketAddr, optionType, entryTick, positionSizeCurrent } = option;
552
556
  const { pool, optionAssetIsToken0, payoutAssetDecimals, tickSpacing } = useMarketData(marketAddr);
@@ -580,7 +584,7 @@ const useOptionPnl = (option) => {
580
584
  };
581
585
 
582
586
  //#endregion
583
- //#region src/hooks/market/useOptionPremium.ts
587
+ //#region src/hooks/options/useOptionPremium.ts
584
588
  const useOptionPremium = (marketAddr, optionType, optionAmount, addedDuration, remainingDuration = 0, strikeTick) => {
585
589
  const { pool, payoutAssetDecimals, optionAssetIsToken0 } = useMarketData(marketAddr);
586
590
  const { tickSpacing } = usePoolData(pool);
@@ -625,7 +629,7 @@ const useOptionPremium = (marketAddr, optionType, optionAmount, addedDuration, r
625
629
  };
626
630
 
627
631
  //#endregion
628
- //#region src/hooks/market/useUserOptions.ts
632
+ //#region src/hooks/options/useUserOptions.ts
629
633
  const useUserOptions = (userAddr, marketAddr, active = false) => {
630
634
  const { graphqlClient } = useTimelockConfig();
631
635
  userAddr = userAddr === null || userAddr === void 0 ? void 0 : userAddr.toLowerCase();
@@ -678,7 +682,7 @@ const useClosedUserOptions = (userAddr, marketAddr) => {
678
682
  };
679
683
 
680
684
  //#endregion
681
- //#region src/hooks/market/useExtendOption.ts
685
+ //#region src/hooks/options/useExtendOption.ts
682
686
  const useExtendOption = (marketAddr) => {
683
687
  const { payoutAsset } = useMarketData(marketAddr);
684
688
  const queryClient = useQueryClient();
@@ -689,7 +693,7 @@ const useExtendOption = (marketAddr) => {
689
693
  const extendOption = async ({ option, duration }) => {
690
694
  if (!client || !address) throw new Error("Wallet not connected");
691
695
  if (!marketAddr || !payoutAsset) throw new Error("Market address not available");
692
- const market = getTimelockMarket(marketAddr, client);
696
+ const market = getTimelockMarket$1(marketAddr, client);
693
697
  const remainingDuration = Math.max(0, Math.floor((option.expiresAt.getTime() - Date.now()) / 1e3));
694
698
  const [premium, protocolFee] = await market.read.calculatePremium([
695
699
  option.optionType === "CALL" ? 0 : 1,
@@ -717,70 +721,7 @@ const useExtendOption = (marketAddr) => {
717
721
  };
718
722
 
719
723
  //#endregion
720
- //#region src/hooks/market/useUserOperators.ts
721
- const useUserOperators = (userAddr, marketAddr) => {
722
- const { graphqlClient } = useTimelockConfig();
723
- const { data,...rest } = useQuery({
724
- queryKey: [
725
- "userOperators",
726
- (userAddr === null || userAddr === void 0 ? void 0 : userAddr.toLowerCase()) || "--",
727
- (marketAddr === null || marketAddr === void 0 ? void 0 : marketAddr.toLowerCase()) || "--"
728
- ],
729
- queryFn: async () => {
730
- if (!userAddr || !marketAddr) return void 0;
731
- return (await graphqlClient.GetUserMarketOperators({
732
- userAddr: userAddr.toLowerCase(),
733
- marketAddr: marketAddr.toLowerCase()
734
- })).UserMarketOperator.map((operator) => ({
735
- ...operator,
736
- spendingApproval: BigInt(operator.spendingApproval),
737
- operatorAddr: operator.operator.address.toLowerCase()
738
- }));
739
- },
740
- enabled: !!userAddr && !!marketAddr && !!graphqlClient
741
- });
742
- return {
743
- ...rest,
744
- data: data || EMPTY_ARRAY
745
- };
746
- };
747
-
748
- //#endregion
749
- //#region src/hooks/market/useSetOperatorPerms.ts
750
- const useSetOperatorPerms = (marketAddr) => {
751
- const queryClient = useQueryClient();
752
- const client = useClient();
753
- const { address } = useAccount();
754
- const { writeContractAsync } = useWriteContract();
755
- const setOperatorPerms = async ({ operator, canExtend, canExercise, canTransfer, canMint, spendingApproval }) => {
756
- if (!client || !address) throw new Error("Wallet not connected");
757
- if (!marketAddr) throw new Error("Market address not available");
758
- const hash = await writeContractAsync({
759
- address: marketAddr,
760
- abi: optionsMarketAbi,
761
- functionName: "setOperatorPerms",
762
- args: [
763
- operator,
764
- canExtend,
765
- canExercise,
766
- canTransfer,
767
- canMint,
768
- spendingApproval
769
- ]
770
- });
771
- await waitForTransactionReceipt(client, { hash });
772
- queryClient.invalidateQueries({ queryKey: [
773
- "userOperators",
774
- address.toLowerCase(),
775
- marketAddr.toLowerCase()
776
- ] });
777
- return hash;
778
- };
779
- return useMutation({ mutationFn: setOperatorPerms });
780
- };
781
-
782
- //#endregion
783
- //#region src/hooks/market/useOptionTimeline.ts
724
+ //#region src/hooks/options/useOptionTimeline.ts
784
725
  const useOptionTimeline = (marketAddr, optionId) => {
785
726
  const { graphqlClient } = useTimelockConfig();
786
727
  marketAddr = marketAddr === null || marketAddr === void 0 ? void 0 : marketAddr.toLowerCase();
@@ -851,6 +792,220 @@ const useOptionTimeline = (marketAddr, optionId) => {
851
792
  };
852
793
  };
853
794
 
795
+ //#endregion
796
+ //#region src/lib/perpsOperator.ts
797
+ var PerpsOperator = class {
798
+ baseUrl;
799
+ constructor(baseUrl) {
800
+ this.baseUrl = baseUrl;
801
+ }
802
+ async #request(path, body) {
803
+ const url = new URL(path, this.baseUrl);
804
+ const res = await fetch(url, {
805
+ method: body ? "POST" : "GET",
806
+ headers: {
807
+ Connection: "keep-alive",
808
+ "Content-Type": "application/json",
809
+ "Keep-Alive": "timeout=120"
810
+ },
811
+ body: body ? JSON.stringify(body) : void 0
812
+ });
813
+ if (res.ok) {
814
+ const { data } = await res.json();
815
+ return data;
816
+ }
817
+ const resText = await res.text();
818
+ try {
819
+ const error = JSON.parse(resText);
820
+ throw new Error(`${res.status} ${res.statusText}: ${error.error}`);
821
+ } catch (error) {
822
+ throw new Error(`${res.status} ${res.statusText}: ${resText}`);
823
+ }
824
+ }
825
+ async getOperatorAddr() {
826
+ const { address } = await this.#request("api/operator/address");
827
+ return address;
828
+ }
829
+ async getUserPerps(userAddr, marketAddr, type, offset = 0, limit = 1e3) {
830
+ const params = new URLSearchParams({
831
+ offset: offset.toString(),
832
+ limit: limit.toString()
833
+ });
834
+ if (type) params.append("type", type);
835
+ if (marketAddr) params.append("marketAddr", marketAddr);
836
+ const url = `api/positions/${userAddr}?${params.toString()}`;
837
+ return (await this.#request(url)).map((p) => ({
838
+ ...p,
839
+ optionId: BigInt(p.optionId)
840
+ }));
841
+ }
842
+ async mintPerp(body) {
843
+ const { txHash, optionId } = await this.#request("api/positions/mint", {
844
+ ...body,
845
+ amount: body.amount.toString()
846
+ });
847
+ return {
848
+ txHash,
849
+ optionId: BigInt(optionId)
850
+ };
851
+ }
852
+ async exercisePerp(body) {
853
+ const { txHash, optionId } = await this.#request("api/positions/exercise", {
854
+ ...body,
855
+ optionId: body.optionId.toString(),
856
+ liquidities: body.liquidities.map((l) => l.toString())
857
+ });
858
+ return {
859
+ txHash,
860
+ optionId: BigInt(optionId)
861
+ };
862
+ }
863
+ };
864
+
865
+ //#endregion
866
+ //#region src/hooks/perps/usePerpsOperator.ts
867
+ const usePerpsOperator = () => {
868
+ const { perpsOperatorUrl } = useTimelockConfig();
869
+ const operator = useMemo(() => perpsOperatorUrl ? new PerpsOperator(perpsOperatorUrl) : void 0, [perpsOperatorUrl]);
870
+ const { data: address } = useQuery({
871
+ queryKey: ["perpsOperatorAddr", perpsOperatorUrl || "--"],
872
+ queryFn: () => operator === null || operator === void 0 ? void 0 : operator.getOperatorAddr(),
873
+ staleTime: 1e4,
874
+ refetchInterval: 1e4,
875
+ enabled: !!operator
876
+ });
877
+ return {
878
+ operator,
879
+ address
880
+ };
881
+ };
882
+
883
+ //#endregion
884
+ //#region src/hooks/perps/useMintPerp.ts
885
+ const useMintPerp = (marketAddr) => {
886
+ const queryClient = useQueryClient();
887
+ const client = useClient();
888
+ const { address } = useAccount();
889
+ const { operator, address: operatorAddr } = usePerpsOperator();
890
+ const { askForApproval } = useApproval$1();
891
+ const { data: operators } = useUserOperators$1(address, marketAddr);
892
+ const { mutateAsync: setOperatorPerms } = useSetOperatorPerms$1(marketAddr);
893
+ const { pool, optionAssetIsToken0, payoutAsset } = useMarketData$1(marketAddr);
894
+ const { tickSpacing } = usePoolData$1(pool);
895
+ const { exact: currentTick } = useCurrentTick$1(pool);
896
+ const userPerms = operatorAddr ? operators.find((o) => o.operatorAddr.toLowerCase() === operatorAddr.toLowerCase()) : void 0;
897
+ const hasEnoughPerms = userPerms && userPerms.canMint && userPerms.canExtend;
898
+ const mintPerp = async (data) => {
899
+ const { optionType, amount, duration, strikeTick } = data;
900
+ if (!client || !address) throw new Error("Wallet not connected");
901
+ if (!marketAddr) throw new Error("Market address not found");
902
+ if (!operator || !operatorAddr) throw new Error("Operator address not found");
903
+ if (!tickSpacing || currentTick === void 0) throw new Error("Pool data not found");
904
+ if (optionAssetIsToken0 === void 0 || !payoutAsset) throw new Error("Market data not found");
905
+ if (!hasEnoughPerms) await setOperatorPerms({
906
+ operator: operatorAddr,
907
+ canMint: true,
908
+ canExtend: true,
909
+ canExercise: (userPerms === null || userPerms === void 0 ? void 0 : userPerms.canExercise) || false,
910
+ canTransfer: (userPerms === null || userPerms === void 0 ? void 0 : userPerms.canTransfer) || false,
911
+ spendingApproval: maxUint256
912
+ });
913
+ const market = getTimelockMarket(marketAddr, client);
914
+ const validStrikeTick = getNearestValidStrikeTick(optionType, optionAssetIsToken0, tickSpacing, currentTick, strikeTick);
915
+ const [premium, protocolFee] = await market.read.calculatePremium([
916
+ optionType === "CALL" ? 0 : 1,
917
+ amount,
918
+ validStrikeTick,
919
+ duration,
920
+ 0
921
+ ]);
922
+ await askForApproval(payoutAsset, marketAddr, (premium + protocolFee) * 11n / 10n);
923
+ await operator.mintPerp({
924
+ marketAddr,
925
+ userAddr: address,
926
+ amount,
927
+ optionType,
928
+ duration,
929
+ strikeTick: validStrikeTick
930
+ });
931
+ queryClient.invalidateQueries({ queryKey: ["userOptions", address.toLowerCase()] });
932
+ };
933
+ return useMutation({ mutationFn: mintPerp });
934
+ };
935
+
936
+ //#endregion
937
+ //#region src/hooks/perps/useClosePerp.ts
938
+ const useClosePerp = () => {
939
+ const { operator } = usePerpsOperator();
940
+ return useMutation({ mutationFn: (body) => {
941
+ if (!operator) throw new Error("Operator not connected");
942
+ return operator.exercisePerp(body);
943
+ } });
944
+ };
945
+
946
+ //#endregion
947
+ //#region src/hooks/operators/useUserOperators.ts
948
+ const useUserOperators = (userAddr, marketAddr) => {
949
+ const { graphqlClient } = useTimelockConfig();
950
+ const { data,...rest } = useQuery({
951
+ queryKey: [
952
+ "userOperators",
953
+ (userAddr === null || userAddr === void 0 ? void 0 : userAddr.toLowerCase()) || "--",
954
+ (marketAddr === null || marketAddr === void 0 ? void 0 : marketAddr.toLowerCase()) || "--"
955
+ ],
956
+ queryFn: async () => {
957
+ if (!userAddr || !marketAddr) return void 0;
958
+ return (await graphqlClient.GetUserMarketOperators({
959
+ userAddr: userAddr.toLowerCase(),
960
+ marketAddr: marketAddr.toLowerCase()
961
+ })).UserMarketOperator.map((operator) => ({
962
+ ...operator,
963
+ spendingApproval: BigInt(operator.spendingApproval),
964
+ operatorAddr: operator.operator.address.toLowerCase()
965
+ }));
966
+ },
967
+ enabled: !!userAddr && !!marketAddr && !!graphqlClient
968
+ });
969
+ return {
970
+ ...rest,
971
+ data: data || EMPTY_ARRAY
972
+ };
973
+ };
974
+
975
+ //#endregion
976
+ //#region src/hooks/operators/useSetOperatorPerms.ts
977
+ const useSetOperatorPerms = (marketAddr) => {
978
+ const queryClient = useQueryClient();
979
+ const client = useClient();
980
+ const { address } = useAccount();
981
+ const { writeContractAsync } = useWriteContract();
982
+ const setOperatorPerms = async ({ operator, canExtend, canExercise, canTransfer, canMint, spendingApproval }) => {
983
+ if (!client || !address) throw new Error("Wallet not connected");
984
+ if (!marketAddr) throw new Error("Market address not available");
985
+ const hash = await writeContractAsync({
986
+ address: marketAddr,
987
+ abi: optionsMarketAbi,
988
+ functionName: "setOperatorPerms",
989
+ args: [
990
+ operator,
991
+ canExtend,
992
+ canExercise,
993
+ canTransfer,
994
+ canMint,
995
+ spendingApproval
996
+ ]
997
+ });
998
+ await waitForTransactionReceipt(client, { hash });
999
+ queryClient.invalidateQueries({ queryKey: [
1000
+ "userOperators",
1001
+ address.toLowerCase(),
1002
+ marketAddr.toLowerCase()
1003
+ ] });
1004
+ return hash;
1005
+ };
1006
+ return useMutation({ mutationFn: setOperatorPerms });
1007
+ };
1008
+
854
1009
  //#endregion
855
1010
  //#region src/hooks/pool/usePriceAtTick.ts
856
1011
  const usePriceAtTick = (tick, poolAddr) => {
@@ -987,25 +1142,17 @@ const useLiquidityBlocks = (vaultAddr) => {
987
1142
 
988
1143
  //#endregion
989
1144
  //#region src/hooks/vault/useMintLiquidity.ts
990
- const batchGetAmountsFromLiquidity = async (lens, tickLower, tickUpper, liquidity, currentTick) => {
991
- const currentTicksArray = new Array(tickLower.length).fill(currentTick);
992
- const amounts = await lens.read.batchGetAmountsForLiquidityTicks([
993
- currentTicksArray,
994
- tickLower,
995
- tickUpper,
996
- liquidity
997
- ]);
1145
+ const batchGetAmountsFromLiquidity = (tickLowers, tickUppers, liquidities, currentTick) => {
998
1146
  let totalAmount0 = 0n;
999
1147
  let totalAmount1 = 0n;
1000
1148
  const amounts0 = [];
1001
1149
  const amounts1 = [];
1002
- for (const scaled of amounts[0]) {
1003
- totalAmount0 += scaled;
1004
- amounts0.push(scaled);
1005
- }
1006
- for (const scaled of amounts[1]) {
1007
- totalAmount1 += scaled;
1008
- amounts1.push(scaled);
1150
+ for (const [i, tickLower] of tickLowers.entries()) {
1151
+ const [amount0, amount1] = getAmountsFromLiquidity(tickLower, tickUppers[i], liquidities[i], currentTick);
1152
+ totalAmount0 += amount0;
1153
+ totalAmount1 += amount1;
1154
+ amounts0.push(amount0);
1155
+ amounts1.push(amount1);
1009
1156
  }
1010
1157
  return {
1011
1158
  totalAmount0,
@@ -1016,97 +1163,42 @@ const batchGetAmountsFromLiquidity = async (lens, tickLower, tickUpper, liquidit
1016
1163
  };
1017
1164
  const useMintLiquidity = (vaultAddr) => {
1018
1165
  const client = useClient();
1019
- const { address } = useAccount();
1020
1166
  const { pool } = useVaultData(vaultAddr);
1021
- const { timelockLens, uniswapLens } = useLens();
1022
- const currentTick = useCurrentTick(pool);
1167
+ const { timelockLens } = useLens();
1168
+ const { exact: currentTick } = useCurrentTick(pool);
1023
1169
  const { token0, token1 } = usePoolData(pool);
1024
- const { writeContractAsync, data: hash, isPending, error } = useWriteContract();
1025
- const { isLoading: isConfirming, isSuccess } = useWaitForTransactionReceipt({ hash });
1026
- const askForApproval = async (params) => {
1027
- if (!address || !client) throw new Error("Wallet not connected");
1028
- if (currentTick.exact === void 0 || !token0 || !token1 || !vaultAddr || !uniswapLens) throw new Error("Current tick not available");
1029
- const { totalAmount0, totalAmount1 } = await batchGetAmountsFromLiquidity(uniswapLens, params.map((p) => p.tickLower), params.map((p) => p.tickUpper), params.map((p) => p.liquidity), currentTick.exact);
1030
- const [allowance0, allowance1] = await Promise.all([getErc20(token0, client).read.allowance([address, vaultAddr]), getErc20(token1, client).read.allowance([address, vaultAddr])]);
1031
- const approvalPromises = [];
1032
- if (allowance0 <= totalAmount0) {
1033
- const approvalHash = await writeContractAsync({
1034
- address: token0,
1035
- abi: erc20Abi,
1036
- functionName: "approve",
1037
- args: [vaultAddr, maxUint256]
1038
- });
1039
- approvalPromises.push(waitForTransactionReceipt(client, { hash: approvalHash }));
1040
- }
1041
- if (allowance1 <= totalAmount1) {
1042
- const approvalHash1 = await writeContractAsync({
1043
- address: token1,
1044
- abi: erc20Abi,
1045
- functionName: "approve",
1046
- args: [vaultAddr, maxUint256]
1047
- });
1048
- approvalPromises.push(waitForTransactionReceipt(client, { hash: approvalHash1 }));
1049
- }
1050
- if (approvalPromises.length > 0) await Promise.all(approvalPromises);
1170
+ const { askForApproval } = useApproval();
1171
+ const { writeContractAsync } = useWriteContract();
1172
+ const processApproval = async (params) => {
1173
+ if (currentTick === void 0 || !token0 || !token1 || !vaultAddr) throw new Error("Current tick not available");
1174
+ const { totalAmount0, totalAmount1 } = batchGetAmountsFromLiquidity(params.map((p) => p.tickLower), params.map((p) => p.tickUpper), params.map((p) => p.liquidity), currentTick);
1175
+ await askForApproval(token0, vaultAddr, totalAmount0);
1176
+ await askForApproval(token1, vaultAddr, totalAmount1);
1051
1177
  };
1052
- const mint = async (tickLower, tickUpper, liquidity) => {
1178
+ return useMutation({ mutationFn: async (params) => {
1053
1179
  if (!client) throw new Error("Wallet not connected");
1054
- if (!vaultAddr || !timelockLens) throw new Error("Vault/lens not available");
1055
- await askForApproval([{
1056
- tickLower,
1057
- tickUpper,
1058
- liquidity
1059
- }]);
1060
- const hash$1 = await writeContractAsync({
1180
+ if (currentTick === void 0) throw new Error("Current tick not available");
1181
+ if (!timelockLens || !vaultAddr) throw new Error("Vault/lens not available");
1182
+ if (!Array.isArray(params)) params = [params];
1183
+ if (params.length === 0) throw new Error("No positions to mint");
1184
+ await processApproval(params);
1185
+ const refTicks = await timelockLens.read.batchGetRefTick([vaultAddr, params.map((position) => position.tickLower)]);
1186
+ await waitForTransactionReceipt(client, { hash: await writeContractAsync({
1061
1187
  address: vaultAddr,
1062
1188
  abi: singleOwnerVaultAbi,
1063
- functionName: "mint",
1064
- args: [
1065
- tickLower,
1066
- tickUpper,
1067
- liquidity,
1068
- await timelockLens.read.getRefTick([vaultAddr, tickLower])
1069
- ]
1070
- });
1071
- await waitForTransactionReceipt(client, { hash: hash$1 });
1072
- return hash$1;
1073
- };
1074
- const mintMultiple = async (positions) => {
1075
- if (!client) throw new Error("Wallet not connected");
1076
- if (!currentTick.exact) throw new Error("Current tick not available");
1077
- if (positions.length === 0) throw new Error("No positions to mint");
1078
- if (!timelockLens || !vaultAddr) throw new Error("Vault/lens not available");
1079
- if (positions.length === 1) await mint(positions[0].tickLower, positions[0].tickUpper, positions[0].liquidity);
1080
- else {
1081
- await askForApproval(positions);
1082
- const refTicks = await timelockLens.read.batchGetRefTick([vaultAddr, positions.map((position) => position.tickLower)]);
1083
- await waitForTransactionReceipt(client, { hash: await writeContractAsync({
1084
- address: vaultAddr,
1189
+ functionName: "multicall",
1190
+ args: [params.map((p, i) => encodeFunctionData({
1085
1191
  abi: singleOwnerVaultAbi,
1086
- functionName: "multicall",
1087
- args: [positions.map((p, i) => encodeFunctionData({
1088
- abi: singleOwnerVaultAbi,
1089
- functionName: "mint",
1090
- args: [
1091
- p.tickLower,
1092
- p.tickUpper,
1093
- p.liquidity,
1094
- refTicks[i]
1095
- ]
1096
- }))]
1097
- }) });
1098
- }
1099
- };
1100
- return {
1101
- mintMultiple,
1102
- mint,
1103
- hash,
1104
- isPending,
1105
- isConfirming,
1106
- isSuccess,
1107
- error,
1108
- isLoading: isPending || isConfirming
1109
- };
1192
+ functionName: "mint",
1193
+ args: [
1194
+ p.tickLower,
1195
+ p.tickUpper,
1196
+ p.liquidity,
1197
+ refTicks[i]
1198
+ ]
1199
+ }))]
1200
+ }) });
1201
+ } });
1110
1202
  };
1111
1203
 
1112
1204
  //#endregion
@@ -1147,5 +1239,5 @@ const useVaultTVL = (vaultAddr) => {
1147
1239
  };
1148
1240
 
1149
1241
  //#endregion
1150
- export { TimelockMarketProvider, batchGetAmountsFromLiquidity, useActiveUserOptions, useApproval, useBurnLiquidity, useClosedUserOptions, useCurrentMarket, useCurrentPrice, useCurrentTick, useExerciseOption, useExtendOption, useLens, useLiquidityBlocks, useMarketData, useMaxPositionSize, useMintLiquidity, useMintOption, useOptionPnl, useOptionPremium, useOptionTimeline, usePoolData, usePriceAtTick, usePriceHistory, useSetOperatorPerms, useTimelockConfig, useUserOperators, useVaultData, useVaultTVL };
1242
+ export { TimelockProvider, batchGetAmountsFromLiquidity, useActiveUserOptions, useApproval, useBurnLiquidity, useClosePerp, useClosedUserOptions, useCurrentMarket, useCurrentPrice, useCurrentTick, useExerciseOption, useExtendOption, useLens, useLiquidityBlocks, useMarketData, useMaxPositionSize, useMintLiquidity, useMintOption, useMintPerp, useOptionPnl, useOptionPremium, useOptionTimeline, usePerpsOperator, usePoolData, usePriceAtTick, usePriceHistory, useSetOperatorPerms, useTimelockConfig, useUserOperators, useVaultData, useVaultTVL };
1151
1243
  //# sourceMappingURL=client.js.map