@opensea/sdk 12.5.0 → 12.7.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 (50) hide show
  1. package/README.md +53 -0
  2. package/lib/api/api.d.ts +19 -3
  3. package/lib/api/api.js +24 -13
  4. package/lib/api/api.js.map +1 -1
  5. package/lib/api/nfts.d.ts +7 -2
  6. package/lib/api/nfts.js +10 -1
  7. package/lib/api/nfts.js.map +1 -1
  8. package/lib/api/types.d.ts +37 -1
  9. package/lib/api/types.js.map +1 -1
  10. package/lib/auth/index.d.ts +2 -0
  11. package/lib/auth/index.js +13 -10
  12. package/lib/auth/index.js.map +1 -1
  13. package/lib/auth/oauth-types.d.ts +10 -0
  14. package/lib/auth/oauth.d.ts +16 -0
  15. package/lib/auth/oauth.js +61 -22
  16. package/lib/auth/oauth.js.map +1 -1
  17. package/lib/auth/siwx.d.ts +17 -1
  18. package/lib/auth/siwx.js +10 -4
  19. package/lib/auth/siwx.js.map +1 -1
  20. package/lib/auth/types.d.ts +11 -0
  21. package/lib/sdk/base.d.ts +9 -2
  22. package/lib/sdk/base.js +7 -2
  23. package/lib/sdk/base.js.map +1 -1
  24. package/lib/sdk/orders.d.ts +27 -3
  25. package/lib/sdk/orders.js +142 -176
  26. package/lib/sdk/orders.js.map +1 -1
  27. package/lib/types.d.ts +8 -3
  28. package/lib/types.js.map +1 -1
  29. package/lib/utils/case.d.ts +22 -0
  30. package/lib/utils/fetchTransport.d.ts +29 -0
  31. package/lib/utils/fetchTransport.js +26 -0
  32. package/lib/utils/fetchTransport.js.map +1 -0
  33. package/lib/utils/index.d.ts +1 -0
  34. package/lib/utils/index.js +7 -0
  35. package/lib/utils/index.js.map +1 -1
  36. package/package.json +2 -2
  37. package/src/api/api.ts +36 -18
  38. package/src/api/nfts.ts +11 -0
  39. package/src/api/types.ts +43 -0
  40. package/src/auth/index.ts +45 -26
  41. package/src/auth/oauth-types.ts +11 -0
  42. package/src/auth/oauth.ts +70 -26
  43. package/src/auth/siwx.ts +30 -10
  44. package/src/auth/types.ts +12 -0
  45. package/src/sdk/base.ts +8 -1
  46. package/src/sdk/orders.ts +196 -226
  47. package/src/types.ts +9 -3
  48. package/src/utils/case.ts +22 -0
  49. package/src/utils/fetchTransport.ts +36 -0
  50. package/src/utils/index.ts +7 -0
@@ -1,2 +1,3 @@
1
+ export * from "./case";
1
2
  export * from "./dateHelper";
2
3
  export * from "./utils";
@@ -14,6 +14,13 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ // `./case` carries the SDK's response-casing contract: the API speaks
18
+ // snake_case, the SDK hands back camelCase. Consumers need `Camelize` by name
19
+ // to write down the shape of anything they get back whose camelized view has
20
+ // no dedicated alias in this package. Without it the only spelled-out type for
21
+ // such a response is the raw `@opensea/api-types` one, which is the wrong
22
+ // shape at runtime and, for some schemas, still type-checks.
23
+ __exportStar(require("./case"), exports);
17
24
  __exportStar(require("./dateHelper"), exports);
18
25
  __exportStar(require("./utils"), exports);
19
26
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+CAA4B;AAC5B,0CAAuB"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,sEAAsE;AACtE,8EAA8E;AAC9E,6EAA6E;AAC7E,+EAA+E;AAC/E,0EAA0E;AAC1E,6DAA6D;AAC7D,yCAAsB;AACtB,+CAA4B;AAC5B,0CAAuB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opensea/sdk",
3
- "version": "12.5.0",
3
+ "version": "12.7.0",
4
4
  "description": "TypeScript SDK for the OpenSea marketplace helps developers build new experiences using NFTs, tokens, and our marketplace data",
5
5
  "license": "MIT",
6
6
  "author": "OpenSea Developers",
@@ -47,7 +47,7 @@
47
47
  "types": "lib/index.d.ts",
48
48
  "dependencies": {
49
49
  "@noble/hashes": "^2.0.1",
50
- "@opensea/api-types": "^0.10.0",
50
+ "@opensea/api-types": "^0.11.1",
51
51
  "@opensea/seaport-js": "^4.2.0",
52
52
  "ethers": "^6.16.0"
53
53
  },
package/src/api/api.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  camelizeKeysDeep,
18
18
  snakeizeKeysDeep,
19
19
  } from "../utils/case"
20
+ import { type FetchImpl, fetchWith } from "../utils/fetchTransport"
20
21
  import { executeWithRateLimit } from "../utils/rateLimit"
21
22
  import { AccountsAPI } from "./accounts"
22
23
  import { getInstantApiKeyPath } from "./apiPaths"
@@ -87,6 +88,7 @@ import {
87
88
  type GetListingsResponse,
88
89
  type GetNFTMetadataResponse,
89
90
  type GetNFTResponse,
91
+ type GetNFTsByAccountOptions,
90
92
  type GetOffersResponse,
91
93
  type GetOrderByHashResponse,
92
94
  type GetSwapQuoteArgs,
@@ -155,6 +157,15 @@ import { WalletAuthAPI } from "./walletAuth"
155
157
 
156
158
  /**
157
159
  * The API class for the OpenSea SDK.
160
+ *
161
+ * Every method returns the camelCase view of the response. The API sends
162
+ * snake_case, and the `@opensea/api-types` type of the same name describes
163
+ * that wire shape, so annotating a return value here with one of those types
164
+ * leaves every renamed field `undefined` at runtime, while single-word keys
165
+ * survive the rewrite and still read correctly. Use the camelized type this
166
+ * package exports, or `Camelize<WireType>`. {@link RequestOptions.camelizeResponse}
167
+ * turns the rewrite off where the response keys are data rather than field names.
168
+ *
158
169
  * @category Main Classes
159
170
  */
160
171
  export class OpenSeaAPI {
@@ -174,7 +185,7 @@ export class OpenSeaAPI {
174
185
  private apiKey: string | undefined
175
186
  private authToken: string | undefined
176
187
  /** Transport for every instance request. See {@link OpenSeaAPIConfig.fetch}. */
177
- private readonly fetchImpl: typeof globalThis.fetch
188
+ private readonly fetchImpl: FetchImpl | undefined
178
189
  private chain: Chain
179
190
 
180
191
  /**
@@ -209,10 +220,9 @@ export class OpenSeaAPI {
209
220
  * @param logger Optional function for logging debug strings before and after requests are made. Defaults to no logging
210
221
  */
211
222
  constructor(config: OpenSeaAPIConfig, logger?: (arg: string) => void) {
212
- // Read through globalThis rather than captured at construction, so a caller who swaps
213
- // globalThis.fetch afterwards still takes effect.
214
- this.fetchImpl =
215
- config.fetch ?? ((url, init) => globalThis.fetch(url, init))
223
+ // Stored as given, including undefined: fetchWith falls back to globalThis.fetch at call
224
+ // time, so a caller who swaps globalThis.fetch after construction still takes effect.
225
+ this.fetchImpl = config.fetch
216
226
  this.apiKey = config.apiKey
217
227
  this.authToken = config.authToken
218
228
  this.chain = config.chain ?? Chain.Mainnet
@@ -600,6 +610,7 @@ export class OpenSeaAPI {
600
610
  * @param limit The number of NFTs to retrieve. Must be greater than 0 and less than 51.
601
611
  * @param next Cursor to retrieve the next page of NFTs
602
612
  * @param chain The chain to query. Defaults to the chain set in the constructor.
613
+ * @param options Non-pagination filters, currently `includeAutoHidden`.
603
614
  * @returns The {@link ListNFTsResponse} returned by the API.
604
615
  * @deprecated Use `api.nfts.getNFTsByAccount()`. Removed in the next major.
605
616
  */
@@ -608,8 +619,9 @@ export class OpenSeaAPI {
608
619
  limit: number | undefined = undefined,
609
620
  next: string | undefined = undefined,
610
621
  chain = this.chain,
622
+ options?: GetNFTsByAccountOptions,
611
623
  ): Promise<ListNFTsResponse> {
612
- return this.nfts.getNFTsByAccount(address, limit, next, chain)
624
+ return this.nfts.getNFTsByAccount(address, limit, next, chain, options)
613
625
  }
614
626
 
615
627
  /**
@@ -1718,11 +1730,9 @@ export class OpenSeaAPI {
1718
1730
  }
1719
1731
 
1720
1732
  try {
1721
- // .call(globalThis, ...) rather than a plain call: a caller can pass native fetch
1722
- // unbound (`fetch: globalThis.fetch`), and browsers throw "Illegal invocation" when it
1723
- // runs with anything but the global as its receiver. A bound function or an arrow
1724
- // ignores the thisArg, so this does not clobber a deliberately bound transport.
1725
- const response = await this.fetchImpl.call(globalThis, url, {
1733
+ // fetchWith, not a plain call: it supplies the global receiver that unbound native fetch
1734
+ // needs, and falls back to globalThis.fetch when no transport was configured.
1735
+ const response = await fetchWith(this.fetchImpl, url, {
1726
1736
  method,
1727
1737
  headers: mergedHeaders,
1728
1738
  body: body != null ? JSON.stringify(body) : undefined,
@@ -1796,20 +1806,28 @@ export class OpenSeaAPI {
1796
1806
  * ```
1797
1807
  *
1798
1808
  * @param apiBaseUrl Optional base URL override (defaults to mainnet).
1809
+ * @param options Optional `fetch` transport. This is a static method with no instance to read
1810
+ * {@link OpenSeaAPIConfig.fetch} from, so a consumer that routes every request
1811
+ * through its own transport passes it here. Defaults to the global `fetch`.
1799
1812
  * @returns The {@link RequestInstantApiKeyResponse} containing the new key,
1800
1813
  * with response keys camelized to match SDK conventions.
1801
1814
  */
1802
1815
  public static async requestInstantApiKey(
1803
1816
  apiBaseUrl: string = API_BASE_MAINNET,
1817
+ options: { fetch?: FetchImpl } = {},
1804
1818
  ): Promise<RequestInstantApiKeyResponse> {
1805
- const response = await fetch(`${apiBaseUrl}${getInstantApiKeyPath()}`, {
1806
- method: "POST",
1807
- headers: {
1808
- "Content-Type": "application/json",
1809
- "x-app-id": "opensea-js",
1819
+ const response = await fetchWith(
1820
+ options.fetch,
1821
+ `${apiBaseUrl}${getInstantApiKeyPath()}`,
1822
+ {
1823
+ method: "POST",
1824
+ headers: {
1825
+ "Content-Type": "application/json",
1826
+ "x-app-id": "opensea-js",
1827
+ },
1828
+ body: "{}",
1810
1829
  },
1811
- body: "{}",
1812
- })
1830
+ )
1813
1831
  if (!response.ok) {
1814
1832
  throw OpenSeaAPI._createApiError(
1815
1833
  response,
package/src/api/nfts.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  type GetContractResponse,
22
22
  type GetNFTMetadataResponse,
23
23
  type GetNFTResponse,
24
+ type GetNFTsByAccountOptions,
24
25
  type ListNFTsResponse,
25
26
  type NFTOwnersArgs,
26
27
  type NftAnalyticsResponse,
@@ -77,18 +78,28 @@ export class NFTsAPI {
77
78
 
78
79
  /**
79
80
  * Fetch NFTs owned by an account.
81
+ *
82
+ * Pass `options.includeAutoHidden` to also return NFTs that were hidden
83
+ * automatically because a third party minted or sent them to this account.
84
+ * NFTs the account holder hid themselves stay out of the response either
85
+ * way, and this does not surface NFTs removed for policy violations.
80
86
  */
81
87
  async getNFTsByAccount(
82
88
  address: string,
83
89
  limit: number | undefined = undefined,
84
90
  next: string | undefined = undefined,
85
91
  chain = this.chain,
92
+ options?: GetNFTsByAccountOptions,
86
93
  ): Promise<ListNFTsResponse> {
87
94
  const response = await this.fetcher.get<ListNFTsResponse>(
88
95
  getListNFTsByAccountPath(chain, address),
89
96
  {
90
97
  limit,
91
98
  next,
99
+ // Snakeized to `include_auto_hidden` by the fetcher. Left undefined
100
+ // when the caller sets nothing, so the parameter is absent from the
101
+ // URL rather than sent as an explicit false.
102
+ includeAutoHidden: options?.includeAutoHidden,
92
103
  },
93
104
  )
94
105
 
package/src/api/types.ts CHANGED
@@ -49,6 +49,7 @@ import type {
49
49
  NftListResponse,
50
50
  NftResponse,
51
51
  OffersResponse,
52
+ paths,
52
53
  TokenAccountActivityPaginatedResponse,
53
54
  TokenBalancePaginatedResponse,
54
55
  TokenBalanceResponse,
@@ -833,8 +834,27 @@ export interface GetTokensArgs {
833
834
  next?: string
834
835
  /** Filter to these chains */
835
836
  chains?: ChainIdentifier[]
837
+ /**
838
+ * Field to rank by. Defaults to one-day volume on `getTopTokens` and to the trending score on
839
+ * `getTrendingTokens`, which is what each endpoint returned before sorting was exposed.
840
+ */
841
+ sortBy?: TokenRankingSortBy
842
+ /** Sort direction. Defaults to descending. */
843
+ sortDirection?: "asc" | "desc"
836
844
  }
837
845
 
846
+ /**
847
+ * Sort keys the token ranking endpoints accept.
848
+ *
849
+ * Derived from the spec rather than written out, so a key added or removed upstream reaches this
850
+ * union in the same regeneration instead of drifting until someone notices.
851
+ */
852
+ export type TokenRankingSortBy = NonNullable<
853
+ NonNullable<
854
+ paths["/api/v2/tokens/trending"]["get"]["parameters"]["query"]
855
+ >["sort_by"]
856
+ >
857
+
838
858
  /**
839
859
  * Query args for Get Swap Quote endpoint.
840
860
  * @category API Query Args
@@ -1439,6 +1459,29 @@ export interface NFTOwnersArgs {
1439
1459
  next?: string
1440
1460
  }
1441
1461
 
1462
+ /**
1463
+ * Non-pagination options for the NFTs-by-account endpoint.
1464
+ *
1465
+ * Pagination and chain stay positional on `getNFTsByAccount`; this carries
1466
+ * the filters the endpoint has gained since, so later ones can be added
1467
+ * without another positional argument.
1468
+ *
1469
+ * @category API Query Args
1470
+ */
1471
+ export interface GetNFTsByAccountOptions {
1472
+ /**
1473
+ * Include NFTs that were hidden automatically because a third party minted
1474
+ * or sent them to this account. Serialized as `include_auto_hidden`, and
1475
+ * omitted from the request when unset, which leaves the server default of
1476
+ * `false` in place.
1477
+ *
1478
+ * This covers only the automatic hiding. NFTs the account holder hid
1479
+ * themselves are still not returned, and NFTs removed for policy violations
1480
+ * are not surfaced by it either.
1481
+ */
1482
+ includeAutoHidden?: boolean
1483
+ }
1484
+
1442
1485
  /**
1443
1486
  * Query args for the account portfolio and portfolio history endpoints.
1444
1487
  * @category API Query Args
package/src/auth/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type FetchImpl, fetchWith } from "../utils/fetchTransport"
1
2
  import { createSiwxMessage, parseSiwxMessage } from "./siwx"
2
3
  import type {
3
4
  AuthenticateOptions,
@@ -75,6 +76,8 @@ interface ScopedTokenExchangeResponse {
75
76
  */
76
77
  export class OpenSeaAuth {
77
78
  private readonly apiBaseUrl: string
79
+ /** Transport for every request this instance makes. See {@link OpenSeaAuthConfig.fetch}. */
80
+ private readonly fetchImpl: FetchImpl | undefined
78
81
  private cachedToken: AuthToken | undefined
79
82
  private scopedTokenId: string | undefined
80
83
  private sessionCookies: string | undefined
@@ -85,6 +88,9 @@ export class OpenSeaAuth {
85
88
  config.authBaseUrl ??
86
89
  DEFAULT_API_BASE_URL
87
90
  ).replace(/\/$/, "")
91
+ // Stored as given, including undefined: fetchWith falls back to globalThis.fetch at call
92
+ // time, so a caller who swaps globalThis.fetch after construction still takes effect.
93
+ this.fetchImpl = config.fetch
88
94
  }
89
95
 
90
96
  /** Run the current SIWE, scoped-token creation, and token-exchange flow. */
@@ -157,7 +163,8 @@ export class OpenSeaAuth {
157
163
  // The refresh token rotates, so retain the replacement if DELETE needs a
158
164
  // retry after a transient failure.
159
165
  this.sessionCookies = refreshedCookies
160
- const response = await fetch(
166
+ const response = await fetchWith(
167
+ this.fetchImpl,
161
168
  `${this.apiBaseUrl}/api/v2/auth/tokens/${this.scopedTokenId}`,
162
169
  { method: "DELETE", headers: { Cookie: refreshedCookies } },
163
170
  )
@@ -169,10 +176,11 @@ export class OpenSeaAuth {
169
176
 
170
177
  /** Request a single-use SIWE nonce. */
171
178
  async requestNonce(): Promise<AuthNonceResponse> {
172
- const response = await fetch(`${this.apiBaseUrl}/api/v2/auth/siwe/nonce`, {
173
- method: "POST",
174
- headers: { Accept: "application/json" },
175
- })
179
+ const response = await fetchWith(
180
+ this.fetchImpl,
181
+ `${this.apiBaseUrl}/api/v2/auth/siwe/nonce`,
182
+ { method: "POST", headers: { Accept: "application/json" } },
183
+ )
176
184
  await requireOk(response, "Nonce request")
177
185
  return response.json() as Promise<AuthNonceResponse>
178
186
  }
@@ -181,15 +189,19 @@ export class OpenSeaAuth {
181
189
  message: string,
182
190
  signature: string,
183
191
  ): Promise<string> {
184
- const response = await fetch(`${this.apiBaseUrl}/api/v2/auth/siwe/verify`, {
185
- method: "POST",
186
- headers: { "Content-Type": "application/json" },
187
- body: JSON.stringify({
188
- message: parseSiwxMessage(message),
189
- signature,
190
- chainArch: "EVM",
191
- }),
192
- })
192
+ const response = await fetchWith(
193
+ this.fetchImpl,
194
+ `${this.apiBaseUrl}/api/v2/auth/siwe/verify`,
195
+ {
196
+ method: "POST",
197
+ headers: { "Content-Type": "application/json" },
198
+ body: JSON.stringify({
199
+ message: parseSiwxMessage(message),
200
+ signature,
201
+ chainArch: "EVM",
202
+ }),
203
+ },
204
+ )
193
205
  await requireOk(response, "SIWE verification")
194
206
  return extractSessionCookies(response.headers)
195
207
  }
@@ -198,15 +210,19 @@ export class OpenSeaAuth {
198
210
  cookie: string,
199
211
  scopes: string[],
200
212
  ): Promise<ScopedTokenCreatedResponse> {
201
- const response = await fetch(`${this.apiBaseUrl}/api/v2/auth/tokens`, {
202
- method: "POST",
203
- headers: { "Content-Type": "application/json", Cookie: cookie },
204
- body: JSON.stringify({
205
- label: `opensea-sdk-${Date.now()}`,
206
- scopes,
207
- expiresInDays: 1,
208
- }),
209
- })
213
+ const response = await fetchWith(
214
+ this.fetchImpl,
215
+ `${this.apiBaseUrl}/api/v2/auth/tokens`,
216
+ {
217
+ method: "POST",
218
+ headers: { "Content-Type": "application/json", Cookie: cookie },
219
+ body: JSON.stringify({
220
+ label: `opensea-sdk-${Date.now()}`,
221
+ scopes,
222
+ expiresInDays: 1,
223
+ }),
224
+ },
225
+ )
210
226
  await requireOk(response, "Scoped token creation")
211
227
  return response.json() as Promise<ScopedTokenCreatedResponse>
212
228
  }
@@ -214,7 +230,8 @@ export class OpenSeaAuth {
214
230
  private async exchangeScopedToken(
215
231
  scopedToken: string,
216
232
  ): Promise<ScopedTokenExchangeResponse> {
217
- const response = await fetch(
233
+ const response = await fetchWith(
234
+ this.fetchImpl,
218
235
  `${this.apiBaseUrl}/api/v2/auth/tokens/exchange`,
219
236
  {
220
237
  method: "POST",
@@ -232,7 +249,8 @@ export class OpenSeaAuth {
232
249
  private async cleanupScopedToken(cookie: string, id: string): Promise<void> {
233
250
  for (let attempt = 0; attempt < SCOPED_TOKEN_CLEANUP_ATTEMPTS; attempt++) {
234
251
  try {
235
- const response = await fetch(
252
+ const response = await fetchWith(
253
+ this.fetchImpl,
236
254
  `${this.apiBaseUrl}/api/v2/auth/tokens/${id}`,
237
255
  { method: "DELETE", headers: { Cookie: cookie } },
238
256
  )
@@ -244,7 +262,8 @@ export class OpenSeaAuth {
244
262
  }
245
263
 
246
264
  private async refreshSession(cookie: string): Promise<string> {
247
- const response = await fetch(
265
+ const response = await fetchWith(
266
+ this.fetchImpl,
248
267
  `${this.apiBaseUrl}/api/v2/auth/session/refresh`,
249
268
  { method: "POST", headers: { Cookie: cookie } },
250
269
  )
@@ -1,3 +1,5 @@
1
+ import type { FetchImpl } from "../utils/fetchTransport"
2
+
1
3
  /**
2
4
  * Configuration for the {@link OpenSeaOAuth} helper.
3
5
  */
@@ -15,6 +17,15 @@ export interface OpenSeaOAuthConfig {
15
17
  * connection stalling `opensea login` (or an SDK consumer) indefinitely.
16
18
  */
17
19
  timeoutMs?: number
20
+ /**
21
+ * Transport used for every request this instance makes to the authorization server,
22
+ * defaulting to the global `fetch`. Same seam as {@link OpenSeaAPIConfig.fetch}.
23
+ *
24
+ * It sees the PKCE code verifier, the device code and the returned token set, so anything it
25
+ * logs or caches is a credential. The per-request timeout is applied before the transport
26
+ * runs: it receives an init whose `signal` is already the timeout's.
27
+ */
28
+ fetch?: FetchImpl
18
29
  }
19
30
 
20
31
  /**
package/src/auth/oauth.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AUTH_SCOPES } from "@opensea/api-types"
2
+ import { type FetchImpl, fetchWith } from "../utils/fetchTransport"
2
3
  import type {
3
4
  DeviceAuthorizationResponse,
4
5
  OAuthDiscoveryDocument,
@@ -55,6 +56,8 @@ export class OpenSeaOAuth {
55
56
  private readonly issuer: string
56
57
  private readonly clientId: string
57
58
  private readonly timeoutMs: number
59
+ /** Transport for every request this instance makes. See {@link OpenSeaOAuthConfig.fetch}. */
60
+ private readonly fetchImpl: FetchImpl | undefined
58
61
  private discovery: OAuthDiscoveryDocument | undefined
59
62
 
60
63
  constructor(config: OpenSeaOAuthConfig) {
@@ -66,6 +69,9 @@ export class OpenSeaOAuth {
66
69
  this.issuer = issuer
67
70
  this.clientId = config.clientId
68
71
  this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS
72
+ // Stored as given, including undefined: fetchWith falls back to globalThis.fetch at call
73
+ // time, so a caller who swaps globalThis.fetch after construction still takes effect.
74
+ this.fetchImpl = config.fetch
69
75
  }
70
76
 
71
77
  /**
@@ -284,7 +290,10 @@ export class OpenSeaOAuth {
284
290
  const controller = new AbortController()
285
291
  const timer = setTimeout(() => controller.abort(), this.timeoutMs)
286
292
  try {
287
- return await fetch(input, { ...init, signal: controller.signal })
293
+ return await fetchWith(this.fetchImpl, input, {
294
+ ...init,
295
+ signal: controller.signal,
296
+ })
288
297
  } catch (error) {
289
298
  // Detect our own timeout via the controller rather than the error type:
290
299
  // an aborted fetch rejects with a `DOMException` in browsers (not always
@@ -372,18 +381,16 @@ function canonicalOpenSeaScopes(scopes: string[]): string[] {
372
381
  * authorization decision.
373
382
  */
374
383
  export function extractOpenSeaScopes(accessToken: string): string[] {
375
- try {
376
- const claim = decodeJwtPayload(accessToken).opensea_scopes
377
- if (typeof claim === "string") {
378
- return canonicalOpenSeaScopes(claim.split(/\s+/).filter(Boolean))
379
- }
380
- if (Array.isArray(claim)) {
381
- return canonicalOpenSeaScopes(
382
- claim.filter((scope): scope is string => typeof scope === "string"),
383
- )
384
- }
385
- } catch {
386
- // Opaque access tokens cannot provide a scope fallback.
384
+ // An opaque token has no claims, and a malformed one cannot be read; either way
385
+ // there is no scope fallback here.
386
+ const claim = tryDecodeJwtPayload(accessToken)?.opensea_scopes
387
+ if (typeof claim === "string") {
388
+ return canonicalOpenSeaScopes(claim.split(/\s+/).filter(Boolean))
389
+ }
390
+ if (Array.isArray(claim)) {
391
+ return canonicalOpenSeaScopes(
392
+ claim.filter((scope): scope is string => typeof scope === "string"),
393
+ )
387
394
  }
388
395
  return []
389
396
  }
@@ -463,27 +470,52 @@ export function extractWalletAddress(
463
470
  * decision.
464
471
  */
465
472
  export function extractLinkedWallets(accessToken: string): string[] {
473
+ // An opaque token has no claims and a malformed one cannot be read, so `[]`
474
+ // here means "nothing readable" as well as "no linked wallets". A caller that
475
+ // must not silently under-report a portfolio should check
476
+ // `tryDecodeJwtPayload(token) === null` to tell those apart before treating an
477
+ // empty result as the whole picture. The malformed case is the dangerous one:
478
+ // an opaque token is a deliberate choice, a corrupted one looks identical to
479
+ // an account that simply has one wallet.
480
+ const claim = tryDecodeJwtPayload(accessToken)?.linked_wallets
481
+ if (!Array.isArray(claim)) return []
482
+ const wallets = claim.filter(
483
+ (wallet): wallet is string =>
484
+ typeof wallet === "string" && wallet.trim().length > 0,
485
+ )
486
+ // Exact dedupe, not case-folded: EVM addresses differ only by checksum
487
+ // casing, but Solana base58 addresses are case-sensitive, so lowercasing
488
+ // to compare would risk collapsing two distinct Solana wallets into one.
489
+ return [...new Set(wallets)]
490
+ }
491
+
492
+ /**
493
+ * Decode a JWT payload without verifying the signature, or return `null` when
494
+ * the token is not a readable JWT.
495
+ *
496
+ * OpenSea issues both JWT and opaque access tokens, so "not a JWT" is an
497
+ * expected input here rather than an error. Prefer this over wrapping
498
+ * {@link decodeJwtPayload} in a try/catch, and use it to tell "no claim to
499
+ * read" apart from "claim read, and it was empty" — {@link extractLinkedWallets}
500
+ * and {@link extractOpenSeaScopes} both return `[]` for either case.
501
+ */
502
+ export function tryDecodeJwtPayload(
503
+ token: string,
504
+ ): Record<string, unknown> | null {
466
505
  try {
467
- const claim = decodeJwtPayload(accessToken).linked_wallets
468
- if (!Array.isArray(claim)) return []
469
- const wallets = claim.filter(
470
- (wallet): wallet is string =>
471
- typeof wallet === "string" && wallet.trim().length > 0,
472
- )
473
- // Exact dedupe, not case-folded: EVM addresses differ only by checksum
474
- // casing, but Solana base58 addresses are case-sensitive, so lowercasing
475
- // to compare would risk collapsing two distinct Solana wallets into one.
476
- return [...new Set(wallets)]
506
+ return decodeJwtPayload(token)
477
507
  } catch {
478
- // Opaque access tokens carry no claims to read.
508
+ return null
479
509
  }
480
- return []
481
510
  }
482
511
 
483
512
  /**
484
513
  * Decode a JWT payload without verifying the signature. Intended for reading
485
514
  * claims out of a token the authorization server just issued to us over TLS —
486
515
  * NOT for validating inbound tokens.
516
+ *
517
+ * Throws when `token` is not a JWT. {@link tryDecodeJwtPayload} is the
518
+ * non-throwing form, and is what the claim extractors in this module use.
487
519
  */
488
520
  export function decodeJwtPayload(token: string): Record<string, unknown> {
489
521
  const parts = token.split(".")
@@ -503,7 +535,19 @@ export function decodeJwtPayload(token: string): Record<string, unknown> {
503
535
  Uint8Array.from(atob(padded), c => c.charCodeAt(0)),
504
536
  )
505
537
  : Buffer.from(padded, "base64").toString("utf-8")
506
- return JSON.parse(json) as Record<string, unknown>
538
+ const payload: unknown = JSON.parse(json)
539
+ // `JSON.parse` happily returns a number, string, boolean, array or null, and
540
+ // asserting any of those to Record<string, unknown> would be a lie that only
541
+ // shows up as `undefined` at the claim read. Rejecting them here is what lets
542
+ // tryDecodeJwtPayload returning null be the complete "unreadable" signal.
543
+ if (
544
+ typeof payload !== "object" ||
545
+ payload === null ||
546
+ Array.isArray(payload)
547
+ ) {
548
+ throw new Error("JWT payload is not an object")
549
+ }
550
+ return payload as Record<string, unknown>
507
551
  }
508
552
 
509
553
  function randomUrlSafeString(byteLength: number): string {
package/src/auth/siwx.ts CHANGED
@@ -3,6 +3,7 @@ import type {
3
3
  OperationResponse,
4
4
  } from "@opensea/api-types"
5
5
  import { getAddress } from "ethers"
6
+ import { type FetchImpl, fetchWith } from "../utils/fetchTransport"
6
7
  import type { AuthSigner } from "./types"
7
8
 
8
9
  const DEFAULT_API_BASE_URL = "https://api.opensea.io"
@@ -55,6 +56,14 @@ export interface LinkWalletWithSiwxOptions
55
56
  authToken: string
56
57
  chainArch: ChainArch
57
58
  chainId: number
59
+ /**
60
+ * Transport used for the nonce request and the link request, defaulting to the global `fetch`.
61
+ * Same seam as {@link OpenSeaAPIConfig.fetch}.
62
+ *
63
+ * It sees the auth token, the API key and the wallet signature, so anything it logs or caches
64
+ * is sensitive.
65
+ */
66
+ fetch?: FetchImpl
58
67
  }
59
68
 
60
69
  const DOMAIN_REGEX =
@@ -253,11 +262,18 @@ export function parseSiwxMessage(message: string): ParseSiwxMessageResult {
253
262
 
254
263
  /**
255
264
  * Request a single-use nonce from the OpenSea API.
265
+ *
266
+ * @param apiBaseUrl Base URL to request the nonce from. Defaults to mainnet.
267
+ * @param options Optional `fetch` transport, defaulting to the global `fetch`. Same seam as
268
+ * {@link OpenSeaAPIConfig.fetch}, for a caller routing every request through
269
+ * its own transport.
256
270
  */
257
271
  export async function requestSiwxNonce(
258
272
  apiBaseUrl = DEFAULT_API_BASE_URL,
273
+ options: { fetch?: FetchImpl } = {},
259
274
  ): Promise<string> {
260
- const response = await fetch(
275
+ const response = await fetchWith(
276
+ options.fetch,
261
277
  `${stripTrailingSlash(apiBaseUrl)}/api/v2/auth/siwe/nonce`,
262
278
  {
263
279
  method: "POST",
@@ -290,7 +306,7 @@ export async function linkWalletWithSiwx(
290
306
  const apiBaseUrl = stripTrailingSlash(
291
307
  options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
292
308
  )
293
- const nonce = await requestSiwxNonce(apiBaseUrl)
309
+ const nonce = await requestSiwxNonce(apiBaseUrl, { fetch: options.fetch })
294
310
  const address = await signer.getAddress()
295
311
  const message = createSiwxMessage({
296
312
  address,
@@ -315,15 +331,19 @@ export async function linkWalletWithSiwx(
315
331
  chainArch: options.chainArch,
316
332
  }
317
333
 
318
- const response = await fetch(`${apiBaseUrl}/api/v2/accounts/wallets/siwx`, {
319
- method: "POST",
320
- headers: {
321
- Authorization: `Bearer ${options.authToken}`,
322
- "Content-Type": "application/json",
323
- ...(options.apiKey ? { "X-API-KEY": options.apiKey } : {}),
334
+ const response = await fetchWith(
335
+ options.fetch,
336
+ `${apiBaseUrl}/api/v2/accounts/wallets/siwx`,
337
+ {
338
+ method: "POST",
339
+ headers: {
340
+ Authorization: `Bearer ${options.authToken}`,
341
+ "Content-Type": "application/json",
342
+ ...(options.apiKey ? { "X-API-KEY": options.apiKey } : {}),
343
+ },
344
+ body: JSON.stringify(payload),
324
345
  },
325
- body: JSON.stringify(payload),
326
- })
346
+ )
327
347
  if (!response.ok) {
328
348
  const body = await response.text().catch(() => "")
329
349
  throw new Error(