timelock-sdk 0.0.94 → 0.0.96

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,13 +1,13 @@
1
- import { n as optionsMarketAbi, r as lensAbi, t as uniswapMathLensAbi } from "./uniswapMathLens-ChJFZ6hc.js";
1
+ import { n as optionsMarketAbi, r as lensAbi, t as uniswapMathLensAbi } from "./uniswapMathLens-B_cHjOOB.cjs";
2
2
  import * as viem145 from "viem";
3
- import { Address, Client, GetContractReturnType, PublicClient } from "viem";
4
- import Big from "big.js";
3
+ import { Address, Client, GetContractReturnType, Hex, PublicClient } from "viem";
5
4
  import React, { ReactNode } from "react";
5
+ import "graphql";
6
6
  import { GraphQLClient, RequestOptions } from "graphql-request";
7
7
  import * as _tanstack_react_query0 from "@tanstack/react-query";
8
8
  import { NonUndefinedGuard } from "@tanstack/react-query";
9
- import "graphql";
10
9
  import * as _tanstack_query_core17 from "@tanstack/query-core";
10
+ import Big from "big.js";
11
11
  import * as _wagmi_core0 from "@wagmi/core";
12
12
 
13
13
  //#region src/generated/graphql.d.ts
@@ -34921,9 +34921,15 @@ type ExercisePerpBody = {
34921
34921
  };
34922
34922
  declare class PerpsOperator {
34923
34923
  #private;
34924
- private baseUrl;
34925
34924
  constructor(baseUrl: string);
34926
34925
  getOperatorAddr(): Promise<Address>;
34926
+ genAuthMessage(userAddr: Address): Promise<string>;
34927
+ validateAuthMessage(authMessage: string, signature: Hex): Promise<{
34928
+ address: `0x${string}`;
34929
+ createdAt: number;
34930
+ validUntil: number;
34931
+ }>;
34932
+ setAuth(authMessage: string, signature: Hex): void;
34927
34933
  getUserPerps(userAddr: Address, marketAddr?: Address, type?: 'active' | 'closed', offset?: number, limit?: number): Promise<{
34928
34934
  optionId: bigint;
34929
34935
  id: string;
@@ -34953,9 +34959,10 @@ declare const useClosePerp: () => _tanstack_react_query0.UseMutationResult<{
34953
34959
  declare const usePerpsOperator: () => {
34954
34960
  operator: PerpsOperator | undefined;
34955
34961
  address: `0x${string}` | undefined;
34962
+ signMessage: _tanstack_react_query0.UseMutationResult<void, Error, void, unknown>;
34956
34963
  };
34957
34964
  //#endregion
34958
- //#region src/hooks/operators/useOperatorPerps.d.ts
34965
+ //#region src/hooks/operators/useOperatorPerms.d.ts
34959
34966
  declare const useOperatorPerms: (marketAddr?: Address, userAddr?: Address, operatorAddr?: Address) => {
34960
34967
  error: viem145.ReadContractErrorType;
34961
34968
  isError: true;
@@ -61922,4 +61929,4 @@ declare const useApproval: () => {
61922
61929
  };
61923
61930
  //#endregion
61924
61931
  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-S6cJb7ZQ.d.ts.map
61932
+ //# sourceMappingURL=client-CLDy2ktP.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
 
@@ -943,6 +1026,7 @@ const useSetOperatorPerms = (marketAddr) => {
943
1026
  address.toLowerCase(),
944
1027
  marketAddr.toLowerCase()
945
1028
  ] });
1029
+ queryClient.invalidateQueries({ queryKey: ["readContract"] });
946
1030
  return hash;
947
1031
  };
948
1032
  return (0, __tanstack_react_query.useMutation)({ mutationFn: setOperatorPerms });
@@ -1012,7 +1096,7 @@ const useClosePerp = () => {
1012
1096
  };
1013
1097
 
1014
1098
  //#endregion
1015
- //#region src/hooks/operators/useOperatorPerps.ts
1099
+ //#region src/hooks/operators/useOperatorPerms.ts
1016
1100
  const useOperatorPerms = (marketAddr, userAddr, operatorAddr) => {
1017
1101
  const { data,...rest } = (0, wagmi.useReadContract)({
1018
1102
  abi: require_optionsMarket.optionsMarketAbi,