@pear-protocol/symmio-client 0.2.39 → 0.2.41

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.
@@ -3,6 +3,7 @@ import { createContext, useContext, useMemo, useRef, useCallback, useEffect } fr
3
3
  import { createSymmSDK, isAuthExpiredError, isNetworkError, isInsufficientMarginError, isRateLimitedError, isTimeoutError } from '@pear-protocol/symm-core';
4
4
  import { create } from 'zustand';
5
5
  import { jsx } from 'react/jsx-runtime';
6
+ import { SiweMessage } from 'siwe';
6
7
  import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query';
7
8
  import { isAddress, encodeFunctionData } from 'viem';
8
9
 
@@ -554,19 +555,17 @@ function createSiweMessage(params) {
554
555
  const expirationTime = new Date(
555
556
  Date.now() + 30 * 24 * 60 * 60 * 1e3
556
557
  ).toISOString();
557
- const message = [
558
- `${params.domain} wants you to sign in with your Ethereum account:`,
559
- params.address,
560
- "",
561
- params.statement,
562
- "",
563
- `URI: ${params.uri}`,
564
- `Version: ${version}`,
565
- `Chain ID: ${params.chainId}`,
566
- `Nonce: ${params.nonce}`,
567
- `Issued At: ${issuedAt}`,
568
- `Expiration Time: ${expirationTime}`
569
- ].join("\n");
558
+ const message = new SiweMessage({
559
+ domain: params.domain,
560
+ address: params.address,
561
+ statement: params.statement,
562
+ chainId: params.chainId,
563
+ nonce: params.nonce,
564
+ version,
565
+ uri: params.uri,
566
+ issuedAt,
567
+ expirationTime
568
+ }).prepareMessage();
570
569
  return { message, issuedAt, expirationTime };
571
570
  }
572
571
  async function getNonce(chainId, subAccount) {
@@ -595,10 +594,24 @@ async function login(chainId, params) {
595
594
  body: JSON.stringify(body)
596
595
  });
597
596
  if (!response.ok) {
598
- const errorData = await response.json().catch(() => null);
599
- throw new Error(
600
- errorData?.error_message ?? `Login failed: ${response.statusText}`
601
- );
597
+ let errorMessage = "";
598
+ if (typeof response.text === "function") {
599
+ const rawBody = await response.text().catch(() => "");
600
+ if (rawBody) {
601
+ try {
602
+ const parsed = JSON.parse(rawBody);
603
+ errorMessage = parsed.error_message ?? parsed.message ?? parsed.detail ?? rawBody;
604
+ } catch {
605
+ errorMessage = rawBody;
606
+ }
607
+ }
608
+ }
609
+ if (!errorMessage && typeof response.json === "function") {
610
+ const errorData = await response.json().catch(() => null);
611
+ errorMessage = errorData?.error_message ?? errorData?.message ?? errorData?.detail ?? "";
612
+ }
613
+ const reason = errorMessage || response.statusText;
614
+ throw new Error(reason ? `Login failed: ${reason}` : "Login failed");
602
615
  }
603
616
  const data = await response.json();
604
617
  if (!data.access_token) {
@@ -662,15 +675,15 @@ function clearCachedToken(address, chainId) {
662
675
  }
663
676
  async function fetchAccessToken(walletClient, signerAddress, accountAddress, chainId, domain) {
664
677
  const resolvedDomain = domain ?? (typeof window !== "undefined" ? window.location.host : "localhost");
665
- const uri = typeof window !== "undefined" ? window.location.origin : `https://${resolvedDomain}`;
678
+ const hedgerLoginUrl = new URL("login", getHedgerBaseUrl(chainId)).href;
666
679
  const nonce = await getNonce(chainId, accountAddress);
667
680
  const { message, issuedAt, expirationTime } = createSiweMessage({
668
681
  address: signerAddress,
669
- statement: "Sign in to Symm Protocol",
682
+ statement: `msg: ${accountAddress}`,
670
683
  chainId,
671
684
  nonce,
672
685
  domain: resolvedDomain,
673
- uri
686
+ uri: hedgerLoginUrl
674
687
  });
675
688
  const signature = await walletClient.signMessage({
676
689
  account: signerAddress,
@@ -730,40 +743,30 @@ function logSymmAuth(event, details) {
730
743
  }
731
744
  console.log("[symm-auth]", event, details ?? {});
732
745
  }
733
- function extractSubaccountAddresses(summary) {
734
- const accounts = summary?.data?.accounts;
735
- if (!Array.isArray(accounts)) {
736
- return [];
737
- }
738
- return accounts.flatMap((account) => {
739
- const accountAddress = account.accountAddress ?? account.address;
740
- return accountAddress ? [accountAddress] : [];
741
- });
742
- }
743
746
  function useSymmAuth(params) {
744
747
  const context = useSymmContext();
745
748
  const ctx = context;
746
- const { symmCoreClient } = context;
747
749
  const address = params?.address ?? ctx.address;
748
750
  const chainId = params?.chainId ?? ctx.chainId ?? 42161;
749
751
  const walletClient = params?.walletClient ?? ctx.walletClient;
750
752
  const siweDomain = params?.siweDomain;
753
+ const activeAccountAddress = params?.activeAccountAddress ?? address;
751
754
  const token = useSymmAuthStore((state) => {
752
- if (address) {
753
- return state.tokensByKey[symmAuthTokenKey(address, chainId)] ?? null;
755
+ if (activeAccountAddress) {
756
+ return state.tokensByKey[symmAuthTokenKey(activeAccountAddress, chainId)] ?? null;
754
757
  }
755
758
  return ctx.accessToken ?? ctx.authToken ?? null;
756
759
  });
757
760
  const setToken = useSymmAuthStore((state) => state.setToken);
758
761
  const getToken = useSymmAuthStore((state) => state.getToken);
759
762
  const clearToken = useSymmAuthStore((state) => state.clearToken);
760
- const previousAddressRef = useRef(address);
763
+ const previousAddressRef = useRef(activeAccountAddress);
761
764
  const previousChainIdRef = useRef(chainId);
762
765
  const refreshAuthRef = useRef(async () => null);
763
766
  const refreshAuth = useCallback(
764
767
  async (accountAddress, options) => {
765
768
  if (!walletClient || !address) return null;
766
- const resolvedAccountAddress = accountAddress ?? address;
769
+ const resolvedAccountAddress = accountAddress ?? activeAccountAddress ?? address;
767
770
  if (!options?.force) {
768
771
  const inStore = getToken(resolvedAccountAddress, chainId);
769
772
  if (inStore) {
@@ -815,139 +818,70 @@ function useSymmAuth(params) {
815
818
  return null;
816
819
  }
817
820
  },
818
- [walletClient, address, chainId, siweDomain, getToken, setToken, clearToken]
821
+ [walletClient, address, activeAccountAddress, chainId, siweDomain, getToken, setToken, clearToken]
819
822
  );
820
823
  refreshAuthRef.current = refreshAuth;
821
824
  const clearAuth = useCallback(() => {
822
- if (address) {
823
- clearCachedToken(address, chainId);
824
- clearToken(address, chainId);
825
+ if (activeAccountAddress) {
826
+ clearCachedToken(activeAccountAddress, chainId);
827
+ clearToken(activeAccountAddress, chainId);
825
828
  }
826
- }, [address, chainId, clearToken]);
827
- console.log("symm auth", {
828
- address,
829
- chainId,
830
- walletClient,
831
- symmCoreClient
832
- });
829
+ }, [activeAccountAddress, chainId, clearToken]);
833
830
  useEffect(() => {
834
831
  const previousAddress = previousAddressRef.current;
835
832
  const previousChainId = previousChainIdRef.current;
836
- const addressChanged = previousAddress !== address;
833
+ const addressChanged = previousAddress !== activeAccountAddress;
837
834
  const chainChanged = previousChainId !== chainId;
838
835
  let cancelled = false;
839
- previousAddressRef.current = address;
836
+ previousAddressRef.current = activeAccountAddress;
840
837
  previousChainIdRef.current = chainId;
841
838
  logSymmAuth("bootstrap:dependencies", {
842
- address,
839
+ signerAddress: address,
840
+ activeAccountAddress,
843
841
  chainId,
844
842
  hasWalletClient: !!walletClient,
845
- hasSymmCoreClient: !!symmCoreClient,
846
843
  hasRefreshAuth: !!refreshAuthRef.current,
847
844
  addressChanged,
848
845
  chainChanged,
849
846
  previousAddress,
850
847
  previousChainId
851
848
  });
852
- console.log("bootstrap:dependencies", {
853
- address,
854
- chainId,
855
- hasWalletClient: !!walletClient,
856
- hasSymmCoreClient: !!symmCoreClient,
857
- hasRefreshAuth: !!refreshAuthRef.current,
858
- addressChanged,
859
- chainChanged,
860
- previousAddress,
861
- previousChainId
862
- });
863
- if (!address) {
864
- logSymmAuth("bootstrap:skip-no-address", {
849
+ if (!activeAccountAddress) {
850
+ logSymmAuth("bootstrap:skip-no-active-account", {
851
+ signerAddress: address,
865
852
  chainId,
866
- hasWalletClient: !!walletClient,
867
- hasSymmCoreClient: !!symmCoreClient
868
- });
869
- console.log("bootstrap:skip-no-address", {
870
- chainId,
871
- hasWalletClient: !!walletClient,
872
- hasSymmCoreClient: !!symmCoreClient
853
+ hasWalletClient: !!walletClient
873
854
  });
874
855
  return;
875
856
  }
876
- const userAddress = address;
877
857
  if (previousAddress && (addressChanged || chainChanged)) {
878
858
  clearCachedToken(previousAddress, previousChainId);
879
859
  clearToken(previousAddress, previousChainId);
880
860
  }
881
861
  async function bootstrapAuth() {
882
862
  logSymmAuth("bootstrap:run", {
883
- userAddress,
863
+ signerAddress: address,
864
+ activeAccountAddress,
884
865
  chainId,
885
866
  hasWalletClient: !!walletClient,
886
- hasSymmCoreClient: !!symmCoreClient,
887
867
  hasRefreshAuth: !!refreshAuthRef.current
888
868
  });
889
- console.log("bootstrap:run", {
890
- userAddress,
891
- chainId,
892
- hasWalletClient: !!walletClient,
893
- hasSymmCoreClient: !!symmCoreClient,
894
- hasRefreshAuth: !!refreshAuthRef.current
895
- });
896
- let targets = [userAddress];
897
- if (symmCoreClient) {
898
- try {
899
- const summary = await symmCoreClient.accounts.getSummary({
900
- userAddress,
901
- chainId
902
- });
903
- const subaccounts = extractSubaccountAddresses(summary);
904
- if (subaccounts.length > 0) {
905
- targets = subaccounts;
906
- }
907
- logSymmAuth("bootstrap:subaccounts-resolved", {
908
- userAddress,
909
- chainId,
910
- subaccounts
911
- });
912
- console.log("bootstrap:subaccounts-resolved", {
913
- userAddress,
914
- chainId,
915
- subaccounts
916
- });
917
- } catch (error) {
918
- logSymmAuth("bootstrap:subaccounts-failed", {
919
- userAddress,
920
- chainId,
921
- error: error instanceof Error ? error.message : String(error)
922
- });
923
- console.log("bootstrap:subaccounts-failed", {
924
- userAddress,
925
- chainId,
926
- error: error instanceof Error ? error.message : String(error)
927
- });
928
- }
929
- }
930
- const uniqueTargets = [...new Set(targets)].filter(
931
- (accountAddress) => !!accountAddress
932
- );
933
869
  logSymmAuth("bootstrap:start", {
934
- userAddress,
870
+ signerAddress: address,
935
871
  chainId,
936
- targets: uniqueTargets,
872
+ activeAccountAddress,
937
873
  walletReady: !!walletClient
938
874
  });
939
- for (const accountAddress of uniqueTargets) {
940
- if (cancelled) {
941
- return;
942
- }
943
- await refreshAuthRef.current(accountAddress);
875
+ if (cancelled) {
876
+ return;
944
877
  }
878
+ await refreshAuthRef.current(activeAccountAddress);
945
879
  }
946
- bootstrapAuth();
880
+ void bootstrapAuth();
947
881
  return () => {
948
882
  cancelled = true;
949
883
  };
950
- }, [address, walletClient, chainId, symmCoreClient]);
884
+ }, [address, activeAccountAddress, walletClient, chainId, clearToken]);
951
885
  return {
952
886
  accessToken: token,
953
887
  authToken: token,
@@ -25199,6 +25133,7 @@ function useResolveTradeAuthToken(params = {}) {
25199
25133
  const chainId = params.chainId ?? context.chainId;
25200
25134
  const { refreshAuth } = useSymmAuth({
25201
25135
  address,
25136
+ activeAccountAddress: address,
25202
25137
  chainId,
25203
25138
  walletClient: params.walletClient,
25204
25139
  siweDomain: params.siweDomain