@polyester/sdk 0.33.0 → 0.34.0-devnet-20261105175240

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 (33) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/services/changelog/changelog.schemas.d.ts +17 -17
  3. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  4. package/dist/services/lifecycle/lifecycle.schemas.d.ts +79 -79
  5. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  6. package/dist/services/orders/orders-batch.schemas.d.ts +7 -7
  7. package/dist/services/orders/orders-input.schemas.d.ts +2 -2
  8. package/dist/services/orders/orders-input.schemas.js +2 -2
  9. package/dist/services/orders/orders-input.schemas.js.map +1 -1
  10. package/dist/services/orders/orders.d.ts +2 -2
  11. package/dist/services/orders/orders.js +2 -2
  12. package/dist/services/orders/orders.js.map +1 -1
  13. package/dist/services/social-verification/social-verification.codecs.js +2 -2
  14. package/dist/services/social-verification/social-verification.codecs.js.map +1 -1
  15. package/dist/services/social-verification/social-verification.schemas.d.ts +2 -2
  16. package/dist/services/subaccounts/subaccounts.codecs.js +1 -1
  17. package/dist/services/subaccounts/subaccounts.codecs.js.map +1 -1
  18. package/dist/services/subaccounts/subaccounts.schemas.d.ts +5 -5
  19. package/dist/services/subaccounts/subaccounts.schemas.js +1 -1
  20. package/dist/services/subaccounts/subaccounts.schemas.js.map +1 -1
  21. package/dist/services/triggers/trigger-input.schemas.d.ts +1 -1
  22. package/dist/services/triggers/triggers-output.schemas.d.ts +15 -15
  23. package/dist/services/triggers/triggers.codecs.js +3 -3
  24. package/dist/services/triggers/triggers.codecs.js.map +1 -1
  25. package/dist/shared/connect-error-mapping.d.ts +1 -1
  26. package/dist/shared/connect-error-mapping.js +1 -1
  27. package/dist/shared/connect-error-mapping.js.map +1 -1
  28. package/dist/shared/request-options.d.ts +1 -1
  29. package/dist/shared/request-options.js.map +1 -1
  30. package/dist/shared/validation.js +22 -1
  31. package/dist/shared/validation.js.map +1 -1
  32. package/dist/smart-account/smart-account.js.map +1 -1
  33. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"connect-error-mapping.js","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"sourcesContent":["import { Code, ConnectError, type Interceptor, type Transport } from \"@connectrpc/connect\";\nimport {\n loadErrorDetailDecoders,\n parseConnectErrorDetail,\n type PolyesterErrorDetail,\n} from \"./error-detail.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n NotImplementedError,\n isAbortError,\n isTimeoutAbortError,\n MfaEnrollmentRequiredError,\n MfaLastFactorRequiredError,\n MfaVerificationError,\n type MfaVerificationFailureReason,\n normalizeErrorMessage,\n OutcomeUnknownError,\n PermissionError,\n PolicyInUseError,\n PolicyLockedError,\n PolicyScopeMismatchError,\n PolyesterError,\n type PolyesterErrorOptions,\n PreconditionFailedError,\n RateLimitError,\n ResourceNotFoundError,\n RevisionConflictError,\n ServiceUnavailableError,\n SessionElevationRequiredError,\n StaleQuoteError,\n SubaccountChallengeInvalidError,\n StepUpRequiredError,\n TimeoutError,\n TimestampSkewError,\n TransientError,\n ValidationError,\n WithdrawDeadlineExpiredError,\n} from \"./errors.js\";\nimport type { RateLimitDetail } from \"./rate-limit.schemas.js\";\n\n/** Backend code for API-key signatures whose timestamp is outside the skew window. */\nexport const TIMESTAMP_SKEW_CODE = \"TIMESTAMP_SKEW\";\n\n// The withdraw service has no structured code for this; match its message.\nconst WITHDRAW_DEADLINE_EXPIRED_MESSAGE = \"deadline_ts_sec has expired\";\n\nfunction hasTransientServiceError(detail: PolyesterErrorDetail | undefined): boolean {\n if (detail?.service === \"withdraw\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SOURCE_SMART_ACCOUNT_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"CHAIN_METADATA_UNAVAILABLE\",\n \"FEE_UNAVAILABLE\",\n \"SUPPLY_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"DESTINATION_VALIDATION_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"internal_transfer\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SMART_ACCOUNT_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"claims\") {\n return [\"SERVICE_UNAVAILABLE\", \"CLAIM_TEMPORARILY_UNAVAILABLE\"].includes(detail.code);\n }\n // The account request changed nothing; the same request can be retried.\n if (detail?.service === \"auth\") {\n return detail.code === \"AUTH_TEMPORARILY_UNAVAILABLE\";\n }\n return false;\n}\n\nfunction safeRetryAfterMs(rateLimit: RateLimitDetail | undefined): number | undefined {\n if (rateLimit?.retryAfterMs === undefined) return undefined;\n const value = BigInt(rateLimit.retryAfterMs);\n return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined;\n}\n\nconst HTTP_WEEKDAY = \"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\";\nconst HTTP_WEEKDAY_LONG = \"(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\";\nconst HTTP_MONTH = \"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\";\nconst HTTP_DATE_RE = new RegExp(\n `^(?:${HTTP_WEEKDAY}, \\\\d{2} ${HTTP_MONTH} \\\\d{4} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY_LONG}, \\\\d{2}-${HTTP_MONTH}-\\\\d{2} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY} ${HTTP_MONTH} {1,2}\\\\d{1,2} \\\\d{2}:\\\\d{2}:\\\\d{2} \\\\d{4})$`,\n \"u\",\n);\n\n/**\n * Returns the error message without the leading \"[code] \" prefix that\n * `ConnectError` prepends, e.g. \"[invalid_argument] Insufficient funds.\"\n * becomes \"Insufficient funds.\".\n */\nexport function getNormalizedConnectMessage(err: unknown): string {\n const ce = ConnectError.from(err);\n const raw = ce.message ?? \"\";\n return normalizeErrorMessage(raw);\n}\n\nexport type MfaErrorKind = \"session-elevation\" | \"enrollment\" | \"step-up\";\n\n/**\n * Classifies an error as one of the MFA flows the backend can demand.\n * Classification is based only on stable structured auth error details.\n */\nexport function detectMfaErrorKind(err: unknown): MfaErrorKind | null {\n const mapped = toPolyesterError(err);\n return mfaErrorKind(mapped instanceof PolyesterError ? mapped.detail : undefined);\n}\n\nfunction mfaErrorKind(detail: PolyesterErrorDetail | undefined): MfaErrorKind | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_ELEVATION_REQUIRED\") {\n return \"session-elevation\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_STEP_UP_REQUIRED\") return \"step-up\";\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_NOT_ENROLLED\") return \"enrollment\";\n return null;\n}\n\nfunction parseRetryAfterMs(ce: ConnectError): number | undefined {\n const value = ce.metadata.get(\"retry-after\");\n if (!value) return undefined;\n if (/^\\d+$/u.test(value)) {\n const seconds = BigInt(value);\n const maxSafeSeconds = BigInt(Math.floor(Number.MAX_SAFE_INTEGER / 1000));\n return seconds <= maxSafeSeconds ? Number(seconds) * 1000 : undefined;\n }\n if (!HTTP_DATE_RE.test(value)) return undefined;\n const date = Date.parse(value);\n if (!Number.isNaN(date)) return Math.max(0, date - Date.now());\n return undefined;\n}\n\nconst MFA_ERROR_CLASSES = {\n \"session-elevation\": SessionElevationRequiredError,\n enrollment: MfaEnrollmentRequiredError,\n \"step-up\": StepUpRequiredError,\n} as const;\n\n// Client-side failures (timeouts, fetch errors, aborts) carry no response metadata.\nfunction hasResponseMetadata(ce: ConnectError): boolean {\n return !ce.metadata.keys().next().done;\n}\n\n// HTTP status Connect servers send for each error code\n// (https://connectrpc.com/docs/protocol#error-codes). Connect's own\n// codeToHttpStatus is internal and outside its semver.\nconst CONNECT_CODE_HTTP_STATUS: Record<Code, number> = {\n [Code.Canceled]: 499,\n [Code.Unknown]: 500,\n [Code.InvalidArgument]: 400,\n [Code.DeadlineExceeded]: 504,\n [Code.NotFound]: 404,\n [Code.AlreadyExists]: 409,\n [Code.PermissionDenied]: 403,\n [Code.ResourceExhausted]: 429,\n [Code.FailedPrecondition]: 400,\n [Code.Aborted]: 409,\n [Code.OutOfRange]: 400,\n [Code.Unimplemented]: 501,\n [Code.Internal]: 500,\n [Code.Unavailable]: 503,\n [Code.DataLoss]: 500,\n [Code.Unauthenticated]: 401,\n};\n\nfunction responseStatusFromCode(ce: ConnectError): number | undefined {\n return hasResponseMetadata(ce) ? CONNECT_CODE_HTTP_STATUS[ce.code] : undefined;\n}\n\n// Runtimes word AbortSignal.timeout() reasons differently (\"signal timed out\",\n// \"The operation timed out.\", \"The operation was aborted due to timeout\"), and\n// ConnectError.from keeps only the message. Only matched on client-side cancels,\n// so a server-sent `canceled` mentioning a timeout passes through.\nconst TIMEOUT_ABORT_MESSAGE_RE = /timed out|due to timeout/iu;\n\n/**\n * Maps a `ConnectError` from the Polyester backend onto the typed\n * {@link PolyesterError} tree. The original error is preserved as `cause`.\n */\nexport function connectErrorToPolyesterError(ce: ConnectError): PolyesterError {\n const message = getNormalizedConnectMessage(ce);\n const detail = parseConnectErrorDetail(ce);\n const httpStatus = /^HTTP (\\d{3})$/u.exec(ce.rawMessage)?.[1];\n const options: PolyesterErrorOptions = {\n cause: ce,\n detail,\n status: httpStatus ? Number(httpStatus) : responseStatusFromCode(ce),\n };\n const withFallback = (fallback: string) => message || fallback;\n\n if (\n ce.rawMessage === TIMESTAMP_SKEW_CODE ||\n (detail?.service === \"auth\" && detail.code === \"AUTH_TIMESTAMP_SKEW\")\n ) {\n return new TimestampSkewError(\n \"API key timestamp is outside the allowed skew window.\",\n options,\n );\n }\n\n if (ce.code === Code.InvalidArgument && ce.rawMessage === WITHDRAW_DEADLINE_EXPIRED_MESSAGE) {\n return new WithdrawDeadlineExpiredError(\n \"Withdraw signature deadline has passed. Prepare the withdraw again.\",\n options,\n );\n }\n\n // Connect reports non-Connect HTTP error bodies as \"HTTP <status>\" with a lossy\n // code (e.g. 501 → Unknown), so map the real status. Bare 404 keeps Connect's\n // Unimplemented: it means the route is missing, not the resource.\n if (!detail && httpStatus && httpStatus !== \"404\") {\n return errorFromHttpStatus(Number(httpStatus), message, {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_RESOURCE_NOT_FOUND\") {\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_REVISION_CONFLICT\") {\n return new RevisionConflictError(\n withFallback(\"Resource changed since it was last read.\"),\n options,\n );\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SUBACCOUNT_CHALLENGE_INVALID\") {\n return new SubaccountChallengeInvalidError(\n withFallback(\"Subaccount challenge is expired, replaced, or invalid.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SOCIAL_ACCOUNT_ALREADY_LINKED\") {\n return new AlreadyExistsError(\n withFallback(\"Social account is already linked to another Polyester account.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_IN_USE\") {\n return new PolicyInUseError(withFallback(\"Policy is still in use.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_LOCKED\") {\n return new PolicyLockedError(withFallback(\"Policy is locked.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_SCOPE_MISMATCH\") {\n return new PolicyScopeMismatchError(\n withFallback(\"Policy does not belong to the target account scope.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_LAST_FACTOR_REQUIRED\") {\n return new MfaLastFactorRequiredError(\n withFallback(\"At least one active MFA factor must remain enrolled.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_INTERNAL_ERROR\") {\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n\n const mfaVerificationReason = getMfaVerificationFailureReason(detail);\n if (mfaVerificationReason) {\n return new MfaVerificationError(\n withFallback(\"MFA verification failed.\"),\n mfaVerificationReason,\n options,\n );\n }\n\n const mfaKind = mfaErrorKind(detail);\n if (mfaKind) {\n return new MFA_ERROR_CLASSES[mfaKind](\n withFallback(\"Multi-factor authentication required.\"),\n options,\n );\n }\n\n // Checked before rate limits and the transport code: these arrive as\n // DeadlineExceeded, which would otherwise map to a retryable TimeoutError.\n if (detail?.service === \"orders\" && detail.code.endsWith(\"_OUTCOME_UNKNOWN\")) {\n return new OutcomeUnknownError(\n withFallback(\"Outcome unknown; read the current state before retrying.\"),\n options,\n );\n }\n\n if (detail?.service === \"orders\" && detail.code === \"STALE_QUOTE\") {\n return new StaleQuoteError(withFallback(\"The submitted market quote is stale.\"), options);\n }\n\n const rateLimit = detail?.service === \"orders\" ? detail.rateLimit : undefined;\n if (\n rateLimit ||\n ((detail?.service === \"orders\" ||\n detail?.service === \"withdraw\" ||\n detail?.service === \"internal_transfer\" ||\n detail?.service === \"claims\") &&\n detail.code === \"RATE_LIMIT_EXCEEDED\")\n ) {\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n rateLimit,\n retryAfterMs: safeRetryAfterMs(rateLimit) ?? parseRetryAfterMs(ce),\n });\n }\n\n if (hasTransientServiceError(detail)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n }\n\n switch (ce.code) {\n case Code.InvalidArgument:\n case Code.OutOfRange:\n return new ValidationError(withFallback(\"Invalid request.\"), options);\n case Code.NotFound:\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n case Code.AlreadyExists:\n return new AlreadyExistsError(withFallback(\"Resource already exists.\"), options);\n case Code.PermissionDenied:\n return new PermissionError(withFallback(\"Permission denied.\"), options);\n case Code.Unauthenticated:\n return new AuthenticationError(withFallback(\"Authentication required.\"), options);\n case Code.FailedPrecondition:\n return new PreconditionFailedError(withFallback(\"Precondition failed.\"), options);\n case Code.ResourceExhausted:\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n case Code.DeadlineExceeded:\n return new TimeoutError(withFallback(\"Request timed out.\"), options);\n case Code.Unavailable:\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n case Code.Unimplemented:\n return new NotImplementedError(withFallback(\"Operation not implemented.\"), options);\n case Code.Aborted:\n return new TransientError(withFallback(\"Operation aborted by the backend.\"), options);\n default:\n // Gateways sometimes surface outages as Unknown with this stock phrase.\n if (/service temporarily unavailable/i.test(message)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n }\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n}\n\nfunction getMfaVerificationFailureReason(\n detail: PolyesterErrorDetail | undefined,\n): MfaVerificationFailureReason | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_INVALID\") {\n return \"challenge-invalid\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_LOCKED\") {\n return \"challenge-locked\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_OTP_INVALID\") return \"otp-invalid\";\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_RECOVERY_INVALID\") {\n return \"recovery-code-invalid\";\n }\n if (\n (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_PASSKEY_CREDENTIAL_INVALID\") ||\n (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_PASSKEY_VERIFY_FAILED\")\n ) {\n return \"passkey-invalid\";\n }\n\n return null;\n}\n\nfunction findPolyesterErrorInCauseChain(err: unknown): PolyesterError | null {\n let current: unknown = err;\n for (let depth = 0; depth < 5 && current instanceof Error; depth++) {\n current = current.cause;\n if (current instanceof PolyesterError) return current;\n }\n return null;\n}\n\n/**\n * Converts any RPC-layer failure into its typed SDK error. Abort errors and\n * caller-cancelled requests pass through unchanged, as do errors that are\n * already typed (e.g. a `NetworkError` from the SDK fetch wrapper).\n * `AbortSignal.timeout()` expiries become {@link TimeoutError}, whether the\n * timeout signal was passed by the caller or added by an interceptor. Prefer the\n * `timeoutMs` request option, which Connect reports as `DeadlineExceeded`.\n */\nexport function toPolyesterError(err: unknown): unknown {\n if (err instanceof PolyesterError) return err;\n if (isTimeoutAbortError(err)) return new TimeoutError(\"Request timed out.\", { cause: err });\n if (isAbortError(err)) return err;\n if (err instanceof ConnectError) {\n if (err.code === Code.Canceled) {\n return !hasResponseMetadata(err) && TIMEOUT_ABORT_MESSAGE_RE.test(err.rawMessage)\n ? new TimeoutError(\"Request timed out.\", { cause: err })\n : err;\n }\n const wrapped = findPolyesterErrorInCauseChain(err);\n if (wrapped) return wrapped;\n return connectErrorToPolyesterError(err);\n }\n return err;\n}\n\nfunction callerAbortError(signal: AbortSignal): DOMException | TimeoutError {\n const reason: unknown = signal.reason;\n if (isTimeoutAbortError(reason))\n return new TimeoutError(\"Request timed out.\", { cause: reason });\n return preAbortedError(signal);\n}\n\n// A signal that fired before the call started is a cancellation even when it was\n// a timeout: a retryable TimeoutError would let retry loops spin on a dead signal.\nfunction preAbortedError(signal: AbortSignal): DOMException {\n const reason: unknown = signal.reason;\n return reason instanceof DOMException && reason.name === \"AbortError\"\n ? reason\n : new DOMException(\"Request canceled.\", \"AbortError\");\n}\n\nasync function toTransportError(err: unknown, signal?: AbortSignal): Promise<unknown> {\n if (signal?.aborted && err instanceof ConnectError && err.code === Code.Canceled) {\n return callerAbortError(signal);\n }\n await loadErrorDetailDecoders(err);\n return toPolyesterError(err);\n}\n\nasync function* mapStreamErrors<T>(\n source: AsyncIterable<T>,\n signal?: AbortSignal,\n): AsyncIterable<T> {\n try {\n yield* source;\n } catch (err) {\n throw await toTransportError(err, signal);\n }\n}\n\n/**\n * Interceptor that converts every RPC failure (unary and streaming) into the\n * typed {@link PolyesterError} hierarchy. Installed outermost by\n * `createTransports`, so callers of SDK services always see typed errors.\n */\nexport function createErrorMappingInterceptor(): Interceptor {\n return (next) => async (req) => {\n try {\n const res = await next(req);\n if (res.stream) {\n return { ...res, message: mapStreamErrors(res.message) };\n }\n return res;\n } catch (err) {\n await loadErrorDetailDecoders(err);\n throw toPolyesterError(err);\n }\n };\n}\n\n/**\n * Wraps a Connect transport so errors are translated after Connect's call\n * runner has applied its own error normalization.\n */\nexport function createErrorMappingTransport(transport: Transport): Transport {\n return {\n async unary(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw preAbortedError(signal);\n try {\n return await transport.unary(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n } catch (error) {\n throw await toTransportError(error, signal);\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw preAbortedError(signal);\n try {\n const response = await transport.stream(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n return { ...response, message: mapStreamErrors(response.message, signal) };\n } catch (error) {\n throw await toTransportError(error, signal);\n }\n },\n };\n}\n"],"mappings":";;;;;AA4CA,MAAa,sBAAsB;AAGnC,MAAM,oCAAoC;AAE1C,SAAS,yBAAyB,QAAmD;CACjF,IAAI,QAAQ,YAAY,YACpB,OAAO;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC,CAAC,SAAS,OAAO,IAAI;CAE1B,IAAI,QAAQ,YAAY,qBACpB,OAAO;EACH;EACA;EACA;EACA;EACA;CACJ,CAAC,CAAC,SAAS,OAAO,IAAI;CAE1B,IAAI,QAAQ,YAAY,UACpB,OAAO,CAAC,uBAAuB,+BAA+B,CAAC,CAAC,SAAS,OAAO,IAAI;CAGxF,IAAI,QAAQ,YAAY,QACpB,OAAO,OAA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,QAAQ,SAAS,MAAM,gBAAgB,MAAM;GACjD,IAAI;IACA,MAAM,WAAW,MAAM,UAAU,OAC7B,QACA,QACA,WACA,QACA,OACA,aACJ;IACA,OAAO;KAAE,GAAG;KAAU,SAAS,gBAAgB,SAAS,SAAS,MAAM;IAAE;GAC7E,SAAS,OAAO;IACZ,MAAM,MAAM,iBAAiB,OAAO,MAAM;GAC9C;EACJ;CACJ;AACJ"}
1
+ {"version":3,"file":"connect-error-mapping.js","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"sourcesContent":["import { Code, ConnectError, type Interceptor, type Transport } from \"@connectrpc/connect\";\nimport {\n loadErrorDetailDecoders,\n parseConnectErrorDetail,\n type PolyesterErrorDetail,\n} from \"./error-detail.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n NotImplementedError,\n isAbortError,\n isTimeoutAbortError,\n MfaEnrollmentRequiredError,\n MfaLastFactorRequiredError,\n MfaVerificationError,\n type MfaVerificationFailureReason,\n normalizeErrorMessage,\n OutcomeUnknownError,\n PermissionError,\n PolicyInUseError,\n PolicyLockedError,\n PolicyScopeMismatchError,\n PolyesterError,\n type PolyesterErrorOptions,\n PreconditionFailedError,\n RateLimitError,\n ResourceNotFoundError,\n RevisionConflictError,\n ServiceUnavailableError,\n SessionElevationRequiredError,\n StaleQuoteError,\n SubaccountChallengeInvalidError,\n StepUpRequiredError,\n TimeoutError,\n TimestampSkewError,\n TransientError,\n ValidationError,\n WithdrawDeadlineExpiredError,\n} from \"./errors.js\";\nimport type { RateLimitDetail } from \"./rate-limit.schemas.js\";\n\n/** Backend code for API-key signatures whose timestamp is outside the skew window. */\nexport const TIMESTAMP_SKEW_CODE = \"TIMESTAMP_SKEW\";\n\n// The withdraw service has no structured code for this; match its message.\nconst WITHDRAW_DEADLINE_EXPIRED_MESSAGE = \"deadline_ts_sec has expired\";\n\nfunction hasTransientServiceError(detail: PolyesterErrorDetail | undefined): boolean {\n if (detail?.service === \"withdraw\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SOURCE_SMART_ACCOUNT_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"CHAIN_METADATA_UNAVAILABLE\",\n \"FEE_UNAVAILABLE\",\n \"SUPPLY_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"DESTINATION_VALIDATION_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"internal_transfer\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SMART_ACCOUNT_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"claims\") {\n return [\"SERVICE_UNAVAILABLE\", \"CLAIM_TEMPORARILY_UNAVAILABLE\"].includes(detail.code);\n }\n // The account request changed nothing; the same request can be retried.\n if (detail?.service === \"auth\") {\n return detail.code === \"AUTH_TEMPORARILY_UNAVAILABLE\";\n }\n return false;\n}\n\nfunction safeRetryAfterMs(rateLimit: RateLimitDetail | undefined): number | undefined {\n if (rateLimit?.retryAfterMs === undefined) return undefined;\n const value = BigInt(rateLimit.retryAfterMs);\n return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined;\n}\n\nconst HTTP_WEEKDAY = \"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\";\nconst HTTP_WEEKDAY_LONG = \"(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\";\nconst HTTP_MONTH = \"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\";\nconst HTTP_DATE_RE = new RegExp(\n `^(?:${HTTP_WEEKDAY}, \\\\d{2} ${HTTP_MONTH} \\\\d{4} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY_LONG}, \\\\d{2}-${HTTP_MONTH}-\\\\d{2} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY} ${HTTP_MONTH} {1,2}\\\\d{1,2} \\\\d{2}:\\\\d{2}:\\\\d{2} \\\\d{4})$`,\n \"u\",\n);\n\n/**\n * Returns the error message without the leading \"[code] \" prefix that\n * `ConnectError` prepends, e.g. \"[invalid_argument] Insufficient funds.\"\n * becomes \"Insufficient funds.\".\n */\nexport function getNormalizedConnectMessage(err: unknown): string {\n const ce = ConnectError.from(err);\n const raw = ce.message ?? \"\";\n return normalizeErrorMessage(raw);\n}\n\nexport type MfaErrorKind = \"session-elevation\" | \"enrollment\" | \"step-up\";\n\n/**\n * Classifies an error as one of the MFA flows the backend can demand.\n * Classification is based only on stable structured auth error details.\n */\nexport function detectMfaErrorKind(err: unknown): MfaErrorKind | null {\n const mapped = toPolyesterError(err);\n return mfaErrorKind(mapped instanceof PolyesterError ? mapped.detail : undefined);\n}\n\nfunction mfaErrorKind(detail: PolyesterErrorDetail | undefined): MfaErrorKind | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_ELEVATION_REQUIRED\") {\n return \"session-elevation\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_STEP_UP_REQUIRED\") return \"step-up\";\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_NOT_ENROLLED\") return \"enrollment\";\n return null;\n}\n\nfunction parseRetryAfterMs(ce: ConnectError): number | undefined {\n const value = ce.metadata.get(\"retry-after\");\n if (!value) return undefined;\n if (/^\\d+$/u.test(value)) {\n const seconds = BigInt(value);\n const maxSafeSeconds = BigInt(Math.floor(Number.MAX_SAFE_INTEGER / 1000));\n return seconds <= maxSafeSeconds ? Number(seconds) * 1000 : undefined;\n }\n if (!HTTP_DATE_RE.test(value)) return undefined;\n const date = Date.parse(value);\n if (!Number.isNaN(date)) return Math.max(0, date - Date.now());\n return undefined;\n}\n\nconst MFA_ERROR_CLASSES = {\n \"session-elevation\": SessionElevationRequiredError,\n enrollment: MfaEnrollmentRequiredError,\n \"step-up\": StepUpRequiredError,\n} as const;\n\n// Client-side failures (timeouts, fetch errors, aborts) carry no response metadata.\nfunction hasResponseMetadata(ce: ConnectError): boolean {\n return !ce.metadata.keys().next().done;\n}\n\n// HTTP status Connect servers send for each error code\n// (https://connectrpc.com/docs/protocol#error-codes). Connect's own\n// codeToHttpStatus is internal and outside its semver.\nconst CONNECT_CODE_HTTP_STATUS: Record<Code, number> = {\n [Code.Canceled]: 499,\n [Code.Unknown]: 500,\n [Code.InvalidArgument]: 400,\n [Code.DeadlineExceeded]: 504,\n [Code.NotFound]: 404,\n [Code.AlreadyExists]: 409,\n [Code.PermissionDenied]: 403,\n [Code.ResourceExhausted]: 429,\n [Code.FailedPrecondition]: 400,\n [Code.Aborted]: 409,\n [Code.OutOfRange]: 400,\n [Code.Unimplemented]: 501,\n [Code.Internal]: 500,\n [Code.Unavailable]: 503,\n [Code.DataLoss]: 500,\n [Code.Unauthenticated]: 401,\n};\n\nfunction responseStatusFromCode(ce: ConnectError): number | undefined {\n return hasResponseMetadata(ce) ? CONNECT_CODE_HTTP_STATUS[ce.code] : undefined;\n}\n\n// Runtimes word AbortSignal.timeout() reasons differently (\"signal timed out\",\n// \"The operation timed out.\", \"The operation was aborted due to timeout\"), and\n// ConnectError.from keeps only the message. Only matched on client-side cancels,\n// so a server-sent `canceled` mentioning a timeout passes through.\nconst TIMEOUT_ABORT_MESSAGE_RE = /timed out|due to timeout/iu;\n\n/**\n * Maps a `ConnectError` from the Polyester backend onto the typed\n * {@link PolyesterError} tree. The original error is preserved as `cause`.\n */\nexport function connectErrorToPolyesterError(ce: ConnectError): PolyesterError {\n const message = getNormalizedConnectMessage(ce);\n const detail = parseConnectErrorDetail(ce);\n const httpStatus = /^HTTP (\\d{3})$/u.exec(ce.rawMessage)?.[1];\n const options: PolyesterErrorOptions = {\n cause: ce,\n detail,\n status: httpStatus ? Number(httpStatus) : responseStatusFromCode(ce),\n };\n const withFallback = (fallback: string) => message || fallback;\n\n if (\n ce.rawMessage === TIMESTAMP_SKEW_CODE ||\n (detail?.service === \"auth\" && detail.code === \"AUTH_TIMESTAMP_SKEW\")\n ) {\n return new TimestampSkewError(\n \"API key timestamp is outside the allowed skew window.\",\n options,\n );\n }\n\n if (ce.code === Code.InvalidArgument && ce.rawMessage === WITHDRAW_DEADLINE_EXPIRED_MESSAGE) {\n return new WithdrawDeadlineExpiredError(\n \"Withdraw signature deadline has passed. Prepare the withdraw again.\",\n options,\n );\n }\n\n // Connect reports non-Connect HTTP error bodies as \"HTTP <status>\" with a lossy\n // code (e.g. 501 → Unknown), so map the real status. Bare 404 keeps Connect's\n // Unimplemented: it means the route is missing, not the resource.\n if (!detail && httpStatus && httpStatus !== \"404\") {\n return errorFromHttpStatus(Number(httpStatus), message, {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_RESOURCE_NOT_FOUND\") {\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_REVISION_CONFLICT\") {\n return new RevisionConflictError(\n withFallback(\"Resource changed since it was last read.\"),\n options,\n );\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SUBACCOUNT_CHALLENGE_INVALID\") {\n return new SubaccountChallengeInvalidError(\n withFallback(\"Subaccount challenge is expired, replaced, or invalid.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SOCIAL_ACCOUNT_ALREADY_LINKED\") {\n return new AlreadyExistsError(\n withFallback(\"Social account is already linked to another Polyester account.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_IN_USE\") {\n return new PolicyInUseError(withFallback(\"Policy is still in use.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_LOCKED\") {\n return new PolicyLockedError(withFallback(\"Policy is locked.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_SCOPE_MISMATCH\") {\n return new PolicyScopeMismatchError(\n withFallback(\"Policy does not belong to the target account scope.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_LAST_FACTOR_REQUIRED\") {\n return new MfaLastFactorRequiredError(\n withFallback(\"At least one active MFA factor must remain enrolled.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_INTERNAL_ERROR\") {\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n\n const mfaVerificationReason = getMfaVerificationFailureReason(detail);\n if (mfaVerificationReason) {\n return new MfaVerificationError(\n withFallback(\"MFA verification failed.\"),\n mfaVerificationReason,\n options,\n );\n }\n\n const mfaKind = mfaErrorKind(detail);\n if (mfaKind) {\n return new MFA_ERROR_CLASSES[mfaKind](\n withFallback(\"Multi-factor authentication required.\"),\n options,\n );\n }\n\n // Checked before rate limits and the transport code: these arrive as\n // DeadlineExceeded, which would otherwise map to a retryable TimeoutError.\n if (detail?.service === \"orders\" && detail.code.endsWith(\"_OUTCOME_UNKNOWN\")) {\n return new OutcomeUnknownError(\n withFallback(\"Outcome unknown; read the current state before retrying.\"),\n options,\n );\n }\n\n if (detail?.service === \"orders\" && detail.code === \"STALE_QUOTE\") {\n return new StaleQuoteError(withFallback(\"The submitted market quote is stale.\"), options);\n }\n\n const rateLimit = detail?.service === \"orders\" ? detail.rateLimit : undefined;\n if (\n rateLimit ||\n ((detail?.service === \"orders\" ||\n detail?.service === \"withdraw\" ||\n detail?.service === \"internal_transfer\" ||\n detail?.service === \"claims\") &&\n detail.code === \"RATE_LIMIT_EXCEEDED\")\n ) {\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n rateLimit,\n retryAfterMs: safeRetryAfterMs(rateLimit) ?? parseRetryAfterMs(ce),\n });\n }\n\n if (hasTransientServiceError(detail)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n }\n\n switch (ce.code) {\n case Code.InvalidArgument:\n case Code.OutOfRange:\n return new ValidationError(withFallback(\"Invalid request.\"), options);\n case Code.NotFound:\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n case Code.AlreadyExists:\n return new AlreadyExistsError(withFallback(\"Resource already exists.\"), options);\n case Code.PermissionDenied:\n return new PermissionError(withFallback(\"Permission denied.\"), options);\n case Code.Unauthenticated:\n return new AuthenticationError(withFallback(\"Authentication required.\"), options);\n case Code.FailedPrecondition:\n return new PreconditionFailedError(withFallback(\"Precondition failed.\"), options);\n case Code.ResourceExhausted:\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n case Code.DeadlineExceeded:\n return new TimeoutError(withFallback(\"Request timed out.\"), options);\n case Code.Unavailable:\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n case Code.Unimplemented:\n return new NotImplementedError(withFallback(\"Operation not implemented.\"), options);\n case Code.Aborted:\n return new TransientError(withFallback(\"Operation aborted by the backend.\"), options);\n default:\n // Gateways sometimes surface outages as Unknown with this stock phrase.\n if (/service temporarily unavailable/i.test(message)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n }\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n}\n\nfunction getMfaVerificationFailureReason(\n detail: PolyesterErrorDetail | undefined,\n): MfaVerificationFailureReason | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_INVALID\") {\n return \"challenge-invalid\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_LOCKED\") {\n return \"challenge-locked\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_OTP_INVALID\") return \"otp-invalid\";\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_RECOVERY_INVALID\") {\n return \"recovery-code-invalid\";\n }\n if (\n (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_PASSKEY_CREDENTIAL_INVALID\") ||\n (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_PASSKEY_VERIFY_FAILED\")\n ) {\n return \"passkey-invalid\";\n }\n\n return null;\n}\n\nfunction findPolyesterErrorInCauseChain(err: unknown): PolyesterError | null {\n let current: unknown = err;\n for (let depth = 0; depth < 5 && current instanceof Error; depth++) {\n current = current.cause;\n if (current instanceof PolyesterError) return current;\n }\n return null;\n}\n\n/**\n * Converts any RPC-layer failure into its typed SDK error. Abort errors and\n * caller-canceled requests pass through unchanged, as do errors that are\n * already typed (e.g. a `NetworkError` from the SDK fetch wrapper).\n * `AbortSignal.timeout()` expiries become {@link TimeoutError}, whether the\n * timeout signal was passed by the caller or added by an interceptor. Prefer the\n * `timeoutMs` request option, which Connect reports as `DeadlineExceeded`.\n */\nexport function toPolyesterError(err: unknown): unknown {\n if (err instanceof PolyesterError) return err;\n if (isTimeoutAbortError(err)) return new TimeoutError(\"Request timed out.\", { cause: err });\n if (isAbortError(err)) return err;\n if (err instanceof ConnectError) {\n if (err.code === Code.Canceled) {\n return !hasResponseMetadata(err) && TIMEOUT_ABORT_MESSAGE_RE.test(err.rawMessage)\n ? new TimeoutError(\"Request timed out.\", { cause: err })\n : err;\n }\n const wrapped = findPolyesterErrorInCauseChain(err);\n if (wrapped) return wrapped;\n return connectErrorToPolyesterError(err);\n }\n return err;\n}\n\nfunction callerAbortError(signal: AbortSignal): DOMException | TimeoutError {\n const reason: unknown = signal.reason;\n if (isTimeoutAbortError(reason))\n return new TimeoutError(\"Request timed out.\", { cause: reason });\n return preAbortedError(signal);\n}\n\n// A signal that fired before the call started is a cancellation even when it was\n// a timeout: a retryable TimeoutError would let retry loops spin on a dead signal.\nfunction preAbortedError(signal: AbortSignal): DOMException {\n const reason: unknown = signal.reason;\n return reason instanceof DOMException && reason.name === \"AbortError\"\n ? reason\n : new DOMException(\"Request canceled.\", \"AbortError\");\n}\n\nasync function toTransportError(err: unknown, signal?: AbortSignal): Promise<unknown> {\n if (signal?.aborted && err instanceof ConnectError && err.code === Code.Canceled) {\n return callerAbortError(signal);\n }\n await loadErrorDetailDecoders(err);\n return toPolyesterError(err);\n}\n\nasync function* mapStreamErrors<T>(\n source: AsyncIterable<T>,\n signal?: AbortSignal,\n): AsyncIterable<T> {\n try {\n yield* source;\n } catch (err) {\n throw await toTransportError(err, signal);\n }\n}\n\n/**\n * Interceptor that converts every RPC failure (unary and streaming) into the\n * typed {@link PolyesterError} hierarchy. Installed outermost by\n * `createTransports`, so callers of SDK services always see typed errors.\n */\nexport function createErrorMappingInterceptor(): Interceptor {\n return (next) => async (req) => {\n try {\n const res = await next(req);\n if (res.stream) {\n return { ...res, message: mapStreamErrors(res.message) };\n }\n return res;\n } catch (err) {\n await loadErrorDetailDecoders(err);\n throw toPolyesterError(err);\n }\n };\n}\n\n/**\n * Wraps a Connect transport so errors are translated after Connect's call\n * runner has applied its own error normalization.\n */\nexport function createErrorMappingTransport(transport: Transport): Transport {\n return {\n async unary(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw preAbortedError(signal);\n try {\n return await transport.unary(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n } catch (error) {\n throw await toTransportError(error, signal);\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw preAbortedError(signal);\n try {\n const response = await transport.stream(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n return { ...response, message: mapStreamErrors(response.message, signal) };\n } catch (error) {\n throw await toTransportError(error, signal);\n }\n },\n };\n}\n"],"mappings":";;;;;AA4CA,MAAa,sBAAsB;AAGnC,MAAM,oCAAoC;AAE1C,SAAS,yBAAyB,QAAmD;CACjF,IAAI,QAAQ,YAAY,YACpB,OAAO;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC,CAAC,SAAS,OAAO,IAAI;CAE1B,IAAI,QAAQ,YAAY,qBACpB,OAAO;EACH;EACA;EACA;EAC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AU,MACnB,QACA,QACA,WACA,QACA,OACA,aACJ;GACJ,SAAS,OAAO;IACZ,MAAM,MAAM,iBAAiB,OAAO,MAAM;GAC9C;EACJ;EACA,MAAM,OAAO,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GAClE,IAAI,QAAQ,SAAS,MAAM,gBAAgB,MAAM;GACjD,IAAI;IACA,MAAM,WAAW,MAAM,UAAU,OAC7B,QACA,QACA,WACA,QACA,OACA,aACJ;IACA,OAAO;KAAE,GAAG;KAAU,SAAS,gBAAgB,SAAS,SAAS,MAAM;IAAE;GAC7E,SAAS,OAAO;IACZ,MAAM,MAAM,iBAAiB,OAAO,MAAM;GAC9C;EACJ;CACJ;AACJ"}
@@ -3,7 +3,7 @@ interface PolyesterRequestOptions {
3
3
  signal?: AbortSignal;
4
4
  /**
5
5
  * Deadline for the call in milliseconds, a positive integer of at most
6
- * 2147483647. When it passes, the request is cancelled and
6
+ * 2147483647. When it passes, the request is canceled and
7
7
  * rejects with `TimeoutError`. Also sent to the backend as the Connect
8
8
  * deadline. Other values throw `ValidationError`.
9
9
  */
@@ -1 +1 @@
1
- {"version":3,"file":"request-options.js","names":[],"sources":["../../src/shared/request-options.ts"],"sourcesContent":["import { ValidationError } from \"./errors.js\";\n\nexport interface PolyesterRequestOptions {\n signal?: AbortSignal;\n /**\n * Deadline for the call in milliseconds, a positive integer of at most\n * 2147483647. When it passes, the request is cancelled and\n * rejects with `TimeoutError`. Also sent to the backend as the Connect\n * deadline. Other values throw `ValidationError`.\n */\n timeoutMs?: number;\n}\n\nexport interface PolyesterMutationOptions extends PolyesterRequestOptions {\n stepUpToken?: string | null;\n}\n\nexport const AUTH_STEP_UP_HEADER_NAME = \"X-Auth-Step-Up\";\n\n// Largest `timeoutMs`: `setTimeout` fires immediately for longer delays.\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\nexport type PolyesterConnectCallOptions = {\n signal?: AbortSignal;\n timeoutMs?: number;\n headers?: Headers;\n};\n\n/**\n * Converts SDK request options into Connect RPC call options.\n */\nexport function toConnectCallOptions(\n options?: PolyesterMutationOptions,\n): PolyesterConnectCallOptions | undefined {\n const signal = options?.signal;\n const timeoutMs = options?.timeoutMs;\n const stepUpToken = (options?.stepUpToken ?? \"\").trim();\n\n // Connect treats <= 0 as no deadline and sends the value verbatim as\n // connect-timeout-ms, which must be an integer.\n if (\n timeoutMs !== undefined &&\n !(Number.isInteger(timeoutMs) && timeoutMs > 0 && timeoutMs <= MAX_TIMEOUT_MS)\n ) {\n throw new ValidationError(\n `timeoutMs must be a positive integer of at most ${MAX_TIMEOUT_MS}, got ${timeoutMs}.`,\n );\n }\n\n if (!signal && timeoutMs === undefined && !stepUpToken) return undefined;\n\n const callOptions: PolyesterConnectCallOptions = {};\n if (signal) callOptions.signal = signal;\n if (timeoutMs !== undefined) callOptions.timeoutMs = timeoutMs;\n if (stepUpToken) {\n const headers = new Headers();\n headers.set(AUTH_STEP_UP_HEADER_NAME, stepUpToken);\n callOptions.headers = headers;\n }\n\n return callOptions;\n}\n"],"mappings":";;AAiBA,MAAa,2BAA2B;AAGxC,MAAM,iBAAiB;;;;AAWvB,SAAgB,qBACZ,SACuC;CACvC,MAAM,SAAS,SAAS;CACxB,MAAM,YAAY,SAAS;CAC3B,MAAM,eAAe,SAAS,eAAe,GAAA,CAAI,KAAK;CAItD,IACI,cAAc,KAAA,KACd,EAAE,OAAO,UAAU,SAAS,KAAK,YAAY,KAAK,aAAa,iBAE/D,MAAM,IAAI,gBACN,mDAAmD,eAAe,QAAQ,UAAU,EACxF;CAGJ,IAAI,CAAC,UAAU,cAAc,KAAA,KAAa,CAAC,aAAa,OAAO,KAAA;CAE/D,MAAM,cAA2C,CAAC;CAClD,IAAI,QAAQ,YAAY,SAAS;CACjC,IAAI,cAAc,KAAA,GAAW,YAAY,YAAY;CACrD,IAAI,aAAa;EACb,MAAM,UAAU,IAAI,QAAQ;EAC5B,QAAQ,IAAI,0BAA0B,WAAW;EACjD,YAAY,UAAU;CAC1B;CAEA,OAAO;AACX"}
1
+ {"version":3,"file":"request-options.js","names":[],"sources":["../../src/shared/request-options.ts"],"sourcesContent":["import { ValidationError } from \"./errors.js\";\n\nexport interface PolyesterRequestOptions {\n signal?: AbortSignal;\n /**\n * Deadline for the call in milliseconds, a positive integer of at most\n * 2147483647. When it passes, the request is canceled and\n * rejects with `TimeoutError`. Also sent to the backend as the Connect\n * deadline. Other values throw `ValidationError`.\n */\n timeoutMs?: number;\n}\n\nexport interface PolyesterMutationOptions extends PolyesterRequestOptions {\n stepUpToken?: string | null;\n}\n\nexport const AUTH_STEP_UP_HEADER_NAME = \"X-Auth-Step-Up\";\n\n// Largest `timeoutMs`: `setTimeout` fires immediately for longer delays.\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\nexport type PolyesterConnectCallOptions = {\n signal?: AbortSignal;\n timeoutMs?: number;\n headers?: Headers;\n};\n\n/**\n * Converts SDK request options into Connect RPC call options.\n */\nexport function toConnectCallOptions(\n options?: PolyesterMutationOptions,\n): PolyesterConnectCallOptions | undefined {\n const signal = options?.signal;\n const timeoutMs = options?.timeoutMs;\n const stepUpToken = (options?.stepUpToken ?? \"\").trim();\n\n // Connect treats <= 0 as no deadline and sends the value verbatim as\n // connect-timeout-ms, which must be an integer.\n if (\n timeoutMs !== undefined &&\n !(Number.isInteger(timeoutMs) && timeoutMs > 0 && timeoutMs <= MAX_TIMEOUT_MS)\n ) {\n throw new ValidationError(\n `timeoutMs must be a positive integer of at most ${MAX_TIMEOUT_MS}, got ${timeoutMs}.`,\n );\n }\n\n if (!signal && timeoutMs === undefined && !stepUpToken) return undefined;\n\n const callOptions: PolyesterConnectCallOptions = {};\n if (signal) callOptions.signal = signal;\n if (timeoutMs !== undefined) callOptions.timeoutMs = timeoutMs;\n if (stepUpToken) {\n const headers = new Headers();\n headers.set(AUTH_STEP_UP_HEADER_NAME, stepUpToken);\n callOptions.headers = headers;\n }\n\n return callOptions;\n}\n"],"mappings":";;AAiBA,MAAa,2BAA2B;AAGxC,MAAM,iBAAiB;;;;AAWvB,SAAgB,qBACZ,SACuC;CACvC,MAAM,SAAS,SAAS;CACxB,MAAM,YAAY,SAAS;CAC3B,MAAM,eAAe,SAAS,eAAe,GAAA,CAAI,KAAK;CAItD,IACI,cAAc,KAAA,KACd,EAAE,OAAO,UAAU,SAAS,KAAK,YAAY,KAAK,aAAa,iBAE/D,MAAM,IAAI,gBACN,mDAAmD,eAAe,QAAQ,UAAU,EACxF;CAGJ,IAAI,CAAC,UAAU,cAAc,KAAA,KAAa,CAAC,aAAa,OAAO,KAAA;CAE/D,MAAM,cAA2C,CAAC;CAClD,IAAI,QAAQ,YAAY,SAAS;CACjC,IAAI,cAAc,KAAA,GAAW,YAAY,YAAY;CACrD,IAAI,aAAa;EACb,MAAM,UAAU,IAAI,QAAQ;EAC5B,QAAQ,IAAI,0BAA0B,WAAW;EACjD,YAAY,UAAU;CAC1B;CAEA,OAAO;AACX"}
@@ -2,6 +2,27 @@ import { ValidationError } from "./errors.js";
2
2
  import * as v from "valibot";
3
3
  //#region src/shared/validation.ts
4
4
  /**
5
+ * Builds a message from the most specific issue. Valibot's own message is only
6
+ * `issues[0].message`, which for a failed union is a generic "Expected Object
7
+ * but received Object" with the real causes nested in `issue.issues`. Nested
8
+ * issue paths are relative to the union, so the union's path is prefixed.
9
+ */
10
+ function describeIssue(issue) {
11
+ let path = v.getDotPath(issue) ?? "";
12
+ while (issue.type === "union" && issue.issues?.length && hasDefaultMessage(issue)) {
13
+ issue = issue.issues.find((nested) => nested.kind === "validation") ?? issue.issues[0];
14
+ const nestedPath = v.getDotPath(issue);
15
+ if (nestedPath) path = path ? `${path}.${nestedPath}` : nestedPath;
16
+ }
17
+ const field = path.replace(/\.\d+(?=\.|$)/g, "");
18
+ if (!path || issue.message.startsWith(path) || issue.message.startsWith(field)) return issue.message;
19
+ return `${path}: ${issue.message}`;
20
+ }
21
+ /** Unions given a custom message already say what went wrong. */
22
+ function hasDefaultMessage(issue) {
23
+ return issue.message === `Invalid type: Expected ${issue.expected} but received ${issue.received}`;
24
+ }
25
+ /**
5
26
  * Parses a value with Valibot and translates schema failures into the SDK's
6
27
  * public error hierarchy.
7
28
  */
@@ -9,7 +30,7 @@ function parse(schema, input, config) {
9
30
  try {
10
31
  return v.parse(schema, input, config);
11
32
  } catch (error) {
12
- if (v.isValiError(error)) throw new ValidationError(error.message, { cause: error });
33
+ if (v.isValiError(error)) throw new ValidationError(describeIssue(error.issues[0]), { cause: error });
13
34
  throw error;
14
35
  }
15
36
  }
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","names":[],"sources":["../../src/shared/validation.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { ValidationError } from \"./errors.js\";\n\n/**\n * Parses a value with Valibot and translates schema failures into the SDK's\n * public error hierarchy.\n */\nexport function parse<const TSchema extends v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>>>(\n schema: TSchema,\n input: unknown,\n config?: v.Config<v.InferIssue<TSchema>>,\n): v.InferOutput<TSchema> {\n try {\n return v.parse(schema, input, config);\n } catch (error) {\n if (v.isValiError(error)) throw new ValidationError(error.message, { cause: error });\n throw error;\n }\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,MACZ,QACA,OACA,QACsB;CACtB,IAAI;EACA,OAAO,EAAE,MAAM,QAAQ,OAAO,MAAM;CACxC,SAAS,OAAO;EACZ,IAAI,EAAE,YAAY,KAAK,GAAG,MAAM,IAAI,gBAAgB,MAAM,SAAS,EAAE,OAAO,MAAM,CAAC;EACnF,MAAM;CACV;AACJ"}
1
+ {"version":3,"file":"validation.js","names":[],"sources":["../../src/shared/validation.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { ValidationError } from \"./errors.js\";\n\ntype AnyIssue = v.BaseIssue<unknown>;\n\n/**\n * Builds a message from the most specific issue. Valibot's own message is only\n * `issues[0].message`, which for a failed union is a generic \"Expected Object\n * but received Object\" with the real causes nested in `issue.issues`. Nested\n * issue paths are relative to the union, so the union's path is prefixed.\n */\nfunction describeIssue(issue: AnyIssue): string {\n let path = v.getDotPath(issue) ?? \"\";\n while (issue.type === \"union\" && issue.issues?.length && hasDefaultMessage(issue)) {\n // Nested issues are flattened across branches, so a validation issue\n // (a branch that got past its type checks) stands in for the closest branch.\n issue = issue.issues.find((nested) => nested.kind === \"validation\") ?? issue.issues[0]!;\n const nestedPath = v.getDotPath(issue);\n if (nestedPath) path = path ? `${path}.${nestedPath}` : nestedPath;\n }\n // Some custom messages already name their field, e.g. \"items.orderId must be ...\".\n const field = path.replace(/\\.\\d+(?=\\.|$)/g, \"\");\n if (!path || issue.message.startsWith(path) || issue.message.startsWith(field)) {\n return issue.message;\n }\n return `${path}: ${issue.message}`;\n}\n\n/** Unions given a custom message already say what went wrong. */\nfunction hasDefaultMessage(issue: AnyIssue): boolean {\n return (\n issue.message === `Invalid type: Expected ${issue.expected} but received ${issue.received}`\n );\n}\n\n/**\n * Parses a value with Valibot and translates schema failures into the SDK's\n * public error hierarchy.\n */\nexport function parse<const TSchema extends v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>>>(\n schema: TSchema,\n input: unknown,\n config?: v.Config<v.InferIssue<TSchema>>,\n): v.InferOutput<TSchema> {\n try {\n return v.parse(schema, input, config);\n } catch (error) {\n if (v.isValiError(error)) {\n throw new ValidationError(describeIssue(error.issues[0]), { cause: error });\n }\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;AAWA,SAAS,cAAc,OAAyB;CAC5C,IAAI,OAAO,EAAE,WAAW,KAAK,KAAK;CAClC,OAAO,MAAM,SAAS,WAAW,MAAM,QAAQ,UAAU,kBAAkB,KAAK,GAAG;EAG/E,QAAQ,MAAM,OAAO,MAAM,WAAW,OAAO,SAAS,YAAY,KAAK,MAAM,OAAO;EACpF,MAAM,aAAa,EAAE,WAAW,KAAK;EACrC,IAAI,YAAY,OAAO,OAAO,GAAG,KAAK,GAAG,eAAe;CAC5D;CAEA,MAAM,QAAQ,KAAK,QAAQ,kBAAkB,EAAE;CAC/C,IAAI,CAAC,QAAQ,MAAM,QAAQ,WAAW,IAAI,KAAK,MAAM,QAAQ,WAAW,KAAK,GACzE,OAAO,MAAM;CAEjB,OAAO,GAAG,KAAK,IAAI,MAAM;AAC7B;;AAGA,SAAS,kBAAkB,OAA0B;CACjD,OACI,MAAM,YAAY,0BAA0B,MAAM,SAAS,gBAAgB,MAAM;AAEzF;;;;;AAMA,SAAgB,MACZ,QACA,OACA,QACsB;CACtB,IAAI;EACA,OAAO,EAAE,MAAM,QAAQ,OAAO,MAAM;CACxC,SAAS,OAAO;EACZ,IAAI,EAAE,YAAY,KAAK,GACnB,MAAM,IAAI,gBAAgB,cAAc,MAAM,OAAO,EAAE,GAAG,EAAE,OAAO,MAAM,CAAC;EAE9E,MAAM;CACV;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"smart-account.js","names":[],"sources":["../../src/smart-account/smart-account.ts"],"sourcesContent":["import type { Address, LocalAccount, PublicClient } from \"viem\";\nimport { BaseError, createPublicClient, http, TimeoutError, withTimeout } from \"viem\";\nimport type { EstimateUserOperationGasParameters, UserOperation } from \"viem/account-abstraction\";\nimport {\n estimateUserOperationGas,\n getUserOperationHash,\n prepareUserOperation,\n} from \"viem/account-abstraction\";\nimport { createSmartAccountClient } from \"permissionless\";\nimport { getUserOperationStatus } from \"permissionless/actions/pimlico\";\nimport { toSafeSmartAccount } from \"permissionless/accounts\";\nimport { createPimlicoClient } from \"permissionless/clients/pimlico\";\nimport type { PolyesterEnvironment } from \"../environment.js\";\nimport { predictSafeAddress } from \"../account-signer/predict-safe-address.js\";\nimport {\n UserOperationAlreadyKnownError,\n UserOperationNotExecutedError,\n UserOperationSendTimeoutError,\n} from \"../shared/errors.js\";\n\nexport type SafeSmartAccountInstance = Awaited<ReturnType<typeof toSafeSmartAccount>>;\nexport type PolyesterSmartAccountClient = ReturnType<typeof buildPolyesterSmartAccountClient>;\n\nconst smartAccountEnvironmentFingerprints = new WeakMap<SafeSmartAccountInstance, string>();\nconst smartAccountClientPrimers = new WeakMap<object, () => Promise<unknown>>();\nconst smartAccountClientCacheResets = new WeakMap<object, () => void>();\nconst smartAccountClients = new WeakMap<\n SafeSmartAccountInstance,\n Map<string, PolyesterSmartAccountClient>\n>();\nconst USER_OPERATION_GAS_PRICE_TTL_MS = 60_000;\nconst USER_OPERATION_GAS_BUFFER_BPS = 2_000n;\nconst USER_OPERATION_MIN_GAS_BUFFER = 50_000n;\nconst USER_OPERATION_RECEIPT_POLLING_INTERVAL_MS = 250;\n/**\n * Bundler request deadline. viem's 10s default is shorter than\n * `eth_sendUserOperation` takes under load, and viem never retries that\n * method, so a slow but successful send would surface as a timeout.\n */\nconst BUNDLER_REQUEST_TIMEOUT_MS = 30_000;\n/**\n * While the bundler reports `not_found`, the chain is checked for a receipt\n * on every Nth poll (once per second at the default interval). `not_found` is\n * not definitive — a bundler restart forgets ops whose bundle is still\n * pending — so polling continues until the deadline.\n */\nconst NOT_FOUND_RECEIPT_CHECK_EVERY = 4;\n\nexport interface CreateSmartAccountParams {\n environment: PolyesterEnvironment;\n owner: LocalAccount;\n saltNonce?: bigint;\n publicClient?: PublicClient;\n}\n\nexport interface PredictPolyesterSmartAccountAddressParams {\n environment: PolyesterEnvironment;\n ownerAddress: Address;\n saltNonce?: bigint;\n}\n\nexport function predictPolyesterSmartAccountAddress({\n environment,\n ownerAddress,\n saltNonce = 0n,\n}: PredictPolyesterSmartAccountAddressParams): Address {\n const {\n safeProxyFactoryAddress,\n safeSingletonAddress,\n safeModuleSetupAddress,\n safe4337ModuleAddress,\n multiSendAddress,\n } = environment.accountAbstraction.safe;\n\n return predictSafeAddress({\n owners: [ownerAddress],\n saltNonce,\n safeProxyFactoryAddress,\n safeSingletonAddress,\n safeModuleSetupAddress,\n safe4337ModuleAddress,\n multiSendAddress,\n });\n}\n\n/**\n * Creates a Polyester smart account instance.\n */\nexport async function createPolyesterSmartAccount({\n environment,\n owner,\n saltNonce,\n publicClient,\n}: CreateSmartAccountParams): Promise<SafeSmartAccountInstance> {\n const client =\n publicClient ??\n createPublicClient({\n chain: environment.chain,\n transport: http(environment.rpcUrl),\n });\n\n if (client.chain?.id && client.chain.id !== environment.chain.id) {\n throw new Error(\"Smart account public client chain does not match environment.\");\n }\n\n const account = await toSafeSmartAccount({\n client,\n owners: [owner],\n saltNonce,\n entryPoint: environment.accountAbstraction.entryPoint,\n ...environment.accountAbstraction.safe,\n });\n smartAccountEnvironmentFingerprints.set(account, environment.fingerprint);\n return account;\n}\n\nexport interface PolyesterSmartAccountClientOptions {\n /** How long a fetched gas price is reused, in milliseconds. Defaults to 60s. */\n gasPriceCacheTtlMs?: number;\n /** How often to poll for UserOperation inclusion, in milliseconds. Defaults to 250ms. */\n pollingIntervalMs?: number;\n}\n\n/**\n * Creates a viem client bound to a Polyester smart account. Memoized per\n * (account, environment, options): repeat calls return the same client, so\n * the gas price cache and warmed connections survive across submissions.\n */\nexport function createPolyesterSmartAccountClient(\n account: SafeSmartAccountInstance,\n params: {\n environment: PolyesterEnvironment;\n options?: PolyesterSmartAccountClientOptions;\n },\n) {\n const { environment, options } = params;\n const accountEnvironmentFingerprint = smartAccountEnvironmentFingerprints.get(account);\n if (\n accountEnvironmentFingerprint &&\n accountEnvironmentFingerprint !== environment.fingerprint\n ) {\n throw new Error(\"Smart account environment does not match client environment.\");\n }\n let clients = smartAccountClients.get(account);\n if (!clients) smartAccountClients.set(account, (clients = new Map()));\n const key = JSON.stringify([\n environment.fingerprint,\n options?.gasPriceCacheTtlMs ?? USER_OPERATION_GAS_PRICE_TTL_MS,\n options?.pollingIntervalMs ?? USER_OPERATION_RECEIPT_POLLING_INTERVAL_MS,\n ]);\n let client = clients.get(key);\n if (!client) {\n client = buildPolyesterSmartAccountClient(account, environment, options);\n clients.set(key, client);\n }\n return client;\n}\n\nfunction buildPolyesterSmartAccountClient(\n account: SafeSmartAccountInstance,\n environment: PolyesterEnvironment,\n options: PolyesterSmartAccountClientOptions | undefined,\n) {\n const {\n gasPriceCacheTtlMs = USER_OPERATION_GAS_PRICE_TTL_MS,\n pollingIntervalMs = USER_OPERATION_RECEIPT_POLLING_INTERVAL_MS,\n } = options ?? {};\n\n const paymaster = createPimlicoClient({\n chain: environment.chain,\n transport: http(environment.accountAbstraction.paymasterUrl),\n entryPoint: environment.accountAbstraction.entryPoint,\n });\n\n const gasPrice = cachedForTtl(() => paymaster.getUserOperationGasPrice(), gasPriceCacheTtlMs);\n const getGasPrice = gasPrice.get;\n\n const client = createSmartAccountClient({\n account,\n chain: environment.chain,\n paymaster: {\n getPaymasterStubData: (parameters) => paymaster.getPaymasterStubData(parameters),\n getPaymasterData: (parameters) => paymaster.getPaymasterData(parameters),\n },\n bundlerTransport: http(environment.accountAbstraction.bundlerUrl, {\n timeout: BUNDLER_REQUEST_TIMEOUT_MS,\n }),\n pollingInterval: pollingIntervalMs,\n userOperation: {\n estimateFeesPerGas: async () => (await getGasPrice()).fast,\n // Single prepare pass: viem resolves gas estimation via\n // `getAction(client, estimateUserOperationGas, ...)`, so handing\n // `prepareUserOperation` a client whose estimate action buffers the\n // result makes the buffered limits flow into getPaymasterData\n // before signing — the sponsorship signature commits to them.\n prepareUserOperation: (prepareClient, prepareParameters) => {\n const bufferingClient = {\n ...prepareClient,\n estimateUserOperationGas: async (\n estimateParameters: EstimateUserOperationGasParameters,\n ) =>\n bufferPolyesterUserOperationGas(\n await estimateUserOperationGas(prepareClient, estimateParameters),\n ),\n };\n return prepareUserOperation(\n bufferingClient as typeof prepareClient,\n prepareParameters as Parameters<typeof prepareUserOperation>[1],\n );\n },\n },\n });\n smartAccountClientPrimers.set(client, () => Promise.allSettled([getGasPrice()]));\n smartAccountClientCacheResets.set(client, () => {\n gasPrice.clear();\n });\n return client;\n}\n\n/** Memoizes a promise-returning fetch for `ttlMs`; a rejected fetch is not cached. */\nfunction cachedForTtl<T>(\n fetch: () => Promise<T>,\n ttlMs: number,\n): { get: () => Promise<T>; clear: () => void } {\n let cached: { fetchedAt: number; result: Promise<T> } | undefined;\n return {\n get: () => {\n if (!cached || Date.now() - cached.fetchedAt >= ttlMs) {\n const entry = { fetchedAt: Date.now(), result: fetch() };\n cached = entry;\n entry.result.catch(() => {\n if (cached === entry) cached = undefined;\n });\n }\n return cached.result;\n },\n clear: () => {\n cached = undefined;\n },\n };\n}\n\nfunction addUserOperationGasBuffer(gas: bigint): bigint {\n const percentBuffer = (gas * USER_OPERATION_GAS_BUFFER_BPS) / 10_000n;\n return (\n gas +\n (percentBuffer > USER_OPERATION_MIN_GAS_BUFFER\n ? percentBuffer\n : USER_OPERATION_MIN_GAS_BUFFER)\n );\n}\n\n/**\n * Pads account and paymaster gas limits (+20%, 50k floor) before getPaymasterData.\n */\nfunction bufferPolyesterUserOperationGas<\n T extends {\n callGasLimit?: bigint;\n preVerificationGas?: bigint;\n verificationGasLimit?: bigint;\n paymasterPostOpGasLimit?: bigint;\n paymasterVerificationGasLimit?: bigint;\n },\n>(gas: T): T {\n return {\n ...gas,\n ...(typeof gas.callGasLimit === \"bigint\"\n ? { callGasLimit: addUserOperationGasBuffer(gas.callGasLimit) }\n : {}),\n ...(typeof gas.preVerificationGas === \"bigint\"\n ? { preVerificationGas: addUserOperationGasBuffer(gas.preVerificationGas) }\n : {}),\n ...(typeof gas.verificationGasLimit === \"bigint\"\n ? { verificationGasLimit: addUserOperationGasBuffer(gas.verificationGasLimit) }\n : {}),\n ...(typeof gas.paymasterPostOpGasLimit === \"bigint\"\n ? { paymasterPostOpGasLimit: addUserOperationGasBuffer(gas.paymasterPostOpGasLimit) }\n : {}),\n ...(typeof gas.paymasterVerificationGasLimit === \"bigint\"\n ? {\n paymasterVerificationGasLimit: addUserOperationGasBuffer(\n gas.paymasterVerificationGasLimit,\n ),\n }\n : {}),\n };\n}\n\n/**\n * Warms the network path for an upcoming submission: primes the gas-price\n * cache and opens connections to the RPC endpoint. Never\n * throws; the nonce is intentionally not cached — fetching it here is\n * connection warm-up only.\n */\nexport async function warmPolyesterSmartAccountClient(\n client: PolyesterSmartAccountClient,\n): Promise<void> {\n await Promise.allSettled([\n smartAccountClientPrimers.get(client)?.(),\n client.account.getNonce(),\n client.account.isDeployed(),\n ]);\n}\n\nexport type PolyesterUserOperationPhase = \"prepare\" | \"sign\" | \"send\" | \"receipt\";\n\nexport interface SendPolyesterUserOperationOptions {\n /**\n * Fires once per submission, immediately before the wallet is asked to\n * sign the fully prepared operation — the prepare→sign boundary.\n */\n onWalletSignatureRequested?: () => void;\n /**\n * Reports how long each submission phase took. `prepare` covers nonce,\n * fees and sponsorship; `sign` the wallet signature; `send`\n * `eth_sendUserOperation`. Pass the same callback to\n * {@link waitForPolyesterUserOperationReceipt} to get `receipt`.\n */\n onPhase?: (phase: PolyesterUserOperationPhase, ms: number) => void;\n}\n\nexport async function sendPolyesterUserOperation(\n client: PolyesterSmartAccountClient,\n parameters: Parameters<PolyesterSmartAccountClient[\"sendUserOperation\"]>[0],\n options: SendPolyesterUserOperationOptions = {},\n): Promise<Awaited<ReturnType<PolyesterSmartAccountClient[\"sendUserOperation\"]>>> {\n const { onWalletSignatureRequested, onPhase } = options;\n const account =\n (parameters as { account?: SafeSmartAccountInstance }).account ?? client.account;\n let phaseStartedAt = Date.now();\n const endPhase = (phase: PolyesterUserOperationPhase) => {\n const now = Date.now();\n reportPhase(onPhase, phase, now - phaseStartedAt);\n phaseStartedAt = now;\n };\n let signedUserOperation: UserOperation | undefined;\n try {\n const hash = await client.sendUserOperation({\n ...parameters,\n account: {\n ...account,\n signUserOperation: async (\n userOperation: Parameters<SafeSmartAccountInstance[\"signUserOperation\"]>[0],\n ) => {\n endPhase(\"prepare\");\n onWalletSignatureRequested?.();\n const signature = await account.signUserOperation(userOperation);\n signedUserOperation = userOperation as UserOperation;\n endPhase(\"sign\");\n return signature;\n },\n },\n } as Parameters<PolyesterSmartAccountClient[\"sendUserOperation\"]>[0]);\n endPhase(\"send\");\n return hash;\n } catch (error) {\n const userOperation = signedUserOperation;\n if (!userOperation) throw error;\n // The operation's hash is deterministic, so in both cases below the\n // caller can wait on it rather than sign a second operation.\n const userOpHash = () =>\n getUserOperationHash({\n chainId: client.chain.id,\n entryPointAddress: account.entryPoint.address,\n entryPointVersion: account.entryPoint.version,\n userOperation,\n });\n // \"Already known\": this exact operation is already in the bundler's\n // mempool (e.g. a replayed send).\n if (isAlreadyKnownError(error)) {\n const hash = userOpHash();\n throw new UserOperationAlreadyKnownError(\n `UserOperation ${hash} is already pending.`,\n hash,\n { cause: error },\n );\n }\n // A timeout leaves the outcome unknown: the bundler may have accepted\n // the operation after the deadline. It says nothing about the gas price.\n if (isTimeoutError(error)) {\n const hash = userOpHash();\n throw new UserOperationSendTimeoutError(\n `Sending UserOperation ${hash} timed out; it may still be pending.`,\n hash,\n { cause: error },\n );\n }\n // Only a failure after signing (i.e. from `eth_sendUserOperation`) can\n // mean the bundler rejected the cached gas price. Earlier\n // failures — a cancelled wallet prompt above all — keep the cache so\n // the retry stays cheap.\n smartAccountClientCacheResets.get(client)?.();\n throw error;\n }\n}\n\nfunction isAlreadyKnownError(error: unknown): boolean {\n return (\n error instanceof BaseError &&\n error.walk((cause) => /\\balready known\\b/iu.test((cause as BaseError).details ?? \"\")) !==\n null\n );\n}\n\nfunction isTimeoutError(error: unknown): boolean {\n return (\n error instanceof BaseError && error.walk((cause) => cause instanceof TimeoutError) !== null\n );\n}\n\n/** Observers must never affect the result: a throwing `onPhase` is swallowed. */\nfunction reportPhase(\n onPhase: SendPolyesterUserOperationOptions[\"onPhase\"],\n phase: PolyesterUserOperationPhase,\n ms: number,\n): void {\n try {\n onPhase?.(phase, ms);\n } catch {\n // ignore\n }\n}\n\nexport interface WaitForPolyesterUserOperationReceiptOptions {\n /** Overall deadline in milliseconds. Defaults to viem's 120s. */\n timeoutMs?: number;\n /** Receives `(\"receipt\", ms)` once the receipt is available. */\n onPhase?: SendPolyesterUserOperationOptions[\"onPhase\"];\n}\n\n/**\n * Waits for a UserOperation to land. Polls the bundler's cheap\n * `pimlico_getUserOperationStatus` at the client's polling interval, checking\n * immediately, and only fetches the receipt once the bundler reports it has\n * been mined. Status lives in bundler memory, so `not_found` (e.g. after a\n * bundler restart) also checks the chain for a receipt until the deadline.\n * `timeoutMs` bounds every request, not just the gaps between them.\n */\nexport async function waitForPolyesterUserOperationReceipt(\n client: PolyesterSmartAccountClient,\n hash: `0x${string}`,\n options: WaitForPolyesterUserOperationReceiptOptions = {},\n): Promise<Awaited<ReturnType<PolyesterSmartAccountClient[\"waitForUserOperationReceipt\"]>>> {\n const { timeoutMs = 120_000, onPhase } = options;\n const startedAt = Date.now();\n const deadline = startedAt + timeoutMs;\n const timedOut = () => new Error(`Timed out waiting for UserOperation ${hash}.`);\n const untilDeadline = <T>(fn: () => Promise<T>): Promise<T> => {\n const timeout = deadline - Date.now();\n if (timeout <= 0) return Promise.reject(timedOut());\n return withTimeout(fn, { timeout, errorInstance: timedOut() });\n };\n const statusClient = client as unknown as Parameters<typeof getUserOperationStatus>[0];\n\n let consecutiveNotFound = 0;\n for (;;) {\n const { status } = await untilDeadline(() =>\n getUserOperationStatus(statusClient, { hash }),\n );\n if (status === \"included\" || status === \"reverted\") {\n const receipt = await untilDeadline(() =>\n client.waitForUserOperationReceipt({ hash, timeout: deadline - Date.now() }),\n );\n reportPhase(onPhase, \"receipt\", Date.now() - startedAt);\n return receipt;\n }\n if (status === \"failed\") {\n throw new UserOperationNotExecutedError(\n `UserOperation ${hash} was bundled but the bundle transaction reverted; it was not executed.`,\n hash,\n \"failed\",\n );\n }\n if (status === \"rejected\") {\n // Re-simulation failures are often fee-too-low: drop cached prices.\n smartAccountClientCacheResets.get(client)?.();\n throw new UserOperationNotExecutedError(\n `UserOperation ${hash} was rejected by the bundler; it was not executed.`,\n hash,\n \"rejected\",\n );\n }\n if (status === \"not_found\") {\n if (consecutiveNotFound++ % NOT_FOUND_RECEIPT_CHECK_EVERY === 0) {\n const receipt = await untilDeadline(() =>\n client.getUserOperationReceipt({ hash }),\n ).catch((error: Error) => {\n if (error.name === \"UserOperationReceiptNotFoundError\") return undefined;\n throw error;\n });\n if (receipt) {\n reportPhase(onPhase, \"receipt\", Date.now() - startedAt);\n return receipt;\n }\n }\n } else {\n consecutiveNotFound = 0;\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw timedOut();\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(client.pollingInterval, remaining)),\n );\n }\n}\n"],"mappings":";;;;;;;;;AAuBA,MAAM,sDAAsC,IAAI,QAA0C;AAC1F,MAAM,4CAA4B,IAAI,QAAwC;AAC9E,MAAM,gDAAgC,IAAI,QAA4B;AACtE,MAAM,sCAAsB,IAAI,QAG9B;AACF,MAAM,kCAAkC;AACxC,MAAM,gCAAgC;AACtC,MAAM,gCAAgC;AACtC,MAAM,6CAA6C;;;;;;AAMnD,MAAM,6BAA6B;;;;;;;AAOnC,MAAM,gCAAgC;AAetC,SAAgB,oCAAoC,EAChD,aACA,cACA,YAAY,MACuC;CACnD,MAAM,EACF,yBACA,sBACA,wBACA,uBACA,qBACA,YAAY,mBAAmB;CAEnC,OAAO,mBAAmB;EACtB,QAAQ,CAAC,YAAY;EACrB;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC;AACL;;;;AAKA,eAAsB,4BAA4B,EAC9C,aACA,OACA,WACA,gBAC4D;CAC5D,MAAM,SACF,gBACA,mBAAmB;EACf,OAAO,YAAY;EACnB,WAAW,KAAK,YAAY,MAAM;CACtC,CAAC;CAEL,IAAI,OAAO,OAAO,MAAM,OAAO,MAAM,OAAO,YAAY,MAAM,IAC1D,MAAM,IAAI,MAAM,+DAA+D;CAGnF,MAAM,UAAU,MAAM,mBAAmB;EACrC;EACA,QAAQ,CAAC,KAAK;EACd;EACA,YAAY,YAAY,mBAAmB;EAC3C,GAAG,YAAY,mBAAmB;CACtC,CAAC;CACD,oCAAoC,IAAI,SAAS,YAAY,WAAW;CACxE,OAAO;AACX;;;;;;AAcA,SAAgB,kCACZ,SACA,QAIF;CACE,MAAM,EAAE,aAAa,YAAY;CACjC,MAAM,gCAAgC,oCAAoC,IAAI,O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AC,CAAC,OAAO,UAAiB;KACtB,IAAI,MAAM,SAAS,qCAAqC,OAAO,KAAA;KAC/D,MAAM;IACV,CAAC;IACD,IAAI,SAAS;KACT,YAAY,SAAS,WAAW,KAAK,IAAI,IAAI,SAAS;KACtD,OAAO;IACX;GACJ;SAEA,sBAAsB;EAE1B,MAAM,YAAY,WAAW,KAAK,IAAI;EACtC,IAAI,aAAa,GAAG,MAAM,SAAS;EACnC,MAAM,IAAI,SAAS,YACf,WAAW,SAAS,KAAK,IAAI,OAAO,iBAAiB,SAAS,CAAC,CACnE;CACJ;AACJ"}
1
+ {"version":3,"file":"smart-account.js","names":[],"sources":["../../src/smart-account/smart-account.ts"],"sourcesContent":["import type { Address, LocalAccount, PublicClient } from \"viem\";\nimport { BaseError, createPublicClient, http, TimeoutError, withTimeout } from \"viem\";\nimport type { EstimateUserOperationGasParameters, UserOperation } from \"viem/account-abstraction\";\nimport {\n estimateUserOperationGas,\n getUserOperationHash,\n prepareUserOperation,\n} from \"viem/account-abstraction\";\nimport { createSmartAccountClient } from \"permissionless\";\nimport { getUserOperationStatus } from \"permissionless/actions/pimlico\";\nimport { toSafeSmartAccount } from \"permissionless/accounts\";\nimport { createPimlicoClient } from \"permissionless/clients/pimlico\";\nimport type { PolyesterEnvironment } from \"../environment.js\";\nimport { predictSafeAddress } from \"../account-signer/predict-safe-address.js\";\nimport {\n UserOperationAlreadyKnownError,\n UserOperationNotExecutedError,\n UserOperationSendTimeoutError,\n} from \"../shared/errors.js\";\n\nexport type SafeSmartAccountInstance = Awaited<ReturnType<typeof toSafeSmartAccount>>;\nexport type PolyesterSmartAccountClient = ReturnType<typeof buildPolyesterSmartAccountClient>;\n\nconst smartAccountEnvironmentFingerprints = new WeakMap<SafeSmartAccountInstance, string>();\nconst smartAccountClientPrimers = new WeakMap<object, () => Promise<unknown>>();\nconst smartAccountClientCacheResets = new WeakMap<object, () => void>();\nconst smartAccountClients = new WeakMap<\n SafeSmartAccountInstance,\n Map<string, PolyesterSmartAccountClient>\n>();\nconst USER_OPERATION_GAS_PRICE_TTL_MS = 60_000;\nconst USER_OPERATION_GAS_BUFFER_BPS = 2_000n;\nconst USER_OPERATION_MIN_GAS_BUFFER = 50_000n;\nconst USER_OPERATION_RECEIPT_POLLING_INTERVAL_MS = 250;\n/**\n * Bundler request deadline. viem's 10s default is shorter than\n * `eth_sendUserOperation` takes under load, and viem never retries that\n * method, so a slow but successful send would surface as a timeout.\n */\nconst BUNDLER_REQUEST_TIMEOUT_MS = 30_000;\n/**\n * While the bundler reports `not_found`, the chain is checked for a receipt\n * on every Nth poll (once per second at the default interval). `not_found` is\n * not definitive — a bundler restart forgets ops whose bundle is still\n * pending — so polling continues until the deadline.\n */\nconst NOT_FOUND_RECEIPT_CHECK_EVERY = 4;\n\nexport interface CreateSmartAccountParams {\n environment: PolyesterEnvironment;\n owner: LocalAccount;\n saltNonce?: bigint;\n publicClient?: PublicClient;\n}\n\nexport interface PredictPolyesterSmartAccountAddressParams {\n environment: PolyesterEnvironment;\n ownerAddress: Address;\n saltNonce?: bigint;\n}\n\nexport function predictPolyesterSmartAccountAddress({\n environment,\n ownerAddress,\n saltNonce = 0n,\n}: PredictPolyesterSmartAccountAddressParams): Address {\n const {\n safeProxyFactoryAddress,\n safeSingletonAddress,\n safeModuleSetupAddress,\n safe4337ModuleAddress,\n multiSendAddress,\n } = environment.accountAbstraction.safe;\n\n return predictSafeAddress({\n owners: [ownerAddress],\n saltNonce,\n safeProxyFactoryAddress,\n safeSingletonAddress,\n safeModuleSetupAddress,\n safe4337ModuleAddress,\n multiSendAddress,\n });\n}\n\n/**\n * Creates a Polyester smart account instance.\n */\nexport async function createPolyesterSmartAccount({\n environment,\n owner,\n saltNonce,\n publicClient,\n}: CreateSmartAccountParams): Promise<SafeSmartAccountInstance> {\n const client =\n publicClient ??\n createPublicClient({\n chain: environment.chain,\n transport: http(environment.rpcUrl),\n });\n\n if (client.chain?.id && client.chain.id !== environment.chain.id) {\n throw new Error(\"Smart account public client chain does not match environment.\");\n }\n\n const account = await toSafeSmartAccount({\n client,\n owners: [owner],\n saltNonce,\n entryPoint: environment.accountAbstraction.entryPoint,\n ...environment.accountAbstraction.safe,\n });\n smartAccountEnvironmentFingerprints.set(account, environment.fingerprint);\n return account;\n}\n\nexport interface PolyesterSmartAccountClientOptions {\n /** How long a fetched gas price is reused, in milliseconds. Defaults to 60s. */\n gasPriceCacheTtlMs?: number;\n /** How often to poll for UserOperation inclusion, in milliseconds. Defaults to 250ms. */\n pollingIntervalMs?: number;\n}\n\n/**\n * Creates a viem client bound to a Polyester smart account. Memoized per\n * (account, environment, options): repeat calls return the same client, so\n * the gas price cache and warmed connections survive across submissions.\n */\nexport function createPolyesterSmartAccountClient(\n account: SafeSmartAccountInstance,\n params: {\n environment: PolyesterEnvironment;\n options?: PolyesterSmartAccountClientOptions;\n },\n) {\n const { environment, options } = params;\n const accountEnvironmentFingerprint = smartAccountEnvironmentFingerprints.get(account);\n if (\n accountEnvironmentFingerprint &&\n accountEnvironmentFingerprint !== environment.fingerprint\n ) {\n throw new Error(\"Smart account environment does not match client environment.\");\n }\n let clients = smartAccountClients.get(account);\n if (!clients) smartAccountClients.set(account, (clients = new Map()));\n const key = JSON.stringify([\n environment.fingerprint,\n options?.gasPriceCacheTtlMs ?? USER_OPERATION_GAS_PRICE_TTL_MS,\n options?.pollingIntervalMs ?? USER_OPERATION_RECEIPT_POLLING_INTERVAL_MS,\n ]);\n let client = clients.get(key);\n if (!client) {\n client = buildPolyesterSmartAccountClient(account, environment, options);\n clients.set(key, client);\n }\n return client;\n}\n\nfunction buildPolyesterSmartAccountClient(\n account: SafeSmartAccountInstance,\n environment: PolyesterEnvironment,\n options: PolyesterSmartAccountClientOptions | undefined,\n) {\n const {\n gasPriceCacheTtlMs = USER_OPERATION_GAS_PRICE_TTL_MS,\n pollingIntervalMs = USER_OPERATION_RECEIPT_POLLING_INTERVAL_MS,\n } = options ?? {};\n\n const paymaster = createPimlicoClient({\n chain: environment.chain,\n transport: http(environment.accountAbstraction.paymasterUrl),\n entryPoint: environment.accountAbstraction.entryPoint,\n });\n\n const gasPrice = cachedForTtl(() => paymaster.getUserOperationGasPrice(), gasPriceCacheTtlMs);\n const getGasPrice = gasPrice.get;\n\n const client = createSmartAccountClient({\n account,\n chain: environment.chain,\n paymaster: {\n getPaymasterStubData: (parameters) => paymaster.getPaymasterStubData(parameters),\n getPaymasterData: (parameters) => paymaster.getPaymasterData(parameters),\n },\n bundlerTransport: http(environment.accountAbstraction.bundlerUrl, {\n timeout: BUNDLER_REQUEST_TIMEOUT_MS,\n }),\n pollingInterval: pollingIntervalMs,\n userOperation: {\n estimateFeesPerGas: async () => (await getGasPrice()).fast,\n // Single prepare pass: viem resolves gas estimation via\n // `getAction(client, estimateUserOperationGas, ...)`, so handing\n // `prepareUserOperation` a client whose estimate action buffers the\n // result makes the buffered limits flow into getPaymasterData\n // before signing — the sponsorship signature commits to them.\n prepareUserOperation: (prepareClient, prepareParameters) => {\n const bufferingClient = {\n ...prepareClient,\n estimateUserOperationGas: async (\n estimateParameters: EstimateUserOperationGasParameters,\n ) =>\n bufferPolyesterUserOperationGas(\n await estimateUserOperationGas(prepareClient, estimateParameters),\n ),\n };\n return prepareUserOperation(\n bufferingClient as typeof prepareClient,\n prepareParameters as Parameters<typeof prepareUserOperation>[1],\n );\n },\n },\n });\n smartAccountClientPrimers.set(client, () => Promise.allSettled([getGasPrice()]));\n smartAccountClientCacheResets.set(client, () => {\n gasPrice.clear();\n });\n return client;\n}\n\n/** Memoizes a promise-returning fetch for `ttlMs`; a rejected fetch is not cached. */\nfunction cachedForTtl<T>(\n fetch: () => Promise<T>,\n ttlMs: number,\n): { get: () => Promise<T>; clear: () => void } {\n let cached: { fetchedAt: number; result: Promise<T> } | undefined;\n return {\n get: () => {\n if (!cached || Date.now() - cached.fetchedAt >= ttlMs) {\n const entry = { fetchedAt: Date.now(), result: fetch() };\n cached = entry;\n entry.result.catch(() => {\n if (cached === entry) cached = undefined;\n });\n }\n return cached.result;\n },\n clear: () => {\n cached = undefined;\n },\n };\n}\n\nfunction addUserOperationGasBuffer(gas: bigint): bigint {\n const percentBuffer = (gas * USER_OPERATION_GAS_BUFFER_BPS) / 10_000n;\n return (\n gas +\n (percentBuffer > USER_OPERATION_MIN_GAS_BUFFER\n ? percentBuffer\n : USER_OPERATION_MIN_GAS_BUFFER)\n );\n}\n\n/**\n * Pads account and paymaster gas limits (+20%, 50k floor) before getPaymasterData.\n */\nfunction bufferPolyesterUserOperationGas<\n T extends {\n callGasLimit?: bigint;\n preVerificationGas?: bigint;\n verificationGasLimit?: bigint;\n paymasterPostOpGasLimit?: bigint;\n paymasterVerificationGasLimit?: bigint;\n },\n>(gas: T): T {\n return {\n ...gas,\n ...(typeof gas.callGasLimit === \"bigint\"\n ? { callGasLimit: addUserOperationGasBuffer(gas.callGasLimit) }\n : {}),\n ...(typeof gas.preVerificationGas === \"bigint\"\n ? { preVerificationGas: addUserOperationGasBuffer(gas.preVerificationGas) }\n : {}),\n ...(typeof gas.verificationGasLimit === \"bigint\"\n ? { verificationGasLimit: addUserOperationGasBuffer(gas.verificationGasLimit) }\n : {}),\n ...(typeof gas.paymasterPostOpGasLimit === \"bigint\"\n ? { paymasterPostOpGasLimit: addUserOperationGasBuffer(gas.paymasterPostOpGasLimit) }\n : {}),\n ...(typeof gas.paymasterVerificationGasLimit === \"bigint\"\n ? {\n paymasterVerificationGasLimit: addUserOperationGasBuffer(\n gas.paymasterVerificationGasLimit,\n ),\n }\n : {}),\n };\n}\n\n/**\n * Warms the network path for an upcoming submission: primes the gas-price\n * cache and opens connections to the RPC endpoint. Never\n * throws; the nonce is intentionally not cached — fetching it here is\n * connection warm-up only.\n */\nexport async function warmPolyesterSmartAccountClient(\n client: PolyesterSmartAccountClient,\n): Promise<void> {\n await Promise.allSettled([\n smartAccountClientPrimers.get(client)?.(),\n client.account.getNonce(),\n client.account.isDeployed(),\n ]);\n}\n\nexport type PolyesterUserOperationPhase = \"prepare\" | \"sign\" | \"send\" | \"receipt\";\n\nexport interface SendPolyesterUserOperationOptions {\n /**\n * Fires once per submission, immediately before the wallet is asked to\n * sign the fully prepared operation — the prepare→sign boundary.\n */\n onWalletSignatureRequested?: () => void;\n /**\n * Reports how long each submission phase took. `prepare` covers nonce,\n * fees and sponsorship; `sign` the wallet signature; `send`\n * `eth_sendUserOperation`. Pass the same callback to\n * {@link waitForPolyesterUserOperationReceipt} to get `receipt`.\n */\n onPhase?: (phase: PolyesterUserOperationPhase, ms: number) => void;\n}\n\nexport async function sendPolyesterUserOperation(\n client: PolyesterSmartAccountClient,\n parameters: Parameters<PolyesterSmartAccountClient[\"sendUserOperation\"]>[0],\n options: SendPolyesterUserOperationOptions = {},\n): Promise<Awaited<ReturnType<PolyesterSmartAccountClient[\"sendUserOperation\"]>>> {\n const { onWalletSignatureRequested, onPhase } = options;\n const account =\n (parameters as { account?: SafeSmartAccountInstance }).account ?? client.account;\n let phaseStartedAt = Date.now();\n const endPhase = (phase: PolyesterUserOperationPhase) => {\n const now = Date.now();\n reportPhase(onPhase, phase, now - phaseStartedAt);\n phaseStartedAt = now;\n };\n let signedUserOperation: UserOperation | undefined;\n try {\n const hash = await client.sendUserOperation({\n ...parameters,\n account: {\n ...account,\n signUserOperation: async (\n userOperation: Parameters<SafeSmartAccountInstance[\"signUserOperation\"]>[0],\n ) => {\n endPhase(\"prepare\");\n onWalletSignatureRequested?.();\n const signature = await account.signUserOperation(userOperation);\n signedUserOperation = userOperation as UserOperation;\n endPhase(\"sign\");\n return signature;\n },\n },\n } as Parameters<PolyesterSmartAccountClient[\"sendUserOperation\"]>[0]);\n endPhase(\"send\");\n return hash;\n } catch (error) {\n const userOperation = signedUserOperation;\n if (!userOperation) throw error;\n // The operation's hash is deterministic, so in both cases below the\n // caller can wait on it rather than sign a second operation.\n const userOpHash = () =>\n getUserOperationHash({\n chainId: client.chain.id,\n entryPointAddress: account.entryPoint.address,\n entryPointVersion: account.entryPoint.version,\n userOperation,\n });\n // \"Already known\": this exact operation is already in the bundler's\n // mempool (e.g. a replayed send).\n if (isAlreadyKnownError(error)) {\n const hash = userOpHash();\n throw new UserOperationAlreadyKnownError(\n `UserOperation ${hash} is already pending.`,\n hash,\n { cause: error },\n );\n }\n // A timeout leaves the outcome unknown: the bundler may have accepted\n // the operation after the deadline. It says nothing about the gas price.\n if (isTimeoutError(error)) {\n const hash = userOpHash();\n throw new UserOperationSendTimeoutError(\n `Sending UserOperation ${hash} timed out; it may still be pending.`,\n hash,\n { cause: error },\n );\n }\n // Only a failure after signing (i.e. from `eth_sendUserOperation`) can\n // mean the bundler rejected the cached gas price. Earlier\n // failures — a canceled wallet prompt above all — keep the cache so\n // the retry stays cheap.\n smartAccountClientCacheResets.get(client)?.();\n throw error;\n }\n}\n\nfunction isAlreadyKnownError(error: unknown): boolean {\n return (\n error instanceof BaseError &&\n error.walk((cause) => /\\balready known\\b/iu.test((cause as BaseError).details ?? \"\")) !==\n null\n );\n}\n\nfunction isTimeoutError(error: unknown): boolean {\n return (\n error instanceof BaseError && error.walk((cause) => cause instanceof TimeoutError) !== null\n );\n}\n\n/** Observers must never affect the result: a throwing `onPhase` is swallowed. */\nfunction reportPhase(\n onPhase: SendPolyesterUserOperationOptions[\"onPhase\"],\n phase: PolyesterUserOperationPhase,\n ms: number,\n): void {\n try {\n onPhase?.(phase, ms);\n } catch {\n // ignore\n }\n}\n\nexport interface WaitForPolyesterUserOperationReceiptOptions {\n /** Overall deadline in milliseconds. Defaults to viem's 120s. */\n timeoutMs?: number;\n /** Receives `(\"receipt\", ms)` once the receipt is available. */\n onPhase?: SendPolyesterUserOperationOptions[\"onPhase\"];\n}\n\n/**\n * Waits for a UserOperation to land. Polls the bundler's cheap\n * `pimlico_getUserOperationStatus` at the client's polling interval, checking\n * immediately, and only fetches the receipt once the bundler reports it has\n * been mined. Status lives in bundler memory, so `not_found` (e.g. after a\n * bundler restart) also checks the chain for a receipt until the deadline.\n * `timeoutMs` bounds every request, not just the gaps between them.\n */\nexport async function waitForPolyesterUserOperationReceipt(\n client: PolyesterSmartAccountClient,\n hash: `0x${string}`,\n options: WaitForPolyesterUserOperationReceiptOptions = {},\n): Promise<Awaited<ReturnType<PolyesterSmartAccountClient[\"waitForUserOperationReceipt\"]>>> {\n const { timeoutMs = 120_000, onPhase } = options;\n const startedAt = Date.now();\n const deadline = startedAt + timeoutMs;\n const timedOut = () => new Error(`Timed out waiting for UserOperation ${hash}.`);\n const untilDeadline = <T>(fn: () => Promise<T>): Promise<T> => {\n const timeout = deadline - Date.now();\n if (timeout <= 0) return Promise.reject(timedOut());\n return withTimeout(fn, { timeout, errorInstance: timedOut() });\n };\n const statusClient = client as unknown as Parameters<typeof getUserOperationStatus>[0];\n\n let consecutiveNotFound = 0;\n for (;;) {\n const { status } = await untilDeadline(() =>\n getUserOperationStatus(statusClient, { hash }),\n );\n if (status === \"included\" || status === \"reverted\") {\n const receipt = await untilDeadline(() =>\n client.waitForUserOperationReceipt({ hash, timeout: deadline - Date.now() }),\n );\n reportPhase(onPhase, \"receipt\", Date.now() - startedAt);\n return receipt;\n }\n if (status === \"failed\") {\n throw new UserOperationNotExecutedError(\n `UserOperation ${hash} was bundled but the bundle transaction reverted; it was not executed.`,\n hash,\n \"failed\",\n );\n }\n if (status === \"rejected\") {\n // Re-simulation failures are often fee-too-low: drop cached prices.\n smartAccountClientCacheResets.get(client)?.();\n throw new UserOperationNotExecutedError(\n `UserOperation ${hash} was rejected by the bundler; it was not executed.`,\n hash,\n \"rejected\",\n );\n }\n if (status === \"not_found\") {\n if (consecutiveNotFound++ % NOT_FOUND_RECEIPT_CHECK_EVERY === 0) {\n const receipt = await untilDeadline(() =>\n client.getUserOperationReceipt({ hash }),\n ).catch((error: Error) => {\n if (error.name === \"UserOperationReceiptNotFoundError\") return undefined;\n throw error;\n });\n if (receipt) {\n reportPhase(onPhase, \"receipt\", Date.now() - startedAt);\n return receipt;\n }\n }\n } else {\n consecutiveNotFound = 0;\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw timedOut();\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(client.pollingInterval, remaining)),\n );\n }\n}\n"],"mappings":";;;;;;;;;AAuBA,MAAM,sDAAsC,IAAI,QAA0C;AAC1F,MAAM,4CAA4B,IAAI,QAAwC;AAC9E,MAAM,gDAAgC,IAAI,QAA4B;AACtE,MAAM,sCAAsB,IAAI,QAG9B;AACF,MAAM,kCAAkC;AACxC,MAAM,gCAAgC;AACtC,MAAM,gCAAgC;AACtC,MAAM,6CAA6C;;;;;;AAMnD,MAAM,6BAA6B;;;;;;;AAOnC,MAAM,gCAAgC;AAetC,SAAgB,oCAAoC,EAChD,aACA,cACA,YAAY,MACuC;CACnD,MAAM,EACF,yBACA,sBACA,wBACA,uBACA,qBACA,YAAY,mBAAmB;CAEnC,OAAO,mBAAmB;EACtB,QAAQ,CAAC,YAAY;EACrB;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC;AACL;;;;AAKA,eAAsB,4BAA4B,EAC9C,aACA,OACA,WACA,gBAC4D;CAC5D,MAAM,SACF,gBACA,mBAAmB;EACf,OAAO,YAAY;EACnB,WAAW,KAAK,YAAY,MAAM;CACtC,CAAC;CAEL,IAAI,OAAO,OAAO,MAAM,OAAO,MAAM,OAAO,YAAY,MAAM,IAC1D,MAAM,IAAI,MAAM,+DAA+D;CAGnF,MAAM,UAAU,MAAM,mBAAmB;EACrC;EACA,QAAQ,CAAC,KAAK;EACd;EACA,YAAY,YAAY,mBAAmB;EAC3C,GAAG,YAAY,mBAAmB;CACtC,CAAC;CACD,oCAAoC,IAAI,SAAS,YAAY,WAAW;CACxE,OAAO;AACX;;;;;;AAcA,SAAgB,kCACZ,SACA,QAIF;CACE,MAAM,EAAE,aAAa,YAAY;CACjC,MAAM,gCAAgC,oCAAoC,IAAI,OAAO;CACrF,IACI,iCACA,kCAAkC,YAAY,aAE9C,MAAM,IAAI,MAAM,8DAA8D;CAElF,IAAI,UAAU,oBAAoB,IAAI,OAAO;CAC7C,IAAI,CAA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WAAW,KAAK,IAAI,IAAI,SAAS;KACtD,OAAO;IACX;GACJ;SAEA,sBAAsB;EAE1B,MAAM,YAAY,WAAW,KAAK,IAAI;EACtC,IAAI,aAAa,GAAG,MAAM,SAAS;EACnC,MAAM,IAAI,SAAS,YACf,WAAW,SAAS,KAAK,IAAI,OAAO,iBAAiB,SAAS,CAAC,CACnE;CACJ;AACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polyester/sdk",
3
- "version": "0.33.0",
3
+ "version": "0.34.0-devnet-20261105175240",
4
4
  "private": false,
5
5
  "description": "TypeScript SDK providing access to APIs on Polyester Exchange.",
6
6
  "homepage": "https://github.com/Fabric-Labs/polyester-sdk-typescript#readme",