timelock-sdk 0.0.80 → 0.0.81

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.cjs CHANGED
@@ -18,6 +18,10 @@ let viem_actions = require("viem/actions");
18
18
  viem_actions = require_optionUtils.__toESM(viem_actions);
19
19
  let __tanstack_react_query = require("@tanstack/react-query");
20
20
  __tanstack_react_query = require_optionUtils.__toESM(__tanstack_react_query);
21
+ let timelock_sdk = require("timelock-sdk");
22
+ timelock_sdk = require_optionUtils.__toESM(timelock_sdk);
23
+ let timelock_sdk_client = require("timelock-sdk/client");
24
+ timelock_sdk_client = require_optionUtils.__toESM(timelock_sdk_client);
21
25
 
22
26
  //#region src/generated/graphql.ts
23
27
  const UserOptionFieldsFragmentDoc = graphql_tag.default`
@@ -287,9 +291,9 @@ function getSdk(client, withWrapper = defaultWrapper) {
287
291
  }
288
292
 
289
293
  //#endregion
290
- //#region src/providers/TimelockMarketProvider.tsx
291
- const TimelockMarketContext = (0, react.createContext)(void 0);
292
- const TimelockMarketProvider = ({ children, marketData, envioGraphqlUrl }) => {
294
+ //#region src/providers/TimelockProvider.tsx
295
+ const TimelockContext = (0, react.createContext)(void 0);
296
+ const TimelockProvider = ({ children, marketData, envioGraphqlUrl, perpsOperatorUrl }) => {
293
297
  const chainId = (0, wagmi.useChainId)();
294
298
  const lensAddr = require_optionUtils.timelockLenses[chainId];
295
299
  const uniswapMathLensAddr = require_optionUtils.uniswapMathLenses[chainId];
@@ -301,24 +305,26 @@ const TimelockMarketProvider = ({ children, marketData, envioGraphqlUrl }) => {
301
305
  lensAddr,
302
306
  uniswapMathLensAddr,
303
307
  envioGraphqlUrl,
304
- graphqlClient
308
+ graphqlClient,
309
+ perpsOperatorUrl
305
310
  }), [
306
311
  marketData,
307
312
  lensAddr,
308
313
  uniswapMathLensAddr,
309
314
  envioGraphqlUrl,
310
- graphqlClient
315
+ graphqlClient,
316
+ perpsOperatorUrl
311
317
  ]);
312
- return /* @__PURE__ */ react.default.createElement(TimelockMarketContext.Provider, { value: contextValue }, children);
318
+ return /* @__PURE__ */ react.default.createElement(TimelockContext.Provider, { value: contextValue }, children);
313
319
  };
314
320
  const useCurrentMarket = () => {
315
- const context = (0, react.useContext)(TimelockMarketContext);
316
- if (context === void 0) throw new Error("useCurrentMarket must be used within a TimelockMarketProvider");
321
+ const context = (0, react.useContext)(TimelockContext);
322
+ if (context === void 0) throw new Error("useCurrentMarket must be used within a TimelockProvider");
317
323
  return context.marketData;
318
324
  };
319
325
  const useTimelockConfig = () => {
320
- const context = (0, react.useContext)(TimelockMarketContext);
321
- if (context === void 0) throw new Error("useConfig must be used within a TimelockMarketProvider");
326
+ const context = (0, react.useContext)(TimelockContext);
327
+ if (context === void 0) throw new Error("useConfig must be used within a TimelockProvider");
322
328
  return context;
323
329
  };
324
330
 
@@ -333,7 +339,7 @@ const useLens = () => {
333
339
  };
334
340
 
335
341
  //#endregion
336
- //#region src/hooks/market/useMarketData.ts
342
+ //#region src/hooks/options/useMarketData.ts
337
343
  const useMarketData = (marketAddr) => {
338
344
  const { graphqlClient } = useTimelockConfig();
339
345
  const { timelockLens } = useLens();
@@ -383,7 +389,7 @@ const usePoolData = (poolAddr) => {
383
389
  };
384
390
 
385
391
  //#endregion
386
- //#region src/hooks/market/useExerciseOption.ts
392
+ //#region src/hooks/options/useExerciseOption.ts
387
393
  const swapper = "0xc396aa907F8De0c32460050B8Adbf047186C504d";
388
394
  const useExerciseOption = (marketAddr) => {
389
395
  const { vault, pool } = useMarketData(marketAddr);
@@ -421,7 +427,7 @@ const useExerciseOption = (marketAddr) => {
421
427
  };
422
428
 
423
429
  //#endregion
424
- //#region src/hooks/market/useMaxPositionSize.ts
430
+ //#region src/hooks/options/useMaxPositionSize.ts
425
431
  const useMaxPositionSize = (marketAddr, strikeTick, maxBorrowableRange = 100) => {
426
432
  const { timelockLens } = useLens();
427
433
  const { optionAssetDecimals } = useMarketData(marketAddr);
@@ -505,7 +511,7 @@ const useApproval = () => {
505
511
  };
506
512
 
507
513
  //#endregion
508
- //#region src/hooks/market/useMintOption.ts
514
+ //#region src/hooks/options/useMintOption.ts
509
515
  const useMintOption = (marketAddr) => {
510
516
  const { payoutAsset, vault, pool, optionAssetIsToken0 } = useMarketData(marketAddr);
511
517
  const { tickSpacing } = usePoolData(pool);
@@ -553,7 +559,7 @@ const useMintOption = (marketAddr) => {
553
559
  };
554
560
 
555
561
  //#endregion
556
- //#region src/hooks/market/useOptionPnl.ts
562
+ //#region src/hooks/options/useOptionPnl.ts
557
563
  const useOptionPnl = (option) => {
558
564
  const { marketAddr, optionType, entryTick, positionSizeCurrent } = option;
559
565
  const { pool, optionAssetIsToken0, payoutAssetDecimals, tickSpacing } = useMarketData(marketAddr);
@@ -587,7 +593,7 @@ const useOptionPnl = (option) => {
587
593
  };
588
594
 
589
595
  //#endregion
590
- //#region src/hooks/market/useOptionPremium.ts
596
+ //#region src/hooks/options/useOptionPremium.ts
591
597
  const useOptionPremium = (marketAddr, optionType, optionAmount, addedDuration, remainingDuration = 0, strikeTick) => {
592
598
  const { pool, payoutAssetDecimals, optionAssetIsToken0 } = useMarketData(marketAddr);
593
599
  const { tickSpacing } = usePoolData(pool);
@@ -632,7 +638,7 @@ const useOptionPremium = (marketAddr, optionType, optionAmount, addedDuration, r
632
638
  };
633
639
 
634
640
  //#endregion
635
- //#region src/hooks/market/useUserOptions.ts
641
+ //#region src/hooks/options/useUserOptions.ts
636
642
  const useUserOptions = (userAddr, marketAddr, active = false) => {
637
643
  const { graphqlClient } = useTimelockConfig();
638
644
  userAddr = userAddr === null || userAddr === void 0 ? void 0 : userAddr.toLowerCase();
@@ -685,7 +691,7 @@ const useClosedUserOptions = (userAddr, marketAddr) => {
685
691
  };
686
692
 
687
693
  //#endregion
688
- //#region src/hooks/market/useExtendOption.ts
694
+ //#region src/hooks/options/useExtendOption.ts
689
695
  const useExtendOption = (marketAddr) => {
690
696
  const { payoutAsset } = useMarketData(marketAddr);
691
697
  const queryClient = (0, __tanstack_react_query.useQueryClient)();
@@ -724,70 +730,7 @@ const useExtendOption = (marketAddr) => {
724
730
  };
725
731
 
726
732
  //#endregion
727
- //#region src/hooks/market/useUserOperators.ts
728
- const useUserOperators = (userAddr, marketAddr) => {
729
- const { graphqlClient } = useTimelockConfig();
730
- const { data,...rest } = (0, __tanstack_react_query.useQuery)({
731
- queryKey: [
732
- "userOperators",
733
- (userAddr === null || userAddr === void 0 ? void 0 : userAddr.toLowerCase()) || "--",
734
- (marketAddr === null || marketAddr === void 0 ? void 0 : marketAddr.toLowerCase()) || "--"
735
- ],
736
- queryFn: async () => {
737
- if (!userAddr || !marketAddr) return void 0;
738
- return (await graphqlClient.GetUserMarketOperators({
739
- userAddr: userAddr.toLowerCase(),
740
- marketAddr: marketAddr.toLowerCase()
741
- })).UserMarketOperator.map((operator) => ({
742
- ...operator,
743
- spendingApproval: BigInt(operator.spendingApproval),
744
- operatorAddr: operator.operator.address.toLowerCase()
745
- }));
746
- },
747
- enabled: !!userAddr && !!marketAddr && !!graphqlClient
748
- });
749
- return {
750
- ...rest,
751
- data: data || require_optionUtils.EMPTY_ARRAY
752
- };
753
- };
754
-
755
- //#endregion
756
- //#region src/hooks/market/useSetOperatorPerms.ts
757
- const useSetOperatorPerms = (marketAddr) => {
758
- const queryClient = (0, __tanstack_react_query.useQueryClient)();
759
- const client = (0, wagmi.useClient)();
760
- const { address } = (0, wagmi.useAccount)();
761
- const { writeContractAsync } = (0, wagmi.useWriteContract)();
762
- const setOperatorPerms = async ({ operator, canExtend, canExercise, canTransfer, canMint, spendingApproval }) => {
763
- if (!client || !address) throw new Error("Wallet not connected");
764
- if (!marketAddr) throw new Error("Market address not available");
765
- const hash = await writeContractAsync({
766
- address: marketAddr,
767
- abi: require_optionsMarket.optionsMarketAbi,
768
- functionName: "setOperatorPerms",
769
- args: [
770
- operator,
771
- canExtend,
772
- canExercise,
773
- canTransfer,
774
- canMint,
775
- spendingApproval
776
- ]
777
- });
778
- await (0, viem_actions.waitForTransactionReceipt)(client, { hash });
779
- queryClient.invalidateQueries({ queryKey: [
780
- "userOperators",
781
- address.toLowerCase(),
782
- marketAddr.toLowerCase()
783
- ] });
784
- return hash;
785
- };
786
- return (0, __tanstack_react_query.useMutation)({ mutationFn: setOperatorPerms });
787
- };
788
-
789
- //#endregion
790
- //#region src/hooks/market/useOptionTimeline.ts
733
+ //#region src/hooks/options/useOptionTimeline.ts
791
734
  const useOptionTimeline = (marketAddr, optionId) => {
792
735
  const { graphqlClient } = useTimelockConfig();
793
736
  marketAddr = marketAddr === null || marketAddr === void 0 ? void 0 : marketAddr.toLowerCase();
@@ -858,6 +801,220 @@ const useOptionTimeline = (marketAddr, optionId) => {
858
801
  };
859
802
  };
860
803
 
804
+ //#endregion
805
+ //#region src/lib/perpsOperator.ts
806
+ var PerpsOperator = class {
807
+ baseUrl;
808
+ constructor(baseUrl) {
809
+ this.baseUrl = baseUrl;
810
+ }
811
+ async #request(path, body) {
812
+ const url = new URL(path, this.baseUrl);
813
+ const res = await fetch(url, {
814
+ method: body ? "POST" : "GET",
815
+ headers: {
816
+ Connection: "keep-alive",
817
+ "Content-Type": "application/json",
818
+ "Keep-Alive": "timeout=120"
819
+ },
820
+ body: body ? JSON.stringify(body) : void 0
821
+ });
822
+ if (res.ok) {
823
+ const { data } = await res.json();
824
+ return data;
825
+ }
826
+ const resText = await res.text();
827
+ try {
828
+ const error = JSON.parse(resText);
829
+ throw new Error(`${res.status} ${res.statusText}: ${error.error}`);
830
+ } catch (error) {
831
+ throw new Error(`${res.status} ${res.statusText}: ${resText}`);
832
+ }
833
+ }
834
+ async getOperatorAddr() {
835
+ const { address } = await this.#request("api/operator/address");
836
+ return address;
837
+ }
838
+ async getUserPerps(userAddr, marketAddr, type, offset = 0, limit = 1e3) {
839
+ const params = new URLSearchParams({
840
+ offset: offset.toString(),
841
+ limit: limit.toString()
842
+ });
843
+ if (type) params.append("type", type);
844
+ if (marketAddr) params.append("marketAddr", marketAddr);
845
+ const url = `api/positions/${userAddr}?${params.toString()}`;
846
+ return (await this.#request(url)).map((p) => ({
847
+ ...p,
848
+ optionId: BigInt(p.optionId)
849
+ }));
850
+ }
851
+ async mintPerp(body) {
852
+ const { txHash, optionId } = await this.#request("api/positions/mint", {
853
+ ...body,
854
+ amount: body.amount.toString()
855
+ });
856
+ return {
857
+ txHash,
858
+ optionId: BigInt(optionId)
859
+ };
860
+ }
861
+ async exercisePerp(body) {
862
+ const { txHash, optionId } = await this.#request("api/positions/exercise", {
863
+ ...body,
864
+ optionId: body.optionId.toString(),
865
+ liquidities: body.liquidities.map((l) => l.toString())
866
+ });
867
+ return {
868
+ txHash,
869
+ optionId: BigInt(optionId)
870
+ };
871
+ }
872
+ };
873
+
874
+ //#endregion
875
+ //#region src/hooks/perps/usePerpsOperator.ts
876
+ const usePerpsOperator = () => {
877
+ const { perpsOperatorUrl } = useTimelockConfig();
878
+ const operator = (0, react.useMemo)(() => perpsOperatorUrl ? new PerpsOperator(perpsOperatorUrl) : void 0, [perpsOperatorUrl]);
879
+ const { data: address } = (0, __tanstack_react_query.useQuery)({
880
+ queryKey: ["perpsOperatorAddr", perpsOperatorUrl || "--"],
881
+ queryFn: () => operator === null || operator === void 0 ? void 0 : operator.getOperatorAddr(),
882
+ staleTime: 1e4,
883
+ refetchInterval: 1e4,
884
+ enabled: !!operator
885
+ });
886
+ return {
887
+ operator,
888
+ address
889
+ };
890
+ };
891
+
892
+ //#endregion
893
+ //#region src/hooks/perps/useMintPerp.ts
894
+ const useMintPerp = (marketAddr) => {
895
+ const queryClient = (0, __tanstack_react_query.useQueryClient)();
896
+ const client = (0, wagmi.useClient)();
897
+ const { address } = (0, wagmi.useAccount)();
898
+ const { operator, address: operatorAddr } = usePerpsOperator();
899
+ const { askForApproval } = (0, timelock_sdk_client.useApproval)();
900
+ const { data: operators } = (0, timelock_sdk_client.useUserOperators)(address, marketAddr);
901
+ const { mutateAsync: setOperatorPerms } = (0, timelock_sdk_client.useSetOperatorPerms)(marketAddr);
902
+ const { pool, optionAssetIsToken0, payoutAsset } = (0, timelock_sdk_client.useMarketData)(marketAddr);
903
+ const { tickSpacing } = (0, timelock_sdk_client.usePoolData)(pool);
904
+ const { exact: currentTick } = (0, timelock_sdk_client.useCurrentTick)(pool);
905
+ const userPerms = operatorAddr ? operators.find((o) => o.operatorAddr.toLowerCase() === operatorAddr.toLowerCase()) : void 0;
906
+ const hasEnoughPerms = userPerms && userPerms.canMint && userPerms.canExtend;
907
+ const mintPerp = async (data) => {
908
+ const { optionType, amount, duration, strikeTick } = data;
909
+ if (!client || !address) throw new Error("Wallet not connected");
910
+ if (!marketAddr) throw new Error("Market address not found");
911
+ if (!operator || !operatorAddr) throw new Error("Operator address not found");
912
+ if (!tickSpacing || currentTick === void 0) throw new Error("Pool data not found");
913
+ if (optionAssetIsToken0 === void 0 || !payoutAsset) throw new Error("Market data not found");
914
+ if (!hasEnoughPerms) await setOperatorPerms({
915
+ operator: operatorAddr,
916
+ canMint: true,
917
+ canExtend: true,
918
+ canExercise: (userPerms === null || userPerms === void 0 ? void 0 : userPerms.canExercise) || false,
919
+ canTransfer: (userPerms === null || userPerms === void 0 ? void 0 : userPerms.canTransfer) || false,
920
+ spendingApproval: viem.maxUint256
921
+ });
922
+ const market = (0, timelock_sdk.getTimelockMarket)(marketAddr, client);
923
+ const validStrikeTick = (0, timelock_sdk.getNearestValidStrikeTick)(optionType, optionAssetIsToken0, tickSpacing, currentTick, strikeTick);
924
+ const [premium, protocolFee] = await market.read.calculatePremium([
925
+ optionType === "CALL" ? 0 : 1,
926
+ amount,
927
+ validStrikeTick,
928
+ duration,
929
+ 0
930
+ ]);
931
+ await askForApproval(payoutAsset, marketAddr, (premium + protocolFee) * 11n / 10n);
932
+ await operator.mintPerp({
933
+ marketAddr,
934
+ userAddr: address,
935
+ amount,
936
+ optionType,
937
+ duration,
938
+ strikeTick: validStrikeTick
939
+ });
940
+ queryClient.invalidateQueries({ queryKey: ["userOptions", address.toLowerCase()] });
941
+ };
942
+ return (0, __tanstack_react_query.useMutation)({ mutationFn: mintPerp });
943
+ };
944
+
945
+ //#endregion
946
+ //#region src/hooks/perps/useClosePerp.ts
947
+ const useClosePerp = () => {
948
+ const { operator } = usePerpsOperator();
949
+ return (0, __tanstack_react_query.useMutation)({ mutationFn: (body) => {
950
+ if (!operator) throw new Error("Operator not connected");
951
+ return operator.exercisePerp(body);
952
+ } });
953
+ };
954
+
955
+ //#endregion
956
+ //#region src/hooks/operators/useUserOperators.ts
957
+ const useUserOperators = (userAddr, marketAddr) => {
958
+ const { graphqlClient } = useTimelockConfig();
959
+ const { data,...rest } = (0, __tanstack_react_query.useQuery)({
960
+ queryKey: [
961
+ "userOperators",
962
+ (userAddr === null || userAddr === void 0 ? void 0 : userAddr.toLowerCase()) || "--",
963
+ (marketAddr === null || marketAddr === void 0 ? void 0 : marketAddr.toLowerCase()) || "--"
964
+ ],
965
+ queryFn: async () => {
966
+ if (!userAddr || !marketAddr) return void 0;
967
+ return (await graphqlClient.GetUserMarketOperators({
968
+ userAddr: userAddr.toLowerCase(),
969
+ marketAddr: marketAddr.toLowerCase()
970
+ })).UserMarketOperator.map((operator) => ({
971
+ ...operator,
972
+ spendingApproval: BigInt(operator.spendingApproval),
973
+ operatorAddr: operator.operator.address.toLowerCase()
974
+ }));
975
+ },
976
+ enabled: !!userAddr && !!marketAddr && !!graphqlClient
977
+ });
978
+ return {
979
+ ...rest,
980
+ data: data || require_optionUtils.EMPTY_ARRAY
981
+ };
982
+ };
983
+
984
+ //#endregion
985
+ //#region src/hooks/operators/useSetOperatorPerms.ts
986
+ const useSetOperatorPerms = (marketAddr) => {
987
+ const queryClient = (0, __tanstack_react_query.useQueryClient)();
988
+ const client = (0, wagmi.useClient)();
989
+ const { address } = (0, wagmi.useAccount)();
990
+ const { writeContractAsync } = (0, wagmi.useWriteContract)();
991
+ const setOperatorPerms = async ({ operator, canExtend, canExercise, canTransfer, canMint, spendingApproval }) => {
992
+ if (!client || !address) throw new Error("Wallet not connected");
993
+ if (!marketAddr) throw new Error("Market address not available");
994
+ const hash = await writeContractAsync({
995
+ address: marketAddr,
996
+ abi: require_optionsMarket.optionsMarketAbi,
997
+ functionName: "setOperatorPerms",
998
+ args: [
999
+ operator,
1000
+ canExtend,
1001
+ canExercise,
1002
+ canTransfer,
1003
+ canMint,
1004
+ spendingApproval
1005
+ ]
1006
+ });
1007
+ await (0, viem_actions.waitForTransactionReceipt)(client, { hash });
1008
+ queryClient.invalidateQueries({ queryKey: [
1009
+ "userOperators",
1010
+ address.toLowerCase(),
1011
+ marketAddr.toLowerCase()
1012
+ ] });
1013
+ return hash;
1014
+ };
1015
+ return (0, __tanstack_react_query.useMutation)({ mutationFn: setOperatorPerms });
1016
+ };
1017
+
861
1018
  //#endregion
862
1019
  //#region src/hooks/pool/usePriceAtTick.ts
863
1020
  const usePriceAtTick = (tick, poolAddr) => {
@@ -1154,11 +1311,12 @@ const useVaultTVL = (vaultAddr) => {
1154
1311
  };
1155
1312
 
1156
1313
  //#endregion
1157
- exports.TimelockMarketProvider = TimelockMarketProvider;
1314
+ exports.TimelockProvider = TimelockProvider;
1158
1315
  exports.batchGetAmountsFromLiquidity = batchGetAmountsFromLiquidity;
1159
1316
  exports.useActiveUserOptions = useActiveUserOptions;
1160
1317
  exports.useApproval = useApproval;
1161
1318
  exports.useBurnLiquidity = useBurnLiquidity;
1319
+ exports.useClosePerp = useClosePerp;
1162
1320
  exports.useClosedUserOptions = useClosedUserOptions;
1163
1321
  exports.useCurrentMarket = useCurrentMarket;
1164
1322
  exports.useCurrentPrice = useCurrentPrice;
@@ -1171,9 +1329,11 @@ exports.useMarketData = useMarketData;
1171
1329
  exports.useMaxPositionSize = useMaxPositionSize;
1172
1330
  exports.useMintLiquidity = useMintLiquidity;
1173
1331
  exports.useMintOption = useMintOption;
1332
+ exports.useMintPerp = useMintPerp;
1174
1333
  exports.useOptionPnl = useOptionPnl;
1175
1334
  exports.useOptionPremium = useOptionPremium;
1176
1335
  exports.useOptionTimeline = useOptionTimeline;
1336
+ exports.usePerpsOperator = usePerpsOperator;
1177
1337
  exports.usePoolData = usePoolData;
1178
1338
  exports.usePriceAtTick = usePriceAtTick;
1179
1339
  exports.usePriceHistory = usePriceHistory;