@polyester/sdk 0.26.1 → 0.27.1

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.
Files changed (91) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/account-signer/types.d.ts +3 -1
  3. package/dist/account-signer/types.d.ts.map +1 -1
  4. package/dist/account-signer/types.js.map +1 -1
  5. package/dist/gen/auth/v1/auth_pb.d.ts +30 -21
  6. package/dist/gen/auth/v1/auth_pb.d.ts.map +1 -1
  7. package/dist/gen/auth/v1/auth_pb.js +25 -8
  8. package/dist/gen/auth/v1/auth_pb.js.map +1 -1
  9. package/dist/gen/auth/v1/mfa_pb.js +1 -1
  10. package/dist/gen/auth/v1/mfa_pb.js.map +1 -1
  11. package/dist/gen/auth/v1/profile_pb.d.ts +2 -2
  12. package/dist/gen/auth/v1/profile_pb.d.ts.map +1 -1
  13. package/dist/gen/auth/v1/profile_pb.js +2 -1
  14. package/dist/gen/auth/v1/profile_pb.js.map +1 -1
  15. package/dist/gen/auth/v1/resolve_pb.d.ts.map +1 -1
  16. package/dist/gen/auth/v1/resolve_pb.js +2 -1
  17. package/dist/gen/auth/v1/resolve_pb.js.map +1 -1
  18. package/dist/gen/auth/v1/social_verification_pb.d.ts +3 -0
  19. package/dist/gen/auth/v1/social_verification_pb.d.ts.map +1 -1
  20. package/dist/gen/auth/v1/social_verification_pb.js +2 -1
  21. package/dist/gen/auth/v1/social_verification_pb.js.map +1 -1
  22. package/dist/gen/auth/v1/subaccounts_pb.d.ts +90 -10
  23. package/dist/gen/auth/v1/subaccounts_pb.d.ts.map +1 -1
  24. package/dist/gen/auth/v1/subaccounts_pb.js +40 -28
  25. package/dist/gen/auth/v1/subaccounts_pb.js.map +1 -1
  26. package/dist/gen/claims/v1/claims_pb.d.ts +108 -2
  27. package/dist/gen/claims/v1/claims_pb.d.ts.map +1 -1
  28. package/dist/gen/claims/v1/claims_pb.js +109 -11
  29. package/dist/gen/claims/v1/claims_pb.js.map +1 -1
  30. package/dist/gen/index.d.ts +1 -1
  31. package/dist/gen/index.js +1 -1
  32. package/dist/gen/ledger/read/v1/ledger_read_pb.d.ts.map +1 -1
  33. package/dist/gen/ledger/read/v1/ledger_read_pb.js +6 -1
  34. package/dist/gen/ledger/read/v1/ledger_read_pb.js.map +1 -1
  35. package/dist/gen/orderbook/v1/orderbook_pb.d.ts +1 -1
  36. package/dist/gen/orderbook/v1/orderbook_pb.js.map +1 -1
  37. package/dist/gen/orders/v1/orders_read_pb.d.ts +10 -0
  38. package/dist/gen/orders/v1/orders_read_pb.d.ts.map +1 -1
  39. package/dist/gen/orders/v1/orders_read_pb.js +1 -1
  40. package/dist/gen/orders/v1/orders_read_pb.js.map +1 -1
  41. package/dist/gen/polyester/api/options_pb.d.ts +39 -2
  42. package/dist/gen/polyester/api/options_pb.d.ts.map +1 -1
  43. package/dist/gen/polyester/api/options_pb.js +43 -2
  44. package/dist/gen/polyester/api/options_pb.js.map +1 -1
  45. package/dist/index.d.ts +4 -4
  46. package/dist/index.js +2 -2
  47. package/dist/services/auth/account-signer-auth.d.ts +13 -6
  48. package/dist/services/auth/account-signer-auth.d.ts.map +1 -1
  49. package/dist/services/auth/account-signer-auth.js +15 -13
  50. package/dist/services/auth/account-signer-auth.js.map +1 -1
  51. package/dist/services/auth/auth.d.ts +6 -4
  52. package/dist/services/auth/auth.d.ts.map +1 -1
  53. package/dist/services/auth/auth.js +7 -6
  54. package/dist/services/auth/auth.js.map +1 -1
  55. package/dist/services/auth/auth.types.d.ts +2 -2
  56. package/dist/services/auth/session.schemas.js +1 -0
  57. package/dist/services/auth/session.schemas.js.map +1 -1
  58. package/dist/services/auth/session.types.d.ts +1 -1
  59. package/dist/services/claims/claims.js +1 -1
  60. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  61. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  62. package/dist/services/orders/orders-output.schemas.d.ts +12 -6
  63. package/dist/services/orders/orders-output.schemas.d.ts.map +1 -1
  64. package/dist/services/orders/orders-output.schemas.js +2 -0
  65. package/dist/services/orders/orders-output.schemas.js.map +1 -1
  66. package/dist/services/subaccounts/index.d.ts +2 -2
  67. package/dist/services/subaccounts/subaccounts.d.ts +9 -3
  68. package/dist/services/subaccounts/subaccounts.d.ts.map +1 -1
  69. package/dist/services/subaccounts/subaccounts.js +13 -3
  70. package/dist/services/subaccounts/subaccounts.js.map +1 -1
  71. package/dist/services/subaccounts/subaccounts.schemas.d.ts +21 -2
  72. package/dist/services/subaccounts/subaccounts.schemas.d.ts.map +1 -1
  73. package/dist/services/subaccounts/subaccounts.schemas.js +13 -2
  74. package/dist/services/subaccounts/subaccounts.schemas.js.map +1 -1
  75. package/dist/services/subaccounts/subaccounts.types.d.ts +2 -2
  76. package/dist/services/trades/trades.schemas.d.ts +1 -1
  77. package/dist/services/triggers/trigger-input.schemas.d.ts +1 -1
  78. package/dist/services/triggers/triggers-output.schemas.d.ts +15 -15
  79. package/dist/shared/connect-error-mapping.d.ts.map +1 -1
  80. package/dist/shared/connect-error-mapping.js +6 -4
  81. package/dist/shared/connect-error-mapping.js.map +1 -1
  82. package/dist/shared/error-detail.d.ts +12 -8
  83. package/dist/shared/error-detail.d.ts.map +1 -1
  84. package/dist/shared/error-detail.js +30 -19
  85. package/dist/shared/error-detail.js.map +1 -1
  86. package/dist/shared/errors.d.ts +10 -1
  87. package/dist/shared/errors.d.ts.map +1 -1
  88. package/dist/shared/errors.js +12 -1
  89. package/dist/shared/errors.js.map +1 -1
  90. package/dist/wired-services.js +1 -1
  91. package/package.json +1 -1
@@ -1,13 +1,14 @@
1
- import { AccountSigner, AccountSignerConfig } from "../../account-signer/types.js";
1
+ import { AccountSigner, AccountSignerConfig, HexAddress } from "../../account-signer/types.js";
2
2
  import { PolyesterEnvironment } from "../../environment.js";
3
3
  import { AuthAndPublicApiTransports } from "../../shared/transports.js";
4
4
  import { PolyesterRealtime } from "../../realtime/types.js";
5
5
  import "../../realtime/index.js";
6
6
  import { AuthService } from "./auth.js";
7
+ import { SubaccountChallenge } from "../subaccounts/subaccounts.schemas.js";
7
8
  import { SubaccountsService } from "../subaccounts/subaccounts.js";
8
9
  import "../subaccounts/index.js";
9
10
  import { AuthTokenStorage } from "./token-storage.js";
10
- import { AuthHydrationData, AuthLoginMethod, AuthState } from "./session.types.js";
11
+ import { AuthHydrationData, AuthLoginMethod, AuthState, SessionData } from "./session.types.js";
11
12
  import { AuthSessionStore } from "./session.js";
12
13
  import { EventEmitter } from "../../utils/event-emitter.js";
13
14
  //#region src/services/auth/account-signer-auth.d.ts
@@ -33,18 +34,24 @@ interface LoginOptions {
33
34
  /**
34
35
  * The wallet provider to use for login.
35
36
  */
36
- provider: "metamask" | "turnkey" | "other";
37
+ provider: SessionData["provider"];
37
38
  /** Browser origin requesting the signature; defaults to location.origin in browsers. Required outside browsers. */
38
39
  uri?: string;
39
40
  loginMethod?: AuthLoginMethod | null;
40
41
  }
41
42
  interface CreateSubaccountParams {
42
- /** The account signer for the new subaccount (caller derives this, e.g. via Turnkey saltNonce) */
43
- accountSigner: AccountSigner;
43
+ /**
44
+ * Signer for the new subaccount, or a factory that derives it from the server challenge
45
+ * (for example via Turnkey with `challenge.smartAccountSaltNonce`). Its accountAddress must
46
+ * equal `challenge.smartAccountAddress`.
47
+ */
48
+ accountSigner: AccountSigner | ((challenge: SubaccountChallenge) => AccountSigner | Promise<AccountSigner>);
44
49
  /** Optional human-readable label for this subaccount */
45
50
  label?: string;
46
51
  /** Browser origin requesting the signature; defaults to location.origin in browsers. Required outside browsers. */
47
52
  uri?: string;
53
+ /** Root owner EOA bound to the authenticated account; defaults to the configured signer's owner. */
54
+ ownerAddress?: HexAddress;
48
55
  }
49
56
  interface CreateSubaccountResult {
50
57
  subaccountId: string;
@@ -107,7 +114,7 @@ declare class AccountSignerAuthService extends AuthService {
107
114
  refreshSession(params?: {
108
115
  /** Overrides the origin remembered from login. */
109
116
  uri?: string;
110
- provider?: "metamask" | "turnkey" | "other";
117
+ provider?: SessionData["provider"];
111
118
  loginMethod?: AuthLoginMethod | null;
112
119
  }): Promise<LoginResult>;
113
120
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"account-signer-auth.d.ts","names":[],"sources":["../../../src/services/auth/account-signer-auth.ts"],"mappings":";;;;;;;;;;;;;UAyBiB;EACb;IAAiB;IAAmB;;EACpC;EACA;IAAS;IAAc;;EACvB;EACA,aAAa;;UAGA;EACb;EACA;EACA,WAAW;;UAGE;;;;EAIb;;EAEA;EACA,cAAc;;UAGD;;EAEb,eAAe;;EAEf;;EAEA;;UAGa;EACb;EACA;EACA;;;;;cAWS,iCAAiC;;WACjC,QAAM,aAAA;EAoBH,cACR,YACA,qBACA,aACA,aACA,UACA,cACA;IAEA,YAAY;IACZ,sBAAsB;IACtB,aAAa;IACb,aAAa;IACb,UAAU;IACV,cAAc;IACd,eAAe;;;;;EAmBnB,sBAAsB,aAAa;;;;EAOnC,iBAAiB,eAAe;;;;EAWhC,oBAAoB;;;;EAOd,MAAM,SAAS,eAAe,QAAQ;;;;EA0F5C,iBAAiB,OAAO;;;;EAyBlB,kBAAkB;IAAU;IAAmB;;;;;EA0E/C,UAAU;;;;EAqChB;;;;EASM,eAAe;;IAEjB;IACA;IACA,cAAc;MACd,QAAQ;;;;EAmBZ,cACI,mBACA;IAAY;IAA8B;;IACzC;IAAmB;;;EAuBxB,oBAAoB;;;;EASd,iBAAiB,QAAQ,yBAAyB,QAAQ;;;;EAuChE,YAAY"}
1
+ {"version":3,"file":"account-signer-auth.d.ts","names":[],"sources":["../../../src/services/auth/account-signer-auth.ts"],"mappings":";;;;;;;;;;;;;;UAyBiB;EACb;IAAiB;IAAmB;;EACpC;EACA;IAAS;IAAc;;EACvB;EACA,aAAa;;UAGA;EACb;EACA;EACA,WAAW;;UAGE;;;;EAIb,UAAU;;EAEV;EACA,cAAc;;UAGD;;;;;;EAMb,eACM,kBACE,WAAW,wBAAwB,gBAAgB,QAAQ;;EAEnE;;EAEA;;EAEA,eAAe;;UAGF;EACb;EACA;EACA;;;;;cAWS,iCAAiC;;WACjC,QAAM,aAAA;EAoBH,cACR,YACA,qBACA,aACA,aACA,UACA,cACA;IAEA,YAAY;IACZ,sBAAsB;IACtB,aAAa;IACb,aAAa;IACb,UAAU;IACV,cAAc;IACd,eAAe;;;;;EAmBnB,sBAAsB,aAAa;;;;EAOnC,iBAAiB,eAAe;;;;EAWhC,oBAAoB;;;;EAOd,MAAM,SAAS,eAAe,QAAQ;;;;EAyF5C,iBAAiB,OAAO;;;;EAyBlB,kBAAkB;IAAU;IAAmB;;;;;EA0E/C,UAAU;;;;EAqChB;;;;EASM,eAAe;;IAEjB;IACA,WAAW;IACX,cAAc;MACd,QAAQ;;;;EAmBZ,cACI,mBACA;IAAY;IAA8B;;IACzC;IAAmB;;;EAuBxB,oBAAoB;;;;EASd,iBAAiB,QAAQ,yBAAyB,QAAQ;;;;EAyDhE,YAAY"}
@@ -76,8 +76,7 @@ var AccountSignerAuthService = class extends AuthService {
76
76
  const { message } = await this.createWalletChallenge({
77
77
  smartAccountAddress,
78
78
  signerAddress: ownerAddress,
79
- uri,
80
- purpose: "login"
79
+ uri
81
80
  });
82
81
  const signature = await accountSigner.signMessage(message);
83
82
  const response = await this.loginWithWallet({
@@ -88,7 +87,7 @@ var AccountSignerAuthService = class extends AuthService {
88
87
  });
89
88
  if (!this.#isCurrentAuthOperation(generation, startingToken)) throw new DOMException("Authentication operation superseded", "AbortError");
90
89
  const environmentSession = this.#getEnvironmentSession();
91
- const resolvedLoginMethod = loginMethod ?? this.#loginMethod ?? environmentSession?.loginMethod ?? (provider === "metamask" ? "metamask" : null);
90
+ const resolvedLoginMethod = loginMethod ?? this.#loginMethod ?? environmentSession?.loginMethod ?? (provider === "metamask" || provider === "phantom" ? provider : null);
92
91
  const tokenOptions = createAuthTokenStorageSetOptions(response.accessToken);
93
92
  const activeAccount = previousActiveAccount?.mainAccountId === response.accountId ? previousActiveAccount : void 0;
94
93
  this.#sessionStore.commitLogin({
@@ -281,19 +280,22 @@ var AccountSignerAuthService = class extends AuthService {
281
280
  async createSubaccount(params) {
282
281
  if (!this.#isAuthenticated) throw new AuthenticationError("Must be authenticated to create subaccounts");
283
282
  if (!this.#subaccounts) throw new ConfigurationError("SubaccountsService not configured. Pass it to constructor or call setSubaccountsService().");
284
- const { accountSigner, label = "" } = params;
285
- this.#assertAccountSignerEnvironment(accountSigner);
286
- const { message } = await this.createWalletChallenge({
287
- smartAccountAddress: accountSigner.accountAddress,
288
- signerAddress: accountSigner.accountAddress,
289
- uri: resolveChallengeUri(params.uri ?? this.#challengeUri),
290
- purpose: "create_subaccount"
283
+ const identity = this.#accountSigner ?? this.#accountIdentity;
284
+ const ownerAddress = params.ownerAddress ?? identity?.ownerAddress ?? identity?.accountAddress;
285
+ if (!ownerAddress) throw new ConfigurationError("No root owner address available. Pass ownerAddress or configure an account signer.");
286
+ const { label = "" } = params;
287
+ const challenge = await this.#subaccounts.createChallenge({
288
+ ownerAddress,
289
+ uri: resolveChallengeUri(params.uri ?? this.#challengeUri)
291
290
  });
292
- const signature = await accountSigner.signMessage(message);
291
+ const accountSigner = typeof params.accountSigner === "function" ? await params.accountSigner(challenge) : params.accountSigner;
292
+ this.#assertAccountSignerEnvironment(accountSigner);
293
+ if (accountSigner.accountAddress.toLowerCase() !== challenge.smartAccountAddress.toLowerCase()) throw new ConfigurationError(`Subaccount signer address ${accountSigner.accountAddress} does not match the server-derived smart account ${challenge.smartAccountAddress}.`);
294
+ const signature = await accountSigner.signMessage(challenge.message);
293
295
  const response = await this.#subaccounts.create({
294
296
  label,
295
- smartAccountAddress: accountSigner.accountAddress,
296
- message,
297
+ smartAccountAddress: challenge.smartAccountAddress,
298
+ message: challenge.message,
297
299
  signature
298
300
  });
299
301
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"account-signer-auth.js","names":["#accountSignerConfig","#environmentFingerprint","#subaccounts","#tokenStorage","#realtime","#sessionStore","#assertAccountSignerEnvironment","#beginAuthOperation","#accountSigner","#accountIdentity","#identityFromSigner","#notifyStateChange","#login","#resolveAccountSigner","#challengeUri","#isCurrentAuthOperation","#getEnvironmentSession","#loginMethod","#isAuthenticated","#mainAccountId","#activeAccountId","#walletProvider","#loginResult","#getEnvironmentBoundToken","#clearExpiredSessionState","#getCurrentTokenStorageOptions","#resolveRefreshProvider","#authOperationGeneration"],"sources":["../../../src/services/auth/account-signer-auth.ts"],"sourcesContent":["import { AuthService, type LoginWithWalletResponse } from \"./auth.js\";\nimport { AuthenticationError, ConfigurationError } from \"../../shared/errors.js\";\nimport { toPolyesterError } from \"../../shared/connect-error-mapping.js\";\nimport { AuthSessionStore } from \"./session.js\";\nimport type { AccountSigner, AccountSignerConfig, HexAddress } from \"../../account-signer/types.js\";\nimport { assertAccountSigner, resolveAccountSigner } from \"../../account-signer/types.js\";\nimport { EventEmitter } from \"../../utils/event-emitter.js\";\nimport { isJwtValid, getJwtTimeToExpiry } from \"../../utils/jwt.js\";\nimport type { SubaccountsService } from \"../subaccounts/index.js\";\nimport type {\n AuthState,\n AuthHydrationData,\n AuthLoginMethod,\n SessionData,\n ActiveAccountInfo,\n} from \"./session.types.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\nimport type { PolyesterEnvironment } from \"../../environment.js\";\nimport type { AuthAndPublicApiTransports } from \"../../shared/transports.js\";\nimport {\n createAuthTokenStorageSetOptions,\n type AuthTokenStorage,\n type AuthTokenStorageSetOptions,\n} from \"./token-storage.js\";\n\nexport interface AccountSignerAuthEvents {\n authenticated: { accountId: string; username: string };\n loggedOut: void;\n error: { code: string; message: string };\n servicesReady: void;\n stateChange: AuthState;\n}\n\nexport interface LoginResult {\n accountId: string;\n username: string;\n expiresAt: Date;\n}\n\nexport interface LoginOptions {\n /**\n * The wallet provider to use for login.\n */\n provider: \"metamask\" | \"turnkey\" | \"other\";\n /** Browser origin requesting the signature; defaults to location.origin in browsers. Required outside browsers. */\n uri?: string;\n loginMethod?: AuthLoginMethod | null;\n}\n\nexport interface CreateSubaccountParams {\n /** The account signer for the new subaccount (caller derives this, e.g. via Turnkey saltNonce) */\n accountSigner: AccountSigner;\n /** Optional human-readable label for this subaccount */\n label?: string;\n /** Browser origin requesting the signature; defaults to location.origin in browsers. Required outside browsers. */\n uri?: string;\n}\n\nexport interface CreateSubaccountResult {\n subaccountId: string;\n smartAccountSaltNonce: number;\n revision: string;\n}\n\ninterface AccountIdentity {\n accountAddress: HexAddress;\n ownerAddress?: HexAddress;\n}\n\n/**\n * Coordinates wallet/account-signer authentication, session storage, subaccount selection, and session refresh.\n */\nexport class AccountSignerAuthService extends AuthService {\n readonly events = new EventEmitter<AccountSignerAuthEvents>();\n\n #accountSignerConfig: AccountSignerConfig | undefined;\n #accountSigner: AccountSigner | null = null;\n #accountIdentity: AccountIdentity | null = null;\n #isAuthenticated = false;\n #mainAccountId: string | null = null;\n #activeAccountId: string | null = null;\n #subaccounts: SubaccountsService;\n #walletProvider: \"metamask\" | \"turnkey\" | \"other\" | undefined = undefined;\n #loginMethod: AuthLoginMethod | null = null;\n #challengeUri: string | undefined = undefined;\n #environmentFingerprint: string;\n #tokenStorage: AuthTokenStorage;\n #sessionStore: AuthSessionStore;\n #realtime: PolyesterRealtime;\n // Every asynchronous auth transition captures this generation. A later login,\n // logout, signer change, or restore makes older work observational only.\n #authOperationGeneration = 0;\n\n constructor({\n transports,\n accountSignerConfig,\n environment,\n subaccounts,\n realtime,\n tokenStorage,\n sessionStore,\n }: {\n transports: AuthAndPublicApiTransports;\n accountSignerConfig?: AccountSignerConfig;\n environment: PolyesterEnvironment;\n subaccounts: SubaccountsService;\n realtime: PolyesterRealtime;\n tokenStorage: AuthTokenStorage;\n sessionStore?: AuthSessionStore;\n }) {\n super(transports, realtime);\n\n this.#accountSignerConfig = accountSignerConfig;\n this.#environmentFingerprint = environment.fingerprint;\n this.#subaccounts = subaccounts;\n this.#tokenStorage = tokenStorage;\n this.#realtime = realtime;\n this.#sessionStore =\n sessionStore ??\n new AuthSessionStore({\n environmentFingerprint: environment.fingerprint,\n });\n }\n\n /**\n * Attaches the subaccounts service used when creating a subaccount during authenticated flows.\n */\n setSubaccountsService(subaccounts: SubaccountsService): void {\n this.#subaccounts = subaccounts;\n }\n\n /**\n * Sets the account signer used to sign login and account-switch challenges.\n */\n setAccountSigner(accountSigner: AccountSigner | null): void {\n if (accountSigner) this.#assertAccountSignerEnvironment(accountSigner);\n this.#beginAuthOperation();\n this.#accountSigner = accountSigner;\n this.#accountIdentity = accountSigner ? this.#identityFromSigner(accountSigner) : null;\n this.#notifyStateChange();\n }\n\n /**\n * Returns the active account signer, throwing if one has not been configured.\n */\n getAccountSigner(): AccountSigner | null {\n return this.#accountSigner;\n }\n\n /**\n * Signs a server-issued SIWE message with the configured account signer, exchanges it for a session token, and stores the hydrated account/subaccount session state.\n */\n async login(options: LoginOptions): Promise<LoginResult> {\n return this.#login(options);\n }\n\n async #login(\n options: LoginOptions,\n previousActiveAccount?: ActiveAccountInfo,\n ): Promise<LoginResult> {\n const generation = this.#beginAuthOperation();\n const startingToken = this.#tokenStorage.get();\n const { provider, loginMethod } = options;\n\n const accountSigner = await this.#resolveAccountSigner();\n\n if (!accountSigner) {\n throw new ConfigurationError(\n \"No account signer configured. Call setAccountSigner() or pass accountSigner in config.\",\n );\n }\n\n const smartAccountAddress = accountSigner.accountAddress;\n const ownerAddress = accountSigner.ownerAddress ?? accountSigner.accountAddress;\n\n const uri = resolveChallengeUri(options.uri ?? this.#challengeUri);\n const { message } = await this.createWalletChallenge({\n smartAccountAddress,\n signerAddress: ownerAddress,\n uri,\n purpose: \"login\",\n });\n const signature = await accountSigner.signMessage(message);\n\n const response = await this.loginWithWallet({\n smartAccountAddress,\n message,\n signature,\n walletProvider: provider,\n });\n\n if (!this.#isCurrentAuthOperation(generation, startingToken)) {\n throw new DOMException(\"Authentication operation superseded\", \"AbortError\");\n }\n const environmentSession = this.#getEnvironmentSession();\n const resolvedLoginMethod =\n loginMethod ??\n this.#loginMethod ??\n environmentSession?.loginMethod ??\n (provider === \"metamask\" ? \"metamask\" : null);\n\n const tokenOptions = createAuthTokenStorageSetOptions(response.accessToken);\n const activeAccount =\n previousActiveAccount?.mainAccountId === response.accountId\n ? previousActiveAccount\n : undefined;\n this.#sessionStore.commitLogin(\n {\n accessToken: response.accessToken,\n tokenOptions,\n provider,\n loginMethod: resolvedLoginMethod,\n primaryWallet: ownerAddress,\n smartAccount: smartAccountAddress,\n accountId: response.accountId,\n activeAccount,\n username: response.username ?? undefined,\n },\n this.#tokenStorage,\n );\n this.#isAuthenticated = true;\n this.#mainAccountId = response.accountId;\n this.#activeAccountId = activeAccount?.accountId ?? response.accountId;\n this.#walletProvider = provider;\n this.#loginMethod = resolvedLoginMethod;\n this.#challengeUri = uri;\n this.#accountSigner = accountSigner;\n this.#accountIdentity = this.#identityFromSigner(accountSigner);\n\n this.#notifyStateChange();\n\n this.events.emit(\"authenticated\", {\n accountId: response.accountId,\n username: response.username,\n });\n\n return this.#loginResult(response);\n }\n\n /**\n * Builds auth state from a session token and optional active account override.\n */\n hydrateAuthState(state: AuthHydrationData): void {\n this.#beginAuthOperation();\n const existingToken = this.#getEnvironmentBoundToken();\n if (!existingToken || !isJwtValid(existingToken)) return;\n\n const existingSession = this.#getEnvironmentSession();\n this.#walletProvider = existingSession?.provider ?? this.#walletProvider;\n this.#loginMethod = existingSession?.loginMethod ?? this.#loginMethod;\n\n this.#isAuthenticated = true;\n this.#mainAccountId = state.mainAccountId;\n this.#activeAccountId = state.activeAccountId ?? state.mainAccountId;\n this.#accountIdentity = state.smartAccountAddress\n ? {\n accountAddress: state.smartAccountAddress,\n ownerAddress: state.ownerAddress,\n }\n : null;\n\n this.#notifyStateChange();\n }\n\n /**\n * Loads the stored token, validates that it still belongs to this environment, and restores auth state when possible.\n */\n async restoreSession(): Promise<{ accountId: string; username: string } | null> {\n const generation = this.#beginAuthOperation();\n const existingToken = this.#getEnvironmentBoundToken();\n\n if (!existingToken || !isJwtValid(existingToken)) {\n if (this.#isCurrentAuthOperation(generation)) this.#clearExpiredSessionState();\n return null;\n }\n\n let me: Awaited<ReturnType<AuthService[\"me\"]>>;\n try {\n me = await this.me();\n } catch (error) {\n if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;\n const mappedError = toPolyesterError(error);\n if (mappedError instanceof AuthenticationError) {\n this.#clearExpiredSessionState();\n return null;\n }\n throw mappedError;\n }\n if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;\n\n let accountSigner = this.#accountSigner;\n if (!accountSigner) {\n try {\n accountSigner = await resolveAccountSigner(this.#accountSignerConfig);\n } catch (error) {\n if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;\n throw error;\n }\n if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;\n if (accountSigner) this.#assertAccountSignerEnvironment(accountSigner);\n }\n\n if (!isJwtValid(existingToken) || this.#getEnvironmentBoundToken() !== existingToken) {\n this.#clearExpiredSessionState();\n return null;\n }\n\n const existingSession = this.#getEnvironmentSession();\n const walletProvider = existingSession?.provider ?? this.#walletProvider;\n const loginMethod = existingSession?.loginMethod ?? this.#loginMethod;\n const activeAccountId =\n this.#activeAccountId ?? existingSession?.activeAccount?.accountId ?? me.accountId;\n\n // Publish runtime state only after asynchronous restoration has completed.\n if (accountSigner) {\n this.#sessionStore.ensureSession(\n {\n provider: walletProvider ?? \"other\",\n loginMethod: loginMethod ?? (walletProvider === \"metamask\" ? \"metamask\" : null),\n primaryWallet: accountSigner.ownerAddress ?? accountSigner.accountAddress,\n smartAccount: accountSigner.accountAddress,\n accountId: me.accountId,\n username: me.username ?? undefined,\n },\n { maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds },\n );\n this.#accountSigner = accountSigner;\n this.#accountIdentity = this.#identityFromSigner(accountSigner);\n }\n this.#isAuthenticated = true;\n this.#mainAccountId = me.accountId;\n this.#activeAccountId = activeAccountId;\n this.#walletProvider = walletProvider ?? (accountSigner ? \"other\" : undefined);\n this.#loginMethod = loginMethod;\n this.#notifyStateChange();\n return { accountId: me.accountId, username: me.username };\n }\n\n /**\n * Clears stored auth state and removes the persisted auth token.\n */\n async logout(): Promise<void> {\n this.#beginAuthOperation();\n this.#realtime.disconnectPrivate();\n this.#tokenStorage.clear();\n this.#isAuthenticated = false;\n this.#mainAccountId = null;\n this.#activeAccountId = null;\n this.#loginMethod = null;\n this.#challengeUri = undefined;\n this.#accountIdentity = null;\n\n this.#sessionStore.clear();\n\n this.#notifyStateChange();\n this.events.emit(\"loggedOut\", undefined);\n }\n\n #clearExpiredSessionState(): void {\n const shouldEmitLoggedOut = this.#isAuthenticated;\n this.#realtime.disconnectPrivate();\n this.#tokenStorage.clear();\n this.#sessionStore.clear();\n this.#isAuthenticated = false;\n this.#mainAccountId = null;\n this.#activeAccountId = null;\n this.#loginMethod = null;\n this.#challengeUri = undefined;\n this.#accountIdentity = null;\n this.#notifyStateChange();\n if (shouldEmitLoggedOut) {\n this.events.emit(\"loggedOut\", undefined);\n }\n }\n\n /**\n * Returns the remaining lifetime of the stored session token in milliseconds.\n */\n getSessionTimeToExpiry(): number {\n const token = this.#getEnvironmentBoundToken();\n if (!token || !isJwtValid(token)) return 0;\n return getJwtTimeToExpiry(token);\n }\n\n /**\n * Refreshes the active account-signer session and updates persisted auth state.\n */\n async refreshSession(params?: {\n /** Overrides the origin remembered from login. */\n uri?: string;\n provider?: \"metamask\" | \"turnkey\" | \"other\";\n loginMethod?: AuthLoginMethod | null;\n }): Promise<LoginResult> {\n if (!this.#isAuthenticated) {\n throw new AuthenticationError(\"Must be authenticated to refresh session\");\n }\n\n const currentSession = this.#getEnvironmentSession();\n return this.#login(\n {\n provider: this.#resolveRefreshProvider(params?.provider),\n uri: params?.uri,\n loginMethod: params?.loginMethod ?? this.#loginMethod,\n },\n currentSession?.activeAccount,\n );\n }\n\n /**\n * Switches the active account/subaccount by signing the required account switch flow.\n */\n switchAccount(\n accountId: string,\n options?: { smartAccountAddress?: string; label?: string },\n ): { accountId: string; isMain: boolean } {\n if (!this.#isAuthenticated || !this.#mainAccountId) {\n throw new AuthenticationError(\"Must be authenticated to switch accounts\");\n }\n\n this.#activeAccountId = accountId;\n const isMain = accountId === this.#mainAccountId;\n\n this.#sessionStore.setActiveAccount(\n {\n accountId,\n isMain,\n smartAccountAddress: options?.smartAccountAddress,\n label: options?.label,\n },\n { maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds },\n );\n this.#notifyStateChange();\n\n return { accountId, isMain };\n }\n\n /** Keeps the display-session identity current for the next server render. */\n syncSessionUsername(username: string | null): void {\n this.#sessionStore.setUsername(username, {\n maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds,\n });\n }\n\n /**\n * Creates a subaccount for the authenticated account and makes it available to the session state.\n */\n async createSubaccount(params: CreateSubaccountParams): Promise<CreateSubaccountResult> {\n if (!this.#isAuthenticated) {\n throw new AuthenticationError(\"Must be authenticated to create subaccounts\");\n }\n\n if (!this.#subaccounts) {\n throw new ConfigurationError(\n \"SubaccountsService not configured. Pass it to constructor or call setSubaccountsService().\",\n );\n }\n\n const { accountSigner, label = \"\" } = params;\n this.#assertAccountSignerEnvironment(accountSigner);\n\n const { message } = await this.createWalletChallenge({\n smartAccountAddress: accountSigner.accountAddress,\n signerAddress: accountSigner.accountAddress,\n uri: resolveChallengeUri(params.uri ?? this.#challengeUri),\n purpose: \"create_subaccount\",\n });\n const signature = await accountSigner.signMessage(message);\n\n const response = await this.#subaccounts.create({\n label,\n smartAccountAddress: accountSigner.accountAddress,\n message,\n signature,\n });\n\n return {\n subaccountId: response.subaccountId,\n smartAccountSaltNonce: response.smartAccountSaltNonce,\n revision: response.revision,\n };\n }\n\n /**\n * Returns the current account-signer auth state snapshot.\n */\n getState(): AuthState {\n const accountIdentity = this.#accountSigner ?? this.#accountIdentity;\n\n return {\n isAuthenticated: this.#isAuthenticated,\n accountAddress: accountIdentity?.accountAddress ?? null,\n ownerAddress: accountIdentity?.ownerAddress ?? null,\n mainAccountId: this.#mainAccountId,\n activeAccount:\n this.#activeAccountId && this.#mainAccountId\n ? {\n accountId: this.#activeAccountId,\n isMain: this.#activeAccountId === this.#mainAccountId,\n mainAccountId: this.#mainAccountId,\n smartAccountAddress: accountIdentity?.accountAddress,\n }\n : null,\n };\n }\n\n async #resolveAccountSigner(): Promise<AccountSigner | null> {\n if (this.#accountSigner) {\n this.#assertAccountSignerEnvironment(this.#accountSigner);\n return this.#accountSigner;\n }\n\n const resolved = await resolveAccountSigner(this.#accountSignerConfig);\n if (resolved) {\n this.#assertAccountSignerEnvironment(resolved);\n }\n return resolved;\n }\n\n #notifyStateChange(): void {\n this.events.emit(\"stateChange\", this.getState());\n }\n\n #beginAuthOperation(): number {\n this.#authOperationGeneration += 1;\n return this.#authOperationGeneration;\n }\n\n #isCurrentAuthOperation(generation: number, token?: string | null): boolean {\n return (\n generation === this.#authOperationGeneration &&\n (token === undefined || this.#tokenStorage.get() === token)\n );\n }\n\n #loginResult(response: LoginWithWalletResponse): LoginResult {\n const expiresAt = response.expiresAt\n ? new Date(\n Number(response.expiresAt.seconds) * 1000 +\n (response.expiresAt.nanos ?? 0) / 1_000_000,\n )\n : new Date();\n return { accountId: response.accountId, username: response.username, expiresAt };\n }\n\n #getEnvironmentBoundToken(): string | null {\n return this.#sessionStore.getEnvironmentBoundToken(this.#tokenStorage);\n }\n\n #getCurrentTokenStorageOptions(): AuthTokenStorageSetOptions {\n const token = this.#tokenStorage.get();\n if (!token) return { expiresAt: null, maxAgeSeconds: null };\n return createAuthTokenStorageSetOptions(token);\n }\n\n #resolveRefreshProvider(\n provider?: \"metamask\" | \"turnkey\" | \"other\",\n ): \"metamask\" | \"turnkey\" | \"other\" {\n return (\n provider ?? this.#walletProvider ?? this.#getEnvironmentSession()?.provider ?? \"other\"\n );\n }\n\n #assertAccountSignerEnvironment(accountSigner: AccountSigner): void {\n assertAccountSigner(accountSigner);\n if (accountSigner.environmentFingerprint !== this.#environmentFingerprint) {\n throw new ConfigurationError(\n \"Account signer environment does not match client environment.\",\n );\n }\n }\n\n #identityFromSigner(accountSigner: AccountSigner): AccountIdentity {\n return {\n accountAddress: accountSigner.accountAddress,\n ownerAddress: accountSigner.ownerAddress,\n };\n }\n\n #getEnvironmentSession(): SessionData | null {\n return this.#sessionStore.get();\n }\n}\n\nfunction resolveChallengeUri(uri: string | undefined): string {\n const resolved = uri ?? (typeof location === \"undefined\" ? undefined : location.origin);\n if (!resolved)\n throw new ConfigurationError(\n \"Wallet authentication requires a browser origin URI. Pass uri outside a browser.\",\n );\n return resolved;\n}\n"],"mappings":";;;;;;;;;;;;AAwEA,IAAa,2BAAb,cAA8C,YAAY;CACtD,SAAkB,IAAI,aAAsC;CAE5D;CACA,iBAAuC;CACvC,mBAA2C;CAC3C,mBAAmB;CACnB,iBAAgC;CAChC,mBAAkC;CAClC;CACA,kBAAgE,KAAA;CAChE,eAAuC;CACvC,gBAAoC,KAAA;CACpC;CACA;CACA;CACA;CAGA,2BAA2B;CAE3B,YAAY,EACR,YACA,qBACA,aACA,aACA,UACA,cACA,gBASD;EACC,MAAM,YAAY,QAAQ;EAE1B,KAAKA,uBAAuB;EAC5B,KAAKC,0BAA0B,YAAY;EAC3C,KAAKC,eAAe;EACpB,KAAKC,gBAAgB;EACrB,KAAKC,YAAY;EACjB,KAAKC,gBACD,gBACA,IAAI,iBAAiB,EACjB,wBAAwB,YAAY,YACxC,CAAC;CACT;;;;CAKA,sBAAsB,aAAuC;EACzD,KAAKH,eAAe;CACxB;;;;CAKA,iBAAiB,eAA2C;EACxD,IAAI,eAAe,KAAKI,gCAAgC,aAAa;EACrE,KAAKC,oBAAoB;EACzB,KAAKC,iBAAiB;EACtB,KAAKC,mBAAmB,gBAAgB,KAAKC,oBAAoB,aAAa,IAAI;EAClF,KAAKC,mBAAmB;CAC5B;;;;CAKA,mBAAyC;EACrC,OAAO,KAAKH;CAChB;;;;CAKA,MAAM,MAAM,SAA6C;EACrD,OAAO,KAAKI,OAAO,OAAO;CAC9B;CAEA,MAAMA,OACF,SACA,uBACoB;EACpB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","#environmentFingerprint","#subaccounts","#tokenStorage","#realtime","#sessionStore","#assertAccountSignerEnvironment","#beginAuthOperation","#accountSigner","#accountIdentity","#identityFromSigner","#notifyStateChange","#login","#resolveAccountSigner","#challengeUri","#isCurrentAuthOperation","#getEnvironmentSession","#loginMethod","#isAuthenticated","#mainAccountId","#activeAccountId","#walletProvider","#loginResult","#getEnvironmentBoundToken","#clearExpiredSessionState","#getCurrentTokenStorageOptions","#resolveRefreshProvider","#authOperationGeneration"],"sources":["../../../src/services/auth/account-signer-auth.ts"],"sourcesContent":["import { AuthService, type LoginWithWalletResponse } from \"./auth.js\";\nimport { AuthenticationError, ConfigurationError } from \"../../shared/errors.js\";\nimport { toPolyesterError } from \"../../shared/connect-error-mapping.js\";\nimport { AuthSessionStore } from \"./session.js\";\nimport type { AccountSigner, AccountSignerConfig, HexAddress } from \"../../account-signer/types.js\";\nimport { assertAccountSigner, resolveAccountSigner } from \"../../account-signer/types.js\";\nimport { EventEmitter } from \"../../utils/event-emitter.js\";\nimport { isJwtValid, getJwtTimeToExpiry } from \"../../utils/jwt.js\";\nimport type { SubaccountChallenge, SubaccountsService } from \"../subaccounts/index.js\";\nimport type {\n AuthState,\n AuthHydrationData,\n AuthLoginMethod,\n SessionData,\n ActiveAccountInfo,\n} from \"./session.types.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\nimport type { PolyesterEnvironment } from \"../../environment.js\";\nimport type { AuthAndPublicApiTransports } from \"../../shared/transports.js\";\nimport {\n createAuthTokenStorageSetOptions,\n type AuthTokenStorage,\n type AuthTokenStorageSetOptions,\n} from \"./token-storage.js\";\n\nexport interface AccountSignerAuthEvents {\n authenticated: { accountId: string; username: string };\n loggedOut: void;\n error: { code: string; message: string };\n servicesReady: void;\n stateChange: AuthState;\n}\n\nexport interface LoginResult {\n accountId: string;\n username: string;\n expiresAt: Date;\n}\n\nexport interface LoginOptions {\n /**\n * The wallet provider to use for login.\n */\n provider: SessionData[\"provider\"];\n /** Browser origin requesting the signature; defaults to location.origin in browsers. Required outside browsers. */\n uri?: string;\n loginMethod?: AuthLoginMethod | null;\n}\n\nexport interface CreateSubaccountParams {\n /**\n * Signer for the new subaccount, or a factory that derives it from the server challenge\n * (for example via Turnkey with `challenge.smartAccountSaltNonce`). Its accountAddress must\n * equal `challenge.smartAccountAddress`.\n */\n accountSigner:\n | AccountSigner\n | ((challenge: SubaccountChallenge) => AccountSigner | Promise<AccountSigner>);\n /** Optional human-readable label for this subaccount */\n label?: string;\n /** Browser origin requesting the signature; defaults to location.origin in browsers. Required outside browsers. */\n uri?: string;\n /** Root owner EOA bound to the authenticated account; defaults to the configured signer's owner. */\n ownerAddress?: HexAddress;\n}\n\nexport interface CreateSubaccountResult {\n subaccountId: string;\n smartAccountSaltNonce: number;\n revision: string;\n}\n\ninterface AccountIdentity {\n accountAddress: HexAddress;\n ownerAddress?: HexAddress;\n}\n\n/**\n * Coordinates wallet/account-signer authentication, session storage, subaccount selection, and session refresh.\n */\nexport class AccountSignerAuthService extends AuthService {\n readonly events = new EventEmitter<AccountSignerAuthEvents>();\n\n #accountSignerConfig: AccountSignerConfig | undefined;\n #accountSigner: AccountSigner | null = null;\n #accountIdentity: AccountIdentity | null = null;\n #isAuthenticated = false;\n #mainAccountId: string | null = null;\n #activeAccountId: string | null = null;\n #subaccounts: SubaccountsService;\n #walletProvider: SessionData[\"provider\"] | undefined = undefined;\n #loginMethod: AuthLoginMethod | null = null;\n #challengeUri: string | undefined = undefined;\n #environmentFingerprint: string;\n #tokenStorage: AuthTokenStorage;\n #sessionStore: AuthSessionStore;\n #realtime: PolyesterRealtime;\n // Every asynchronous auth transition captures this generation. A later login,\n // logout, signer change, or restore makes older work observational only.\n #authOperationGeneration = 0;\n\n constructor({\n transports,\n accountSignerConfig,\n environment,\n subaccounts,\n realtime,\n tokenStorage,\n sessionStore,\n }: {\n transports: AuthAndPublicApiTransports;\n accountSignerConfig?: AccountSignerConfig;\n environment: PolyesterEnvironment;\n subaccounts: SubaccountsService;\n realtime: PolyesterRealtime;\n tokenStorage: AuthTokenStorage;\n sessionStore?: AuthSessionStore;\n }) {\n super(transports, realtime);\n\n this.#accountSignerConfig = accountSignerConfig;\n this.#environmentFingerprint = environment.fingerprint;\n this.#subaccounts = subaccounts;\n this.#tokenStorage = tokenStorage;\n this.#realtime = realtime;\n this.#sessionStore =\n sessionStore ??\n new AuthSessionStore({\n environmentFingerprint: environment.fingerprint,\n });\n }\n\n /**\n * Attaches the subaccounts service used when creating a subaccount during authenticated flows.\n */\n setSubaccountsService(subaccounts: SubaccountsService): void {\n this.#subaccounts = subaccounts;\n }\n\n /**\n * Sets the account signer used to sign login and account-switch challenges.\n */\n setAccountSigner(accountSigner: AccountSigner | null): void {\n if (accountSigner) this.#assertAccountSignerEnvironment(accountSigner);\n this.#beginAuthOperation();\n this.#accountSigner = accountSigner;\n this.#accountIdentity = accountSigner ? this.#identityFromSigner(accountSigner) : null;\n this.#notifyStateChange();\n }\n\n /**\n * Returns the active account signer, throwing if one has not been configured.\n */\n getAccountSigner(): AccountSigner | null {\n return this.#accountSigner;\n }\n\n /**\n * Signs a server-issued SIWE message with the configured account signer, exchanges it for a session token, and stores the hydrated account/subaccount session state.\n */\n async login(options: LoginOptions): Promise<LoginResult> {\n return this.#login(options);\n }\n\n async #login(\n options: LoginOptions,\n previousActiveAccount?: ActiveAccountInfo,\n ): Promise<LoginResult> {\n const generation = this.#beginAuthOperation();\n const startingToken = this.#tokenStorage.get();\n const { provider, loginMethod } = options;\n\n const accountSigner = await this.#resolveAccountSigner();\n\n if (!accountSigner) {\n throw new ConfigurationError(\n \"No account signer configured. Call setAccountSigner() or pass accountSigner in config.\",\n );\n }\n\n const smartAccountAddress = accountSigner.accountAddress;\n const ownerAddress = accountSigner.ownerAddress ?? accountSigner.accountAddress;\n\n const uri = resolveChallengeUri(options.uri ?? this.#challengeUri);\n const { message } = await this.createWalletChallenge({\n smartAccountAddress,\n signerAddress: ownerAddress,\n uri,\n });\n const signature = await accountSigner.signMessage(message);\n\n const response = await this.loginWithWallet({\n smartAccountAddress,\n message,\n signature,\n walletProvider: provider,\n });\n\n if (!this.#isCurrentAuthOperation(generation, startingToken)) {\n throw new DOMException(\"Authentication operation superseded\", \"AbortError\");\n }\n const environmentSession = this.#getEnvironmentSession();\n const resolvedLoginMethod =\n loginMethod ??\n this.#loginMethod ??\n environmentSession?.loginMethod ??\n (provider === \"metamask\" || provider === \"phantom\" ? provider : null);\n\n const tokenOptions = createAuthTokenStorageSetOptions(response.accessToken);\n const activeAccount =\n previousActiveAccount?.mainAccountId === response.accountId\n ? previousActiveAccount\n : undefined;\n this.#sessionStore.commitLogin(\n {\n accessToken: response.accessToken,\n tokenOptions,\n provider,\n loginMethod: resolvedLoginMethod,\n primaryWallet: ownerAddress,\n smartAccount: smartAccountAddress,\n accountId: response.accountId,\n activeAccount,\n username: response.username ?? undefined,\n },\n this.#tokenStorage,\n );\n this.#isAuthenticated = true;\n this.#mainAccountId = response.accountId;\n this.#activeAccountId = activeAccount?.accountId ?? response.accountId;\n this.#walletProvider = provider;\n this.#loginMethod = resolvedLoginMethod;\n this.#challengeUri = uri;\n this.#accountSigner = accountSigner;\n this.#accountIdentity = this.#identityFromSigner(accountSigner);\n\n this.#notifyStateChange();\n\n this.events.emit(\"authenticated\", {\n accountId: response.accountId,\n username: response.username,\n });\n\n return this.#loginResult(response);\n }\n\n /**\n * Builds auth state from a session token and optional active account override.\n */\n hydrateAuthState(state: AuthHydrationData): void {\n this.#beginAuthOperation();\n const existingToken = this.#getEnvironmentBoundToken();\n if (!existingToken || !isJwtValid(existingToken)) return;\n\n const existingSession = this.#getEnvironmentSession();\n this.#walletProvider = existingSession?.provider ?? this.#walletProvider;\n this.#loginMethod = existingSession?.loginMethod ?? this.#loginMethod;\n\n this.#isAuthenticated = true;\n this.#mainAccountId = state.mainAccountId;\n this.#activeAccountId = state.activeAccountId ?? state.mainAccountId;\n this.#accountIdentity = state.smartAccountAddress\n ? {\n accountAddress: state.smartAccountAddress,\n ownerAddress: state.ownerAddress,\n }\n : null;\n\n this.#notifyStateChange();\n }\n\n /**\n * Loads the stored token, validates that it still belongs to this environment, and restores auth state when possible.\n */\n async restoreSession(): Promise<{ accountId: string; username: string } | null> {\n const generation = this.#beginAuthOperation();\n const existingToken = this.#getEnvironmentBoundToken();\n\n if (!existingToken || !isJwtValid(existingToken)) {\n if (this.#isCurrentAuthOperation(generation)) this.#clearExpiredSessionState();\n return null;\n }\n\n let me: Awaited<ReturnType<AuthService[\"me\"]>>;\n try {\n me = await this.me();\n } catch (error) {\n if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;\n const mappedError = toPolyesterError(error);\n if (mappedError instanceof AuthenticationError) {\n this.#clearExpiredSessionState();\n return null;\n }\n throw mappedError;\n }\n if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;\n\n let accountSigner = this.#accountSigner;\n if (!accountSigner) {\n try {\n accountSigner = await resolveAccountSigner(this.#accountSignerConfig);\n } catch (error) {\n if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;\n throw error;\n }\n if (!this.#isCurrentAuthOperation(generation, existingToken)) return null;\n if (accountSigner) this.#assertAccountSignerEnvironment(accountSigner);\n }\n\n if (!isJwtValid(existingToken) || this.#getEnvironmentBoundToken() !== existingToken) {\n this.#clearExpiredSessionState();\n return null;\n }\n\n const existingSession = this.#getEnvironmentSession();\n const walletProvider = existingSession?.provider ?? this.#walletProvider;\n const loginMethod = existingSession?.loginMethod ?? this.#loginMethod;\n const activeAccountId =\n this.#activeAccountId ?? existingSession?.activeAccount?.accountId ?? me.accountId;\n\n // Publish runtime state only after asynchronous restoration has completed.\n if (accountSigner) {\n this.#sessionStore.ensureSession(\n {\n provider: walletProvider ?? \"other\",\n loginMethod: loginMethod ?? (walletProvider === \"metamask\" ? \"metamask\" : null),\n primaryWallet: accountSigner.ownerAddress ?? accountSigner.accountAddress,\n smartAccount: accountSigner.accountAddress,\n accountId: me.accountId,\n username: me.username ?? undefined,\n },\n { maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds },\n );\n this.#accountSigner = accountSigner;\n this.#accountIdentity = this.#identityFromSigner(accountSigner);\n }\n this.#isAuthenticated = true;\n this.#mainAccountId = me.accountId;\n this.#activeAccountId = activeAccountId;\n this.#walletProvider = walletProvider ?? (accountSigner ? \"other\" : undefined);\n this.#loginMethod = loginMethod;\n this.#notifyStateChange();\n return { accountId: me.accountId, username: me.username };\n }\n\n /**\n * Clears stored auth state and removes the persisted auth token.\n */\n async logout(): Promise<void> {\n this.#beginAuthOperation();\n this.#realtime.disconnectPrivate();\n this.#tokenStorage.clear();\n this.#isAuthenticated = false;\n this.#mainAccountId = null;\n this.#activeAccountId = null;\n this.#loginMethod = null;\n this.#challengeUri = undefined;\n this.#accountIdentity = null;\n\n this.#sessionStore.clear();\n\n this.#notifyStateChange();\n this.events.emit(\"loggedOut\", undefined);\n }\n\n #clearExpiredSessionState(): void {\n const shouldEmitLoggedOut = this.#isAuthenticated;\n this.#realtime.disconnectPrivate();\n this.#tokenStorage.clear();\n this.#sessionStore.clear();\n this.#isAuthenticated = false;\n this.#mainAccountId = null;\n this.#activeAccountId = null;\n this.#loginMethod = null;\n this.#challengeUri = undefined;\n this.#accountIdentity = null;\n this.#notifyStateChange();\n if (shouldEmitLoggedOut) {\n this.events.emit(\"loggedOut\", undefined);\n }\n }\n\n /**\n * Returns the remaining lifetime of the stored session token in milliseconds.\n */\n getSessionTimeToExpiry(): number {\n const token = this.#getEnvironmentBoundToken();\n if (!token || !isJwtValid(token)) return 0;\n return getJwtTimeToExpiry(token);\n }\n\n /**\n * Refreshes the active account-signer session and updates persisted auth state.\n */\n async refreshSession(params?: {\n /** Overrides the origin remembered from login. */\n uri?: string;\n provider?: SessionData[\"provider\"];\n loginMethod?: AuthLoginMethod | null;\n }): Promise<LoginResult> {\n if (!this.#isAuthenticated) {\n throw new AuthenticationError(\"Must be authenticated to refresh session\");\n }\n\n const currentSession = this.#getEnvironmentSession();\n return this.#login(\n {\n provider: this.#resolveRefreshProvider(params?.provider),\n uri: params?.uri,\n loginMethod: params?.loginMethod ?? this.#loginMethod,\n },\n currentSession?.activeAccount,\n );\n }\n\n /**\n * Switches the active account/subaccount by signing the required account switch flow.\n */\n switchAccount(\n accountId: string,\n options?: { smartAccountAddress?: string; label?: string },\n ): { accountId: string; isMain: boolean } {\n if (!this.#isAuthenticated || !this.#mainAccountId) {\n throw new AuthenticationError(\"Must be authenticated to switch accounts\");\n }\n\n this.#activeAccountId = accountId;\n const isMain = accountId === this.#mainAccountId;\n\n this.#sessionStore.setActiveAccount(\n {\n accountId,\n isMain,\n smartAccountAddress: options?.smartAccountAddress,\n label: options?.label,\n },\n { maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds },\n );\n this.#notifyStateChange();\n\n return { accountId, isMain };\n }\n\n /** Keeps the display-session identity current for the next server render. */\n syncSessionUsername(username: string | null): void {\n this.#sessionStore.setUsername(username, {\n maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds,\n });\n }\n\n /**\n * Creates a subaccount for the authenticated account and makes it available to the session state.\n */\n async createSubaccount(params: CreateSubaccountParams): Promise<CreateSubaccountResult> {\n if (!this.#isAuthenticated) {\n throw new AuthenticationError(\"Must be authenticated to create subaccounts\");\n }\n\n if (!this.#subaccounts) {\n throw new ConfigurationError(\n \"SubaccountsService not configured. Pass it to constructor or call setSubaccountsService().\",\n );\n }\n\n const identity = this.#accountSigner ?? this.#accountIdentity;\n const ownerAddress =\n params.ownerAddress ?? identity?.ownerAddress ?? identity?.accountAddress;\n if (!ownerAddress) {\n throw new ConfigurationError(\n \"No root owner address available. Pass ownerAddress or configure an account signer.\",\n );\n }\n\n const { label = \"\" } = params;\n const challenge = await this.#subaccounts.createChallenge({\n ownerAddress,\n uri: resolveChallengeUri(params.uri ?? this.#challengeUri),\n });\n const accountSigner =\n typeof params.accountSigner === \"function\"\n ? await params.accountSigner(challenge)\n : params.accountSigner;\n this.#assertAccountSignerEnvironment(accountSigner);\n if (\n accountSigner.accountAddress.toLowerCase() !==\n challenge.smartAccountAddress.toLowerCase()\n ) {\n throw new ConfigurationError(\n `Subaccount signer address ${accountSigner.accountAddress} does not match the server-derived smart account ${challenge.smartAccountAddress}.`,\n );\n }\n const signature = await accountSigner.signMessage(challenge.message);\n\n const response = await this.#subaccounts.create({\n label,\n smartAccountAddress: challenge.smartAccountAddress,\n message: challenge.message,\n signature,\n });\n\n return {\n subaccountId: response.subaccountId,\n smartAccountSaltNonce: response.smartAccountSaltNonce,\n revision: response.revision,\n };\n }\n\n /**\n * Returns the current account-signer auth state snapshot.\n */\n getState(): AuthState {\n const accountIdentity = this.#accountSigner ?? this.#accountIdentity;\n\n return {\n isAuthenticated: this.#isAuthenticated,\n accountAddress: accountIdentity?.accountAddress ?? null,\n ownerAddress: accountIdentity?.ownerAddress ?? null,\n mainAccountId: this.#mainAccountId,\n activeAccount:\n this.#activeAccountId && this.#mainAccountId\n ? {\n accountId: this.#activeAccountId,\n isMain: this.#activeAccountId === this.#mainAccountId,\n mainAccountId: this.#mainAccountId,\n smartAccountAddress: accountIdentity?.accountAddress,\n }\n : null,\n };\n }\n\n async #resolveAccountSigner(): Promise<AccountSigner | null> {\n if (this.#accountSigner) {\n this.#assertAccountSignerEnvironment(this.#accountSigner);\n return this.#accountSigner;\n }\n\n const resolved = await resolveAccountSigner(this.#accountSignerConfig);\n if (resolved) {\n this.#assertAccountSignerEnvironment(resolved);\n }\n return resolved;\n }\n\n #notifyStateChange(): void {\n this.events.emit(\"stateChange\", this.getState());\n }\n\n #beginAuthOperation(): number {\n this.#authOperationGeneration += 1;\n return this.#authOperationGeneration;\n }\n\n #isCurrentAuthOperation(generation: number, token?: string | null): boolean {\n return (\n generation === this.#authOperationGeneration &&\n (token === undefined || this.#tokenStorage.get() === token)\n );\n }\n\n #loginResult(response: LoginWithWalletResponse): LoginResult {\n const expiresAt = response.expiresAt\n ? new Date(\n Number(response.expiresAt.seconds) * 1000 +\n (response.expiresAt.nanos ?? 0) / 1_000_000,\n )\n : new Date();\n return { accountId: response.accountId, username: response.username, expiresAt };\n }\n\n #getEnvironmentBoundToken(): string | null {\n return this.#sessionStore.getEnvironmentBoundToken(this.#tokenStorage);\n }\n\n #getCurrentTokenStorageOptions(): AuthTokenStorageSetOptions {\n const token = this.#tokenStorage.get();\n if (!token) return { expiresAt: null, maxAgeSeconds: null };\n return createAuthTokenStorageSetOptions(token);\n }\n\n #resolveRefreshProvider(provider?: SessionData[\"provider\"]): SessionData[\"provider\"] {\n return (\n provider ?? this.#walletProvider ?? this.#getEnvironmentSession()?.provider ?? \"other\"\n );\n }\n\n #assertAccountSignerEnvironment(accountSigner: AccountSigner): void {\n assertAccountSigner(accountSigner);\n if (accountSigner.environmentFingerprint !== this.#environmentFingerprint) {\n throw new ConfigurationError(\n \"Account signer environment does not match client environment.\",\n );\n }\n }\n\n #identityFromSigner(accountSigner: AccountSigner): AccountIdentity {\n return {\n accountAddress: accountSigner.accountAddress,\n ownerAddress: accountSigner.ownerAddress,\n };\n }\n\n #getEnvironmentSession(): SessionData | null {\n return this.#sessionStore.get();\n }\n}\n\nfunction resolveChallengeUri(uri: string | undefined): string {\n const resolved = uri ?? (typeof location === \"undefined\" ? undefined : location.origin);\n if (!resolved)\n throw new ConfigurationError(\n \"Wallet authentication requires a browser origin URI. Pass uri outside a browser.\",\n );\n return resolved;\n}\n"],"mappings":";;;;;;;;;;;;AAgFA,IAAa,2BAAb,cAA8C,YAAY;CACtD,SAAkB,IAAI,aAAsC;CAE5D;CACA,iBAAuC;CACvC,mBAA2C;CAC3C,mBAAmB;CACnB,iBAAgC;CAChC,mBAAkC;CAClC;CACA,kBAAuD,KAAA;CACvD,eAAuC;CACvC,gBAAoC,KAAA;CACpC;CACA;CACA;CACA;CAGA,2BAA2B;CAE3B,YAAY,EACR,YACA,qBACA,aACA,aACA,UACA,cACA,gBASD;EACC,MAAM,YAAY,QAAQ;EAE1B,KAAKA,uBAAuB;EAC5B,KAAKC,0BAA0B,Y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AS,KAAK,GAC1C,oBACA,IAAI,KAAK;EACf,OAAO;GAAE,WAAW,SAAS;GAAW,UAAU,SAAS;GAAU;EAAU;CACnF;CAEA,4BAA2C;EACvC,OAAO,KAAKE,cAAc,yBAAyB,KAAKF,aAAa;CACzE;CAEA,iCAA6D;EACzD,MAAM,QAAQ,KAAKA,cAAc,IAAI;EACrC,IAAI,CAAC,OAAO,OAAO;GAAE,WAAW;GAAM,eAAe;EAAK;EAC1D,OAAO,iCAAiC,KAAK;CACjD;CAEA,wBAAwB,UAA6D;EACjF,OACI,YAAY,KAAKkB,mBAAmB,KAAKL,uBAAuB,CAAC,EAAE,YAAY;CAEvF;CAEA,gCAAgC,eAAoC;EAChE,oBAAoB,aAAa;EACjC,IAAI,cAAc,2BAA2B,KAAKf,yBAC9C,MAAM,IAAI,mBACN,+DACJ;CAER;CAEA,oBAAoB,eAA+C;EAC/D,OAAO;GACH,gBAAgB,cAAc;GAC9B,cAAc,cAAc;EAChC;CACJ;CAEA,yBAA6C;EACzC,OAAO,KAAKI,cAAc,IAAI;CAClC;AACJ;AAEA,SAAS,oBAAoB,KAAiC;CAC1D,MAAM,WAAW,QAAQ,OAAO,aAAa,cAAc,KAAA,IAAY,SAAS;CAChF,IAAI,CAAC,UACD,MAAM,IAAI,mBACN,kFACJ;CACJ,OAAO;AACX"}
@@ -9,10 +9,8 @@ declare const CreateWalletChallengeInputSchema: v.StrictObjectSchema<{
9
9
  readonly smartAccountAddress: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Invalid wallet address.">]>;
10
10
  readonly signerAddress: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Invalid wallet address.">]>;
11
11
  readonly uri: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MaxLengthAction<string, 2048, undefined>, v.CheckAction<string, "Wallet challenge URI must be an HTTP(S) origin without a path, query, fragment, or user information.">]>;
12
- readonly purpose: v.PicklistSchema<["login", "create_subaccount"], undefined>;
13
12
  }, undefined>;
14
13
  type CreateWalletChallengeInput = v.InferInput<typeof CreateWalletChallengeInputSchema>;
15
- type WalletChallengePurpose = CreateWalletChallengeInput["purpose"];
16
14
  declare const LoginWithWalletInputSchema: v.StrictObjectSchema<{
17
15
  readonly smartAccountAddress: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Invalid wallet address.">]>;
18
16
  readonly message: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.CheckAction<string, "Wallet challenge message exceeds 4096 UTF-8 bytes.">]>;
@@ -90,8 +88,12 @@ declare class AuthService {
90
88
  */
91
89
  acceptTerms(options?: PolyesterMutationOptions): Promise<void>;
92
90
  /**
93
- * Requests a server-issued SIWE message. Sign its exact UTF-8 bytes with
91
+ * Requests a server-issued SIWE login message. Sign its exact UTF-8 bytes with
94
92
  * personal_sign; do not hash or reconstruct it. Expiry is epoch milliseconds.
93
+ * The backend sets SIWE Chain ID to Ethereum mainnet (1) and binds the
94
+ * Polyester chain in Resources. Do not send a chain ID or rewrite either binding.
95
+ * Wallet adapters must select Ethereum mainnet before signing if required by the wallet.
96
+ * Subaccount creation uses `subaccounts.createChallenge` instead.
95
97
  */
96
98
  createWalletChallenge(input: CreateWalletChallengeInput, options?: PolyesterRequestOptions): Promise<WalletChallenge>;
97
99
  /**
@@ -100,5 +102,5 @@ declare class AuthService {
100
102
  protected loginWithWallet(input: LoginWithWalletInput, options?: PolyesterMutationOptions): Promise<LoginWithWalletResponse>;
101
103
  }
102
104
  //#endregion
103
- export { AuthService, CreateWalletChallengeInput, CreateWalletChallengeInputSchema, LoginWithWalletInput, LoginWithWalletInputSchema, LoginWithWalletResponse, Me, WalletChallenge, WalletChallengePurpose };
105
+ export { AuthService, CreateWalletChallengeInput, CreateWalletChallengeInputSchema, LoginWithWalletInput, LoginWithWalletInputSchema, LoginWithWalletResponse, Me, WalletChallenge };
104
106
  //# sourceMappingURL=auth.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","names":[],"sources":["../../../src/services/auth/auth.ts"],"mappings":";;;;;;;cA0Ba,kCAAgC,EAAA;;;;;;KAMjC,6BAA6B,EAAE,kBAAkB;KACjD,yBAAyB;cAWxB,4BAA0B,EAAA;;;;;;;;KAS3B,uBAAuB,EAAE,kBAAkB;cAEjD,UAAQ,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;KAOF,KAAK,EAAE,mBAAmB;cAEhC,+BAA6B,EAAA;;;;;;;;;KAOvB,0BAA0B,EAAE,mBAAmB;cAErD,uBAAqB,EAAA;;;;;;;;;;KAKf,kBAAkB,EAAE,mBAAmB;;;;cAKtC;;EAGT,SAAS;EAEG,YAAA,YAAY,4BAA4B,UAAU;;;;EASxD,GAAG,UAAU,0BAA0B,QAAQ;;;;;;;EAW/C,YAAY,UAAU,2BAA2B;;;;;EAQjD,sBACF,OAAO,4BACP,UAAU,0BACX,QAAQ;;;;YA4BK,gBACZ,OAAO,sBACP,UAAU,2BACX,QAAQ"}
1
+ {"version":3,"file":"auth.d.ts","names":[],"sources":["../../../src/services/auth/auth.ts"],"mappings":";;;;;;;cAyBa,kCAAgC,EAAA;;;;;KAKjC,6BAA6B,EAAE,kBAAkB;cAWhD,4BAA0B,EAAA;;;;;;;;KAS3B,uBAAuB,EAAE,kBAAkB;cAEjD,UAAQ,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;KAOF,KAAK,EAAE,mBAAmB;cAEhC,+BAA6B,EAAA;;;;;;;;;KAOvB,0BAA0B,EAAE,mBAAmB;cAErD,uBAAqB,EAAA;;;;;;;;;;KAKf,kBAAkB,EAAE,mBAAmB;;;;cAKtC;;EAGT,SAAS;EAEG,YAAA,YAAY,4BAA4B,UAAU;;;;EASxD,GAAG,UAAU,0BAA0B,QAAQ;;;;;;;EAW/C,YAAY,UAAU,2BAA2B;;;;;;;;;EAYjD,sBACF,OAAO,4BACP,UAAU,0BACX,QAAQ;;;;YAcK,gBACZ,OAAO,sBACP,UAAU,2BACX,QAAQ"}
@@ -1,4 +1,3 @@
1
- import { ValidationError } from "../../shared/errors.js";
2
1
  import { AuthService as AuthService$1 } from "../../gen/auth/v1/auth_pb.js";
3
2
  import { OptionalTimestampMsSchema, PublicIdSchema, TimestampSchema } from "../../shared/schemas.js";
4
3
  import { parse } from "../../shared/validation.js";
@@ -12,8 +11,7 @@ import * as v from "valibot";
12
11
  const CreateWalletChallengeInputSchema = v.strictObject({
13
12
  smartAccountAddress: WalletAddressSchema,
14
13
  signerAddress: WalletAddressSchema,
15
- uri: WalletChallengeUriSchema,
16
- purpose: v.picklist(["login", "create_subaccount"])
14
+ uri: WalletChallengeUriSchema
17
15
  });
18
16
  /** An EIP-191 EOA signature: 65 hexadecimal bytes, with an optional 0x prefix. */
19
17
  const LoginEoaSignatureSchema = v.pipe(v.string(), v.regex(/^(?:0x)?[0-9a-fA-F]{130}$/, "Login signature must be a 65-byte hexadecimal EOA signature."));
@@ -70,15 +68,18 @@ var AuthService = class {
70
68
  await this.#authClient.acceptTerms({}, toConnectCallOptions(options));
71
69
  }
72
70
  /**
73
- * Requests a server-issued SIWE message. Sign its exact UTF-8 bytes with
71
+ * Requests a server-issued SIWE login message. Sign its exact UTF-8 bytes with
74
72
  * personal_sign; do not hash or reconstruct it. Expiry is epoch milliseconds.
73
+ * The backend sets SIWE Chain ID to Ethereum mainnet (1) and binds the
74
+ * Polyester chain in Resources. Do not send a chain ID or rewrite either binding.
75
+ * Wallet adapters must select Ethereum mainnet before signing if required by the wallet.
76
+ * Subaccount creation uses `subaccounts.createChallenge` instead.
75
77
  */
76
78
  async createWalletChallenge(input, options) {
77
79
  const validated = parse(CreateWalletChallengeInputSchema, input);
78
- if (validated.purpose === "create_subaccount" && validated.signerAddress.toLowerCase() !== validated.smartAccountAddress.toLowerCase()) throw new ValidationError("Subaccount challenge signer must equal the smart account address.");
79
80
  return parse(WalletChallengeSchema, await this.#publicClient.createWalletChallenge({
80
81
  ...validated,
81
- purpose: validated.purpose === "login" ? 1 : 2
82
+ purpose: 1
82
83
  }, toConnectCallOptions(options)));
83
84
  }
84
85
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","names":["#publicClient","Proto.AuthService","#authClient"],"sources":["../../../src/services/auth/auth.ts"],"sourcesContent":["import { createClient, type Client } from \"@connectrpc/connect\";\nimport * as Proto from \"../../gen/auth/v1/auth_pb.js\";\nimport * as v from \"valibot\";\nimport { ValidationError } from \"../../shared/errors.js\";\nimport { parse } from \"../../shared/validation.js\";\nimport { ProfileService } from \"./profile/profile.js\";\nimport {\n OptionalTimestampMsSchema,\n PublicIdSchema,\n TimestampSchema,\n} from \"../../shared/schemas.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { MfaSessionInfoSchema } from \"../mfa/mfa.schemas.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\nimport type { AuthAndPublicApiTransports } from \"../../shared/transports.js\";\n\nimport {\n WalletAddressSchema,\n WalletChallengeUriSchema,\n WalletChallengeMessageSchema,\n} from \"./wallet-challenge.schemas.js\";\n\nexport const CreateWalletChallengeInputSchema = v.strictObject({\n smartAccountAddress: WalletAddressSchema,\n signerAddress: WalletAddressSchema,\n uri: WalletChallengeUriSchema,\n purpose: v.picklist([\"login\", \"create_subaccount\"]),\n});\nexport type CreateWalletChallengeInput = v.InferInput<typeof CreateWalletChallengeInputSchema>;\nexport type WalletChallengePurpose = CreateWalletChallengeInput[\"purpose\"];\n\n/** An EIP-191 EOA signature: 65 hexadecimal bytes, with an optional 0x prefix. */\nconst LoginEoaSignatureSchema = v.pipe(\n v.string(),\n v.regex(\n /^(?:0x)?[0-9a-fA-F]{130}$/,\n \"Login signature must be a 65-byte hexadecimal EOA signature.\",\n ),\n);\n\nexport const LoginWithWalletInputSchema = v.strictObject({\n smartAccountAddress: WalletAddressSchema,\n message: WalletChallengeMessageSchema,\n signature: LoginEoaSignatureSchema,\n userAgent: v.optional(v.string(), \"\"),\n ip: v.optional(v.string(), \"\"),\n walletProvider: v.optional(v.string(), \"\"),\n});\n\nexport type LoginWithWalletInput = v.InferInput<typeof LoginWithWalletInputSchema>;\n\nconst MeSchema = v.object({\n accountId: PublicIdSchema,\n apiKeyId: v.optional(v.string()),\n username: v.string(),\n session: v.optional(MfaSessionInfoSchema),\n});\n\nexport type Me = v.InferOutput<typeof MeSchema>;\n\nconst LoginWithWalletResponseSchema = v.object({\n accessToken: v.string(),\n expiresAt: v.optional(TimestampSchema),\n accountId: PublicIdSchema,\n username: v.string(),\n});\n\nexport type LoginWithWalletResponse = v.InferOutput<typeof LoginWithWalletResponseSchema>;\n\nconst WalletChallengeSchema = v.object({\n message: WalletChallengeMessageSchema,\n expiresAt: OptionalTimestampMsSchema,\n});\n\nexport type WalletChallenge = v.InferOutput<typeof WalletChallengeSchema>;\n\n/**\n * Handles wallet-based authentication, caller introspection, and authenticated profile operations.\n */\nexport class AuthService {\n #publicClient: Client<typeof Proto.AuthService>;\n #authClient: Client<typeof Proto.AuthService>;\n profile: ProfileService;\n\n constructor(transports: AuthAndPublicApiTransports, realtime: PolyesterRealtime) {\n this.#publicClient = createClient(Proto.AuthService, transports.publicApi);\n this.#authClient = createClient(Proto.AuthService, transports.authApi);\n this.profile = new ProfileService(transports, realtime);\n }\n\n /**\n * Returns the authenticated caller's account context, including account ID, optional API key ID, username, and session assurance details from the presented token or API key.\n */\n async me(options?: PolyesterRequestOptions): Promise<Me> {\n const res = await this.#authClient.me({}, toConnectCallOptions(options));\n return parse(MeSchema, res);\n }\n\n /**\n * Records explicit consent to the current terms for the caller's root account.\n * Call only after the user consents. Requires an interactive JWT session;\n * API keys are not allowed. Repeated acceptance succeeds without changing\n * the first acceptance time. No MFA is required.\n */\n async acceptTerms(options?: PolyesterMutationOptions): Promise<void> {\n await this.#authClient.acceptTerms({}, toConnectCallOptions(options));\n }\n\n /**\n * Requests a server-issued SIWE message. Sign its exact UTF-8 bytes with\n * personal_sign; do not hash or reconstruct it. Expiry is epoch milliseconds.\n */\n async createWalletChallenge(\n input: CreateWalletChallengeInput,\n options?: PolyesterRequestOptions,\n ): Promise<WalletChallenge> {\n const validated = parse(CreateWalletChallengeInputSchema, input);\n if (\n validated.purpose === \"create_subaccount\" &&\n validated.signerAddress.toLowerCase() !== validated.smartAccountAddress.toLowerCase()\n ) {\n throw new ValidationError(\n \"Subaccount challenge signer must equal the smart account address.\",\n );\n }\n return parse(\n WalletChallengeSchema,\n await this.#publicClient.createWalletChallenge(\n {\n ...validated,\n purpose:\n validated.purpose === \"login\"\n ? Proto.WalletChallengePurpose.LOGIN\n : Proto.WalletChallengePurpose.CREATE_SUBACCOUNT,\n },\n toConnectCallOptions(options),\n ),\n );\n }\n\n /**\n * Exchanges a signed SIWE message for an authenticated session token and account identity returned by the auth API.\n */\n protected async loginWithWallet(\n input: LoginWithWalletInput,\n options?: PolyesterMutationOptions,\n ): Promise<LoginWithWalletResponse> {\n const validatedInput = parse(LoginWithWalletInputSchema, input);\n const res = await this.#publicClient.loginWithWallet(\n validatedInput,\n toConnectCallOptions(options),\n );\n return parse(LoginWithWalletResponseSchema, res);\n }\n}\n"],"mappings":";;;;;;;;;;;AA0BA,MAAa,mCAAmC,EAAE,aAAa;CAC3D,qBAAqB;CACrB,eAAe;CACf,KAAK;CACL,SAAS,EAAE,SAAS,CAAC,SAAS,mBAAmB,CAAC;AACtD,CAAC;;AAKD,MAAM,0BAA0B,EAAE,KAC9B,EAAE,OAAO,GACT,EAAE,MACE,6BACA,8DACJ,CACJ;AAEA,MAAa,6BAA6B,EAAE,aAAa;CACrD,qBAAqB;CACrB,SAAS;CACT,WAAW;CACX,WAAW,EAAE,SAAS,EAAE,OAAO,GAAG,EAAE;CACpC,IAAI,EAAE,SAAS,EAAE,OAAO,GAAG,EAAE;CAC7B,gBAAgB,EAAE,SAAS,EAAE,OAAO,GAAG,EAAE;AAC7C,CAAC;AAID,MAAM,WAAW,EAAE,OAAO;CACt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qB,OAAO,CAChC;EACA,OAAO,MAAM,+BAA+B,GAAG;CACnD;AACJ"}
1
+ {"version":3,"file":"auth.js","names":["#publicClient","Proto.AuthService","#authClient"],"sources":["../../../src/services/auth/auth.ts"],"sourcesContent":["import { createClient, type Client } from \"@connectrpc/connect\";\nimport * as Proto from \"../../gen/auth/v1/auth_pb.js\";\nimport * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport { ProfileService } from \"./profile/profile.js\";\nimport {\n OptionalTimestampMsSchema,\n PublicIdSchema,\n TimestampSchema,\n} from \"../../shared/schemas.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { MfaSessionInfoSchema } from \"../mfa/mfa.schemas.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\nimport type { AuthAndPublicApiTransports } from \"../../shared/transports.js\";\n\nimport {\n WalletAddressSchema,\n WalletChallengeUriSchema,\n WalletChallengeMessageSchema,\n} from \"./wallet-challenge.schemas.js\";\n\nexport const CreateWalletChallengeInputSchema = v.strictObject({\n smartAccountAddress: WalletAddressSchema,\n signerAddress: WalletAddressSchema,\n uri: WalletChallengeUriSchema,\n});\nexport type CreateWalletChallengeInput = v.InferInput<typeof CreateWalletChallengeInputSchema>;\n\n/** An EIP-191 EOA signature: 65 hexadecimal bytes, with an optional 0x prefix. */\nconst LoginEoaSignatureSchema = v.pipe(\n v.string(),\n v.regex(\n /^(?:0x)?[0-9a-fA-F]{130}$/,\n \"Login signature must be a 65-byte hexadecimal EOA signature.\",\n ),\n);\n\nexport const LoginWithWalletInputSchema = v.strictObject({\n smartAccountAddress: WalletAddressSchema,\n message: WalletChallengeMessageSchema,\n signature: LoginEoaSignatureSchema,\n userAgent: v.optional(v.string(), \"\"),\n ip: v.optional(v.string(), \"\"),\n walletProvider: v.optional(v.string(), \"\"),\n});\n\nexport type LoginWithWalletInput = v.InferInput<typeof LoginWithWalletInputSchema>;\n\nconst MeSchema = v.object({\n accountId: PublicIdSchema,\n apiKeyId: v.optional(v.string()),\n username: v.string(),\n session: v.optional(MfaSessionInfoSchema),\n});\n\nexport type Me = v.InferOutput<typeof MeSchema>;\n\nconst LoginWithWalletResponseSchema = v.object({\n accessToken: v.string(),\n expiresAt: v.optional(TimestampSchema),\n accountId: PublicIdSchema,\n username: v.string(),\n});\n\nexport type LoginWithWalletResponse = v.InferOutput<typeof LoginWithWalletResponseSchema>;\n\nconst WalletChallengeSchema = v.object({\n message: WalletChallengeMessageSchema,\n expiresAt: OptionalTimestampMsSchema,\n});\n\nexport type WalletChallenge = v.InferOutput<typeof WalletChallengeSchema>;\n\n/**\n * Handles wallet-based authentication, caller introspection, and authenticated profile operations.\n */\nexport class AuthService {\n #publicClient: Client<typeof Proto.AuthService>;\n #authClient: Client<typeof Proto.AuthService>;\n profile: ProfileService;\n\n constructor(transports: AuthAndPublicApiTransports, realtime: PolyesterRealtime) {\n this.#publicClient = createClient(Proto.AuthService, transports.publicApi);\n this.#authClient = createClient(Proto.AuthService, transports.authApi);\n this.profile = new ProfileService(transports, realtime);\n }\n\n /**\n * Returns the authenticated caller's account context, including account ID, optional API key ID, username, and session assurance details from the presented token or API key.\n */\n async me(options?: PolyesterRequestOptions): Promise<Me> {\n const res = await this.#authClient.me({}, toConnectCallOptions(options));\n return parse(MeSchema, res);\n }\n\n /**\n * Records explicit consent to the current terms for the caller's root account.\n * Call only after the user consents. Requires an interactive JWT session;\n * API keys are not allowed. Repeated acceptance succeeds without changing\n * the first acceptance time. No MFA is required.\n */\n async acceptTerms(options?: PolyesterMutationOptions): Promise<void> {\n await this.#authClient.acceptTerms({}, toConnectCallOptions(options));\n }\n\n /**\n * Requests a server-issued SIWE login message. Sign its exact UTF-8 bytes with\n * personal_sign; do not hash or reconstruct it. Expiry is epoch milliseconds.\n * The backend sets SIWE Chain ID to Ethereum mainnet (1) and binds the\n * Polyester chain in Resources. Do not send a chain ID or rewrite either binding.\n * Wallet adapters must select Ethereum mainnet before signing if required by the wallet.\n * Subaccount creation uses `subaccounts.createChallenge` instead.\n */\n async createWalletChallenge(\n input: CreateWalletChallengeInput,\n options?: PolyesterRequestOptions,\n ): Promise<WalletChallenge> {\n const validated = parse(CreateWalletChallengeInputSchema, input);\n return parse(\n WalletChallengeSchema,\n await this.#publicClient.createWalletChallenge(\n { ...validated, purpose: Proto.WalletChallengePurpose.LOGIN },\n toConnectCallOptions(options),\n ),\n );\n }\n\n /**\n * Exchanges a signed SIWE message for an authenticated session token and account identity returned by the auth API.\n */\n protected async loginWithWallet(\n input: LoginWithWalletInput,\n options?: PolyesterMutationOptions,\n ): Promise<LoginWithWalletResponse> {\n const validatedInput = parse(LoginWithWalletInputSchema, input);\n const res = await this.#publicClient.loginWithWallet(\n validatedInput,\n toConnectCallOptions(options),\n );\n return parse(LoginWithWalletResponseSchema, res);\n }\n}\n"],"mappings":";;;;;;;;;;AAyBA,MAAa,mCAAmC,EAAE,aAAa;CAC3D,qBAAqB;CACrB,eAAe;CACf,KAAK;AACT,CAAC;;AAID,MAAM,0BAA0B,EAAE,KAC9B,EAAE,OAAO,GACT,EAAE,MACE,6BACA,8DACJ,CACJ;AAEA,MAAa,6BAA6B,EAAE,aAAa;CACrD,qBAAqB;CACrB,SAAS;CACT,WAAW;CACX,WAAW,EAAE,SAAS,EAAE,OAAO,GAAG,EAAE;CACpC,IAAI,EAAE,SAAS,EAAE,OAAO,GAAG,EAAE;CAC7B,gBAAgB,EAAE,SAAS,EAAE,OAAO,GAAG,EAAE;AAC7C,CAAC;AAID,MAAM,WAAW,EAAE,OAAO;CACtB,WAAW;CACX,UAAU,EAAE,SAAS,EAAE,OAAO,CAAC;CAC/B,UAAU,EAAE,OAAO;CACnB,SAAS,EAAE,SAAS,oBAAoB;AAC5C,CAAC;AAID,MAAM,gCAAgC,EAAE,OAAO;CAC3C,aAAa,EAAE,OAAO;CACtB,WAAW,EAAE,SAAS,eAAe;CACrC,WAAW;CACX,UAAU,EAAE,OAAO;AACvB,CAAC;AAID,MAAM,wBAAwB,EAAE,OAAO;CACnC,SAAS;CACT,WAAW;AACf,CAAC;;;;AAOD,IAAa,cAAb,MAAyB;CACrB;CACA;CACA;CAEA,YAAY,YAAwC,UAA6B;EAC7E,KAAKA,gBAAgB,aAAaC,eAAmB,WAAW,SAAS;EACzE,KAAKC,cAAc,aAAaD,eAAmB,WAAW,OAAO;EACrE,KAAK,UAAU,IAAI,eAAe,YAAY,QAAQ;CAC1D;;;;CAKA,MAAM,GAAG,SAAgD;EACrD,MAAM,MAAM,MAAM,KAAKC,YAAY,GAAG,CAAC,GAAG,qBAAqB,OAAO,CAAC;EACvE,OAAO,MAAM,UAAU,GAAG;CAC9B;;;;;;;CAQA,MAAM,YAAY,SAAmD;EACjE,MAAM,KAAKA,YAAY,YAAY,CAAC,GAAG,qBAAqB,OAAO,CAAC;CACxE;;;;;;;;;CAUA,MAAM,sBACF,OACA,SACwB;EACxB,MAAM,YAAY,MAAM,kCAAkC,KAAK;EAC/D,OAAO,MACH,uBACA,MAAM,KAAKF,cAAc,sBACrB;GAAE,GAAG;GAAW,SAAA;EAA4C,GAC5D,qBAAqB,OAAO,CAChC,CACJ;CACJ;;;;CAKA,MAAgB,gBACZ,OACA,SACgC;EAChC,MAAM,iBAAiB,MAAM,4BAA4B,KAAK;EAC9D,MAAM,MAAM,MAAM,KAAKA,cAAc,gBACjC,gBACA,qBAAqB,OAAO,CAChC;EACA,OAAO,MAAM,+BAA+B,GAAG;CACnD;AACJ"}
@@ -1,3 +1,3 @@
1
- import { CreateWalletChallengeInput, LoginWithWalletInput, LoginWithWalletResponse, Me, WalletChallenge, WalletChallengePurpose } from "./auth.js";
1
+ import { CreateWalletChallengeInput, LoginWithWalletInput, LoginWithWalletResponse, Me, WalletChallenge } from "./auth.js";
2
2
  import { AccountSignerAuthEvents, CreateSubaccountParams, CreateSubaccountResult, LoginOptions, LoginResult } from "./account-signer-auth.js";
3
- export type { AccountSignerAuthEvents, CreateSubaccountResult as AccountSignerCreateSubaccountResult, CreateSubaccountParams, CreateWalletChallengeInput, LoginOptions, LoginResult, LoginWithWalletInput, LoginWithWalletResponse, Me, WalletChallenge, WalletChallengePurpose };
3
+ export type { AccountSignerAuthEvents, CreateSubaccountResult as AccountSignerCreateSubaccountResult, CreateSubaccountParams, CreateWalletChallengeInput, LoginOptions, LoginResult, LoginWithWalletInput, LoginWithWalletResponse, Me, WalletChallenge };
@@ -19,6 +19,7 @@ const SessionDataSchema = v.object({
19
19
  environmentFingerprint: v.string(),
20
20
  provider: v.picklist([
21
21
  "metamask",
22
+ "phantom",
22
23
  "turnkey",
23
24
  "other"
24
25
  ]),
@@ -1 +1 @@
1
- {"version":3,"file":"session.schemas.js","names":[],"sources":["../../../src/services/auth/session.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport type { SessionData } from \"./session.types.js\";\n\nexport const AuthLoginMethodSchema = v.picklist([\n \"google\",\n \"email\",\n \"metamask\",\n \"rabby\",\n \"phantom\",\n \"walletconnect\",\n]);\n\nexport const ActiveAccountInfoSchema = v.object({\n accountId: v.string(),\n isMain: v.boolean(),\n mainAccountId: v.string(),\n smartAccountAddress: v.optional(v.string()),\n label: v.optional(v.string()),\n});\n\nexport const SessionDataSchema = v.object({\n environmentFingerprint: v.string(),\n provider: v.picklist([\"metamask\", \"turnkey\", \"other\"]),\n loginMethod: v.nullable(AuthLoginMethodSchema),\n primaryWallet: v.string(),\n smartAccount: v.string(),\n activeAccount: v.optional(ActiveAccountInfoSchema),\n username: v.optional(v.string()),\n});\n\n/**\n * Parses raw session data into the SDK session shape.\n */\nexport function parseSessionData(value: unknown): SessionData | null {\n const parsed = v.safeParse(SessionDataSchema, value);\n return parsed.success ? parsed.output : null;\n}\n"],"mappings":";;AAGA,MAAa,wBAAwB,EAAE,SAAS;CAC5C;CACA;CACA;CACA;CACA;CACA;AACJ,CAAC;AAED,MAAa,0BAA0B,EAAE,OAAO;CAC5C,WAAW,EAAE,OAAO;CACpB,QAAQ,EAAE,QAAQ;CAClB,eAAe,EAAE,OAAO;CACxB,qBAAqB,EAAE,SAAS,EAAE,OAAO,CAAC;CAC1C,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC;AAChC,CAAC;AAED,MAAa,oBAAoB,EAAE,OAAO;CACtC,wBAAwB,EAAE,OAAO;CACjC,UAAU,EAAE,SAAS;EAAC;EAAY;EAAW;CAAO,CAAC;CACrD,aAAa,EAAE,SAAS,qBAAqB;CAC7C,eAAe,EAAE,OAAO;CACxB,cAAc,EAAE,OAAO;CACvB,eAAe,EAAE,SAAS,uBAAuB;CACjD,UAAU,EAAE,SAAS,EAAE,OAAO,CAAC;AACnC,CAAC;;;;AAKD,SAAgB,iBAAiB,OAAoC;CACjE,MAAM,SAAS,EAAE,UAAU,mBAAmB,KAAK;CACnD,OAAO,OAAO,UAAU,OAAO,SAAS;AAC5C"}
1
+ {"version":3,"file":"session.schemas.js","names":[],"sources":["../../../src/services/auth/session.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport type { SessionData } from \"./session.types.js\";\n\nexport const AuthLoginMethodSchema = v.picklist([\n \"google\",\n \"email\",\n \"metamask\",\n \"rabby\",\n \"phantom\",\n \"walletconnect\",\n]);\n\nexport const ActiveAccountInfoSchema = v.object({\n accountId: v.string(),\n isMain: v.boolean(),\n mainAccountId: v.string(),\n smartAccountAddress: v.optional(v.string()),\n label: v.optional(v.string()),\n});\n\nexport const SessionDataSchema = v.object({\n environmentFingerprint: v.string(),\n provider: v.picklist([\"metamask\", \"phantom\", \"turnkey\", \"other\"]),\n loginMethod: v.nullable(AuthLoginMethodSchema),\n primaryWallet: v.string(),\n smartAccount: v.string(),\n activeAccount: v.optional(ActiveAccountInfoSchema),\n username: v.optional(v.string()),\n});\n\n/**\n * Parses raw session data into the SDK session shape.\n */\nexport function parseSessionData(value: unknown): SessionData | null {\n const parsed = v.safeParse(SessionDataSchema, value);\n return parsed.success ? parsed.output : null;\n}\n"],"mappings":";;AAGA,MAAa,wBAAwB,EAAE,SAAS;CAC5C;CACA;CACA;CACA;CACA;CACA;AACJ,CAAC;AAED,MAAa,0BAA0B,EAAE,OAAO;CAC5C,WAAW,EAAE,OAAO;CACpB,QAAQ,EAAE,QAAQ;CAClB,eAAe,EAAE,OAAO;CACxB,qBAAqB,EAAE,SAAS,EAAE,OAAO,CAAC;CAC1C,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC;AAChC,CAAC;AAED,MAAa,oBAAoB,EAAE,OAAO;CACtC,wBAAwB,EAAE,OAAO;CACjC,UAAU,EAAE,SAAS;EAAC;EAAY;EAAW;EAAW;CAAO,CAAC;CAChE,aAAa,EAAE,SAAS,qBAAqB;CAC7C,eAAe,EAAE,OAAO;CACxB,cAAc,EAAE,OAAO;CACvB,eAAe,EAAE,SAAS,uBAAuB;CACjD,UAAU,EAAE,SAAS,EAAE,OAAO,CAAC;AACnC,CAAC;;;;AAKD,SAAgB,iBAAiB,OAAoC;CACjE,MAAM,SAAS,EAAE,UAAU,mBAAmB,KAAK;CACnD,OAAO,OAAO,UAAU,OAAO,SAAS;AAC5C"}
@@ -18,7 +18,7 @@ type AuthLoginMethod = "google" | "email" | "metamask" | "rabby" | "phantom" | "
18
18
  */
19
19
  interface SessionData {
20
20
  environmentFingerprint: string;
21
- provider: "metamask" | "turnkey" | "other";
21
+ provider: "metamask" | "phantom" | "turnkey" | "other";
22
22
  loginMethod: AuthLoginMethod | null;
23
23
  primaryWallet: string;
24
24
  smartAccount: string;
@@ -1,6 +1,6 @@
1
+ import { ClaimsService as ClaimsService$1 } from "../../gen/claims/v1/claims_pb.js";
1
2
  import { parse } from "../../shared/validation.js";
2
3
  import { toConnectCallOptions } from "../../shared/request-options.js";
3
- import { ClaimsService as ClaimsService$1 } from "../../gen/claims/v1/claims_pb.js";
4
4
  import { ClaimDailyRewardResultSchema, DailyClaimStatusSchema } from "./claims.schemas.js";
5
5
  import { createClient } from "@connectrpc/connect";
6
6
  //#region src/services/claims/claims.ts
@@ -14,7 +14,7 @@ type TimestampInit = {
14
14
  declare const GetOrderbookHeatmapInputSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
15
15
  readonly symbolId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>;
16
16
  readonly interval: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["1s", "1m", "5m", "1h"], undefined>, "1s">, v.TransformAction<"1s" | "1m" | "5m" | "1h", HeatmapInterval>]>;
17
- readonly depth: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly [1, 5, 10, 20, 50, 100, 200, 500, 1000], undefined>, 50>, v.TransformAction<1 | 10 | 5 | 20 | 200 | 500 | 1000 | 100 | 50, HeatmapDepth>]>;
17
+ readonly depth: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly [1, 5, 10, 20, 50, 100, 200, 500, 1000], undefined>, 50>, v.TransformAction<1 | 10 | 5 | 20 | 200 | 500 | 100 | 50 | 1000, HeatmapDepth>]>;
18
18
  readonly quantityMode: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["close", "peak"], undefined>, "close">, v.TransformAction<"close" | "peak", HeatmapQuantityMode>]>;
19
19
  readonly limit: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 20000, undefined>]>;
20
20
  readonly startTsSec: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>, v.MaxValueAction<number, number, undefined>, v.TransformAction<number, bigint>]>, undefined>;
@@ -227,7 +227,7 @@ type OrderbookHeatmapDeltaChain = ReturnType<typeof convertHeatmapDeltaChain>;
227
227
  declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
228
228
  readonly symbolId: v.NumberSchema<undefined>;
229
229
  readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1s" | "1m" | "5m" | "1h">>]>;
230
- readonly depth: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, 1 | "unspecified" | 10 | 5 | 20 | 200 | 500 | 1000 | 100 | 50>]>;
230
+ readonly depth: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, 1 | "unspecified" | 10 | 5 | 20 | 200 | 500 | 100 | 50 | 1000>]>;
231
231
  readonly chain: v.OptionalSchema<v.ObjectSchema<{
232
232
  readonly baseKeyframe: v.OptionalSchema<v.ObjectSchema<{
233
233
  readonly tsSec: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, number>]>;
@@ -287,7 +287,7 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
287
287
  }, undefined>, v.TransformAction<{
288
288
  symbolId: number;
289
289
  interval: DecodedEnum<"1s" | "1m" | "5m" | "1h">;
290
- depth: 1 | "unspecified" | 10 | 5 | 20 | 200 | 500 | 1000 | 100 | 50;
290
+ depth: 1 | "unspecified" | 10 | 5 | 20 | 200 | 500 | 100 | 50 | 1000;
291
291
  chain?: {
292
292
  baseKeyframe?: {
293
293
  tsSec: number;
@@ -347,7 +347,7 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
347
347
  }, {
348
348
  symbolId: number;
349
349
  interval: DecodedEnum<"1s" | "1m" | "5m" | "1h">;
350
- depth: 1 | "unspecified" | 10 | 5 | 20 | 200 | 500 | 1000 | 100 | 50;
350
+ depth: 1 | "unspecified" | 10 | 5 | 20 | 200 | 500 | 100 | 50 | 1000;
351
351
  chain: {
352
352
  baseKeyframe: {
353
353
  tsSec: number;
@@ -10,7 +10,7 @@ declare const GetOrderbookInputSchema: v.SchemaWithPipe<readonly [v.ObjectSchema
10
10
  depth: number;
11
11
  }, {
12
12
  symbolId: number;
13
- depth: 1 | 10 | 5 | 20 | 200 | 500 | 1000 | 100 | 50;
13
+ depth: 1 | 10 | 5 | 20 | 200 | 500 | 100 | 50 | 1000;
14
14
  protoDepth: Depth;
15
15
  }>]>;
16
16
  type GetOrderbookInput = v.InferInput<typeof GetOrderbookInputSchema>;
@@ -19,6 +19,7 @@ declare function createOrderSchema(scales: SdkScales): v.SchemaWithPipe<readonly
19
19
  readonly postOnly: v.BooleanSchema<undefined>;
20
20
  readonly origQtyScaled: v.BigintSchema<undefined>;
21
21
  readonly cumQtyScaled: v.BigintSchema<undefined>;
22
+ readonly inheritedCumQtyScaled: v.OptionalSchema<v.BigintSchema<undefined>, 0n>;
22
23
  readonly leavesQtyScaled: v.BigintSchema<undefined>;
23
24
  readonly avgPriceTicks: v.BigintSchema<undefined>;
24
25
  readonly priceTicks: v.BigintSchema<undefined>;
@@ -132,6 +133,7 @@ declare function createOrderSchema(scales: SdkScales): v.SchemaWithPipe<readonly
132
133
  postOnly: boolean;
133
134
  origQtyScaled: bigint;
134
135
  cumQtyScaled: bigint;
136
+ inheritedCumQtyScaled: bigint;
135
137
  leavesQtyScaled: bigint;
136
138
  avgPriceTicks: bigint;
137
139
  priceTicks: bigint;
@@ -247,6 +249,7 @@ declare function createOrderSchema(scales: SdkScales): v.SchemaWithPipe<readonly
247
249
  postOnly: boolean;
248
250
  totalQty: string;
249
251
  cumQty: string;
252
+ inheritedCumQty: string;
250
253
  leavesQty: string;
251
254
  avgPx: string;
252
255
  price: string;
@@ -257,7 +260,7 @@ declare function createOrderSchema(scales: SdkScales): v.SchemaWithPipe<readonly
257
260
  attachedRisk: {
258
261
  takeProfit: {
259
262
  state: {
260
- status: "unspecified" | "failed" | "created" | "completed" | "canceled" | "not_configured" | "armed" | "running" | "paused";
263
+ status: "unspecified" | "failed" | "completed" | "created" | "canceled" | "not_configured" | "armed" | "running" | "paused";
261
264
  armedTs: number | undefined;
262
265
  armedTsNs: string | undefined;
263
266
  terminalTs: number | undefined;
@@ -276,7 +279,7 @@ declare function createOrderSchema(scales: SdkScales): v.SchemaWithPipe<readonly
276
279
  } | undefined;
277
280
  stopLoss: {
278
281
  state: {
279
- status: "unspecified" | "failed" | "created" | "completed" | "canceled" | "not_configured" | "armed" | "running" | "paused";
282
+ status: "unspecified" | "failed" | "completed" | "created" | "canceled" | "not_configured" | "armed" | "running" | "paused";
280
283
  armedTs: number | undefined;
281
284
  armedTsNs: string | undefined;
282
285
  terminalTs: number | undefined;
@@ -295,7 +298,7 @@ declare function createOrderSchema(scales: SdkScales): v.SchemaWithPipe<readonly
295
298
  } | undefined;
296
299
  trailingStop: {
297
300
  state: {
298
- status: "unspecified" | "failed" | "created" | "completed" | "canceled" | "not_configured" | "armed" | "running" | "paused";
301
+ status: "unspecified" | "failed" | "completed" | "created" | "canceled" | "not_configured" | "armed" | "running" | "paused";
299
302
  armedTs: number | undefined;
300
303
  armedTsNs: string | undefined;
301
304
  terminalTs: number | undefined;
@@ -387,6 +390,7 @@ declare function createOrderDetailsSchema(scales: SdkScales): v.ObjectSchema<{
387
390
  readonly postOnly: v.BooleanSchema<undefined>;
388
391
  readonly origQtyScaled: v.BigintSchema<undefined>;
389
392
  readonly cumQtyScaled: v.BigintSchema<undefined>;
393
+ readonly inheritedCumQtyScaled: v.OptionalSchema<v.BigintSchema<undefined>, 0n>;
390
394
  readonly leavesQtyScaled: v.BigintSchema<undefined>;
391
395
  readonly avgPriceTicks: v.BigintSchema<undefined>;
392
396
  readonly priceTicks: v.BigintSchema<undefined>;
@@ -500,6 +504,7 @@ declare function createOrderDetailsSchema(scales: SdkScales): v.ObjectSchema<{
500
504
  postOnly: boolean;
501
505
  origQtyScaled: bigint;
502
506
  cumQtyScaled: bigint;
507
+ inheritedCumQtyScaled: bigint;
503
508
  leavesQtyScaled: bigint;
504
509
  avgPriceTicks: bigint;
505
510
  priceTicks: bigint;
@@ -615,6 +620,7 @@ declare function createOrderDetailsSchema(scales: SdkScales): v.ObjectSchema<{
615
620
  postOnly: boolean;
616
621
  totalQty: string;
617
622
  cumQty: string;
623
+ inheritedCumQty: string;
618
624
  leavesQty: string;
619
625
  avgPx: string;
620
626
  price: string;
@@ -625,7 +631,7 @@ declare function createOrderDetailsSchema(scales: SdkScales): v.ObjectSchema<{
625
631
  attachedRisk: {
626
632
  takeProfit: {
627
633
  state: {
628
- status: "unspecified" | "failed" | "created" | "completed" | "canceled" | "not_configured" | "armed" | "running" | "paused";
634
+ status: "unspecified" | "failed" | "completed" | "created" | "canceled" | "not_configured" | "armed" | "running" | "paused";
629
635
  armedTs: number | undefined;
630
636
  armedTsNs: string | undefined;
631
637
  terminalTs: number | undefined;
@@ -644,7 +650,7 @@ declare function createOrderDetailsSchema(scales: SdkScales): v.ObjectSchema<{
644
650
  } | undefined;
645
651
  stopLoss: {
646
652
  state: {
647
- status: "unspecified" | "failed" | "created" | "completed" | "canceled" | "not_configured" | "armed" | "running" | "paused";
653
+ status: "unspecified" | "failed" | "completed" | "created" | "canceled" | "not_configured" | "armed" | "running" | "paused";
648
654
  armedTs: number | undefined;
649
655
  armedTsNs: string | undefined;
650
656
  terminalTs: number | undefined;
@@ -663,7 +669,7 @@ declare function createOrderDetailsSchema(scales: SdkScales): v.ObjectSchema<{
663
669
  } | undefined;
664
670
  trailingStop: {
665
671
  state: {
666
- status: "unspecified" | "failed" | "created" | "completed" | "canceled" | "not_configured" | "armed" | "running" | "paused";
672
+ status: "unspecified" | "failed" | "completed" | "created" | "canceled" | "not_configured" | "armed" | "running" | "paused";
667
673
  armedTs: number | undefined;
668
674
  armedTsNs: string | undefined;
669
675
  terminalTs: number | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"orders-output.schemas.d.ts","names":[],"sources":["../../../src/services/orders/orders-output.schemas.ts"],"mappings":";;;;iBAoCgB,kBAAkB,QAAQ,YAAS,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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38
+ inheritedCumQtyScaled: v.optional(v.bigint(), 0n),
38
39
  leavesQtyScaled: v.bigint(),
39
40
  avgPriceTicks: v.bigint(),
40
41
  priceTicks: v.bigint(),
@@ -70,6 +71,7 @@ function createOrderSchema(scales) {
70
71
  postOnly: o.postOnly,
71
72
  totalQty: scaledToDecimalOutput(o.origQtyScaled, baseQtyScale),
72
73
  cumQty: scaledToDecimalOutput(o.cumQtyScaled, baseQtyScale),
74
+ inheritedCumQty: scaledToDecimalOutput(o.inheritedCumQtyScaled, baseQtyScale),
73
75
  leavesQty: scaledToDecimalOutput(o.leavesQtyScaled, baseQtyScale),
74
76
  avgPx: scaledToDecimalOutput(o.avgPriceTicks, scales.price()),
75
77
  price: scaledToDecimalOutput(o.priceTicks, scales.price()),