@opensea/sdk 12.15.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.
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"
@@ -214,6 +215,8 @@ export class OpenSeaAPI {
214
215
  public readonly drops: DropsAPI
215
216
  public readonly transactions: TransactionsAPI
216
217
  public readonly assets: AssetsAPI
218
+ /** Public OpenSea signals. Creating and deleting them is on `walletAuth`. */
219
+ public readonly signals: SignalsAPI
217
220
  /** Tool registry endpoints. Beta: they may change without notice. */
218
221
  public readonly tools: ToolsAPI
219
222
  /** Wallet-authenticated scoped REST helpers. */
@@ -265,6 +268,7 @@ export class OpenSeaAPI {
265
268
  this.drops = new DropsAPI(fetcher)
266
269
  this.transactions = new TransactionsAPI(fetcher)
267
270
  this.assets = new AssetsAPI(fetcher)
271
+ this.signals = new SignalsAPI(fetcher)
268
272
  this.tools = new ToolsAPI(fetcher)
269
273
  this.walletAuth = new WalletAuthAPI(fetcher)
270
274
  }
@@ -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
+ }
@@ -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,
@@ -1798,3 +1800,23 @@ export type GetToolResponse = Omit<
1798
1800
  * @category API Response Types
1799
1801
  */
1800
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<
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
package/src/sdk/assets.ts CHANGED
@@ -3,15 +3,10 @@ import {
3
3
  ERC20_ABI,
4
4
  ERC721_ABI,
5
5
  ERC1155_ABI,
6
- MULTICALL3_ABI,
7
6
  SET_APPROVAL_FOR_ALL_ABI,
8
7
  TRANSFER_HELPER_ABI,
9
8
  } from "../abi/abis"
10
- import {
11
- MAX_UINT256,
12
- MULTICALL3_ADDRESS,
13
- TRANSFER_HELPER_ADDRESS,
14
- } from "../constants"
9
+ import { MAX_UINT256, TRANSFER_HELPER_ADDRESS } from "../constants"
15
10
  import {
16
11
  type Amount,
17
12
  type AssetWithTokenStandard,
@@ -299,7 +294,7 @@ export class AssetsManager {
299
294
  if (unapprovedAssets.length > 0) {
300
295
  throw new Error(
301
296
  `The following asset(s) are not approved for transfer to the OpenSea conduit:\n${unapprovedAssets.join("\n")}\n\n` +
302
- `Please approve these assets before transferring. You can use the batchApproveAssets() method to approve multiple assets efficiently in a single transaction.`,
297
+ `Please approve these assets before transferring. You can use the batchApproveAssets() method to approve them.`,
303
298
  )
304
299
  }
305
300
 
@@ -336,16 +331,17 @@ export class AssetsManager {
336
331
 
337
332
  /**
338
333
  * Batch approve multiple assets for transfer to the OpenSea conduit.
339
- * This method checks which assets need approval and batches them efficiently:
340
- * - 0 approvals needed: Returns early
341
- * - 1 approval needed: Sends single transaction
342
- * - 2+ approvals needed: Uses Multicall3 to batch all approvals in one transaction
334
+ * Sends one approval transaction per token contract that is not yet
335
+ * approved, skipping contracts that already are. Each approval is sent from
336
+ * `fromAddress`, because a token grants an approval to `msg.sender`: routing
337
+ * them through a batching contract such as Multicall3 would approve that
338
+ * contract instead of the owner.
343
339
  *
344
340
  * @param options
345
341
  * @param options.assets Array of assets to approve for transfer
346
342
  * @param options.fromAddress The address that owns the assets
347
343
  * @param options.overrides Transaction overrides, ignored if not set.
348
- * @returns Transaction hash of the approval transaction, or undefined if no approvals needed
344
+ * @returns Hash of the last approval transaction, or undefined if no approvals needed
349
345
  *
350
346
  * @throws Error if the fromAddress is not available through wallet or provider.
351
347
  */
@@ -444,52 +440,30 @@ export class AssetsManager {
444
440
  return undefined
445
441
  }
446
442
 
447
- // Single approval: send directly using the signer
448
- if (approvalsNeeded.length === 1) {
449
- const { target, callData } = approvalsNeeded[0]
450
- const wallet = this.context.wallet
451
- if (!("signer" in wallet)) {
452
- throw new Error("A signer is required to approve assets")
453
- }
454
- const tx = await wallet.signer.sendTransaction({
455
- to: target,
456
- data: callData,
457
- from: fromAddress,
458
- overrides: overrides as Record<string, unknown>,
459
- })
460
-
461
- await this.context.confirmTransaction(
462
- tx.hash,
463
- EventType.ApproveAllAssets,
464
- "Approving asset for transfer",
465
- )
466
-
467
- return tx.hash
443
+ const wallet = this.context.wallet
444
+ if (!("signer" in wallet)) {
445
+ throw new Error("A signer is required to approve assets")
468
446
  }
469
447
 
470
- // Multiple approvals: use Multicall3
471
- const calls = approvalsNeeded.map(({ target, callData }) => ({
472
- target,
473
- allowFailure: false,
474
- callData,
475
- }))
476
-
448
+ let lastHash: string | undefined
477
449
  try {
478
- const transaction = await cc.writeContract({
479
- address: MULTICALL3_ADDRESS,
480
- abi: MULTICALL3_ABI,
481
- functionName: "aggregate3",
482
- args: [calls],
483
- overrides: { ...overrides, from: fromAddress },
484
- })
485
-
486
- await this.context.confirmTransaction(
487
- transaction.hash,
488
- EventType.ApproveAllAssets,
489
- `Batch approving ${approvalsNeeded.length} asset(s) for transfer`,
490
- )
450
+ for (const [index, { target, callData }] of approvalsNeeded.entries()) {
451
+ const tx = await wallet.signer.sendTransaction({
452
+ to: target,
453
+ data: callData,
454
+ from: fromAddress,
455
+ overrides: overrides as Record<string, unknown>,
456
+ })
491
457
 
492
- return transaction.hash
458
+ await this.context.confirmTransaction(
459
+ tx.hash,
460
+ EventType.ApproveAllAssets,
461
+ approvalsNeeded.length === 1
462
+ ? "Approving asset for transfer"
463
+ : `Approving asset ${index + 1} of ${approvalsNeeded.length} for transfer`,
464
+ )
465
+ lastHash = tx.hash
466
+ }
493
467
  } catch (error) {
494
468
  console.error(error)
495
469
  this.context.dispatch(EventType.TransactionDenied, {
@@ -498,6 +472,8 @@ export class AssetsManager {
498
472
  })
499
473
  throw error
500
474
  }
475
+
476
+ return lastHash
501
477
  }
502
478
 
503
479
  /**
@@ -92,9 +92,9 @@ export async function executeWithRateLimit<T>(
92
92
 
93
93
  // Check if this is a rate limit error by status code (robust) or retry-after header
94
94
  const isRateLimitError =
95
- rateLimitError.statusCode === RATE_LIMIT_STATUS_CODE ||
96
- rateLimitError.statusCode === CUSTOM_RATE_LIMIT_STATUS_CODE ||
97
- rateLimitError.retryAfter !== undefined
95
+ rateLimitError?.statusCode === RATE_LIMIT_STATUS_CODE ||
96
+ rateLimitError?.statusCode === CUSTOM_RATE_LIMIT_STATUS_CODE ||
97
+ rateLimitError?.retryAfter !== undefined
98
98
 
99
99
  if (!isRateLimitError || attempt === maxRetries) {
100
100
  // Not a rate limit error or out of retries, throw the error