timelock-sdk 0.0.95 → 0.0.97

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.
@@ -1,6 +1,6 @@
1
1
  import { n as optionsMarketAbi, r as lensAbi, t as uniswapMathLensAbi } from "./uniswapMathLens-B_cHjOOB.cjs";
2
2
  import * as viem0 from "viem";
3
- import { Address, Client, GetContractReturnType, PublicClient } from "viem";
3
+ import { Address, Client, GetContractReturnType, Hex, PublicClient } from "viem";
4
4
  import React, { ReactNode } from "react";
5
5
  import "graphql";
6
6
  import { GraphQLClient, RequestOptions } from "graphql-request";
@@ -34921,9 +34921,19 @@ type ExercisePerpBody = {
34921
34921
  };
34922
34922
  declare class PerpsOperator {
34923
34923
  #private;
34924
- private baseUrl;
34924
+ auth?: {
34925
+ authMessage: string;
34926
+ signature: Hex;
34927
+ };
34925
34928
  constructor(baseUrl: string);
34926
34929
  getOperatorAddr(): Promise<Address>;
34930
+ genAuthMessage(userAddr: Address): Promise<string>;
34931
+ validateAuthMessage(authMessage: string, signature: Hex): Promise<{
34932
+ address: `0x${string}`;
34933
+ createdAt: number;
34934
+ validUntil: number;
34935
+ }>;
34936
+ setAuth(authMessage: string, signature: Hex): void;
34927
34937
  getUserPerps(userAddr: Address, marketAddr?: Address, type?: 'active' | 'closed', offset?: number, limit?: number): Promise<{
34928
34938
  optionId: bigint;
34929
34939
  id: string;
@@ -34953,9 +34963,10 @@ declare const useClosePerp: () => _tanstack_react_query0.UseMutationResult<{
34953
34963
  declare const usePerpsOperator: () => {
34954
34964
  operator: PerpsOperator | undefined;
34955
34965
  address: `0x${string}` | undefined;
34966
+ signMessage: _tanstack_react_query0.UseMutationResult<void, Error, void, unknown>;
34956
34967
  };
34957
34968
  //#endregion
34958
- //#region src/hooks/operators/useOperatorPerps.d.ts
34969
+ //#region src/hooks/operators/useOperatorPerms.d.ts
34959
34970
  declare const useOperatorPerms: (marketAddr?: Address, userAddr?: Address, operatorAddr?: Address) => {
34960
34971
  error: viem0.ReadContractErrorType;
34961
34972
  isError: true;
@@ -61922,4 +61933,4 @@ declare const useApproval: () => {
61922
61933
  };
61923
61934
  //#endregion
61924
61935
  export { scaleAmount as $, PriceDataPoint as A, OptionTimelineData as B, liquiditiesToAmount1 as C, getUniswapMathLens as Ct, token0ToToken1 as D, roundTickUp as E, useUserOperators as F, useMintOption as G, useExtendOption as H, useOperatorPerms as I, EMPTY_ARRAY as J, useMaxPositionSize as K, usePerpsOperator as L, getCurrentPrice as M, getPriceHistory as N, token1ToToken0 as O, useSetOperatorPerms as P, formatVagueAmount as Q, useClosePerp as R, liquiditiesToAmount0 as S, getTimelockMarket as St, roundTickDown as T, uniswapMathLenses as Tt, useOptionPremium as U, useOptionTimeline as V, useOptionPnl as W, formatCondensed as X, formatAmount as Y, formatUSD as Z, PRICE_PRECISION as _, TimelockMarket as _t, batchGetAmountsFromLiquidity as a, wrapPrice as at, getPriceAtTick as b, getErc20 as bt, useLiquidityBlocks as c, useMarketData as ct, usePriceAtTick as d, useActiveUserOptions as dt, scalePrice as et, UniswapPoolData as f, useClosedUserOptions as ft, getPayoutAtTick as g, TimelockLens as gt, useCurrentPrice as h, useTimelockConfig as ht, useVaultData as i, wrapAmountUnscaled as it, PriceResolution as j, PriceData as k, useBurnLiquidity as l, useExerciseOption as lt, useCurrentTick as m, useCurrentMarket as mt, useLens as n, unscalePrice as nt, useMintLiquidity as o, wrapPriceUnscaled as ot, usePoolData as p, TimelockProvider as pt, Amount as q, useVaultTVL as r, wrapAmount as rt, LiquidityBlockData as s, zero as st, useApproval as t, unscaleAmount as tt, usePriceHistory as u, OptionData as ut, getAmountsFromLiquidity as v, TimelockMarketData as vt, liquiditiesToAmounts as w, timelockLenses as wt, getTickAtPrice as x, getTimelockLens as xt, getNearestValidStrikeTick as y, UniswapMathLens as yt, useMintPerp as z };
61925
- //# sourceMappingURL=client-BanYHaNs.d.cts.map
61936
+ //# sourceMappingURL=client-uwDDNqle.d.cts.map
package/dist/client.cjs CHANGED
@@ -18,6 +18,8 @@ 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 zod = require("zod");
22
+ zod = require_optionUtils.__toESM(zod);
21
23
 
22
24
  //#region src/generated/graphql.ts
23
25
  const UserOptionFieldsFragmentDoc = graphql_tag.default`
@@ -800,12 +802,13 @@ const useOptionTimeline = (marketAddr, optionId) => {
800
802
  //#endregion
801
803
  //#region src/lib/perpsOperator.ts
802
804
  var PerpsOperator = class {
803
- baseUrl;
805
+ #baseUrl;
806
+ auth;
804
807
  constructor(baseUrl) {
805
- this.baseUrl = baseUrl;
808
+ this.#baseUrl = baseUrl;
806
809
  }
807
810
  async #request(path, body) {
808
- const url = new URL(path, this.baseUrl);
811
+ const url = new URL(path, this.#baseUrl);
809
812
  const res = await fetch(url, {
810
813
  method: body ? "POST" : "GET",
811
814
  headers: {
@@ -831,6 +834,27 @@ var PerpsOperator = class {
831
834
  const { address } = await this.#request("api/operator/address");
832
835
  return address;
833
836
  }
837
+ async genAuthMessage(userAddr) {
838
+ const { message } = await this.#request("api/auth/message", { userAddr });
839
+ return message;
840
+ }
841
+ async validateAuthMessage(authMessage, signature) {
842
+ const { address, createdAt, validUntil } = await this.#request("api/auth/validate", {
843
+ authMessage,
844
+ signature
845
+ });
846
+ return {
847
+ address,
848
+ createdAt,
849
+ validUntil
850
+ };
851
+ }
852
+ setAuth(authMessage, signature) {
853
+ this.auth = {
854
+ authMessage,
855
+ signature
856
+ };
857
+ }
834
858
  async getUserPerps(userAddr, marketAddr, type, offset = 0, limit = 1e3) {
835
859
  const params = new URLSearchParams({
836
860
  offset: offset.toString(),
@@ -845,8 +869,10 @@ var PerpsOperator = class {
845
869
  }));
846
870
  }
847
871
  async mintPerp(body) {
872
+ if (!this.auth) throw new Error("Authentication required. Call setAuth() with authMessage and signature before exercising perps.");
848
873
  const { txHash, optionId } = await this.#request("api/positions/mint", {
849
874
  ...body,
875
+ ...this.auth,
850
876
  amount: body.amount.toString()
851
877
  });
852
878
  return {
@@ -855,8 +881,10 @@ var PerpsOperator = class {
855
881
  };
856
882
  }
857
883
  async exercisePerp(body) {
884
+ if (!this.auth) throw new Error("Authentication required. Call setAuth() with authMessage and signature before exercising perps.");
858
885
  const { txHash, optionId } = await this.#request("api/positions/exercise", {
859
886
  ...body,
887
+ ...this.auth,
860
888
  optionId: body.optionId.toString(),
861
889
  liquidities: body.liquidities.map((l) => l.toString())
862
890
  });
@@ -869,8 +897,38 @@ var PerpsOperator = class {
869
897
 
870
898
  //#endregion
871
899
  //#region src/hooks/perps/usePerpsOperator.ts
900
+ const ZHex = zod.z.string().regex(/^0x[a-fA-F0-9]+$/, "Invalid hex string").transform((v) => v);
901
+ const ZSavedSignature = zod.z.object({
902
+ signature: ZHex,
903
+ message: zod.z.string()
904
+ });
905
+ const getSavedSignature = (userAddr) => {
906
+ const key = `perps-auth-${userAddr.toLowerCase()}`;
907
+ const raw = localStorage.getItem(key);
908
+ if (!raw) return;
909
+ try {
910
+ return ZSavedSignature.parse(JSON.parse(raw));
911
+ } catch (error) {
912
+ clearSignature(userAddr);
913
+ throw new Error("Invalid stored signature: " + raw);
914
+ }
915
+ };
916
+ const saveSignature = (userAddr, message, signature) => {
917
+ const key = `perps-auth-${userAddr.toLowerCase()}`;
918
+ const data = JSON.stringify({
919
+ message,
920
+ signature
921
+ });
922
+ localStorage.setItem(key, data);
923
+ };
924
+ const clearSignature = (userAddr) => {
925
+ const key = `perps-auth-${userAddr.toLowerCase()}`;
926
+ localStorage.removeItem(key);
927
+ };
872
928
  const usePerpsOperator = () => {
929
+ const { address: userAddr } = (0, wagmi.useAccount)();
873
930
  const { perpsOperatorUrl } = useTimelockConfig();
931
+ const { signMessageAsync } = (0, wagmi.useSignMessage)();
874
932
  const operator = (0, react.useMemo)(() => perpsOperatorUrl ? new PerpsOperator(perpsOperatorUrl) : void 0, [perpsOperatorUrl]);
875
933
  const { data: address } = (0, __tanstack_react_query.useQuery)({
876
934
  queryKey: ["perpsOperatorAddr", perpsOperatorUrl || "--"],
@@ -879,9 +937,34 @@ const usePerpsOperator = () => {
879
937
  refetchInterval: 1e4,
880
938
  enabled: !!operator
881
939
  });
940
+ const validateAndSetAuth = async (message, signature) => {
941
+ if (!operator || !userAddr) return;
942
+ try {
943
+ const { address: address$1, validUntil } = await operator.validateAuthMessage(message, signature);
944
+ if (validUntil < Date.now()) throw new Error("Signature expired");
945
+ if (address$1 !== userAddr) throw new Error("Valid signature but different user address");
946
+ operator.setAuth(userAddr, signature);
947
+ } catch (error) {
948
+ clearSignature(userAddr);
949
+ console.error(error);
950
+ }
951
+ };
952
+ (0, react.useEffect)(() => {
953
+ if (!userAddr || !operator) return;
954
+ const sig = getSavedSignature(userAddr);
955
+ if (!sig) return;
956
+ validateAndSetAuth(sig.message, sig.signature);
957
+ }, [userAddr, operator]);
882
958
  return {
883
959
  operator,
884
- address
960
+ address,
961
+ signMessage: (0, __tanstack_react_query.useMutation)({ mutationFn: async () => {
962
+ if (!operator || !userAddr || !signMessageAsync) return;
963
+ const message = await operator.genAuthMessage(userAddr);
964
+ const signature = await signMessageAsync({ message });
965
+ saveSignature(userAddr, message, signature);
966
+ operator.setAuth(message, signature);
967
+ } })
885
968
  };
886
969
  };
887
970
 
@@ -955,7 +1038,7 @@ const useMintPerp = (marketAddr) => {
955
1038
  const queryClient = (0, __tanstack_react_query.useQueryClient)();
956
1039
  const client = (0, wagmi.useClient)();
957
1040
  const { address } = (0, wagmi.useAccount)();
958
- const { operator, address: operatorAddr } = usePerpsOperator();
1041
+ const { operator, address: operatorAddr, signMessage: { mutateAsync: signMessage } } = usePerpsOperator();
959
1042
  const { askForApproval } = useApproval();
960
1043
  const { data: operators } = useUserOperators(address, marketAddr);
961
1044
  const { mutateAsync: setOperatorPerms } = useSetOperatorPerms(marketAddr);
@@ -971,6 +1054,7 @@ const useMintPerp = (marketAddr) => {
971
1054
  if (!operator || !operatorAddr) throw new Error("Operator address not found");
972
1055
  if (!tickSpacing || currentTick === void 0) throw new Error("Pool data not found");
973
1056
  if (optionAssetIsToken0 === void 0 || !payoutAsset) throw new Error("Market data not found");
1057
+ if (!operator.auth) await signMessage();
974
1058
  if (!hasEnoughPerms) await setOperatorPerms({
975
1059
  operator: operatorAddr,
976
1060
  canMint: true,
@@ -1005,15 +1089,16 @@ const useMintPerp = (marketAddr) => {
1005
1089
  //#endregion
1006
1090
  //#region src/hooks/perps/useClosePerp.ts
1007
1091
  const useClosePerp = () => {
1008
- const { operator } = usePerpsOperator();
1009
- return (0, __tanstack_react_query.useMutation)({ mutationFn: (body) => {
1092
+ const { operator, signMessage: { mutateAsync: signMessage } } = usePerpsOperator();
1093
+ return (0, __tanstack_react_query.useMutation)({ mutationFn: async (body) => {
1010
1094
  if (!operator) throw new Error("Operator not connected");
1011
- return operator.exercisePerp(body);
1095
+ if (!operator.auth) await signMessage();
1096
+ return await operator.exercisePerp(body);
1012
1097
  } });
1013
1098
  };
1014
1099
 
1015
1100
  //#endregion
1016
- //#region src/hooks/operators/useOperatorPerps.ts
1101
+ //#region src/hooks/operators/useOperatorPerms.ts
1017
1102
  const useOperatorPerms = (marketAddr, userAddr, operatorAddr) => {
1018
1103
  const { data,...rest } = (0, wagmi.useReadContract)({
1019
1104
  abi: require_optionsMarket.optionsMarketAbi,