@opensea/sdk 11.1.0 → 11.2.0

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 (61) hide show
  1. package/lib/api/accounts.d.ts +13 -1
  2. package/lib/api/accounts.js +18 -0
  3. package/lib/api/accounts.js.map +1 -1
  4. package/lib/api/api.d.ts +14 -1
  5. package/lib/api/api.js +22 -0
  6. package/lib/api/api.js.map +1 -1
  7. package/lib/api/apiPaths.d.ts +3 -0
  8. package/lib/api/apiPaths.js +13 -1
  9. package/lib/api/apiPaths.js.map +1 -1
  10. package/lib/api/types.d.ts +46 -12
  11. package/lib/auth/index.d.ts +65 -0
  12. package/lib/auth/index.js +168 -0
  13. package/lib/auth/index.js.map +1 -0
  14. package/lib/auth/oauth-types.d.ts +69 -0
  15. package/lib/auth/oauth-types.js +3 -0
  16. package/lib/auth/oauth-types.js.map +1 -0
  17. package/lib/auth/oauth.d.ts +109 -0
  18. package/lib/auth/oauth.js +342 -0
  19. package/lib/auth/oauth.js.map +1 -0
  20. package/lib/auth/types.d.ts +50 -0
  21. package/lib/auth/types.js +3 -0
  22. package/lib/auth/types.js.map +1 -0
  23. package/lib/index.d.ts +7 -1
  24. package/lib/index.js +9 -1
  25. package/lib/index.js.map +1 -1
  26. package/lib/scopes.d.ts +29 -0
  27. package/lib/scopes.js +27 -0
  28. package/lib/scopes.js.map +1 -0
  29. package/lib/sdk/base.d.ts +1 -0
  30. package/lib/sdk/base.js +6 -3
  31. package/lib/sdk/base.js.map +1 -1
  32. package/lib/sdk/cancellation.js +33 -23
  33. package/lib/sdk/cancellation.js.map +1 -1
  34. package/lib/types.d.ts +5 -1
  35. package/lib/types.js +1 -0
  36. package/lib/types.js.map +1 -1
  37. package/lib/utils/chain.d.ts +1 -1
  38. package/lib/utils/chain.js +29 -5
  39. package/lib/utils/chain.js.map +1 -1
  40. package/lib/utils/chainIds.generated.js +1 -0
  41. package/lib/utils/chainIds.generated.js.map +1 -1
  42. package/lib/viem.d.ts +1 -0
  43. package/lib/viem.js +1 -0
  44. package/lib/viem.js.map +1 -1
  45. package/package.json +2 -2
  46. package/src/api/accounts.ts +41 -0
  47. package/src/api/api.ts +36 -0
  48. package/src/api/apiPaths.ts +12 -0
  49. package/src/api/types.ts +51 -11
  50. package/src/auth/index.ts +230 -0
  51. package/src/auth/oauth-types.ts +73 -0
  52. package/src/auth/oauth.ts +428 -0
  53. package/src/auth/types.ts +55 -0
  54. package/src/index.ts +10 -0
  55. package/src/scopes.ts +39 -0
  56. package/src/sdk/base.ts +6 -4
  57. package/src/sdk/cancellation.ts +39 -25
  58. package/src/types.ts +4 -0
  59. package/src/utils/chain.ts +36 -5
  60. package/src/utils/chainIds.generated.ts +1 -0
  61. package/src/viem.ts +1 -0
@@ -0,0 +1,428 @@
1
+ import type {
2
+ DeviceAuthorizationResponse,
3
+ OAuthDiscoveryDocument,
4
+ OAuthToken,
5
+ OAuthTokenResponse,
6
+ OpenSeaOAuthConfig,
7
+ } from "./oauth-types"
8
+
9
+ const DEFAULT_ISSUER = "https://auth.opensea.io"
10
+
11
+ /** Grant type for the OAuth 2.0 device authorization flow (RFC 8628). */
12
+ const DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"
13
+
14
+ /** Default per-request network timeout for authorization-server calls. */
15
+ const DEFAULT_TIMEOUT_MS = 30_000
16
+
17
+ /**
18
+ * OAuth 2.1 authorization-code + PKCE helper for OpenSea (OS2-33722).
19
+ *
20
+ * Runs the standard flow against the OpenSea authorization server (Zitadel at
21
+ * `auth.opensea.io`) using a public client — no client secret, no private key,
22
+ * no SIWE message signing. This is the same flow spec-compliant MCP clients
23
+ * discover via the MCP server's Protected Resource Metadata, exposed here for
24
+ * programmatic consumers (the CLI's keyless `opensea login` is built on it).
25
+ *
26
+ * Endpoints are resolved from OIDC discovery
27
+ * (`/.well-known/openid-configuration`) rather than hardcoded.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * const oauth = new OpenSeaOAuth({ clientId: "..." })
32
+ *
33
+ * // Authorization code + PKCE (browser-capable environments)
34
+ * const req = await oauth.createAuthorizationRequest({
35
+ * redirectUri: "http://127.0.0.1:8151/callback",
36
+ * scopes: ["read:eligibility"],
37
+ * })
38
+ * // ...direct the user to req.url, receive `code` + `state` on the redirect...
39
+ * const token = await oauth.exchangeCode({
40
+ * code,
41
+ * codeVerifier: req.codeVerifier,
42
+ * redirectUri: "http://127.0.0.1:8151/callback",
43
+ * })
44
+ *
45
+ * // Device flow (headless environments)
46
+ * const device = await oauth.requestDeviceAuthorization()
47
+ * // ...show device.user_code + device.verification_uri to the user...
48
+ * const token2 = await oauth.pollDeviceToken(device)
49
+ * ```
50
+ *
51
+ * @category Authentication
52
+ */
53
+ export class OpenSeaOAuth {
54
+ private readonly issuer: string
55
+ private readonly clientId: string
56
+ private readonly timeoutMs: number
57
+ private discovery: OAuthDiscoveryDocument | undefined
58
+
59
+ constructor(config: OpenSeaOAuthConfig) {
60
+ if (!config.clientId) {
61
+ throw new Error("OpenSeaOAuth requires a clientId")
62
+ }
63
+ const issuer = (config.issuer ?? DEFAULT_ISSUER).replace(/\/+$/, "")
64
+ assertSecureUrl(issuer, "issuer")
65
+ this.issuer = issuer
66
+ this.clientId = config.clientId
67
+ this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS
68
+ }
69
+
70
+ /**
71
+ * Fetch (and cache) the OIDC discovery document for the issuer, then
72
+ * validate it: the advertised `issuer` must match the configured issuer
73
+ * (OpenID Connect Discovery §4.3 / OAuth 2.1 mix-up defense) and the
74
+ * authorization/token endpoints must be secure (`https:`, or loopback for
75
+ * local testing). This prevents a compromised discovery response from
76
+ * redirecting the flow to an attacker-controlled endpoint.
77
+ */
78
+ async getDiscovery(): Promise<OAuthDiscoveryDocument> {
79
+ if (this.discovery) return this.discovery
80
+ const response = await this.fetchWithTimeout(
81
+ `${this.issuer}/.well-known/openid-configuration`,
82
+ { headers: { Accept: "application/json" } },
83
+ )
84
+ if (!response.ok) {
85
+ throw new Error(
86
+ `OAuth discovery failed (${response.status}): ${response.statusText}`,
87
+ )
88
+ }
89
+ const discovery = (await response.json()) as OAuthDiscoveryDocument
90
+ const advertisedIssuer = discovery.issuer?.replace(/\/+$/, "")
91
+ if (advertisedIssuer !== this.issuer) {
92
+ throw new Error(
93
+ `OAuth discovery issuer mismatch: expected ${this.issuer}, got ${discovery.issuer}`,
94
+ )
95
+ }
96
+ assertSecureUrl(discovery.authorization_endpoint, "authorization_endpoint")
97
+ assertSecureUrl(discovery.token_endpoint, "token_endpoint")
98
+ this.discovery = discovery
99
+ return discovery
100
+ }
101
+
102
+ /**
103
+ * Build an authorization request for the code + PKCE flow. Returns the URL
104
+ * to open in a browser plus the `codeVerifier` and `state` the caller must
105
+ * hold on to for {@link exchangeCode} and redirect validation.
106
+ */
107
+ async createAuthorizationRequest(options: {
108
+ redirectUri: string
109
+ scopes?: string[]
110
+ }): Promise<{ url: string; codeVerifier: string; state: string }> {
111
+ const discovery = await this.getDiscovery()
112
+ const codeVerifier = randomUrlSafeString(64)
113
+ const state = randomUrlSafeString(32)
114
+ const codeChallenge = await sha256Base64Url(codeVerifier)
115
+
116
+ const url = new URL(discovery.authorization_endpoint)
117
+ url.searchParams.set("response_type", "code")
118
+ url.searchParams.set("client_id", this.clientId)
119
+ url.searchParams.set("redirect_uri", options.redirectUri)
120
+ url.searchParams.set("scope", buildScopeParam(options.scopes))
121
+ url.searchParams.set("state", state)
122
+ url.searchParams.set("code_challenge", codeChallenge)
123
+ url.searchParams.set("code_challenge_method", "S256")
124
+
125
+ return { url: url.toString(), codeVerifier, state }
126
+ }
127
+
128
+ /** Exchange an authorization code (plus PKCE verifier) for tokens. */
129
+ async exchangeCode(options: {
130
+ code: string
131
+ codeVerifier: string
132
+ redirectUri: string
133
+ }): Promise<OAuthToken> {
134
+ const discovery = await this.getDiscovery()
135
+ const response = await this.postToken(discovery.token_endpoint, {
136
+ grant_type: "authorization_code",
137
+ code: options.code,
138
+ code_verifier: options.codeVerifier,
139
+ redirect_uri: options.redirectUri,
140
+ client_id: this.clientId,
141
+ })
142
+ return toOAuthToken(response)
143
+ }
144
+
145
+ /** Refresh an access token using a refresh token. */
146
+ async refresh(refreshToken: string): Promise<OAuthToken> {
147
+ const discovery = await this.getDiscovery()
148
+ const response = await this.postToken(discovery.token_endpoint, {
149
+ grant_type: "refresh_token",
150
+ refresh_token: refreshToken,
151
+ client_id: this.clientId,
152
+ })
153
+ return toOAuthToken(response)
154
+ }
155
+
156
+ /** Revoke an access or refresh token. */
157
+ async revoke(token: string): Promise<void> {
158
+ const discovery = await this.getDiscovery()
159
+ if (!discovery.revocation_endpoint) {
160
+ throw new Error("Authorization server does not support revocation")
161
+ }
162
+ assertSecureUrl(discovery.revocation_endpoint, "revocation_endpoint")
163
+ const response = await this.fetchWithTimeout(
164
+ discovery.revocation_endpoint,
165
+ {
166
+ method: "POST",
167
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
168
+ body: new URLSearchParams({ token, client_id: this.clientId }),
169
+ },
170
+ )
171
+ if (!response.ok) {
172
+ throw new Error(
173
+ `Token revocation failed (${response.status}): ${response.statusText}`,
174
+ )
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Start a device authorization flow (RFC 8628) — for headless environments
180
+ * where a browser redirect is not possible.
181
+ */
182
+ async requestDeviceAuthorization(options?: {
183
+ scopes?: string[]
184
+ }): Promise<DeviceAuthorizationResponse> {
185
+ const discovery = await this.getDiscovery()
186
+ if (!discovery.device_authorization_endpoint) {
187
+ throw new Error(
188
+ "Authorization server does not support the device authorization flow",
189
+ )
190
+ }
191
+ assertSecureUrl(
192
+ discovery.device_authorization_endpoint,
193
+ "device_authorization_endpoint",
194
+ )
195
+ const response = await this.fetchWithTimeout(
196
+ discovery.device_authorization_endpoint,
197
+ {
198
+ method: "POST",
199
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
200
+ body: new URLSearchParams({
201
+ client_id: this.clientId,
202
+ scope: buildScopeParam(options?.scopes),
203
+ }),
204
+ },
205
+ )
206
+ if (!response.ok) {
207
+ throw new Error(
208
+ `Device authorization failed (${response.status}): ${response.statusText}`,
209
+ )
210
+ }
211
+ return (await response.json()) as DeviceAuthorizationResponse
212
+ }
213
+
214
+ /**
215
+ * Poll the token endpoint until the user completes device authorization.
216
+ * Respects the server-provided `interval` and `slow_down` responses, and
217
+ * stops when `expires_in` elapses.
218
+ */
219
+ async pollDeviceToken(
220
+ device: DeviceAuthorizationResponse,
221
+ ): Promise<OAuthToken> {
222
+ const discovery = await this.getDiscovery()
223
+ const deadline = Date.now() + device.expires_in * 1000
224
+ let intervalMs = (device.interval ?? 5) * 1000
225
+
226
+ // Poll first, then sleep between attempts: the user may complete
227
+ // authorization quickly, so waiting a full interval before the first
228
+ // poll only adds latency.
229
+ while (Date.now() < deadline) {
230
+ const response = await this.fetchWithTimeout(discovery.token_endpoint, {
231
+ method: "POST",
232
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
233
+ body: new URLSearchParams({
234
+ grant_type: DEVICE_GRANT_TYPE,
235
+ device_code: device.device_code,
236
+ client_id: this.clientId,
237
+ }),
238
+ })
239
+ if (response.ok) {
240
+ return toOAuthToken((await response.json()) as OAuthTokenResponse)
241
+ }
242
+ const body = (await response.json().catch(() => ({}))) as {
243
+ error?: string
244
+ }
245
+ if (body.error === "slow_down") {
246
+ intervalMs += 5000
247
+ } else if (body.error !== "authorization_pending") {
248
+ throw new Error(
249
+ `Device authorization failed: ${body.error ?? response.status}`,
250
+ )
251
+ }
252
+ await sleep(intervalMs)
253
+ }
254
+ throw new Error("Device authorization timed out")
255
+ }
256
+
257
+ private async postToken(
258
+ tokenEndpoint: string,
259
+ params: Record<string, string>,
260
+ ): Promise<OAuthTokenResponse> {
261
+ const response = await this.fetchWithTimeout(tokenEndpoint, {
262
+ method: "POST",
263
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
264
+ body: new URLSearchParams(params),
265
+ })
266
+ if (!response.ok) {
267
+ const body = await response.text().catch(() => "")
268
+ throw new Error(
269
+ `Token request failed (${response.status}): ${body || response.statusText}`,
270
+ )
271
+ }
272
+ return (await response.json()) as OAuthTokenResponse
273
+ }
274
+
275
+ /**
276
+ * `fetch` wrapper that aborts the request after `this.timeoutMs`, so a hung
277
+ * authorization server can't stall the flow indefinitely.
278
+ */
279
+ private async fetchWithTimeout(
280
+ input: string,
281
+ init: RequestInit,
282
+ ): Promise<Response> {
283
+ const controller = new AbortController()
284
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs)
285
+ try {
286
+ return await fetch(input, { ...init, signal: controller.signal })
287
+ } catch (error) {
288
+ // Detect our own timeout via the controller rather than the error type:
289
+ // an aborted fetch rejects with a `DOMException` in browsers (not always
290
+ // `instanceof Error`) and an `AbortError` in Node, so `signal.aborted`
291
+ // is the portable signal.
292
+ if (controller.signal.aborted) {
293
+ throw new Error(
294
+ `OAuth request to ${input} timed out after ${this.timeoutMs}ms`,
295
+ )
296
+ }
297
+ throw error
298
+ } finally {
299
+ clearTimeout(timer)
300
+ }
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Assert a URL is safe to use as an OAuth endpoint: `https:`, or an `http:`
306
+ * loopback address (`127.0.0.1`/`localhost`/`[::1]`) to support local testing.
307
+ */
308
+ function assertSecureUrl(value: string | undefined, label: string): void {
309
+ let url: URL
310
+ try {
311
+ url = new URL(value ?? "")
312
+ } catch {
313
+ throw new Error(`OAuth ${label} is not a valid URL: ${value}`)
314
+ }
315
+ const isLoopback =
316
+ url.hostname === "127.0.0.1" ||
317
+ url.hostname === "localhost" ||
318
+ url.hostname === "[::1]" ||
319
+ url.hostname === "::1"
320
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopback)) {
321
+ throw new Error(
322
+ `OAuth ${label} must use https (or http on loopback): ${value}`,
323
+ )
324
+ }
325
+ }
326
+
327
+ /**
328
+ * OIDC scopes requested alongside OpenSea scopes: `openid` for an ID token
329
+ * and `offline_access` for a refresh token.
330
+ */
331
+ const BASE_OIDC_SCOPES = ["openid", "offline_access"]
332
+
333
+ function buildScopeParam(scopes?: string[]): string {
334
+ return [...BASE_OIDC_SCOPES, ...(scopes ?? [])].join(" ")
335
+ }
336
+
337
+ /** Fallback access-token lifetime when the server omits `expires_in`. */
338
+ const DEFAULT_EXPIRES_IN_SECONDS = 3600
339
+
340
+ function toOAuthToken(response: OAuthTokenResponse): OAuthToken {
341
+ const expiresIn =
342
+ typeof response.expires_in === "number" &&
343
+ Number.isFinite(response.expires_in)
344
+ ? response.expires_in
345
+ : DEFAULT_EXPIRES_IN_SECONDS
346
+ return {
347
+ accessToken: response.access_token,
348
+ refreshToken: response.refresh_token,
349
+ idToken: response.id_token,
350
+ expiresAt: new Date(Date.now() + expiresIn * 1000),
351
+ scopes: response.scope ? response.scope.split(" ") : [],
352
+ }
353
+ }
354
+
355
+ /**
356
+ * Read the wallet address from decoded JWT claims. Zitadel injects it as a
357
+ * top-level `wallet` claim (plaintext) via the `inject_wallet_claim` action —
358
+ * the same claim `opensea-mcp` and the os2-core REST API read. `sub` is the
359
+ * fallback identifier (the Zitadel account id) when no wallet claim is present.
360
+ * Returns `undefined` if neither is available.
361
+ */
362
+ export function extractWalletAddress(
363
+ claims: Record<string, unknown>,
364
+ ): string | undefined {
365
+ if (typeof claims.wallet === "string" && claims.wallet.length > 0) {
366
+ return claims.wallet
367
+ }
368
+ if (typeof claims.sub === "string" && claims.sub.length > 0) {
369
+ return claims.sub
370
+ }
371
+ return undefined
372
+ }
373
+
374
+ /**
375
+ * Decode a JWT payload without verifying the signature. Intended for reading
376
+ * claims out of a token the authorization server just issued to us over TLS —
377
+ * NOT for validating inbound tokens.
378
+ */
379
+ export function decodeJwtPayload(token: string): Record<string, unknown> {
380
+ const parts = token.split(".")
381
+ if (parts.length !== 3) {
382
+ throw new Error("Not a JWT")
383
+ }
384
+ // JWT segments are base64url without padding; restore `+`/`/` and re-pad
385
+ // to a multiple of 4 so `atob` (which is strict about length) won't throw.
386
+ const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/")
387
+ const padded = base64.padEnd(
388
+ base64.length + ((4 - (base64.length % 4)) % 4),
389
+ "=",
390
+ )
391
+ const json =
392
+ typeof atob === "function"
393
+ ? new TextDecoder().decode(
394
+ Uint8Array.from(atob(padded), c => c.charCodeAt(0)),
395
+ )
396
+ : Buffer.from(padded, "base64").toString("utf-8")
397
+ return JSON.parse(json) as Record<string, unknown>
398
+ }
399
+
400
+ function randomUrlSafeString(byteLength: number): string {
401
+ const bytes = new Uint8Array(byteLength)
402
+ crypto.getRandomValues(bytes)
403
+ return base64UrlEncode(bytes)
404
+ }
405
+
406
+ async function sha256Base64Url(value: string): Promise<string> {
407
+ const digest = await crypto.subtle.digest(
408
+ "SHA-256",
409
+ new TextEncoder().encode(value),
410
+ )
411
+ return base64UrlEncode(new Uint8Array(digest))
412
+ }
413
+
414
+ function base64UrlEncode(bytes: Uint8Array): string {
415
+ let binary = ""
416
+ for (const b of bytes) {
417
+ binary += String.fromCharCode(b)
418
+ }
419
+ const base64 =
420
+ typeof btoa === "function"
421
+ ? btoa(binary)
422
+ : Buffer.from(bytes).toString("base64")
423
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")
424
+ }
425
+
426
+ function sleep(ms: number): Promise<void> {
427
+ return new Promise(resolve => setTimeout(resolve, ms))
428
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * A scoped JWT token returned by the auth server.
3
+ */
4
+ export interface AuthToken {
5
+ /** JWT access token */
6
+ accessToken: string
7
+ /** Refresh token for obtaining a new access token */
8
+ refreshToken: string
9
+ /** When the access token expires */
10
+ expiresAt: Date
11
+ /** Scopes granted to this token */
12
+ scopes: string[]
13
+ }
14
+
15
+ /**
16
+ * Options for the {@link OpenSeaAuth.authenticate} method.
17
+ */
18
+ export interface AuthenticateOptions {
19
+ /** Scopes to request (e.g. `["read:eligibility", "write:orders"]`) */
20
+ scopes?: string[]
21
+ }
22
+
23
+ /**
24
+ * Configuration for the {@link OpenSeaAuth} class.
25
+ */
26
+ export interface OpenSeaAuthConfig {
27
+ /** Auth server base URL. Defaults to `https://auth.opensea.io`. */
28
+ authBaseUrl?: string
29
+ }
30
+
31
+ /**
32
+ * Signer interface compatible with both ethers and viem signers.
33
+ * Requires `getAddress()` and `signMessage(message)`.
34
+ */
35
+ export interface AuthSigner {
36
+ getAddress(): Promise<string>
37
+ signMessage(message: string): Promise<string>
38
+ }
39
+
40
+ /**
41
+ * Raw token response from the auth server `/api/token` and `/api/refresh` endpoints.
42
+ */
43
+ export interface AuthTokenResponse {
44
+ access_token: string
45
+ refresh_token: string
46
+ expires_in: number
47
+ scopes: string[]
48
+ }
49
+
50
+ /**
51
+ * Nonce response from the auth server `/api/nonce` endpoint.
52
+ */
53
+ export interface AuthNonceResponse {
54
+ nonce: string
55
+ }
package/src/index.ts CHANGED
@@ -1,7 +1,12 @@
1
1
  import { OpenSeaAPI } from "./api/api"
2
+ import { OpenSeaAuth } from "./auth"
3
+ import { OpenSeaOAuth } from "./auth/oauth"
2
4
  import { OpenSeaSDK } from "./sdk"
3
5
 
4
6
  export * from "./api/types"
7
+ export * from "./auth"
8
+ export * from "./auth/oauth"
9
+ export * from "./auth/oauth-types"
5
10
  export * from "./constants"
6
11
  export * from "./orders/types"
7
12
  export type {
@@ -11,6 +16,7 @@ export type {
11
16
  OpenSeaWallet,
12
17
  TransactionResponse,
13
18
  } from "./provider/types"
19
+ export * from "./scopes"
14
20
  export * from "./types"
15
21
  export * from "./utils"
16
22
  /**
@@ -29,6 +35,10 @@ export {
29
35
  // API client (for direct use or accessing static helpers like
30
36
  // `OpenSeaAPI.requestInstantApiKey()`)
31
37
  OpenSeaAPI,
38
+ // Auth helper for SIWE-based wallet authentication
39
+ OpenSeaAuth,
40
+ // OAuth 2.1 (code + PKCE / device) helper for keyless login
41
+ OpenSeaOAuth,
32
42
  // Main SDK export
33
43
  OpenSeaSDK,
34
44
  }
package/src/scopes.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { AuthScope } from "@opensea/api-types"
2
+
3
+ /**
4
+ * OAuth-style scopes recognized by the OpenSea API.
5
+ *
6
+ * The set of valid scopes is defined by the `AuthScope` schema in the
7
+ * OpenAPI spec (via `@opensea/api-types`). The compile-time assertions
8
+ * below fail the build if this runtime constant drifts from the spec
9
+ * in either direction.
10
+ * @category Auth
11
+ */
12
+ export const OPENSEA_SCOPES = {
13
+ READ_ELIGIBILITY: "read:eligibility",
14
+ READ_FAVORITES: "read:favorites",
15
+ READ_REWARDS: "read:rewards",
16
+ WRITE_ORDERS: "write:orders",
17
+ WRITE_DROPS: "write:drops",
18
+ WRITE_WALLETS: "write:wallets",
19
+ } as const satisfies Record<string, AuthScope>
20
+
21
+ /**
22
+ * Union of all valid OpenSea API scope strings, derived from the
23
+ * OpenAPI spec's `AuthScope` schema.
24
+ * @category Auth
25
+ */
26
+ export type OpenSeaScope = AuthScope
27
+
28
+ type _AssertAllAuthScopesCovered =
29
+ AuthScope extends (typeof OPENSEA_SCOPES)[keyof typeof OPENSEA_SCOPES]
30
+ ? true
31
+ : never
32
+
33
+ const _assertAllAuthScopesCovered: _AssertAllAuthScopesCovered = true
34
+
35
+ /**
36
+ * All OpenSea API scopes as a readonly list.
37
+ * @category Auth
38
+ */
39
+ export const ALL_SCOPES: readonly OpenSeaScope[] = Object.values(OPENSEA_SCOPES)
package/src/sdk/base.ts CHANGED
@@ -585,15 +585,17 @@ export class BaseOpenSeaSDK {
585
585
  }
586
586
  }
587
587
 
588
- const amountWei = parseUnits(amount.toString(), decimals)
589
- const basePrice = amountWei
590
-
591
- if (amount == null || amountWei < 0) {
588
+ if (amount == null) {
592
589
  throw new Error("Starting price must be a number >= 0")
593
590
  }
594
591
  if (isEther && orderSide === OrderSide.OFFER) {
595
592
  throw new Error("Offers must use wrapped ETH or an ERC-20 token.")
596
593
  }
594
+ const amountWei = parseUnits(amount.toString(), decimals)
595
+ const basePrice = amountWei
596
+ if (amountWei < 0) {
597
+ throw new Error("Starting price must be a number >= 0")
598
+ }
597
599
  return { basePrice }
598
600
  }
599
601
 
@@ -167,39 +167,35 @@ export class CancellationManager {
167
167
  throw new Error("At least one order hash must be provided")
168
168
  }
169
169
 
170
- requireValidProtocol(protocolAddress)
170
+ let orderComponents: OrderComponents[]
171
+ const protocolAddresses = new Set<string>()
172
+ let firstOrderV2: OrderV2 | undefined
173
+ let firstFetchedOrder: Offer | Listing | undefined
171
174
 
172
- // Check account availability after parameter validation
173
- await this.context.requireAccountIsAvailable(accountAddress)
175
+ requireValidProtocol(protocolAddress)
174
176
 
175
- let orderComponents: OrderComponents[]
176
- let effectiveProtocolAddress = protocolAddress
177
+ const addProtocolAddress = (value: string) => {
178
+ requireValidProtocol(value)
179
+ protocolAddresses.add(value)
180
+ }
177
181
 
178
182
  if (orders) {
179
183
  // Extract OrderComponents from either OrderV2 objects or use OrderComponents directly
180
- let firstOrderV2: OrderV2 | undefined
181
184
  orderComponents = orders.map(order => {
182
185
  if ("protocolData" in order) {
183
186
  // It's an OrderV2 object
184
187
  const orderV2 = order as OrderV2
185
- requireValidProtocol(orderV2.protocolAddress)
186
- effectiveProtocolAddress = orderV2.protocolAddress
188
+ addProtocolAddress(orderV2.protocolAddress)
187
189
  if (!firstOrderV2) {
188
190
  firstOrderV2 = orderV2
189
191
  }
190
192
  return orderV2.protocolData.parameters
191
193
  } else {
192
194
  // It's already OrderComponents
195
+ addProtocolAddress(protocolAddress)
193
196
  return order as OrderComponents
194
197
  }
195
198
  })
196
- // Dispatch event for the first OrderV2 if available
197
- if (firstOrderV2) {
198
- this.context.dispatch(EventType.CancelOrder, {
199
- orderV2: firstOrderV2,
200
- accountAddress,
201
- })
202
- }
203
199
  } else if (orderHashes) {
204
200
  // Fetch orders from the API using order hashes
205
201
  const fetchedOrders: (Offer | Listing)[] = []
@@ -219,23 +215,41 @@ export class CancellationManager {
219
215
  `Order ${fetched.orderHash} is missing protocolAddress or protocolData — cannot cancel.`,
220
216
  )
221
217
  }
222
- requireValidProtocol(fetched.protocolAddress)
223
- effectiveProtocolAddress = fetched.protocolAddress
218
+ addProtocolAddress(fetched.protocolAddress)
224
219
  return fetched.protocolData.parameters
225
220
  })
226
-
227
- // Dispatch event for the first fetched order
228
- if (fetchedOrders.length > 0) {
229
- this.context.dispatch(EventType.CancelOrder, {
230
- order: fetchedOrders[0],
231
- accountAddress,
232
- })
233
- }
221
+ firstFetchedOrder = fetchedOrders[0]
234
222
  } else {
235
223
  // Should never reach here due to earlier validation
236
224
  throw new Error("Invalid input")
237
225
  }
238
226
 
227
+ if (protocolAddresses.size > 1) {
228
+ throw new Error(
229
+ "All orders in a cancelOrders batch must share the same protocolAddress. Cancel each protocol separately.",
230
+ )
231
+ }
232
+
233
+ const effectiveProtocolAddress = protocolAddresses.values().next().value
234
+ if (effectiveProtocolAddress == null) {
235
+ throw new Error("Invalid input")
236
+ }
237
+
238
+ // Check account availability after parameter validation
239
+ await this.context.requireAccountIsAvailable(accountAddress)
240
+
241
+ if (firstOrderV2) {
242
+ this.context.dispatch(EventType.CancelOrder, {
243
+ orderV2: firstOrderV2,
244
+ accountAddress,
245
+ })
246
+ } else if (firstFetchedOrder) {
247
+ this.context.dispatch(EventType.CancelOrder, {
248
+ order: firstFetchedOrder,
249
+ accountAddress,
250
+ })
251
+ }
252
+
239
253
  // Transact and get the transaction hash
240
254
  const transactionHash = await this.cancelSeaportOrders({
241
255
  orders: orderComponents,