@opensea/sdk 12.14.0 → 13.0.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/lib/abi/abis.d.ts +0 -30
  2. package/lib/abi/abis.js +1 -29
  3. package/lib/abi/abis.js.map +1 -1
  4. package/lib/api/api.d.ts +12 -5
  5. package/lib/api/api.js +16 -8
  6. package/lib/api/api.js.map +1 -1
  7. package/lib/api/apiPaths.d.ts +2 -0
  8. package/lib/api/apiPaths.js +9 -1
  9. package/lib/api/apiPaths.js.map +1 -1
  10. package/lib/api/listings.d.ts +2 -1
  11. package/lib/api/listings.js +3 -1
  12. package/lib/api/listings.js.map +1 -1
  13. package/lib/api/nfts.d.ts +1 -1
  14. package/lib/api/nfts.js +2 -2
  15. package/lib/api/nfts.js.map +1 -1
  16. package/lib/api/offers.d.ts +8 -4
  17. package/lib/api/offers.js +21 -4
  18. package/lib/api/offers.js.map +1 -1
  19. package/lib/api/signals.d.ts +21 -0
  20. package/lib/api/signals.js +31 -0
  21. package/lib/api/signals.js.map +1 -0
  22. package/lib/api/types.d.ts +28 -1
  23. package/lib/api/types.js.map +1 -1
  24. package/lib/api/walletAuth.d.ts +274 -259
  25. package/lib/api/walletAuth.js +26 -10
  26. package/lib/api/walletAuth.js.map +1 -1
  27. package/lib/auth/oauth.d.ts +3 -1
  28. package/lib/auth/oauth.js +47 -30
  29. package/lib/auth/oauth.js.map +1 -1
  30. package/lib/auth/siwx.d.ts +1 -4
  31. package/lib/sdk/assets.d.ts +6 -5
  32. package/lib/sdk/assets.js +24 -36
  33. package/lib/sdk/assets.js.map +1 -1
  34. package/lib/sdk/base.d.ts +8 -8
  35. package/lib/utils/rateLimit.js +3 -3
  36. package/lib/utils/rateLimit.js.map +1 -1
  37. package/package.json +2 -2
  38. package/src/abi/abis.ts +0 -29
  39. package/src/api/api.ts +25 -4
  40. package/src/api/apiPaths.ts +8 -0
  41. package/src/api/listings.ts +3 -0
  42. package/src/api/nfts.ts +2 -1
  43. package/src/api/offers.ts +33 -13
  44. package/src/api/signals.ts +33 -0
  45. package/src/api/types.ts +36 -0
  46. package/src/api/walletAuth.ts +39 -18
  47. package/src/auth/oauth.ts +86 -53
  48. package/src/auth/siwx.ts +1 -1
  49. package/src/sdk/assets.ts +30 -54
  50. package/src/utils/rateLimit.ts +3 -3
package/src/abi/abis.ts CHANGED
@@ -180,35 +180,6 @@ export const TRANSFER_HELPER_ABI = [
180
180
  },
181
181
  ] as const
182
182
 
183
- export const MULTICALL3_ABI = [
184
- {
185
- name: "aggregate3",
186
- type: "function",
187
- stateMutability: "payable",
188
- inputs: [
189
- {
190
- name: "calls",
191
- type: "tuple[]",
192
- components: [
193
- { name: "target", type: "address" },
194
- { name: "allowFailure", type: "bool" },
195
- { name: "callData", type: "bytes" },
196
- ],
197
- },
198
- ],
199
- outputs: [
200
- {
201
- name: "returnData",
202
- type: "tuple[]",
203
- components: [
204
- { name: "success", type: "bool" },
205
- { name: "returnData", type: "bytes" },
206
- ],
207
- },
208
- ],
209
- },
210
- ] as const
211
-
212
183
  export const SET_APPROVAL_FOR_ALL_ABI = [
213
184
  {
214
185
  name: "setApprovalForAll",
package/src/api/api.ts CHANGED
@@ -33,6 +33,7 @@ import { NFTsAPI } from "./nfts"
33
33
  import { OffersAPI } from "./offers"
34
34
  import { OrdersAPI } from "./orders"
35
35
  import { SearchAPI } from "./search"
36
+ import { SignalsAPI } from "./signals"
36
37
  import { TokensAPI } from "./tokens"
37
38
  import { ToolsAPI } from "./tools"
38
39
  import { TransactionsAPI } from "./transactions"
@@ -146,6 +147,7 @@ import {
146
147
  type TokenTimeSeriesArgs,
147
148
  type TraitFilter,
148
149
  type TraitFloorsResponse,
150
+ type TraitOffersFilters,
149
151
  type TransactionReceiptRequest,
150
152
  type TransactionReceiptResponse,
151
153
  type TransferRequest,
@@ -213,6 +215,8 @@ export class OpenSeaAPI {
213
215
  public readonly drops: DropsAPI
214
216
  public readonly transactions: TransactionsAPI
215
217
  public readonly assets: AssetsAPI
218
+ /** Public OpenSea signals. Creating and deleting them is on `walletAuth`. */
219
+ public readonly signals: SignalsAPI
216
220
  /** Tool registry endpoints. Beta: they may change without notice. */
217
221
  public readonly tools: ToolsAPI
218
222
  /** Wallet-authenticated scoped REST helpers. */
@@ -264,6 +268,7 @@ export class OpenSeaAPI {
264
268
  this.drops = new DropsAPI(fetcher)
265
269
  this.transactions = new TransactionsAPI(fetcher)
266
270
  this.assets = new AssetsAPI(fetcher)
271
+ this.signals = new SignalsAPI(fetcher)
267
272
  this.tools = new ToolsAPI(fetcher)
268
273
  this.walletAuth = new WalletAuthAPI(fetcher)
269
274
  }
@@ -290,6 +295,7 @@ export class OpenSeaAPI {
290
295
  * @param collectionSlug The slug of the collection.
291
296
  * @param limit The number of offers to return. Must be between 1 and 100. Default: 100
292
297
  * @param next The cursor for the next page of results. This is returned from a previous request.
298
+ * @param maker Only return offers made by this wallet address.
293
299
  * @returns The {@link GetOffersResponse} returned by the API.
294
300
  * @deprecated Use `api.offers.getAllOffers()`. Removed in the next major.
295
301
  */
@@ -297,8 +303,9 @@ export class OpenSeaAPI {
297
303
  collectionSlug: string,
298
304
  limit?: number,
299
305
  next?: string,
306
+ maker?: string,
300
307
  ): Promise<GetOffersResponse> {
301
- return this.offers.getAllOffers(collectionSlug, limit, next)
308
+ return this.offers.getAllOffers(collectionSlug, limit, next, maker)
302
309
  }
303
310
 
304
311
  /**
@@ -307,6 +314,7 @@ export class OpenSeaAPI {
307
314
  * @param limit The number of listings to return. Must be between 1 and 100. Default: 100
308
315
  * @param next The cursor for the next page of results. This is returned from a previous request.
309
316
  * @param includePrivateListings Whether to include private listings (default: false)
317
+ * @param maker Only return listings made by this wallet address.
310
318
  * @returns The {@link GetListingsResponse} returned by the API.
311
319
  * @deprecated Use `api.listings.getAllListings()`. Removed in the next major.
312
320
  */
@@ -315,12 +323,14 @@ export class OpenSeaAPI {
315
323
  limit?: number,
316
324
  next?: string,
317
325
  includePrivateListings?: boolean,
326
+ maker?: string,
318
327
  ): Promise<GetListingsResponse> {
319
328
  return this.listings.getAllListings(
320
329
  collectionSlug,
321
330
  limit,
322
331
  next,
323
332
  includePrivateListings,
333
+ maker,
324
334
  )
325
335
  }
326
336
 
@@ -333,17 +343,19 @@ export class OpenSeaAPI {
333
343
  * @param next The cursor for the next page of results. This is returned from a previous request.
334
344
  * @param floatValue The value of the trait for decimal-based numeric traits.
335
345
  * @param intValue The value of the trait for integer-based numeric traits.
346
+ * @param filters Optional {@link TraitOffersFilters}: `mode`, a numeric range, or multi-trait `traits`.
336
347
  * @returns The {@link GetOffersResponse} returned by the API.
337
348
  * @deprecated Use `api.offers.getTraitOffers()`. Removed in the next major.
338
349
  */
339
350
  public async getTraitOffers(
340
351
  collectionSlug: string,
341
- type: string,
342
- value: string,
352
+ type: string | undefined,
353
+ value: string | undefined,
343
354
  limit?: number,
344
355
  next?: string,
345
356
  floatValue?: number,
346
357
  intValue?: number,
358
+ filters?: TraitOffersFilters,
347
359
  ): Promise<GetOffersResponse> {
348
360
  return this.offers.getTraitOffers(
349
361
  collectionSlug,
@@ -353,6 +365,7 @@ export class OpenSeaAPI {
353
365
  next,
354
366
  floatValue,
355
367
  intValue,
368
+ filters,
356
369
  )
357
370
  }
358
371
 
@@ -582,6 +595,7 @@ export class OpenSeaAPI {
582
595
  * @param limit The number of NFTs to retrieve. Must be greater than 0 and less than 51.
583
596
  * @param next Cursor to retrieve the next page of NFTs
584
597
  * @param traits Optional {@link TraitFilter} array. Returns 400 if a single trait matches more than 1000 items.
598
+ * @param hasAgentBinding Only return NFTs that do (`true`) or do not (`false`) have an ERC-8217 agent binding.
585
599
  * @returns The {@link ListNFTsResponse} returned by the API.
586
600
  * @deprecated Use `api.nfts.getNFTsByCollection()`. Removed in the next major.
587
601
  */
@@ -590,8 +604,15 @@ export class OpenSeaAPI {
590
604
  limit: number | undefined = undefined,
591
605
  next: string | undefined = undefined,
592
606
  traits: TraitFilter[] | undefined = undefined,
607
+ hasAgentBinding: boolean | undefined = undefined,
593
608
  ): Promise<ListNFTsResponse> {
594
- return this.nfts.getNFTsByCollection(slug, limit, next, traits)
609
+ return this.nfts.getNFTsByCollection(
610
+ slug,
611
+ limit,
612
+ next,
613
+ traits,
614
+ hasAgentBinding,
615
+ )
595
616
  }
596
617
 
597
618
  /**
@@ -502,3 +502,11 @@ export const getToolActivityPath = (
502
502
  export const getToolUsagePath = () => {
503
503
  return `${API_V2_PREFIX}/tools/usage`
504
504
  }
505
+
506
+ export const getSignalsPath = () => {
507
+ return `${API_V2_PREFIX}/signals`
508
+ }
509
+
510
+ export const getSignalPath = (signalId: string) => {
511
+ return `${API_V2_PREFIX}/signals/${segment(signalId)}`
512
+ }
@@ -35,12 +35,14 @@ export class ListingsAPI {
35
35
  * @param limit The number of listings to return
36
36
  * @param next The cursor for pagination
37
37
  * @param includePrivateListings Whether to include private listings (default: false)
38
+ * @param maker Only return listings made by this wallet address
38
39
  */
39
40
  async getAllListings(
40
41
  collectionSlug: string,
41
42
  limit?: number,
42
43
  next?: string,
43
44
  includePrivateListings?: boolean,
45
+ maker?: string,
44
46
  ): Promise<GetListingsResponse> {
45
47
  const response = await this.fetcher.get<GetListingsResponse>(
46
48
  getAllListingsAPIPath(collectionSlug),
@@ -50,6 +52,7 @@ export class ListingsAPI {
50
52
  ...(includePrivateListings !== undefined && {
51
53
  includePrivateListings,
52
54
  }),
55
+ ...(maker !== undefined && { maker }),
53
56
  },
54
57
  )
55
58
  return response
package/src/api/nfts.ts CHANGED
@@ -55,10 +55,11 @@ export class NFTsAPI {
55
55
  limit: number | undefined = undefined,
56
56
  next: string | undefined = undefined,
57
57
  traits: TraitFilter[] | undefined = undefined,
58
+ hasAgentBinding: boolean | undefined = undefined,
58
59
  ): Promise<ListNFTsResponse> {
59
60
  const response = await this.fetcher.get<ListNFTsResponse>(
60
61
  getListNFTsByCollectionPath(slug),
61
- { limit, next, traits: encodeTraitsParam(traits) },
62
+ { limit, next, traits: encodeTraitsParam(traits), hasAgentBinding },
62
63
  )
63
64
  return response
64
65
  }
package/src/api/offers.ts CHANGED
@@ -16,15 +16,17 @@ import {
16
16
  getTraitOffersPath,
17
17
  } from "./apiPaths"
18
18
  import type { Fetcher } from "./fetcher"
19
- import type {
20
- BuildOfferResponse,
21
- CollectionOffer,
22
- CreateOfferActionsRequest,
23
- CreateOfferActionsResponse,
24
- CreateOfferFulfillmentActionsRequest,
25
- CreateOfferFulfillmentActionsResponse,
26
- GetBestOfferResponse,
27
- GetOffersResponse,
19
+ import {
20
+ type BuildOfferResponse,
21
+ type CollectionOffer,
22
+ type CreateOfferActionsRequest,
23
+ type CreateOfferActionsResponse,
24
+ type CreateOfferFulfillmentActionsRequest,
25
+ type CreateOfferFulfillmentActionsResponse,
26
+ encodeTraitsParam,
27
+ type GetBestOfferResponse,
28
+ type GetOffersResponse,
29
+ type TraitOffersFilters,
28
30
  } from "./types"
29
31
 
30
32
  /**
@@ -92,37 +94,55 @@ export class OffersAPI {
92
94
 
93
95
  /**
94
96
  * Gets all offers for a given collection.
97
+ * @param maker Only return offers made by this wallet address.
95
98
  */
96
99
  async getAllOffers(
97
100
  collectionSlug: string,
98
101
  limit?: number,
99
102
  next?: string,
103
+ maker?: string,
100
104
  ): Promise<GetOffersResponse> {
101
105
  const response = await this.fetcher.get<GetOffersResponse>(
102
106
  getAllOffersAPIPath(collectionSlug),
103
107
  {
104
108
  limit,
105
109
  next,
110
+ maker,
106
111
  },
107
112
  )
108
113
  return response
109
114
  }
110
115
 
111
116
  /**
112
- * Gets trait offers for a given collection.
117
+ * Gets trait offers for a given collection. Pass `type` and `value` for a single string trait,
118
+ * `type` with `filters.minValue`/`filters.maxValue` for a numeric range, or `filters.traits` for
119
+ * a multi-trait query (leave `type` and `value` undefined). The API infers `filters.mode` from
120
+ * the other params when it is omitted.
113
121
  */
114
122
  async getTraitOffers(
115
123
  collectionSlug: string,
116
- type: string,
117
- value: string,
124
+ type: string | undefined,
125
+ value: string | undefined,
118
126
  limit?: number,
119
127
  next?: string,
120
128
  floatValue?: number,
121
129
  intValue?: number,
130
+ filters?: TraitOffersFilters,
122
131
  ): Promise<GetOffersResponse> {
123
132
  return this.fetcher.get<GetOffersResponse>(
124
133
  getTraitOffersPath(collectionSlug),
125
- { type, value, limit, next, floatValue, intValue },
134
+ {
135
+ type,
136
+ value,
137
+ limit,
138
+ next,
139
+ floatValue,
140
+ intValue,
141
+ mode: filters?.mode,
142
+ minValue: filters?.minValue,
143
+ maxValue: filters?.maxValue,
144
+ traits: encodeTraitsParam(filters?.traits),
145
+ },
126
146
  )
127
147
  }
128
148
 
@@ -0,0 +1,33 @@
1
+ import type { SignalResponse, SignalsResponse } from "@opensea/api-types"
2
+ import { getSignalPath, getSignalsPath } from "./apiPaths"
3
+ import type { Fetcher } from "./fetcher"
4
+ import type {
5
+ GetSignalResponse,
6
+ ListSignalsArgs,
7
+ ListSignalsResponse,
8
+ } from "./types"
9
+
10
+ /**
11
+ * Public OpenSea signals. Reads need only the API key. Creating and deleting a signal needs a
12
+ * bearer token with the `write:posts` scope, so those live on `api.walletAuth` (`createSignal`,
13
+ * `deleteSignal`).
14
+ */
15
+ export class SignalsAPI {
16
+ constructor(private fetcher: Fetcher) {}
17
+
18
+ /**
19
+ * Get one public signal. `signalId` is the opaque `sig_v1_...` reference the API returned; pass
20
+ * it unchanged. Removed, private and pending signals return 404.
21
+ */
22
+ async getSignal(signalId: string): Promise<GetSignalResponse> {
23
+ return this.fetcher.get<SignalResponse>(getSignalPath(signalId))
24
+ }
25
+
26
+ /**
27
+ * List public signals about one subject, newest first. A page can be empty while `next` is
28
+ * set, so keep passing `next` back as `cursor` until it is null.
29
+ */
30
+ async listSignals(args: ListSignalsArgs): Promise<ListSignalsResponse> {
31
+ return this.fetcher.get<SignalsResponse>(getSignalsPath(), args)
32
+ }
33
+ }
package/src/api/types.ts CHANGED
@@ -55,6 +55,8 @@ import type {
55
55
  OperationQueryParams,
56
56
  paths,
57
57
  RegisteredToolResponse,
58
+ SignalResponse,
59
+ SignalsResponse,
58
60
  StandardizedNft,
59
61
  StandardizedNftFacetsResponse,
60
62
  StandardizedNftListResponse,
@@ -99,6 +101,20 @@ export interface TraitFilter {
99
101
  value: string
100
102
  }
101
103
 
104
+ /**
105
+ * Filters for `getTraitOffers` beyond a single `type`/`value` pair. Derived from the spec's
106
+ * `get_offers_collection_trait` query params, except `traits`, which takes {@link TraitFilter}
107
+ * entries and is JSON-encoded on the wire.
108
+ * @category API Query Args
109
+ */
110
+ export type TraitOffersFilters = Pick<
111
+ Camelize<OperationQueryParams<"get_offers_collection_trait">>,
112
+ "mode" | "minValue" | "maxValue"
113
+ > & {
114
+ /** Multi-trait (`MULTI` mode) filters; offers must match all of them. */
115
+ traits?: TraitFilter[]
116
+ }
117
+
102
118
  /**
103
119
  * Encode a {@link TraitFilter} array as the JSON-string form the API expects
104
120
  * on the `traits` query parameter, or `undefined` if the array is empty.
@@ -1784,3 +1800,23 @@ export type GetToolResponse = Omit<
1784
1800
  * @category API Response Types
1785
1801
  */
1786
1802
  export type GetToolActivityResponse = Camelize<ToolActivityPaginatedResponse>
1803
+
1804
+ /**
1805
+ * Query args for `GET /api/v2/signals`. Select exactly one subject: `chain` and `contract` for a
1806
+ * currency, plus `tokenId` for an item, or `collection` alone.
1807
+ * @category API Query Args
1808
+ */
1809
+ export type ListSignalsArgs = Camelize<OperationQueryParams<"list_signals">>
1810
+
1811
+ /**
1812
+ * A public OpenSea signal.
1813
+ * @category API Response Types
1814
+ */
1815
+ export type GetSignalResponse = Camelize<SignalResponse>
1816
+
1817
+ /**
1818
+ * Response from `GET /api/v2/signals`. `next` is the cursor for the following page, or null on
1819
+ * the last one.
1820
+ * @category API Response Types
1821
+ */
1822
+ export type ListSignalsResponse = Camelize<SignalsResponse>
@@ -151,6 +151,31 @@ export class WalletAuthAPI {
151
151
  )
152
152
  }
153
153
 
154
+ /**
155
+ * Create a signal as the token's account. Needs the `write:posts` scope. Pick the subject as
156
+ * `listSignals` does; `authorAddress` defaults to the wallet the token signed in with. Not
157
+ * idempotent: a retry after an unknown outcome can post twice once the per-subject cooldown,
158
+ * which returns 422, has passed.
159
+ */
160
+ createSignal(body: WalletAuthRequest<"create_signal">) {
161
+ return this.fetcher.request<OperationResponse<"create_signal">>(
162
+ "POST",
163
+ "/api/v2/signals",
164
+ body,
165
+ )
166
+ }
167
+
168
+ /**
169
+ * Delete a signal the token's account owns. Needs the `write:posts` scope. A signal that is
170
+ * missing, already deleted or owned by another account returns 404.
171
+ */
172
+ async deleteSignal(signalId: string): Promise<void> {
173
+ await this.fetcher.request<void>(
174
+ "DELETE",
175
+ `/api/v2/signals/${segment(signalId)}`,
176
+ )
177
+ }
178
+
154
179
  /**
155
180
  * `CancelRequest` carries `offererSignature`, which is camelCase on the wire.
156
181
  * It is optional, so snake-casing it didn't fail the request — it just dropped
@@ -257,22 +282,6 @@ export class WalletAuthAPI {
257
282
  )
258
283
  }
259
284
 
260
- /**
261
- * @deprecated Use `saveDropItemMediaBatch`, which saves the same items by
262
- * `uploadBatchId` and filename. This save sends every media token back and
263
- * the API checks each file separately, so it slows down with drop size.
264
- */
265
- saveDropItemMedia(
266
- slug: string,
267
- body: WalletAuthRequest<"save_drop_item_media">,
268
- ) {
269
- return this.fetcher.request<OperationResponse<"save_drop_item_media">>(
270
- "POST",
271
- `/api/v2/drops/${segment(slug)}/items/media/save`,
272
- body,
273
- )
274
- }
275
-
276
285
  /**
277
286
  * Save the drop's items from files uploaded with one `uploadBatchId` through
278
287
  * `createDropItemMediaUpload`, naming them by filename (up to 15,000). Each
@@ -320,8 +329,7 @@ export class WalletAuthAPI {
320
329
  * `UploadContext.fields` is an opaque signed multipart field map that the
321
330
  * caller must submit unchanged, so the response is not camelized. Unlike the
322
331
  * other upload contexts, the returned token is not passed to a later call:
323
- * the next `saveDropItemMediaBatch` (or deprecated `saveDropItemMedia`)
324
- * reads the stored manifest.
332
+ * the next `saveDropItemMediaBatch` reads the stored manifest.
325
333
  */
326
334
  createDropCollectionManifestUpload(slug: string) {
327
335
  return this.fetcher.request<
@@ -590,6 +598,19 @@ export class WalletAuthAPI {
590
598
  )
591
599
  }
592
600
 
601
+ /**
602
+ * Issue a single-use nonce for linking a wallet to the authenticated account,
603
+ * with the statement to sign. Build the SIWX message with both verbatim and
604
+ * submit it to `linkWallet` within 10 minutes; the nonce only works for this
605
+ * account.
606
+ */
607
+ getWalletLinkNonce() {
608
+ return this.fetcher.request<OperationResponse<"get_wallet_link_nonce">>(
609
+ "POST",
610
+ "/api/v2/accounts/wallets/siwx/nonce",
611
+ )
612
+ }
613
+
593
614
  /**
594
615
  * `LinkWalletSiwxRequest` is camelCase on the wire. `chainArch` is required, so
595
616
  * snake-casing it made every call fail validation, and the nested SIWX `message`
package/src/auth/oauth.ts CHANGED
@@ -84,16 +84,18 @@ export class OpenSeaOAuth {
84
84
  */
85
85
  async getDiscovery(): Promise<OAuthDiscoveryDocument> {
86
86
  if (this.discovery) return this.discovery
87
- const response = await this.fetchWithTimeout(
87
+ const discovery = await this.fetchWithTimeout(
88
88
  `${this.issuer}/.well-known/openid-configuration`,
89
89
  { headers: { Accept: "application/json" } },
90
+ async response => {
91
+ if (!response.ok) {
92
+ throw new Error(
93
+ `OAuth discovery failed (${response.status}): ${response.statusText}`,
94
+ )
95
+ }
96
+ return (await response.json()) as OAuthDiscoveryDocument
97
+ },
90
98
  )
91
- if (!response.ok) {
92
- throw new Error(
93
- `OAuth discovery failed (${response.status}): ${response.statusText}`,
94
- )
95
- }
96
- const discovery = (await response.json()) as OAuthDiscoveryDocument
97
99
  const advertisedIssuer = discovery.issuer?.replace(/\/+$/, "")
98
100
  if (advertisedIssuer !== this.issuer) {
99
101
  throw new Error(
@@ -167,19 +169,21 @@ export class OpenSeaOAuth {
167
169
  throw new Error("Authorization server does not support revocation")
168
170
  }
169
171
  assertSecureUrl(discovery.revocation_endpoint, "revocation_endpoint")
170
- const response = await this.fetchWithTimeout(
172
+ await this.fetchWithTimeout(
171
173
  discovery.revocation_endpoint,
172
174
  {
173
175
  method: "POST",
174
176
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
175
177
  body: new URLSearchParams({ token, client_id: this.clientId }),
176
178
  },
179
+ async response => {
180
+ if (!response.ok) {
181
+ throw new Error(
182
+ `Token revocation failed (${response.status}): ${response.statusText}`,
183
+ )
184
+ }
185
+ },
177
186
  )
178
- if (!response.ok) {
179
- throw new Error(
180
- `Token revocation failed (${response.status}): ${response.statusText}`,
181
- )
182
- }
183
187
  }
184
188
 
185
189
  /**
@@ -199,7 +203,7 @@ export class OpenSeaOAuth {
199
203
  discovery.device_authorization_endpoint,
200
204
  "device_authorization_endpoint",
201
205
  )
202
- const response = await this.fetchWithTimeout(
206
+ return this.fetchWithTimeout(
203
207
  discovery.device_authorization_endpoint,
204
208
  {
205
209
  method: "POST",
@@ -209,13 +213,15 @@ export class OpenSeaOAuth {
209
213
  scope: buildScopeParam(options?.scopes),
210
214
  }),
211
215
  },
216
+ async response => {
217
+ if (!response.ok) {
218
+ throw new Error(
219
+ `Device authorization failed (${response.status}): ${response.statusText}`,
220
+ )
221
+ }
222
+ return (await response.json()) as DeviceAuthorizationResponse
223
+ },
212
224
  )
213
- if (!response.ok) {
214
- throw new Error(
215
- `Device authorization failed (${response.status}): ${response.statusText}`,
216
- )
217
- }
218
- return (await response.json()) as DeviceAuthorizationResponse
219
225
  }
220
226
 
221
227
  /**
@@ -234,26 +240,40 @@ export class OpenSeaOAuth {
234
240
  // authorization quickly, so waiting a full interval before the first
235
241
  // poll only adds latency.
236
242
  while (Date.now() < deadline) {
237
- const response = await this.fetchWithTimeout(discovery.token_endpoint, {
238
- method: "POST",
239
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
240
- body: new URLSearchParams({
241
- grant_type: DEVICE_GRANT_TYPE,
242
- device_code: device.device_code,
243
- client_id: this.clientId,
244
- }),
245
- })
246
- if (response.ok) {
247
- return toOAuthToken((await response.json()) as OAuthTokenResponse)
248
- }
249
- const body = (await response.json().catch(() => ({}))) as {
250
- error?: string
243
+ const poll = await this.fetchWithTimeout(
244
+ discovery.token_endpoint,
245
+ {
246
+ method: "POST",
247
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
248
+ body: new URLSearchParams({
249
+ grant_type: DEVICE_GRANT_TYPE,
250
+ device_code: device.device_code,
251
+ client_id: this.clientId,
252
+ }),
253
+ },
254
+ async (
255
+ response,
256
+ ): Promise<
257
+ | { token: OAuthTokenResponse }
258
+ | { error: string | undefined; status: number }
259
+ > => {
260
+ if (response.ok) {
261
+ return { token: (await response.json()) as OAuthTokenResponse }
262
+ }
263
+ const body = (await response.json().catch(() => ({}))) as {
264
+ error?: string
265
+ }
266
+ return { error: body.error, status: response.status }
267
+ },
268
+ )
269
+ if ("token" in poll) {
270
+ return toOAuthToken(poll.token)
251
271
  }
252
- if (body.error === "slow_down") {
272
+ if (poll.error === "slow_down") {
253
273
  intervalMs += 5000
254
- } else if (body.error !== "authorization_pending") {
274
+ } else if (poll.error !== "authorization_pending") {
255
275
  throw new Error(
256
- `Device authorization failed: ${body.error ?? response.status}`,
276
+ `Device authorization failed: ${poll.error ?? poll.status}`,
257
277
  )
258
278
  }
259
279
  await sleep(intervalMs)
@@ -265,35 +285,48 @@ export class OpenSeaOAuth {
265
285
  tokenEndpoint: string,
266
286
  params: Record<string, string>,
267
287
  ): Promise<OAuthTokenResponse> {
268
- const response = await this.fetchWithTimeout(tokenEndpoint, {
269
- method: "POST",
270
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
271
- body: new URLSearchParams(params),
272
- })
273
- if (!response.ok) {
274
- const body = await response.text().catch(() => "")
275
- throw new Error(
276
- `Token request failed (${response.status}): ${body || response.statusText}`,
277
- )
278
- }
279
- return (await response.json()) as OAuthTokenResponse
288
+ return this.fetchWithTimeout(
289
+ tokenEndpoint,
290
+ {
291
+ method: "POST",
292
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
293
+ body: new URLSearchParams(params),
294
+ },
295
+ async response => {
296
+ if (!response.ok) {
297
+ const body = await response.text().catch(() => "")
298
+ throw new Error(
299
+ `Token request failed (${response.status}): ${body || response.statusText}`,
300
+ )
301
+ }
302
+ return (await response.json()) as OAuthTokenResponse
303
+ },
304
+ )
280
305
  }
281
306
 
282
307
  /**
283
308
  * `fetch` wrapper that aborts the request after `this.timeoutMs`, so a hung
284
- * authorization server can't stall the flow indefinitely.
309
+ * authorization server can't stall the flow indefinitely. The deadline
310
+ * covers `read` as well, since a server can send headers and then stall the
311
+ * body.
285
312
  */
286
- private async fetchWithTimeout(
313
+ private async fetchWithTimeout<T>(
287
314
  input: string,
288
315
  init: RequestInit,
289
- ): Promise<Response> {
316
+ read: (response: Response) => Promise<T>,
317
+ ): Promise<T> {
290
318
  const controller = new AbortController()
291
319
  const timer = setTimeout(() => controller.abort(), this.timeoutMs)
292
320
  try {
293
- return await fetchWith(this.fetchImpl, input, {
321
+ const response = await fetchWith(this.fetchImpl, input, {
294
322
  ...init,
295
323
  signal: controller.signal,
296
324
  })
325
+ const result = await read(response)
326
+ // A read that swallows its own failure, like `.text().catch(() => "")`,
327
+ // can still resolve after the abort.
328
+ if (controller.signal.aborted) throw new Error("aborted")
329
+ return result
297
330
  } catch (error) {
298
331
  // Detect our own timeout via the controller rather than the error type:
299
332
  // an aborted fetch rejects with a `DOMException` in browsers (not always