@polyester/sdk 0.35.0-devnet-20261110150127 → 0.35.0-devnet-20261110160258

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 (43) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/dist/index.d.ts +3 -2
  3. package/dist/index.js +2 -1
  4. package/dist/services/auth/account-signer-auth.d.ts +3 -0
  5. package/dist/services/auth/account-signer-auth.d.ts.map +1 -1
  6. package/dist/services/auth/account-signer-auth.js +2 -1
  7. package/dist/services/auth/account-signer-auth.js.map +1 -1
  8. package/dist/services/auth/auth.d.ts +26 -2
  9. package/dist/services/auth/auth.d.ts.map +1 -1
  10. package/dist/services/auth/auth.js +6 -3
  11. package/dist/services/auth/auth.js.map +1 -1
  12. package/dist/services/balances/balances.schemas.d.ts +8 -2
  13. package/dist/services/balances/balances.schemas.d.ts.map +1 -1
  14. package/dist/services/balances/balances.schemas.js +5 -1
  15. package/dist/services/balances/balances.schemas.js.map +1 -1
  16. package/dist/services/candles/candles.schemas.d.ts +10 -10
  17. package/dist/services/changelog/changelog.schemas.d.ts +17 -17
  18. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  19. package/dist/services/internal-transfers/internal-transfers.codecs.d.ts +6 -0
  20. package/dist/services/internal-transfers/internal-transfers.codecs.d.ts.map +1 -0
  21. package/dist/services/internal-transfers/internal-transfers.codecs.js +8 -1
  22. package/dist/services/internal-transfers/internal-transfers.codecs.js.map +1 -1
  23. package/dist/services/internal-transfers/internal-transfers.d.ts +1 -1
  24. package/dist/services/internal-transfers/internal-transfers.js +1 -1
  25. package/dist/services/internal-transfers/internal-transfers.js.map +1 -1
  26. package/dist/services/internal-transfers/internal-transfers.schemas.d.ts +3 -0
  27. package/dist/services/internal-transfers/internal-transfers.schemas.d.ts.map +1 -1
  28. package/dist/services/internal-transfers/internal-transfers.schemas.js +4 -2
  29. package/dist/services/internal-transfers/internal-transfers.schemas.js.map +1 -1
  30. package/dist/services/internal-transfers/internal-transfers.types.d.ts +2 -1
  31. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  32. package/dist/services/orders/orders-batch.schemas.d.ts +14 -14
  33. package/dist/services/orders/orders-output.schemas.d.ts +12 -12
  34. package/dist/services/rewards/rewards.schemas.d.ts +3 -3
  35. package/dist/services/subaccounts/subaccounts.schemas.d.ts +4 -4
  36. package/dist/services/trades/trades.schemas.d.ts +1 -1
  37. package/dist/services/triggers/trigger-input.schemas.d.ts +2 -2
  38. package/dist/services/triggers/triggers-output.schemas.d.ts +18 -18
  39. package/dist/services/triggers/triggers.d.ts +10 -4
  40. package/dist/services/triggers/triggers.d.ts.map +1 -1
  41. package/dist/services/triggers/triggers.js +8 -0
  42. package/dist/services/triggers/triggers.js.map +1 -1
  43. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @polyester/sdk
2
2
 
3
- ## 0.35.0-devnet-20261110150127
3
+ ## 0.35.0-devnet-20261110160258
4
4
 
5
5
  ### Minor Changes
6
6
 
@@ -26,8 +26,16 @@
26
26
 
27
27
  - `expandColumnarTimestampsSec` and `columnarTimestampSecAt` now end at `endTsSec`, so the last columnar history point is no longer one bucket early. ([#233](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/233))
28
28
 
29
+ - `formatLedgerBalance` is now exported from the package root. It converts a `ledger.read.v1.AssetBalance` message to the `LedgerBalance` that `balances.list` returns. Its U128 amounts are always at the 18-decimal ledger scale, whatever the asset's own decimals, so callers holding these messages from other APIs no longer convert them by hand. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
30
+
31
+ - `internalTransfers.create()` results now carry `status`: `"accepted"`, `"rejected"`, `"failed"`, or `"unspecified"` for a value this SDK version doesn't know. The response field was previously dropped. Rejected and failed transfers, such as insufficient funds or a missing step-up, still raise errors rather than returning a result. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
32
+
29
33
  - `lifecycle.listFlows` with an `accountSelector` now also returns the transfers the account received from other accounts, such as transfers from other users or subaccounts and reward payouts. Each row carries `participation`: `"owner"` for a flow the account owns, including a transfer it sent, and `"recipient"` for a received transfer. Rows are `"unspecified"` without an account selector and in flow detail and realtime updates. Pass `participation: "owner"` to keep the previous owner-only list or `"recipient"` for received transfers only. `participation` requires `accountSelector` and throws `ValidationError` without one. A `pageToken` now resumes only the request it came from, so change nothing but `limit` between pages. ([#237](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/237))
30
34
 
35
+ - `auth.login()` and `auth.refreshSession()` results now carry `session`, the issued token's assurance details (`sessionId`, `sessionLevel`, `authenticationMethods`, `authTimeMs`) in the same shape as `auth.me().session`. The wallet login response sent them, but the SDK dropped them. `session` is `undefined` when the response omits it. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
36
+
37
+ - `auth.me()` now returns `rootSmartAccountAddress`, the caller's root smart-account address as lowercase `0x` hex, or `""` when the account has none. It was previously dropped. A new account can read `""` for a moment right after its first login, until the backend records the address. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
38
+
31
39
  - A ConnectRPC `resource_exhausted` that carries a `RateLimitDetail`, as wallet sign-in and the public catalog calls now send, maps to a `RateLimitError` with `rateLimit` set and `retryAfterMs` taken from the detail. Its `detail` is `{ service: "rate_limit", code: "RATE_LIMIT_EXCEEDED", rateLimit }`. The gateway's own refusal has no detail: `retryAfterMs` comes from `Retry-After` when present and is `undefined` for a concurrency refusal, so back off without a server hint. ([#236](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/236))
32
40
 
33
41
  - Realtime token requests (`/v1/rt/token` and `/v1/rt/subscribe`) now go through the `fetch` passed to `PolyesterClient`, like every other SDK request. They used the global `fetch` before, so proxies, mocks and request logging never saw them. `RealtimeClient` takes the same optional `fetch`. Without one, both keep using the global `fetch`. ([#238](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/238))
@@ -48,6 +56,8 @@
48
56
 
49
57
  - `tradeWsPb` in `@polyester/sdk/unstable/gen` adds the `cancelAllAfter` client command and acknowledgement, which arm, refresh or disarm the account's dead-man switch, plus the `ClientFrame` fields `timestampMs` and `recvWindowMs`, which set a per-command receive window. The SDK has no trading WebSocket client yet. ([#237](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/237))
50
58
 
59
+ - `triggers.fromProto(trigger)` converts a `triggers.v1.Trigger` message received from another API into the same `Trigger` record that `triggers.get`, `list`, and `subscribe` return, with quantities and prices scaled by the client's catalog. It waits for the catalog and throws when the trigger's market isn't in it. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
60
+
51
61
  - A wallet login refused with `AUTH_WALLET_ALREADY_LINKED` maps to a non-retryable `AlreadyExistsError`. The wallet already belongs to another account, so the same login fails again. Log in with the account address the wallet already uses. ([#236](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/236))
52
62
 
53
63
  ## 0.34.0
package/dist/index.d.ts CHANGED
@@ -19,7 +19,7 @@ import { ApiKeyPolicy, ApiKeyPolicyApplyInput, ApiKeyPolicyCreateInput, ApiKeyPo
19
19
  import { ApiKey, ApiKeyIdInput, ApiKeyStatus, ApiKeysCreateInput, ApiKeysListInput, ApiKeysUpdateInput } from "./services/api-keys/api-keys.schemas.js";
20
20
  import { SubaccountPolicy, SubaccountPolicyApplyInput, SubaccountPolicyCreateInput, SubaccountPolicyUpdateInput } from "./services/policies/subaccount-policies/subaccount-policies.schemas.js";
21
21
  import { AccountCodeValue, TransferCodeValue } from "./shared/ledger-codes.js";
22
- import { BalanceHistoryInput, BalanceHistoryResponse, BalanceRange, EquityGroupBy, EquityHistoryInput, EquityHistoryResponse, EquitySeries, EquitySeriesGrouping, LedgerBalance, PortfolioEquityHistoryInput, PortfolioEquityHistoryResponse, PortfolioEquitySeries, PortfolioEquitySeriesGrouping, PortfolioEquitySnapshotResponse } from "./services/balances/balances.schemas.js";
22
+ import { BalanceHistoryInput, BalanceHistoryResponse, BalanceRange, EquityGroupBy, EquityHistoryInput, EquityHistoryResponse, EquitySeries, EquitySeriesGrouping, LedgerBalance, PortfolioEquityHistoryInput, PortfolioEquityHistoryResponse, PortfolioEquitySeries, PortfolioEquitySeriesGrouping, PortfolioEquitySnapshotResponse, formatLedgerBalance } from "./services/balances/balances.schemas.js";
23
23
  import { CreateSubaccountChallengeInput, CreateSubaccountInput, CreateSubaccountResult as CreateSubaccountResult$1, EffectiveSubaccountPermissions, GetSubaccountInput, InviteSubaccountMemberInput, ListSubaccountInvitesInput, RemoveSubaccountMemberInput, RespondSubaccountInviteInput, SetSubaccountMemberMfaRequirementInput, Subaccount, SubaccountActivityInput, SubaccountChallenge, SubaccountEvent, SubaccountIdInput, SubaccountInvite, SubaccountInviteStatus, SubaccountMember, SubaccountPermission, SubaccountPermissionDefinition, SubaccountRole, SubaccountRoleCatalog, SubaccountRoleDefinition, SubaccountStatus, UpdateSubaccountInput, UpdateSubaccountMemberRoleInput } from "./services/subaccounts/subaccounts.schemas.js";
24
24
  import { Candle, CandleColumnar, CandleColumnarInt, CandleInt, GetCandlesColumnsInput, GetCandlesInput, Timeframe } from "./services/candles/candles.schemas.js";
25
25
  import { ChainAnalyticsRange, GetUnifiedAssetBalancesInput, GetZippedAssetSupplyGroupInput, GetZippedAssetSupplyInput, UnifiedAssetBalancesResponse, ZippedAssetSupplyGroupResponse, ZippedAssetSupplyResponse, ZippedAssetSupplySeries } from "./services/chain-analytics/chain-analytics.schemas.js";
@@ -101,6 +101,7 @@ import "./services/deposit/deposit.types.js";
101
101
  import "./services/fees/fees.types.js";
102
102
  import "./services/guard-signer/guard-signer.types.js";
103
103
  import "./services/heatmap/heatmap.types.js";
104
+ import { InternalTransferStatus } from "./services/internal-transfers/internal-transfers.codecs.js";
104
105
  import "./services/internal-transfers/internal-transfers.types.js";
105
106
  import "./services/lifecycle/lifecycle.types.js";
106
107
  import "./services/market-data/market-data.types.js";
@@ -124,4 +125,4 @@ import "./services/transfers/transfers.types.js";
124
125
  import "./services/triggers/triggers.types.js";
125
126
  import "./services/vip/vip.types.js";
126
127
  import "./services/zipper/zipper.types.js";
127
- export { type AccountCodeValue, type AccountIdentity, type AccountScope, type AccountScopedInput, type AccountSigner, type AccountSignerAuthEvents, type AccountSignerConfig, type CreateSubaccountResult as AccountSignerCreateSubaccountResult, type AccountSignerFactory, type ActiveAccountInfo, type AddressBook, type AddressBookAccountScope, type AddressBookEntries, type AddressBookEntriesView, type AddressBookEntry, type AddressBookRecentDestinationsView, type AddressBookTag, type AddressBookTagSummary, type AddressBookView, type AddressBookViewInvalidated, AlreadyExistsError, type ApiKey, type ApiKeyEd25519AuthProvider, type ApiKeyIdInput, type ApiKeyPolicy, type ApiKeyPolicyApplyInput, type ApiKeyPolicyCreateInput, type ApiKeyPolicyUpdateInput, type ApiKeyStatus, type ApiKeysCreateInput, type ApiKeysListInput, type ApiKeysUpdateInput, type AssetConfig, type AuthCookieLocation, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type AutoWithdrawCadence, type AutoWithdrawDestination, type AutoWithdrawDestinationInput, type AutoWithdrawPause, type AutoWithdrawPauseReason, type AutoWithdrawRule, type AutoWithdrawRun, type AutoWithdrawRunReason, type AutoWithdrawRunState, type AutoWithdrawSchedule, type AutoWithdrawScheduleInput, type AutoWithdrawScopedInput, type AutoWithdrawStep, type AutoWithdrawStepReason, type AutoWithdrawStepState, type AutoWithdrawWeekday, type BalanceHistoryInput, type BalanceHistoryResponse, type BalanceRange, type BatchCancelOrderInput, type BatchCancelOrderResult, type BatchCancelOrdersInput, type BatchCancelOrdersResult, type BatchCreateOrderResult, type BatchCreateOrdersInput, type BatchCreateOrdersResult, type BatchGuardApprovals, type BatchReplaceAdmissionItem, type BatchReplaceOrdersInput, type BatchReplaceOrdersResult, type BatchSignProtectedActionInput, type BeginMfaChallengeInput, type BeginMfaChallengeResult, type BeginPasskeyEnrollmentInput, type BeginPasskeyEnrollmentResult, type BeginTotpEnrollmentInput, type BeginTotpEnrollmentResult, type CancelAllAfterInput, type CancelAllAfterResult, type CancelAllOrdersInput, type CancelAllOrdersResponse, type CancelOrderInput, type CancelOrderResult, type CancelTriggerInput, type CancelTriggerResult, type Candle, type CandleColumnar, type CandleColumnarInt, type CandleInt, type ChainAnalyticsRange, type ChangelogAudience, type ChangelogChange, type ChangelogChangeCategory, type ChangelogChangeEntry, type ChangelogPost, type ChangelogPostSummary, type ChangelogSection, type ChangelogSort, type ChangelogSurface, type Checkpoint, type CheckpointAssetAmount, type CheckpointBadge, type CheckpointBiggestTrade, type CheckpointChainFlow, type CheckpointEarnedBadge, type CheckpointField, type CheckpointFlowTotal, type CheckpointFundingDay, type CheckpointFundingFlowSummary, type CheckpointOrderToolCounts, type CheckpointOrderTypeCounts, type CheckpointPairActivity, type CheckpointPortfolioValuePoint, type CheckpointTimeInForceCounts, type CheckpointVipTierChange, type CheckpointVolumePoint, type ClaimCampaign, type ClaimDailyRewardInput, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, type ClaimPayoutDelayReason, type ClaimPolicy, type ColumnarTimeWindow, type CompleteMfaChallengeResult, ConfigurationError, type ConnectChannelParams, type ConnectPrivateOrdersParams, type ConsumeFreshStepUpInput, type CookieAuthTokenStorageOptions, type CopyAddressBookEntryInput, type CreateAddressBookEntryInput, type CreateAddressBookTagInput, type CreateDepositAddressInput, type CreateGuardSignerWalletResult, type CreateInternalTransferInput, type CreateInternalTransferResult, type CreateOrderResult, type CreateOrderbookSubscriptionInput, type CreatePolyesterAccountSignerParams, type CreatePolyesterEnvironmentParams, type CreateServerClientFromCookiesParams, type CreateServerClientFromRequestParams, type CreateSubaccountChallengeInput, type CreateSubaccountInput, type CreateSubaccountParams, type CreateSubaccountResult$1 as CreateSubaccountResult, type CreateSubaccountResult$1 as CreateSubaccountServiceResult, type CreateTradingWithdrawResult, type CreateTradingWithdrawToExternalChainInput, type CreateTradingWithdrawToExternalChainServiceInput, type CreateTradingWithdrawToFundingInput, type CreateTradingWithdrawToFundingServiceInput, type CreateTriggerInput, type CreateTriggerResult, type CreateWalletChallengeInput, type CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type DisableAutoWithdrawRuleInput, type EffectiveSubaccountPermissions, type EquityGroupBy, type EquityHistoryInput, type EquityHistoryResponse, type EquitySeries, type EquitySeriesGrouping, type EvmHex, type ExportGuardSignerWalletResult, type FiatConversionRate, type FiatConversionSnapshot, type FinishPasskeyChallengeInput, type FinishPasskeyEnrollmentInput, type FinishPasskeyEnrollmentResult, type FinishTotpEnrollmentInput, type FinishTotpEnrollmentResult, type GeneratedUsernameOffer, type GetAddressBookViewInput, type GetBatchReplaceStatusInput, type GetBatchReplaceStatusResult, type GetCandlesColumnsInput, type GetCandlesInput, type GetChangelogPostInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetSubaccountInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, type GetZippedAssetSupplyGroupInput, type GetZippedAssetSupplyInput, type GuardApproval, type GuardSignerScopedInput, type GuardSignerStatus, type HeatmapDepthValue, type HeatmapIntervalValue, type HeatmapQuantityModeValue, type HexAddress, InternalServerError, type InternalTransferDestination, type InternalTransferWhitelistEntries, type InternalTransferWhitelistEntry, type InviteSubaccountMemberInput, type JwtAuthProvider, type LadderDetailsOutput, type LedgerBalance, type LedgerTransfer, type LedgerTransferSide, type LifecycleAssetIds, type LifecycleFlowDetail, type LifecycleFlowState, type LifecycleFlowStep, type LifecycleFlowStepActivity, type LifecycleFlowSummary, type LifecycleFlowSummaryProgress, type LifecycleFlowTimelineItem, type LifecycleFlowTxMatch, type LifecycleListOrderBy, type LifecycleListScope, type LifecycleReason, type LifecycleRequestFee, type LifecycleRequestFeeStatus, type LifecycleSort, type LifecycleTxLookupKind, type LifecycleZipperReason, type ListAddressBookEntriesInput, type ListApiKeyPoliciesResponse, type ListAutoWithdrawRunsInput, type ListAutoWithdrawRunsResult, type ListChangelogChangesInput, type ListChangelogChangesResult, type ListChangelogPostsInput, type ListChangelogPostsResult, type ListCheckpointsInput, type ListDepositAddressesInput, type ListInternalTransferWhitelistEntriesInput, type ListLifecycleFlowsByTxInput, type ListLifecycleFlowsByTxOutput, type ListLifecycleFlowsInput, type ListLifecycleFlowsOutput, type ListMarketOverviewInput, type ListMfaFactorsResult, type ListRewardAwardsInput, type ListRewardAwardsResult, type ListSubaccountInvitesInput, type ListTransferCounterpartiesInput, type ListTransferDestinationsInput, type ListTransfersInput, type ListTriggerEventsInput, type ListTriggerEventsResult, type ListTriggersInput, type ListTriggersResult, type LoginOptions, type LoginResult, type LoginWithWalletInput, type LoginWithWalletResponse, type MarketOverview, type MarketOverviewOrderBy, type MarketOverviewSort, type MarketOverviewSparkline, type MarketTrade, type Me, MfaEnrollmentRequiredError, type MfaFactor, MfaLastFactorRequiredError, MfaRequiredError, type MfaSessionInfo, MfaVerificationError, type MfaVerificationFailureReason, type MirroredWithdrawWhitelistEntry, type ModifyOrderInput, type ModifyOrderResult, type ModifyTriggerInput, type ModifyTriggerResult, NetworkError, type NewOrderInput, type NextVipTierThresholds, NotImplementedError, type OpenOrdersInput, type Order, type OrderDetails, type OrderErrorCode, type OrderErrorDetail, type OrderHistoryInput, type OrderIntentInput, type OrderLineage, type OrderTransfer, type OrderbookData, type OrderbookHeatmapDeltaBucket, type OrderbookHeatmapDeltaChain, type OrderbookHeatmapDeltaLevels, type OrderbookHeatmapKeyframe, type OrderbookHeatmapLevels, type OrderbookHeatmapLiveBucket, type OrderbookHeatmapResponse, type OrderbookLevel, type OrderbookStreamHandlers, type OrderbookSubscription, OutcomeUnknownError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, type PairConfig, type PairStatus, type PauseTriggerInput, type PauseTriggerResult, PermissionError, type PolicyAction, PolicyInUseError, PolicyLockedError, type PolicyMarketScope, PolicyScopeMismatchError, type PolyesterAccountAbstractionEnvironment, PolyesterBrowserClient, type PolyesterBrowserClientConfig, PolyesterBrowserCore, PolyesterClient, type PolyesterClientBaseConfig, type PolyesterClientConfig, type PolyesterContractsEnvironment, PolyesterCore, type PolyesterEntryPointConfig, type PolyesterEnvironment, PolyesterError, type PolyesterErrorCode, type PolyesterErrorDetail, type PolyesterErrorOptions, type PolyesterMutationOptions, type PolyesterRealtime, type PolyesterRealtimeAuthConfig, type PolyesterRequestOptions, type PolyesterSafeDeploymentConfig, PolyesterServerClient, type PolyesterServerClientConfig, PolyesterServerCore, type PolyesterServices, type PortfolioEquityHistoryInput, type PortfolioEquityHistoryResponse, type PortfolioEquitySeries, type PortfolioEquitySeriesGrouping, type PortfolioEquitySnapshotResponse, PreconditionFailedError, type PreparedTradingWithdraw, type PreviewOrderResult, type PrivateOrdersEvent, type Profile, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, type RealtimeConnection, type RealtimeConnectionState, type RealtimeConnectionStatus, RealtimeError, type RealtimeErrorOptions, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestDeadlineExceededError, RequestError, RequestTooLargeError, type ResolveAccountInput, type ResolvedAccount, type ResolvedInternalTransferDestination, ResourceNotFoundError, type RespondSubaccountInviteInput, type ResumeTriggerInput, type ResumeTriggerResult, RevisionConflictError, type RewardAward, type RewardFulfillmentMethod, type RewardFulfillmentState, type RiskPolicyInput, type RotateGuardSignerWalletResult, type SdkSubscriptionErrorContext, type ServerSessionCookieOptions, type ServerSessionSnapshot, ServiceUnavailableError, type SessionData, SessionElevationRequiredError, type SetAutoWithdrawRuleInput, type SetRewardDestinationInput, type SetRewardDestinationResult, type SetSubaccountMemberMfaRequirementInput, type SignProtectedActionInput, type SocialProvider, type SocialProviderInput, type SocialVerification, type SocialVerificationErrorCode, type SocialVerificationMethod, type SocialVerificationStatus, type SparklineIntervalName, type SpotConfig, type SpotFeeDiscount, type SpotFeeRate, type SpotFeeRateBreakdown, type SpotPairVolumeSeries, type SpotVolumeHistoryInput, type SpotVolumeHistoryResponse, type StablecoinConversionRate, StaleQuoteError, type StartVerificationInput, type StartVerificationResponse, StepUpRequiredError, type StopDetailsOutput, type StopLossInput, type Subaccount, type SubaccountActivityInput, type SubaccountChallenge, SubaccountChallengeInvalidError, type SubaccountEvent, type SubaccountIdInput, type SubaccountInvite, type SubaccountInviteStatus, type SubaccountMember, type SubaccountPermission, type SubaccountPermissionDefinition, type SubaccountPolicy, type SubaccountPolicyApplyInput, type SubaccountPolicyCreateInput, type SubaccountPolicyUpdateInput, type SubaccountRole, type SubaccountRoleCatalog, type SubaccountRoleDefinition, type SubaccountScopedInput, type SubaccountStatus, type SubscribeHandlers, type SubscribeZippedAssetSupplyInput, type TakeProfitInput, type Timeframe, TimeoutError, TimestampSkewError, type Trade, type TradeBackfill, type TradingRateLimitClass, type TradingRateLimitRule, type TradingRateLimits, type TradingWithdrawSigningConfig, type TradingWithdrawWalletSigner, type TrailingDetailsOutput, type TrailingStopInput, type TransferCodeValue, type TransferCounterparties, type TransferCounterparty, type TransferDestination, type TransferDestinations, type TransferSideKind, TransientError, type Transports, type Trigger, type TriggerDetailsOutput, type TriggerEvent, type TwapDetailsOutput, type UnifiedAssetBalancesResponse, type UpdateAddressBookEntryInput, type UpdateAddressBookTagInput, type UpdateMfaFactorInput, type UpdateMfaFactorResult, type UpdateProfileInput, type UpdateSubaccountInput, type UpdateSubaccountMemberRoleInput, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipMetricQuality, type VipMetricStatus, type VipStatus, type VipTier, type VipTierCatalog, type WalletChallenge, WithdrawDeadlineExpiredError, type WithdrawWhitelistView, type ZippedAssetSupplyBatch, type ZippedAssetSupplyGroupResponse, type ZippedAssetSupplyResponse, type ZippedAssetSupplySeries, type ZippedAssetSupplyUpdate, type ZipperAssetChainVariant, type ZipperAssetConfig, type ZipperChainConfig, type ZipperChainContractConfig, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
128
+ export { type AccountCodeValue, type AccountIdentity, type AccountScope, type AccountScopedInput, type AccountSigner, type AccountSignerAuthEvents, type AccountSignerConfig, type CreateSubaccountResult as AccountSignerCreateSubaccountResult, type AccountSignerFactory, type ActiveAccountInfo, type AddressBook, type AddressBookAccountScope, type AddressBookEntries, type AddressBookEntriesView, type AddressBookEntry, type AddressBookRecentDestinationsView, type AddressBookTag, type AddressBookTagSummary, type AddressBookView, type AddressBookViewInvalidated, AlreadyExistsError, type ApiKey, type ApiKeyEd25519AuthProvider, type ApiKeyIdInput, type ApiKeyPolicy, type ApiKeyPolicyApplyInput, type ApiKeyPolicyCreateInput, type ApiKeyPolicyUpdateInput, type ApiKeyStatus, type ApiKeysCreateInput, type ApiKeysListInput, type ApiKeysUpdateInput, type AssetConfig, type AuthCookieLocation, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type AutoWithdrawCadence, type AutoWithdrawDestination, type AutoWithdrawDestinationInput, type AutoWithdrawPause, type AutoWithdrawPauseReason, type AutoWithdrawRule, type AutoWithdrawRun, type AutoWithdrawRunReason, type AutoWithdrawRunState, type AutoWithdrawSchedule, type AutoWithdrawScheduleInput, type AutoWithdrawScopedInput, type AutoWithdrawStep, type AutoWithdrawStepReason, type AutoWithdrawStepState, type AutoWithdrawWeekday, type BalanceHistoryInput, type BalanceHistoryResponse, type BalanceRange, type BatchCancelOrderInput, type BatchCancelOrderResult, type BatchCancelOrdersInput, type BatchCancelOrdersResult, type BatchCreateOrderResult, type BatchCreateOrdersInput, type BatchCreateOrdersResult, type BatchGuardApprovals, type BatchReplaceAdmissionItem, type BatchReplaceOrdersInput, type BatchReplaceOrdersResult, type BatchSignProtectedActionInput, type BeginMfaChallengeInput, type BeginMfaChallengeResult, type BeginPasskeyEnrollmentInput, type BeginPasskeyEnrollmentResult, type BeginTotpEnrollmentInput, type BeginTotpEnrollmentResult, type CancelAllAfterInput, type CancelAllAfterResult, type CancelAllOrdersInput, type CancelAllOrdersResponse, type CancelOrderInput, type CancelOrderResult, type CancelTriggerInput, type CancelTriggerResult, type Candle, type CandleColumnar, type CandleColumnarInt, type CandleInt, type ChainAnalyticsRange, type ChangelogAudience, type ChangelogChange, type ChangelogChangeCategory, type ChangelogChangeEntry, type ChangelogPost, type ChangelogPostSummary, type ChangelogSection, type ChangelogSort, type ChangelogSurface, type Checkpoint, type CheckpointAssetAmount, type CheckpointBadge, type CheckpointBiggestTrade, type CheckpointChainFlow, type CheckpointEarnedBadge, type CheckpointField, type CheckpointFlowTotal, type CheckpointFundingDay, type CheckpointFundingFlowSummary, type CheckpointOrderToolCounts, type CheckpointOrderTypeCounts, type CheckpointPairActivity, type CheckpointPortfolioValuePoint, type CheckpointTimeInForceCounts, type CheckpointVipTierChange, type CheckpointVolumePoint, type ClaimCampaign, type ClaimDailyRewardInput, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, type ClaimPayoutDelayReason, type ClaimPolicy, type ColumnarTimeWindow, type CompleteMfaChallengeResult, ConfigurationError, type ConnectChannelParams, type ConnectPrivateOrdersParams, type ConsumeFreshStepUpInput, type CookieAuthTokenStorageOptions, type CopyAddressBookEntryInput, type CreateAddressBookEntryInput, type CreateAddressBookTagInput, type CreateDepositAddressInput, type CreateGuardSignerWalletResult, type CreateInternalTransferInput, type CreateInternalTransferResult, type CreateOrderResult, type CreateOrderbookSubscriptionInput, type CreatePolyesterAccountSignerParams, type CreatePolyesterEnvironmentParams, type CreateServerClientFromCookiesParams, type CreateServerClientFromRequestParams, type CreateSubaccountChallengeInput, type CreateSubaccountInput, type CreateSubaccountParams, type CreateSubaccountResult$1 as CreateSubaccountResult, type CreateSubaccountResult$1 as CreateSubaccountServiceResult, type CreateTradingWithdrawResult, type CreateTradingWithdrawToExternalChainInput, type CreateTradingWithdrawToExternalChainServiceInput, type CreateTradingWithdrawToFundingInput, type CreateTradingWithdrawToFundingServiceInput, type CreateTriggerInput, type CreateTriggerResult, type CreateWalletChallengeInput, type CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type DisableAutoWithdrawRuleInput, type EffectiveSubaccountPermissions, type EquityGroupBy, type EquityHistoryInput, type EquityHistoryResponse, type EquitySeries, type EquitySeriesGrouping, type EvmHex, type ExportGuardSignerWalletResult, type FiatConversionRate, type FiatConversionSnapshot, type FinishPasskeyChallengeInput, type FinishPasskeyEnrollmentInput, type FinishPasskeyEnrollmentResult, type FinishTotpEnrollmentInput, type FinishTotpEnrollmentResult, type GeneratedUsernameOffer, type GetAddressBookViewInput, type GetBatchReplaceStatusInput, type GetBatchReplaceStatusResult, type GetCandlesColumnsInput, type GetCandlesInput, type GetChangelogPostInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetSubaccountInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, type GetZippedAssetSupplyGroupInput, type GetZippedAssetSupplyInput, type GuardApproval, type GuardSignerScopedInput, type GuardSignerStatus, type HeatmapDepthValue, type HeatmapIntervalValue, type HeatmapQuantityModeValue, type HexAddress, InternalServerError, type InternalTransferDestination, type InternalTransferStatus, type InternalTransferWhitelistEntries, type InternalTransferWhitelistEntry, type InviteSubaccountMemberInput, type JwtAuthProvider, type LadderDetailsOutput, type LedgerBalance, type LedgerTransfer, type LedgerTransferSide, type LifecycleAssetIds, type LifecycleFlowDetail, type LifecycleFlowState, type LifecycleFlowStep, type LifecycleFlowStepActivity, type LifecycleFlowSummary, type LifecycleFlowSummaryProgress, type LifecycleFlowTimelineItem, type LifecycleFlowTxMatch, type LifecycleListOrderBy, type LifecycleListScope, type LifecycleReason, type LifecycleRequestFee, type LifecycleRequestFeeStatus, type LifecycleSort, type LifecycleTxLookupKind, type LifecycleZipperReason, type ListAddressBookEntriesInput, type ListApiKeyPoliciesResponse, type ListAutoWithdrawRunsInput, type ListAutoWithdrawRunsResult, type ListChangelogChangesInput, type ListChangelogChangesResult, type ListChangelogPostsInput, type ListChangelogPostsResult, type ListCheckpointsInput, type ListDepositAddressesInput, type ListInternalTransferWhitelistEntriesInput, type ListLifecycleFlowsByTxInput, type ListLifecycleFlowsByTxOutput, type ListLifecycleFlowsInput, type ListLifecycleFlowsOutput, type ListMarketOverviewInput, type ListMfaFactorsResult, type ListRewardAwardsInput, type ListRewardAwardsResult, type ListSubaccountInvitesInput, type ListTransferCounterpartiesInput, type ListTransferDestinationsInput, type ListTransfersInput, type ListTriggerEventsInput, type ListTriggerEventsResult, type ListTriggersInput, type ListTriggersResult, type LoginOptions, type LoginResult, type LoginWithWalletInput, type LoginWithWalletResponse, type MarketOverview, type MarketOverviewOrderBy, type MarketOverviewSort, type MarketOverviewSparkline, type MarketTrade, type Me, MfaEnrollmentRequiredError, type MfaFactor, MfaLastFactorRequiredError, MfaRequiredError, type MfaSessionInfo, MfaVerificationError, type MfaVerificationFailureReason, type MirroredWithdrawWhitelistEntry, type ModifyOrderInput, type ModifyOrderResult, type ModifyTriggerInput, type ModifyTriggerResult, NetworkError, type NewOrderInput, type NextVipTierThresholds, NotImplementedError, type OpenOrdersInput, type Order, type OrderDetails, type OrderErrorCode, type OrderErrorDetail, type OrderHistoryInput, type OrderIntentInput, type OrderLineage, type OrderTransfer, type OrderbookData, type OrderbookHeatmapDeltaBucket, type OrderbookHeatmapDeltaChain, type OrderbookHeatmapDeltaLevels, type OrderbookHeatmapKeyframe, type OrderbookHeatmapLevels, type OrderbookHeatmapLiveBucket, type OrderbookHeatmapResponse, type OrderbookLevel, type OrderbookStreamHandlers, type OrderbookSubscription, OutcomeUnknownError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, type PairConfig, type PairStatus, type PauseTriggerInput, type PauseTriggerResult, PermissionError, type PolicyAction, PolicyInUseError, PolicyLockedError, type PolicyMarketScope, PolicyScopeMismatchError, type PolyesterAccountAbstractionEnvironment, PolyesterBrowserClient, type PolyesterBrowserClientConfig, PolyesterBrowserCore, PolyesterClient, type PolyesterClientBaseConfig, type PolyesterClientConfig, type PolyesterContractsEnvironment, PolyesterCore, type PolyesterEntryPointConfig, type PolyesterEnvironment, PolyesterError, type PolyesterErrorCode, type PolyesterErrorDetail, type PolyesterErrorOptions, type PolyesterMutationOptions, type PolyesterRealtime, type PolyesterRealtimeAuthConfig, type PolyesterRequestOptions, type PolyesterSafeDeploymentConfig, PolyesterServerClient, type PolyesterServerClientConfig, PolyesterServerCore, type PolyesterServices, type PortfolioEquityHistoryInput, type PortfolioEquityHistoryResponse, type PortfolioEquitySeries, type PortfolioEquitySeriesGrouping, type PortfolioEquitySnapshotResponse, PreconditionFailedError, type PreparedTradingWithdraw, type PreviewOrderResult, type PrivateOrdersEvent, type Profile, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, type RealtimeConnection, type RealtimeConnectionState, type RealtimeConnectionStatus, RealtimeError, type RealtimeErrorOptions, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestDeadlineExceededError, RequestError, RequestTooLargeError, type ResolveAccountInput, type ResolvedAccount, type ResolvedInternalTransferDestination, ResourceNotFoundError, type RespondSubaccountInviteInput, type ResumeTriggerInput, type ResumeTriggerResult, RevisionConflictError, type RewardAward, type RewardFulfillmentMethod, type RewardFulfillmentState, type RiskPolicyInput, type RotateGuardSignerWalletResult, type SdkSubscriptionErrorContext, type ServerSessionCookieOptions, type ServerSessionSnapshot, ServiceUnavailableError, type SessionData, SessionElevationRequiredError, type SetAutoWithdrawRuleInput, type SetRewardDestinationInput, type SetRewardDestinationResult, type SetSubaccountMemberMfaRequirementInput, type SignProtectedActionInput, type SocialProvider, type SocialProviderInput, type SocialVerification, type SocialVerificationErrorCode, type SocialVerificationMethod, type SocialVerificationStatus, type SparklineIntervalName, type SpotConfig, type SpotFeeDiscount, type SpotFeeRate, type SpotFeeRateBreakdown, type SpotPairVolumeSeries, type SpotVolumeHistoryInput, type SpotVolumeHistoryResponse, type StablecoinConversionRate, StaleQuoteError, type StartVerificationInput, type StartVerificationResponse, StepUpRequiredError, type StopDetailsOutput, type StopLossInput, type Subaccount, type SubaccountActivityInput, type SubaccountChallenge, SubaccountChallengeInvalidError, type SubaccountEvent, type SubaccountIdInput, type SubaccountInvite, type SubaccountInviteStatus, type SubaccountMember, type SubaccountPermission, type SubaccountPermissionDefinition, type SubaccountPolicy, type SubaccountPolicyApplyInput, type SubaccountPolicyCreateInput, type SubaccountPolicyUpdateInput, type SubaccountRole, type SubaccountRoleCatalog, type SubaccountRoleDefinition, type SubaccountScopedInput, type SubaccountStatus, type SubscribeHandlers, type SubscribeZippedAssetSupplyInput, type TakeProfitInput, type Timeframe, TimeoutError, TimestampSkewError, type Trade, type TradeBackfill, type TradingRateLimitClass, type TradingRateLimitRule, type TradingRateLimits, type TradingWithdrawSigningConfig, type TradingWithdrawWalletSigner, type TrailingDetailsOutput, type TrailingStopInput, type TransferCodeValue, type TransferCounterparties, type TransferCounterparty, type TransferDestination, type TransferDestinations, type TransferSideKind, TransientError, type Transports, type Trigger, type TriggerDetailsOutput, type TriggerEvent, type TwapDetailsOutput, type UnifiedAssetBalancesResponse, type UpdateAddressBookEntryInput, type UpdateAddressBookTagInput, type UpdateMfaFactorInput, type UpdateMfaFactorResult, type UpdateProfileInput, type UpdateSubaccountInput, type UpdateSubaccountMemberRoleInput, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipMetricQuality, type VipMetricStatus, type VipStatus, type VipTier, type VipTierCatalog, type WalletChallenge, WithdrawDeadlineExpiredError, type WithdrawWhitelistView, type ZippedAssetSupplyBatch, type ZippedAssetSupplyGroupResponse, type ZippedAssetSupplyResponse, type ZippedAssetSupplySeries, type ZippedAssetSupplyUpdate, type ZipperAssetChainVariant, type ZipperAssetConfig, type ZipperChainConfig, type ZipperChainContractConfig, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatLedgerBalance, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ import { POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_TESTNET_ENVIRONMENT, createPoly
6
6
  import { tsObjToNsString } from "./utils/time.js";
7
7
  import { PolyesterCore } from "./core-client.js";
8
8
  import { validateCreateAddressBookEntryInput } from "./services/address-book/address-book.schemas.js";
9
+ import { formatLedgerBalance } from "./services/balances/balances.schemas.js";
9
10
  import { formatConnectError, formatUserFacingError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError } from "./utils/errors.js";
10
11
  import { PolyesterClient } from "./client.js";
11
12
  import { POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME, resolveAuthCookieName } from "./services/auth/cookie-constants.js";
@@ -18,4 +19,4 @@ import { isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFact
18
19
  import { columnarTimestampSecAt, expandColumnarTimestampsSec } from "./utils/columnar-time.js";
19
20
  import { compareUnsignedIntegerStrings, shouldApplyReconciliationUpdate } from "./shared/reconciliation.js";
20
21
  import { mergeLedgerBalances } from "./services/balances/balances.merge.js";
21
- export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, NotImplementedError, OutcomeUnknownError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterBrowserClient, PolyesterBrowserCore, PolyesterClient, PolyesterCore, PolyesterError, PolyesterServerClient, PolyesterServerCore, PreconditionFailedError, RateLimitError, RealtimeError, RequestDeadlineExceededError, RequestError, RequestTooLargeError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, ValidationError, WithdrawDeadlineExpiredError, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
22
+ export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, NotImplementedError, OutcomeUnknownError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterBrowserClient, PolyesterBrowserCore, PolyesterClient, PolyesterCore, PolyesterError, PolyesterServerClient, PolyesterServerCore, PreconditionFailedError, RateLimitError, RealtimeError, RequestDeadlineExceededError, RequestError, RequestTooLargeError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, ValidationError, WithdrawDeadlineExpiredError, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatLedgerBalance, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
@@ -5,6 +5,7 @@ import { PolyesterRealtime } from "../../realtime/types.js";
5
5
  import "../../realtime/index.js";
6
6
  import { SubaccountChallenge } from "../subaccounts/subaccounts.schemas.js";
7
7
  import { SubaccountsService } from "../subaccounts/subaccounts.js";
8
+ import { MfaSessionInfo } from "../mfa/mfa.schemas.js";
8
9
  import { AuthService } from "./auth.js";
9
10
  import { AuthTokenStorage } from "./token-storage.js";
10
11
  import { AuthHydrationData, AuthLoginMethod, AuthState, SessionData } from "./session.types.js";
@@ -29,6 +30,8 @@ interface LoginResult {
29
30
  accountId: string;
30
31
  username: string;
31
32
  expiresAt: Date;
33
+ /** Session assurance details for the issued token, such as its level and authentication methods. */
34
+ session?: MfaSessionInfo;
32
35
  }
33
36
  interface LoginOptions {
34
37
  /**
@@ -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,UAAU;;EAEV;EACA,cAAc;;UAGD;;;;;;EAMb,eACM,kBACE,WAAW,wBAAwB,gBAAgB,QAAQ;;EAEnE;;EAEA;;EAEA,eAAe;;UAGF;EACb;EACA;EACA;;;KAIQ,2BAA2B,4BAA4B,QAAQ;;;;cAU9D,iCAAiC;;WACjC,QAAM,aAAA;EAwBH,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;;;;EAqG5C,iBAAiB,OAAO;;;;EAyBlB,kBAAkB;IAAU;IAAmB;;;;;EA0E/C,UAAU;;;;;;;;EAwBhB,oBAAoB,gBAAgB;;;;EA4CpC;;;;EASM,eAAe;;IAEjB;IACA,WAAW;IACX,cAAc;MACd,QAAQ;;;;EAmBZ,cACI,mBACA;IAAY;IAA8B;;IACzC;IAAmB;;;EAuBxB,oBAAoB;;;;EASd,iBAAiB,QAAQ,yBAAyB,QAAQ;;;;EA2DhE,YAAY"}
1
+ {"version":3,"file":"account-signer-auth.d.ts","names":[],"sources":["../../../src/services/auth/account-signer-auth.ts"],"mappings":";;;;;;;;;;;;;;;UA0BiB;EACb;IAAiB;IAAmB;;EACpC;EACA;IAAS;IAAc;;EACvB;EACA,aAAa;;UAGA;EACb;EACA;EACA,WAAW;;EAEX,UAAU;;UAGG;;;;EAIb,UAAU;;EAEV;EACA,cAAc;;UAGD;;;;;;EAMb,eACM,kBACE,WAAW,wBAAwB,gBAAgB,QAAQ;;EAEnE;;EAEA;;EAEA,eAAe;;UAGF;EACb;EACA;EACA;;;KAIQ,2BAA2B,4BAA4B,QAAQ;;;;cAU9D,iCAAiC;;WACjC,QAAM,aAAA;EAwBH,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;;;;EAqG5C,iBAAiB,OAAO;;;;EAyBlB,kBAAkB;IAAU;IAAmB;;;;;EA0E/C,UAAU;;;;;;;;EAwBhB,oBAAoB,gBAAgB;;;;EA4CpC;;;;EASM,eAAe;;IAEjB;IACA,WAAW;IACX,cAAc;MACd,QAAQ;;;;EAmBZ,cACI,mBACA;IAAY;IAA8B;;IACzC;IAAmB;;;EAuBxB,oBAAoB;;;;EASd,iBAAiB,QAAQ,yBAAyB,QAAQ;;;;EA2DhE,YAAY"}
@@ -384,7 +384,8 @@ var AccountSignerAuthService = class extends AuthService {
384
384
  return {
385
385
  accountId: response.accountId,
386
386
  username: response.username,
387
- expiresAt
387
+ expiresAt,
388
+ session: response.session
388
389
  };
389
390
  }
390
391
  #getEnvironmentBoundToken() {
@@ -1 +1 @@
1
- {"version":3,"file":"account-signer-auth.js","names":["#accountSignerConfig","#environmentFingerprint","#subaccounts","#tokenStorage","#realtime","#sessionStore","#assertAccountSignerEnvironment","#beginAuthOperation","#accountSigner","#accountIdentity","#identityFromSigner","#notifyStateChange","#login","#loginsInFlight","#performLogin","#resolveAccountSigner","#challengeUri","#isCurrentAuthOperation","#getEnvironmentSession","#loginMethod","#isAuthenticated","#mainAccountId","#activeAccountId","#walletProvider","#loginResult","#getEnvironmentBoundToken","#clearExpiredSessionState","#getCurrentTokenStorageOptions","#isRejectableToken","#rejectedTokenCheck","#confirmRejectedToken","#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\n/** A subaccounts service, or a loader that resolves it when a subaccount is first created. */\nexport type SubaccountsServiceSource = SubaccountsService | (() => Promise<SubaccountsService>);\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: SubaccountsServiceSource;\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 // A login or refresh in flight is about to replace the token, so a 401 for\n // the outgoing token must not end the session underneath it.\n #loginsInFlight = 0;\n #rejectedTokenCheck: Promise<void> | null = null;\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: SubaccountsServiceSource;\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 this.#loginsInFlight += 1;\n try {\n return await this.#performLogin(options, previousActiveAccount);\n } finally {\n this.#loginsInFlight -= 1;\n }\n }\n\n async #performLogin(\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 /**\n * Ends the session after the backend rejected `token` as unauthenticated (revoked,\n * or expired despite a lagging local clock), once `me()` confirms the rejection so\n * one misbehaving endpoint cannot sign the user out. Ignored when the token has\n * since been replaced or a login/refresh is in flight; concurrent rejections share\n * one confirmation. Browser clients call this automatically.\n */\n handleRejectedToken(token: string): Promise<void> {\n if (!this.#isRejectableToken(token)) return Promise.resolve();\n // The confirming me() may itself be rejected and re-enter here; it joins this check.\n return (this.#rejectedTokenCheck ??= this.#confirmRejectedToken(token).finally(() => {\n this.#rejectedTokenCheck = null;\n }));\n }\n\n async #confirmRejectedToken(token: string): Promise<void> {\n try {\n await this.me();\n return;\n } catch (error) {\n if (!(toPolyesterError(error) instanceof AuthenticationError)) return;\n }\n if (!this.#isRejectableToken(token)) return;\n this.#beginAuthOperation();\n this.#clearExpiredSessionState();\n }\n\n #isRejectableToken(token: string): boolean {\n return this.#loginsInFlight === 0 && this.#getEnvironmentBoundToken() === token;\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 subaccounts =\n typeof this.#subaccounts === \"function\" ? await this.#subaccounts() : this.#subaccounts;\n const challenge = await 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 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 brow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AAE,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,KAAKoB,mBAAmB,KAAKL,uBAAuB,CAAC,EAAE,YAAY;CAEvF;CAEA,gCAAgC,eAAoC;EAChE,oBAAoB,aAAa;EACjC,IAAI,cAAc,2BAA2B,KAAKjB,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"}
1
+ {"version":3,"file":"account-signer-auth.js","names":["#accountSignerConfig","#environmentFingerprint","#subaccounts","#tokenStorage","#realtime","#sessionStore","#assertAccountSignerEnvironment","#beginAuthOperation","#accountSigner","#accountIdentity","#identityFromSigner","#notifyStateChange","#login","#loginsInFlight","#performLogin","#resolveAccountSigner","#challengeUri","#isCurrentAuthOperation","#getEnvironmentSession","#loginMethod","#isAuthenticated","#mainAccountId","#activeAccountId","#walletProvider","#loginResult","#getEnvironmentBoundToken","#clearExpiredSessionState","#getCurrentTokenStorageOptions","#isRejectableToken","#rejectedTokenCheck","#confirmRejectedToken","#resolveRefreshProvider","#authOperationGeneration"],"sources":["../../../src/services/auth/account-signer-auth.ts"],"sourcesContent":["import { AuthService, type LoginWithWalletResponse } from \"./auth.js\";\nimport type { MfaSessionInfo } from \"../mfa/mfa.schemas.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 /** Session assurance details for the issued token, such as its level and authentication methods. */\n session?: MfaSessionInfo;\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\n/** A subaccounts service, or a loader that resolves it when a subaccount is first created. */\nexport type SubaccountsServiceSource = SubaccountsService | (() => Promise<SubaccountsService>);\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: SubaccountsServiceSource;\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 // A login or refresh in flight is about to replace the token, so a 401 for\n // the outgoing token must not end the session underneath it.\n #loginsInFlight = 0;\n #rejectedTokenCheck: Promise<void> | null = null;\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: SubaccountsServiceSource;\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 this.#loginsInFlight += 1;\n try {\n return await this.#performLogin(options, previousActiveAccount);\n } finally {\n this.#loginsInFlight -= 1;\n }\n }\n\n async #performLogin(\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 /**\n * Ends the session after the backend rejected `token` as unauthenticated (revoked,\n * or expired despite a lagging local clock), once `me()` confirms the rejection so\n * one misbehaving endpoint cannot sign the user out. Ignored when the token has\n * since been replaced or a login/refresh is in flight; concurrent rejections share\n * one confirmation. Browser clients call this automatically.\n */\n handleRejectedToken(token: string): Promise<void> {\n if (!this.#isRejectableToken(token)) return Promise.resolve();\n // The confirming me() may itself be rejected and re-enter here; it joins this check.\n return (this.#rejectedTokenCheck ??= this.#confirmRejectedToken(token).finally(() => {\n this.#rejectedTokenCheck = null;\n }));\n }\n\n async #confirmRejectedToken(token: string): Promise<void> {\n try {\n await this.me();\n return;\n } catch (error) {\n if (!(toPolyesterError(error) instanceof AuthenticationError)) return;\n }\n if (!this.#isRejectableToken(token)) return;\n this.#beginAuthOperation();\n this.#clearExpiredSessionState();\n }\n\n #isRejectableToken(token: string): boolean {\n return this.#loginsInFlight === 0 && this.#getEnvironmentBoundToken() === token;\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 subaccounts =\n typeof this.#subaccounts === \"function\" ? await this.#subaccounts() : this.#subaccounts;\n const challenge = await 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 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 {\n accountId: response.accountId,\n username: response.username,\n expiresAt,\n session: response.session,\n };\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":";;;;;;;;;;;;AAsFA,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;CAG3B,kBAAkB;CAClB,sBAA4C;CAE5C,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;;;;C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ly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
25
25
  readonly apiKeyId: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
26
26
  readonly username: v.StringSchema<undefined>;
27
+ /** Root smart-account EVM address (lowercase 0x hex); empty when not set, which a new account can briefly be. */
28
+ readonly rootSmartAccountAddress: v.OptionalSchema<v.StringSchema<undefined>, "">;
27
29
  readonly session: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ObjectSchema<{
28
30
  readonly sessionId: v.StringSchema<undefined>;
29
31
  readonly sessionLevel: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "primaryAuthenticated" | "mfaElevated" | "freshStepUp">]>;
@@ -56,6 +58,28 @@ declare const LoginWithWalletResponseSchema: v.ObjectSchema<{
56
58
  }, undefined>, undefined>;
57
59
  readonly accountId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
58
60
  readonly username: v.StringSchema<undefined>;
61
+ readonly session: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ObjectSchema<{
62
+ readonly sessionId: v.StringSchema<undefined>;
63
+ readonly sessionLevel: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "primaryAuthenticated" | "mfaElevated" | "freshStepUp">]>;
64
+ readonly authenticationMethods: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, readonly []>;
65
+ readonly authTime: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
66
+ readonly seconds: v.BigintSchema<undefined>;
67
+ readonly nanos: v.OptionalSchema<v.NumberSchema<undefined>, 0>;
68
+ }, undefined>, undefined>, v.TransformAction<{
69
+ seconds: bigint;
70
+ nanos: number;
71
+ } | undefined, number | undefined>]>;
72
+ }, undefined>, v.TransformAction<{
73
+ sessionId: string;
74
+ sessionLevel: "unspecified" | "primaryAuthenticated" | "mfaElevated" | "freshStepUp";
75
+ authenticationMethods: string[];
76
+ authTime?: number | undefined;
77
+ }, {
78
+ sessionId: string;
79
+ sessionLevel: "unspecified" | "primaryAuthenticated" | "mfaElevated" | "freshStepUp";
80
+ authenticationMethods: string[];
81
+ authTimeMs: number | undefined;
82
+ }>]>, undefined>;
59
83
  }, undefined>;
60
84
  type LoginWithWalletResponse = v.InferOutput<typeof LoginWithWalletResponseSchema>;
61
85
  declare const WalletChallengeSchema: v.ObjectSchema<{
@@ -77,7 +101,7 @@ declare class AuthService {
77
101
  profile: ProfileService;
78
102
  constructor(transports: AuthAndPublicApiTransports, realtime: PolyesterRealtime);
79
103
  /**
80
- * 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.
104
+ * Returns the authenticated caller's account context, including account ID, optional API key ID, username, root smart-account address, and session assurance details from the presented token or API key.
81
105
  */
82
106
  me(options?: PolyesterRequestOptions): Promise<Me>;
83
107
  /**
@@ -97,7 +121,7 @@ declare class AuthService {
97
121
  */
98
122
  createWalletChallenge(input: CreateWalletChallengeInput, options?: PolyesterRequestOptions): Promise<WalletChallenge>;
99
123
  /**
100
- * Exchanges a signed SIWE message for an authenticated session token and account identity returned by the auth API.
124
+ * Exchanges a signed SIWE message for an authenticated session token, account identity, and the token's session assurance details.
101
125
  */
102
126
  protected loginWithWallet(input: LoginWithWalletInput, options?: PolyesterMutationOptions): Promise<LoginWithWalletResponse>;
103
127
  }
@@ -1 +1 @@
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
+ {"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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KASF,KAAK,EAAE,mBAAmB;cAEhC,+BAA6B,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAQvB,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"}
@@ -27,13 +27,16 @@ const MeSchema = v.object({
27
27
  accountId: PublicIdSchema,
28
28
  apiKeyId: v.optional(v.string()),
29
29
  username: v.string(),
30
+ /** Root smart-account EVM address (lowercase 0x hex); empty when not set, which a new account can briefly be. */
31
+ rootSmartAccountAddress: v.optional(v.string(), ""),
30
32
  session: v.optional(MfaSessionInfoSchema)
31
33
  });
32
34
  const LoginWithWalletResponseSchema = v.object({
33
35
  accessToken: v.string(),
34
36
  expiresAt: v.optional(TimestampSchema),
35
37
  accountId: PublicIdSchema,
36
- username: v.string()
38
+ username: v.string(),
39
+ session: v.optional(MfaSessionInfoSchema)
37
40
  });
38
41
  const WalletChallengeSchema = v.object({
39
42
  message: WalletChallengeMessageSchema,
@@ -52,7 +55,7 @@ var AuthService = class {
52
55
  this.profile = new ProfileService(transports, realtime);
53
56
  }
54
57
  /**
55
- * 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.
58
+ * Returns the authenticated caller's account context, including account ID, optional API key ID, username, root smart-account address, and session assurance details from the presented token or API key.
56
59
  */
57
60
  async me(options) {
58
61
  const res = await this.#authClient.me({}, toConnectCallOptions(options));
@@ -83,7 +86,7 @@ var AuthService = class {
83
86
  }, toConnectCallOptions(options)));
84
87
  }
85
88
  /**
86
- * Exchanges a signed SIWE message for an authenticated session token and account identity returned by the auth API.
89
+ * Exchanges a signed SIWE message for an authenticated session token, account identity, and the token's session assurance details.
87
90
  */
88
91
  async loginWithWallet(input, options) {
89
92
  const validatedInput = parse(LoginWithWalletInputSchema, input);
@@ -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 { 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;;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KF,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
+ {"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 /** Root smart-account EVM address (lowercase 0x hex); empty when not set, which a new account can briefly be. */\n rootSmartAccountAddress: v.optional(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 session: v.optional(MfaSessionInfoSchema),\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, root smart-account address, 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, account identity, and the token's session assurance details.\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,EA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4B,KAAK;EAC9D,MAAM,MAAM,MAAM,KAAKA,cAAc,gBACjC,gBACA,qBAAqB,OAAO,CAChC;EACA,OAAO,MAAM,+BAA+B,GAAG;CACnD;AACJ"}
@@ -1,5 +1,5 @@
1
1
  import { AccountCode } from "../../gen/ledger/v1/catalog_pb.js";
2
- import { BalanceRange as BalanceRange$1, EquityGroupBy as EquityGroupBy$1 } from "../../gen/ledger/read/v1/ledger_read_pb.js";
2
+ import { AssetBalance, BalanceRange as BalanceRange$1, EquityGroupBy as EquityGroupBy$1 } from "../../gen/ledger/read/v1/ledger_read_pb.js";
3
3
  import { DecodedEnum } from "../../utils/types.js";
4
4
  import { U128Value } from "../../utils/u128.js";
5
5
  import { AccountCodeValue } from "../../shared/ledger-codes.js";
@@ -43,6 +43,12 @@ declare function createLedgerBalanceSchema(): v.SchemaWithPipe<readonly [v.Objec
43
43
  tradingRevision: string;
44
44
  fundingRevision: string;
45
45
  }>]>;
46
+ /**
47
+ * Converts a `ledger.read.v1.AssetBalance` message to the `LedgerBalance` that `balances.list`
48
+ * returns. Its U128 amounts are always at the 18-decimal ledger scale, whatever the asset's own
49
+ * decimals, so the result needs no catalog.
50
+ */
51
+ declare function formatLedgerBalance(b: AssetBalance): LedgerBalance;
46
52
  type LedgerBalance = v.InferOutput<ReturnType<typeof createLedgerBalanceSchema>>;
47
53
  declare const BalanceRangeSchema: v.PicklistSchema<readonly ["1d", "7d", "30d", "90d", "180d", "365d"], undefined>;
48
54
  type BalanceRange = v.InferOutput<typeof BalanceRangeSchema>;
@@ -420,5 +426,5 @@ declare function createPortfolioEquitySnapshotResponseSchema(scales: SdkScales):
420
426
  }>]>;
421
427
  type PortfolioEquitySnapshotResponse = v.InferOutput<ReturnType<typeof createPortfolioEquitySnapshotResponseSchema>>;
422
428
  //#endregion
423
- export { BalanceHistoryInput, BalanceHistoryInputSchema, BalanceHistoryResponse, BalanceRange, BalanceRangeSchema, EquityGroupBy, EquityGroupBySchema, EquityHistoryInput, EquityHistoryInputSchema, EquityHistoryResponse, EquitySeries, EquitySeriesGrouping, EquitySeriesSchema, LedgerBalance, PortfolioEquityHistoryInput, PortfolioEquityHistoryInputSchema, PortfolioEquityHistoryResponse, PortfolioEquitySeries, PortfolioEquitySeriesGrouping, PortfolioEquitySeriesSchema, PortfolioEquitySnapshotResponse, createBalanceHistoryResponseSchema, createEquityHistoryResponseSchema, createLedgerBalanceSchema, createPortfolioEquityHistoryResponseSchema, createPortfolioEquitySnapshotResponseSchema };
429
+ export { BalanceHistoryInput, BalanceHistoryInputSchema, BalanceHistoryResponse, BalanceRange, BalanceRangeSchema, EquityGroupBy, EquityGroupBySchema, EquityHistoryInput, EquityHistoryInputSchema, EquityHistoryResponse, EquitySeries, EquitySeriesGrouping, EquitySeriesSchema, LedgerBalance, PortfolioEquityHistoryInput, PortfolioEquityHistoryInputSchema, PortfolioEquityHistoryResponse, PortfolioEquitySeries, PortfolioEquitySeriesGrouping, PortfolioEquitySeriesSchema, PortfolioEquitySnapshotResponse, createBalanceHistoryResponseSchema, createEquityHistoryResponseSchema, createLedgerBalanceSchema, createPortfolioEquityHistoryResponseSchema, createPortfolioEquitySnapshotResponseSchema, formatLedgerBalance };
424
430
  //# sourceMappingURL=balances.schemas.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"balances.schemas.d.ts","names":[],"sources":["../../../src/services/balances/balances.schemas.ts"],"mappings":";;;;;;;;iBA+DgB,6BAAyB,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAiB7B,gBAAgB,EAAE,YAAY,kBAAkB;cAQ/C,oBAAkB,EAAA;KAEnB,eAAe,EAAE,mBAAmB;cASnC,qBAAmB,EAAA;KAEpB,gBAAgB,EAAE,mBAAmB;cAEpC,2BAAyB,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;KAwB1B,sBAAsB,EAAE,kBAAkB;iBAQtC,sCAAkC,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;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;;;IAZtC,UAAA;IAAuC;;;;;;;;;;;IAAvC,UAAA;IAAuC;;;;;;;;;;;IAAvC,UAAA;IAAuC;;;;KAqCjE,wBAAwB,EAAE,mBAAmB;KAC7C,iCAAiC,EAAE,YAC3C,kBAAkB;iBA6BN,4CAA4C,QAAQ,YAAS,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAmBjE,kCAAkC,EAAE,YAC5C,kBAAkB"}
@@ -45,7 +45,11 @@ function toLedgerBalance(b) {
45
45
  function createLedgerBalanceSchema() {
46
46
  return v.pipe(LedgerBalanceFieldsSchema, v.transform(toLedgerBalance));
47
47
  }
48
- /** Formats a protobuf-decoded balance like {@link createLedgerBalanceSchema} without re-validating it. */
48
+ /**
49
+ * Converts a `ledger.read.v1.AssetBalance` message to the `LedgerBalance` that `balances.list`
50
+ * returns. Its U128 amounts are always at the 18-decimal ledger scale, whatever the asset's own
51
+ * decimals, so the result needs no catalog.
52
+ */
49
53
  function formatLedgerBalance(b) {
50
54
  return toLedgerBalance({
51
55
  assetId: b.assetId,