@opensea/sdk 11.7.2 → 11.9.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 (87) hide show
  1. package/README.md +46 -14
  2. package/lib/abi/abis.d.ts +16 -0
  3. package/lib/abi/abis.js +13 -1
  4. package/lib/abi/abis.js.map +1 -1
  5. package/lib/api/api.d.ts +11 -3
  6. package/lib/api/api.js +17 -5
  7. package/lib/api/api.js.map +1 -1
  8. package/lib/api/collections.d.ts +7 -0
  9. package/lib/api/collections.js +10 -1
  10. package/lib/api/collections.js.map +1 -1
  11. package/lib/api/fetcher.d.ts +5 -2
  12. package/lib/api/walletAuth.d.ts +7 -0
  13. package/lib/api/walletAuth.js +8 -1
  14. package/lib/api/walletAuth.js.map +1 -1
  15. package/lib/constants.d.ts +6 -0
  16. package/lib/constants.js +7 -1
  17. package/lib/constants.js.map +1 -1
  18. package/lib/index.d.ts +1 -1
  19. package/lib/orders/erc20Fulfillment.d.ts +41 -0
  20. package/lib/orders/erc20Fulfillment.js +190 -0
  21. package/lib/orders/erc20Fulfillment.js.map +1 -0
  22. package/lib/orders/orderUseCase.d.ts +18 -0
  23. package/lib/orders/orderUseCase.js +29 -0
  24. package/lib/orders/orderUseCase.js.map +1 -0
  25. package/lib/orders/privateListings.js +8 -0
  26. package/lib/orders/privateListings.js.map +1 -1
  27. package/lib/sdk/base.d.ts +19 -7
  28. package/lib/sdk/base.js +19 -7
  29. package/lib/sdk/base.js.map +1 -1
  30. package/lib/sdk/cancellation.d.ts +2 -1
  31. package/lib/sdk/cancellation.js +2 -0
  32. package/lib/sdk/cancellation.js.map +1 -1
  33. package/lib/sdk/fulfillment.d.ts +57 -3
  34. package/lib/sdk/fulfillment.js +147 -4
  35. package/lib/sdk/fulfillment.js.map +1 -1
  36. package/lib/sdk/orders.d.ts +16 -3
  37. package/lib/sdk/orders.js +27 -13
  38. package/lib/sdk/orders.js.map +1 -1
  39. package/lib/stream/client.d.ts +67 -0
  40. package/lib/stream/client.js +174 -0
  41. package/lib/stream/client.js.map +1 -0
  42. package/lib/stream/constants.d.ts +3 -0
  43. package/lib/stream/constants.js +8 -0
  44. package/lib/stream/constants.js.map +1 -0
  45. package/lib/stream/helpers.d.ts +1 -0
  46. package/lib/stream/helpers.js +8 -0
  47. package/lib/stream/helpers.js.map +1 -0
  48. package/lib/stream/index.d.ts +17 -0
  49. package/lib/stream/index.js +34 -0
  50. package/lib/stream/index.js.map +1 -0
  51. package/lib/stream/transport/phoenix.d.ts +121 -0
  52. package/lib/stream/transport/phoenix.js +642 -0
  53. package/lib/stream/transport/phoenix.js.map +1 -0
  54. package/lib/stream/transport/types.d.ts +85 -0
  55. package/lib/stream/transport/types.js +24 -0
  56. package/lib/stream/transport/types.js.map +1 -0
  57. package/lib/stream/types.d.ts +269 -0
  58. package/lib/stream/types.js +29 -0
  59. package/lib/stream/types.js.map +1 -0
  60. package/lib/types.d.ts +14 -0
  61. package/lib/utils/units.d.ts +5 -0
  62. package/lib/utils/units.js +48 -9
  63. package/lib/utils/units.js.map +1 -1
  64. package/package.json +11 -10
  65. package/src/abi/abis.ts +13 -0
  66. package/src/api/api.ts +21 -5
  67. package/src/api/collections.ts +14 -1
  68. package/src/api/fetcher.ts +5 -2
  69. package/src/api/walletAuth.ts +9 -0
  70. package/src/constants.ts +8 -0
  71. package/src/index.ts +1 -1
  72. package/src/orders/erc20Fulfillment.ts +218 -0
  73. package/src/orders/orderUseCase.ts +34 -0
  74. package/src/orders/privateListings.ts +15 -0
  75. package/src/sdk/base.ts +20 -6
  76. package/src/sdk/cancellation.ts +4 -1
  77. package/src/sdk/fulfillment.ts +188 -6
  78. package/src/sdk/orders.ts +27 -15
  79. package/src/stream/client.ts +277 -0
  80. package/src/stream/constants.ts +5 -0
  81. package/src/stream/helpers.ts +3 -0
  82. package/src/stream/index.ts +18 -0
  83. package/src/stream/transport/phoenix.ts +815 -0
  84. package/src/stream/transport/types.ts +91 -0
  85. package/src/stream/types.ts +314 -0
  86. package/src/types.ts +14 -0
  87. package/src/utils/units.ts +54 -9
@@ -1,6 +1,14 @@
1
1
  import { SeaportABI } from "@opensea/seaport-js/lib/abi/Seaport"
2
2
  import type { OrderComponents } from "@opensea/seaport-js/lib/types"
3
+ import { CONDUIT_CONTROLLER_ABI, ERC20_ABI } from "../abi/abis"
3
4
  import type { Listing, Offer, Order } from "../api/types"
5
+ import { CONDUIT_CONTROLLER_ADDRESS } from "../constants"
6
+ import {
7
+ getErc20Payment,
8
+ getFulfillerConduitKey,
9
+ isZeroConduitKey,
10
+ toBigInt,
11
+ } from "../orders/erc20Fulfillment"
4
12
  import {
5
13
  computePrivateListingValue,
6
14
  constructPrivateListingCounterOrder,
@@ -15,6 +23,7 @@ import {
15
23
  OrderSide,
16
24
  } from "../types"
17
25
  import {
26
+ getDefaultConduit,
18
27
  getSeaportInstance,
19
28
  hasErrorCode,
20
29
  requireValidProtocol,
@@ -221,6 +230,13 @@ export class FulfillmentManager {
221
230
  params = Object.values(inputData)
222
231
  }
223
232
 
233
+ // ERC20-priced listings send no native value; Seaport pulls the payment from
234
+ // the buyer instead, which reverts with a bare "execution reverted" when the
235
+ // spender has not been approved. Catch that before spending gas.
236
+ await this.requireErc20PaymentIsSpendable(inputData, transaction.to, {
237
+ accountAddress,
238
+ })
239
+
224
240
  const encodedData = this.context.contractCaller.encodeFunctionData({
225
241
  abi: SeaportABI,
226
242
  functionName,
@@ -247,6 +263,137 @@ export class FulfillmentManager {
247
263
  return tx.hash
248
264
  }
249
265
 
266
+ /**
267
+ * Throw an actionable error when the buyer cannot pay for an ERC20-priced
268
+ * listing, because they hold too little of the payment token or have not
269
+ * approved the address Seaport pulls it from.
270
+ *
271
+ * The check is skipped for native-priced listings, for offer fulfillments, and
272
+ * for any response shape or RPC read it cannot interpret, so it never blocks a
273
+ * purchase that would otherwise have succeeded.
274
+ */
275
+ private async requireErc20PaymentIsSpendable(
276
+ inputData: unknown,
277
+ seaportAddress: string,
278
+ { accountAddress }: { accountAddress: string },
279
+ ): Promise<void> {
280
+ const payment = getErc20Payment(inputData)
281
+ if (!payment) {
282
+ return
283
+ }
284
+
285
+ const spender = await this.resolveFulfillerSpender(
286
+ getFulfillerConduitKey(inputData),
287
+ seaportAddress,
288
+ )
289
+ if (!spender) {
290
+ return
291
+ }
292
+
293
+ const spendState = await this.readErc20SpendState(
294
+ payment.token,
295
+ accountAddress,
296
+ spender,
297
+ )
298
+ if (!spendState) {
299
+ return
300
+ }
301
+
302
+ const amounts = `have ${spendState.balance}, need ${payment.amount} (base units of the payment token)`
303
+ if (spendState.balance < payment.amount) {
304
+ throw new Error(
305
+ `Insufficient ${payment.token} balance to fulfill this listing: ${amounts}. ` +
306
+ `Fund ${accountAddress} with the payment token before fulfilling.`,
307
+ )
308
+ }
309
+ if (spendState.allowance < payment.amount) {
310
+ throw new Error(
311
+ `Payment token ${payment.token} is not approved for this listing: allowance for ` +
312
+ `${spender} is ${spendState.allowance}, need ${payment.amount} (base units of the ` +
313
+ `payment token). ERC20-priced listings send no native value, so Seaport pulls the ` +
314
+ `payment through this spender. Send approve(${spender}, ${payment.amount}) from ` +
315
+ `${accountAddress} first.`,
316
+ )
317
+ }
318
+ }
319
+
320
+ /**
321
+ * Resolve the address that will pull the payment token: Seaport itself when the
322
+ * fulfiller conduit key is `bytes32(0)`, otherwise the conduit registered for
323
+ * that key. Returns null when the key cannot be resolved.
324
+ */
325
+ private async resolveFulfillerSpender(
326
+ conduitKey: string | null,
327
+ seaportAddress: string,
328
+ ): Promise<string | null> {
329
+ if (!conduitKey || isZeroConduitKey(conduitKey)) {
330
+ return seaportAddress
331
+ }
332
+
333
+ const defaultConduit = getDefaultConduit(this.context.chain)
334
+ if (conduitKey.toLowerCase() === defaultConduit.key.toLowerCase()) {
335
+ return defaultConduit.address
336
+ }
337
+
338
+ try {
339
+ const result = await this.context.contractCaller.readContract({
340
+ address: CONDUIT_CONTROLLER_ADDRESS,
341
+ abi: CONDUIT_CONTROLLER_ABI,
342
+ functionName: "getConduit",
343
+ args: [conduitKey],
344
+ })
345
+ if (
346
+ !Array.isArray(result) ||
347
+ typeof result[0] !== "string" ||
348
+ result[1] !== true
349
+ ) {
350
+ return null
351
+ }
352
+ return result[0]
353
+ } catch (error) {
354
+ this.context.logger(
355
+ `Could not resolve conduit for key ${conduitKey}, skipping the ERC20 approval check: ${error}`,
356
+ )
357
+ return null
358
+ }
359
+ }
360
+
361
+ /** Read the buyer's payment-token balance and allowance for a spender. */
362
+ private async readErc20SpendState(
363
+ token: string,
364
+ owner: string,
365
+ spender: string,
366
+ ): Promise<{ balance: bigint; allowance: bigint } | null> {
367
+ const contractCaller = this.context.contractCaller
368
+ try {
369
+ const [rawBalance, rawAllowance] = await Promise.all([
370
+ contractCaller.readContract({
371
+ address: token,
372
+ abi: ERC20_ABI,
373
+ functionName: "balanceOf",
374
+ args: [owner],
375
+ }),
376
+ contractCaller.readContract({
377
+ address: token,
378
+ abi: ERC20_ABI,
379
+ functionName: "allowance",
380
+ args: [owner, spender],
381
+ }),
382
+ ])
383
+ const balance = toBigInt(rawBalance)
384
+ const allowance = toBigInt(rawAllowance)
385
+ if (balance === null || allowance === null) {
386
+ return null
387
+ }
388
+ return { balance, allowance }
389
+ } catch (error) {
390
+ this.context.logger(
391
+ `Could not read ${token} balance or allowance, skipping the ERC20 approval check: ${error}`,
392
+ )
393
+ return null
394
+ }
395
+ }
396
+
250
397
  /**
251
398
  * Returns whether an order is fulfillable.
252
399
  * An order may not be fulfillable if a target item's transfer function
@@ -324,22 +471,35 @@ export class FulfillmentManager {
324
471
 
325
472
  /**
326
473
  * Validates an order onchain using Seaport's validate() method.
474
+ *
475
+ * The order is left with an empty signature: Seaport takes the transaction
476
+ * sender as proof the offerer approved it. This does not post the order to
477
+ * OpenSea. It becomes discoverable only once OpenSea ingests the resulting
478
+ * `OrderValidated` event.
479
+ *
480
+ * @param orderComponents The order to validate
481
+ * @param accountAddress Address sending the validate transaction
482
+ * @param protocolAddress Seaport protocol address the components were built
483
+ * for. Defaults to {@link DEFAULT_SEAPORT_CONTRACT_ADDRESS}.
484
+ * @returns Transaction hash of the validate transaction
485
+ *
486
+ * @throws Error if the accountAddress is not available through wallet or provider.
487
+ * @throws Error if the protocol address is not supported by OpenSea. See {@link isValidProtocol}.
327
488
  */
328
489
  async validateOrderOnchain(
329
490
  orderComponents: OrderComponents,
330
491
  accountAddress: string,
492
+ protocolAddress: string = DEFAULT_SEAPORT_CONTRACT_ADDRESS,
331
493
  ) {
332
494
  await this.context.requireAccountIsAvailable(accountAddress)
495
+ requireValidProtocol(protocolAddress)
333
496
 
334
497
  this.context.dispatch(EventType.ApproveOrder, {
335
498
  orderV2: { protocolData: orderComponents } as unknown as OrderV2,
336
499
  accountAddress,
337
500
  })
338
501
 
339
- const seaport = getSeaportInstance(
340
- DEFAULT_SEAPORT_CONTRACT_ADDRESS,
341
- this.context.seaport,
342
- )
502
+ const seaport = getSeaportInstance(protocolAddress, this.context.seaport)
343
503
  const transaction = await seaport
344
504
  .validate(
345
505
  [{ parameters: orderComponents, signature: "0x" }],
@@ -357,7 +517,18 @@ export class FulfillmentManager {
357
517
  }
358
518
 
359
519
  /**
360
- * Create and validate a listing onchain.
520
+ * Create a listing and validate it onchain, instead of signing it offchain.
521
+ *
522
+ * Runs any token approvals the listing needs, then sends one `validate()`
523
+ * transaction. The wallet is never asked for an EIP-712 signature, so this
524
+ * works for contract accounts that cannot produce one.
525
+ *
526
+ * Unlike {@link OrdersManager.createListing}, this does not post the listing
527
+ * to OpenSea. It becomes discoverable only once OpenSea ingests the
528
+ * `OrderValidated` event, so the returned hash is a transaction hash, not an
529
+ * order hash.
530
+ *
531
+ * @returns Transaction hash of the validate transaction
361
532
  */
362
533
  async createListingAndValidateOnchain({
363
534
  asset,
@@ -403,7 +574,18 @@ export class FulfillmentManager {
403
574
  }
404
575
 
405
576
  /**
406
- * Create and validate an offer onchain.
577
+ * Create an offer and validate it onchain, instead of signing it offchain.
578
+ *
579
+ * Runs any token approvals the offer needs, then sends one `validate()`
580
+ * transaction. The wallet is never asked for an EIP-712 signature, so this
581
+ * works for contract accounts that cannot produce one.
582
+ *
583
+ * Unlike {@link OrdersManager.createOffer}, this does not post the offer to
584
+ * OpenSea. It becomes discoverable only once OpenSea ingests the
585
+ * `OrderValidated` event, so the returned hash is a transaction hash, not an
586
+ * order hash.
587
+ *
588
+ * @returns Transaction hash of the validate transaction
407
589
  */
408
590
  async createOfferAndValidateOnchain({
409
591
  asset,
package/src/sdk/orders.ts CHANGED
@@ -5,6 +5,7 @@ import type {
5
5
  } from "@opensea/seaport-js/lib/types"
6
6
  import type { CollectionOffer, Listing, NFT, Offer } from "../api/types"
7
7
  import { INVERSE_BASIS_POINT, ZERO_ADDRESS } from "../constants"
8
+ import { executeApprovalsAndGetOrderComponents } from "../orders/orderUseCase"
8
9
  import type { ProtocolData } from "../orders/types"
9
10
  import {
10
11
  type Amount,
@@ -143,7 +144,10 @@ export class OrdersManager {
143
144
  /**
144
145
  * Build listing order without submitting to API
145
146
  * @param options Listing parameters
146
- * @returns OrderWithCounter ready for API submission or onchain validation
147
+ * @returns The seaport-js use case. Call `executeAllActions()` to approve and
148
+ * sign it for API submission, or
149
+ * {@link executeApprovalsAndGetOrderComponents} to approve it without a
150
+ * signature for onchain validation.
147
151
  */
148
152
  private async _buildListingOrder({
149
153
  asset,
@@ -212,7 +216,7 @@ export class OrdersManager {
212
216
  zone = collection.requiredZone
213
217
  }
214
218
 
215
- const { executeAllActions } = await this.context.seaport.createOrder(
219
+ return this.context.seaport.createOrder(
216
220
  {
217
221
  offer: offerAssetItems,
218
222
  consideration: considerationFeeItems,
@@ -227,12 +231,15 @@ export class OrdersManager {
227
231
  },
228
232
  accountAddress,
229
233
  )
230
-
231
- return executeAllActions()
232
234
  }
233
235
 
234
236
  /**
235
- * Build listing order components without submitting to API
237
+ * Build listing order components without submitting to API.
238
+ *
239
+ * Runs any token approvals the order needs, but does not ask the wallet to
240
+ * sign: the components are meant for onchain validation, which needs no
241
+ * offchain signature.
242
+ *
236
243
  * @param options Listing parameters
237
244
  * @returns OrderComponents ready for onchain validation
238
245
  */
@@ -261,7 +268,7 @@ export class OrdersManager {
261
268
  includeOptionalCreatorFees?: boolean
262
269
  zone?: string
263
270
  }): Promise<OrderComponents> {
264
- const order = await this._buildListingOrder({
271
+ const useCase = await this._buildListingOrder({
265
272
  asset,
266
273
  accountAddress,
267
274
  amount,
@@ -274,7 +281,7 @@ export class OrdersManager {
274
281
  includeOptionalCreatorFees,
275
282
  zone,
276
283
  })
277
- return order.parameters
284
+ return executeApprovalsAndGetOrderComponents(useCase)
278
285
  }
279
286
 
280
287
  /**
@@ -334,7 +341,7 @@ export class OrdersManager {
334
341
  zone = collection.requiredZone
335
342
  }
336
343
 
337
- const { executeAllActions } = await this.context.seaport.createOrder(
344
+ return this.context.seaport.createOrder(
338
345
  {
339
346
  offer: [
340
347
  {
@@ -355,12 +362,15 @@ export class OrdersManager {
355
362
  },
356
363
  accountAddress,
357
364
  )
358
-
359
- return executeAllActions()
360
365
  }
361
366
 
362
367
  /**
363
- * Build offer order components without submitting to API
368
+ * Build offer order components without submitting to API.
369
+ *
370
+ * Runs any token approvals the order needs, but does not ask the wallet to
371
+ * sign: the components are meant for onchain validation, which needs no
372
+ * offchain signature.
373
+ *
364
374
  * @param options Offer parameters
365
375
  * @returns OrderComponents ready for onchain validation
366
376
  */
@@ -383,7 +393,7 @@ export class OrdersManager {
383
393
  expirationTime?: Amount
384
394
  zone?: string
385
395
  }): Promise<OrderComponents> {
386
- const order = await this._buildOfferOrder({
396
+ const useCase = await this._buildOfferOrder({
387
397
  asset,
388
398
  accountAddress,
389
399
  amount,
@@ -393,7 +403,7 @@ export class OrdersManager {
393
403
  expirationTime,
394
404
  zone,
395
405
  })
396
- return order.parameters
406
+ return executeApprovalsAndGetOrderComponents(useCase)
397
407
  }
398
408
 
399
409
  /**
@@ -433,7 +443,7 @@ export class OrdersManager {
433
443
  expirationTime?: Amount
434
444
  zone?: string
435
445
  }): Promise<Offer> {
436
- const order = await this._buildOfferOrder({
446
+ const useCase = await this._buildOfferOrder({
437
447
  asset,
438
448
  accountAddress,
439
449
  amount,
@@ -443,6 +453,7 @@ export class OrdersManager {
443
453
  expirationTime,
444
454
  zone,
445
455
  })
456
+ const order = await useCase.executeAllActions()
446
457
 
447
458
  return this.context.api.postOffer(
448
459
  order,
@@ -495,7 +506,7 @@ export class OrdersManager {
495
506
  includeOptionalCreatorFees?: boolean
496
507
  zone?: string
497
508
  }): Promise<Listing> {
498
- const order = await this._buildListingOrder({
509
+ const useCase = await this._buildListingOrder({
499
510
  asset,
500
511
  accountAddress,
501
512
  amount,
@@ -508,6 +519,7 @@ export class OrdersManager {
508
519
  includeOptionalCreatorFees,
509
520
  zone,
510
521
  })
522
+ const order = await useCase.executeAllActions()
511
523
 
512
524
  return this.context.api.postListing(
513
525
  order,
@@ -0,0 +1,277 @@
1
+ import { ENDPOINTS } from "./constants"
2
+ import { collectionTopic } from "./helpers"
3
+ import { PhoenixChannelsTransport } from "./transport/phoenix"
4
+ import type { StreamTransport } from "./transport/types"
5
+ import {
6
+ type BaseStreamMessage,
7
+ type Callback,
8
+ type ClientConfig,
9
+ type CollectionOfferEvent,
10
+ EventType,
11
+ type ItemCancelledEvent,
12
+ type ItemListedEvent,
13
+ type ItemMetadataUpdate,
14
+ type ItemReceivedBidEvent,
15
+ type ItemReceivedOfferEvent,
16
+ type ItemSoldEvent,
17
+ type ItemTransferredEvent,
18
+ LogLevel,
19
+ Network,
20
+ type OnClientEvent,
21
+ type OrderValidationEvent,
22
+ type TraitOfferEvent,
23
+ } from "./types"
24
+
25
+ /**
26
+ * Client for the OpenSea Stream API.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { OpenSeaStreamClient } from "@opensea/sdk/stream"
31
+ *
32
+ * const client = new OpenSeaStreamClient({ apiKey: "YOUR_API_KEY" })
33
+ *
34
+ * const unsubscribe = client.onItemListed("doodles-official", event => {
35
+ * console.log(event.payload.item.nft_id)
36
+ * })
37
+ * ```
38
+ *
39
+ * @category Main Classes
40
+ */
41
+ export class OpenSeaStreamClient {
42
+ private transport: StreamTransport
43
+ private logLevel: LogLevel
44
+ private onEvent: OnClientEvent
45
+
46
+ constructor({
47
+ network = Network.MAINNET,
48
+ apiKey,
49
+ token,
50
+ apiUrl,
51
+ connectOptions,
52
+ logLevel = LogLevel.INFO,
53
+ onError,
54
+ onEvent = () => true,
55
+ }: ClientConfig) {
56
+ const key = apiKey ?? token
57
+ if (!key) {
58
+ throw new Error(
59
+ "An OpenSea API key is required. Pass it as `apiKey` when constructing OpenSeaStreamClient.",
60
+ )
61
+ }
62
+
63
+ this.logLevel = logLevel
64
+ this.onEvent = onEvent
65
+
66
+ const endpoint = apiUrl || ENDPOINTS[network]
67
+ const { params, ...transportOptions } = connectOptions ?? {}
68
+
69
+ this.transport = new PhoenixChannelsTransport({
70
+ endpoint,
71
+ params: { token: key, ...params },
72
+ ...transportOptions,
73
+ logger: message => this.debug(message),
74
+ })
75
+
76
+ this.transport.onError(onError ?? (error => this.error(error)))
77
+ }
78
+
79
+ private debug(message: unknown) {
80
+ if (this.logLevel <= LogLevel.DEBUG) {
81
+ console.debug("[DEBUG]:", message)
82
+ }
83
+ }
84
+
85
+ private info(message: unknown) {
86
+ if (this.logLevel <= LogLevel.INFO) {
87
+ console.info("[INFO]:", message)
88
+ }
89
+ }
90
+
91
+ private error(message: unknown) {
92
+ if (this.logLevel <= LogLevel.ERROR) {
93
+ console.error("[ERROR]:", message)
94
+ }
95
+ }
96
+
97
+ public connect = () => {
98
+ this.debug("Connecting to socket")
99
+ this.transport.connect()
100
+ }
101
+
102
+ public disconnect = (
103
+ callback = () => this.info(`Successfully disconnected from socket`),
104
+ ) => {
105
+ return this.transport.disconnect(callback)
106
+ }
107
+
108
+ private on = <Payload, Event extends BaseStreamMessage<Payload>>(
109
+ eventType: EventType,
110
+ collectionSlug: string,
111
+ callback: Callback<Event>,
112
+ eventTypes?: EventType[],
113
+ ) => {
114
+ const topic = collectionTopic(collectionSlug)
115
+ this.debug(`Subscribing to ${eventType} events on ${topic}`)
116
+
117
+ const onClientEvent = this.onEvent
118
+ const handler = (message: unknown) => {
119
+ const event = message as Event
120
+ if (onClientEvent(collectionSlug, eventType, event)) {
121
+ callback(event)
122
+ }
123
+ }
124
+
125
+ const subscription = this.transport.subscribe(
126
+ topic,
127
+ { eventTypes },
128
+ {
129
+ onSubscribed: () => this.info(`Successfully joined channel "${topic}"`),
130
+ onSubscribeError: reason => {
131
+ this.error(`Failed to join channel "${topic}"`)
132
+ this.debug(reason)
133
+ },
134
+ },
135
+ )
136
+ const off = subscription.on(eventType, handler)
137
+
138
+ return () => {
139
+ this.debug(`Unsubscribing from ${eventType} events on ${topic}`)
140
+ // Removes only this handler. The topic is torn down once nothing is
141
+ // listening to it. The original stream-js client left the whole channel
142
+ // here, which silently killed sibling subscriptions on the same
143
+ // collection.
144
+ off()
145
+ }
146
+ }
147
+
148
+ public onItemMetadataUpdated = (
149
+ collectionSlug: string,
150
+ callback: Callback<ItemMetadataUpdate>,
151
+ ) => {
152
+ this.debug(`Listening for item metadata updates on "${collectionSlug}"`)
153
+ return this.on(EventType.ITEM_METADATA_UPDATED, collectionSlug, callback)
154
+ }
155
+
156
+ public onItemCancelled = (
157
+ collectionSlug: string,
158
+ callback: Callback<ItemCancelledEvent>,
159
+ ) => {
160
+ this.debug(`Listening for item cancellations on "${collectionSlug}"`)
161
+ return this.on(EventType.ITEM_CANCELLED, collectionSlug, callback)
162
+ }
163
+
164
+ public onItemListed = (
165
+ collectionSlug: string,
166
+ callback: Callback<ItemListedEvent>,
167
+ ) => {
168
+ this.debug(`Listening for item listings on "${collectionSlug}"`)
169
+ return this.on(EventType.ITEM_LISTED, collectionSlug, callback)
170
+ }
171
+
172
+ public onItemSold = (
173
+ collectionSlug: string,
174
+ callback: Callback<ItemSoldEvent>,
175
+ ) => {
176
+ this.debug(`Listening for item sales on "${collectionSlug}"`)
177
+ return this.on(EventType.ITEM_SOLD, collectionSlug, callback)
178
+ }
179
+
180
+ public onItemTransferred = (
181
+ collectionSlug: string,
182
+ callback: Callback<ItemTransferredEvent>,
183
+ ) => {
184
+ this.debug(`Listening for item transfers on "${collectionSlug}"`)
185
+ return this.on(EventType.ITEM_TRANSFERRED, collectionSlug, callback)
186
+ }
187
+
188
+ public onItemReceivedOffer = (
189
+ collectionSlug: string,
190
+ callback: Callback<ItemReceivedOfferEvent>,
191
+ ) => {
192
+ this.debug(`Listening for item offers on "${collectionSlug}"`)
193
+ return this.on(EventType.ITEM_RECEIVED_OFFER, collectionSlug, callback)
194
+ }
195
+
196
+ public onItemReceivedBid = (
197
+ collectionSlug: string,
198
+ callback: Callback<ItemReceivedBidEvent>,
199
+ ) => {
200
+ this.debug(`Listening for item bids on "${collectionSlug}"`)
201
+ return this.on(EventType.ITEM_RECEIVED_BID, collectionSlug, callback)
202
+ }
203
+
204
+ public onCollectionOffer = (
205
+ collectionSlug: string,
206
+ callback: Callback<CollectionOfferEvent>,
207
+ ) => {
208
+ this.debug(`Listening for collection offers on "${collectionSlug}"`)
209
+ return this.on(EventType.COLLECTION_OFFER, collectionSlug, callback)
210
+ }
211
+
212
+ public onTraitOffer = (
213
+ collectionSlug: string,
214
+ callback: Callback<TraitOfferEvent>,
215
+ ) => {
216
+ this.debug(`Listening for trait offers on "${collectionSlug}"`)
217
+ return this.on(EventType.TRAIT_OFFER, collectionSlug, callback)
218
+ }
219
+
220
+ public onOrderInvalidate = (
221
+ collectionSlug: string,
222
+ callback: Callback<OrderValidationEvent>,
223
+ ) => {
224
+ this.debug(`Listening for order invalidation events on "${collectionSlug}"`)
225
+ return this.on(EventType.ORDER_INVALIDATE, collectionSlug, callback)
226
+ }
227
+
228
+ public onOrderRevalidate = (
229
+ collectionSlug: string,
230
+ callback: Callback<OrderValidationEvent>,
231
+ ) => {
232
+ this.debug(`Listening for order revalidation events on "${collectionSlug}"`)
233
+ return this.on(EventType.ORDER_REVALIDATE, collectionSlug, callback)
234
+ }
235
+
236
+ /**
237
+ * Subscribe to several event types on one collection with a single callback,
238
+ * filtered server-side to the requested types.
239
+ *
240
+ * The callback receives `BaseStreamMessage<unknown>`: one subscription can
241
+ * deliver several event types, so there is no single payload type to hand
242
+ * back. `event_type` identifies which arrived, and the payload needs
243
+ * narrowing before use.
244
+ *
245
+ * ```ts
246
+ * client.onEvents(slug, [EventType.ITEM_SOLD, EventType.ITEM_LISTED], event => {
247
+ * if (event.event_type === EventType.ITEM_SOLD) {
248
+ * const sale = event as ItemSoldEvent
249
+ * console.log(sale.payload.sale_price)
250
+ * }
251
+ * })
252
+ * ```
253
+ *
254
+ * Use the typed single-event methods, such as `onItemSold`, when you want the
255
+ * payload typed for you.
256
+ *
257
+ * @param collectionSlug collection slug, or `"*"` for all collections
258
+ * @param eventTypes event types to subscribe to
259
+ * @param callback invoked for every subscribed event type
260
+ * @returns a function that removes all of this call's handlers
261
+ */
262
+ public onEvents = (
263
+ collectionSlug: string,
264
+ eventTypes: EventType[],
265
+ callback: Callback<BaseStreamMessage<unknown>>,
266
+ ) => {
267
+ const subscriptions = eventTypes.map(eventType =>
268
+ this.on(eventType, collectionSlug, callback, eventTypes),
269
+ )
270
+
271
+ return () => {
272
+ for (const unsubscribe of subscriptions) {
273
+ unsubscribe()
274
+ }
275
+ }
276
+ }
277
+ }
@@ -0,0 +1,5 @@
1
+ import { Network } from "./types"
2
+
3
+ export const ENDPOINTS = {
4
+ [Network.MAINNET]: "wss://stream-api.opensea.io/socket",
5
+ }
@@ -0,0 +1,3 @@
1
+ export const collectionTopic = (slug: string) => {
2
+ return `collection:${slug}`
3
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * OpenSea Stream API client.
3
+ *
4
+ * Subscribe to real-time marketplace events over WebSocket.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { OpenSeaStreamClient } from "@opensea/sdk/stream"
9
+ *
10
+ * const client = new OpenSeaStreamClient({ apiKey: "YOUR_API_KEY" })
11
+ * client.onItemSold("doodles-official", event => console.log(event))
12
+ * ```
13
+ *
14
+ * @module
15
+ */
16
+
17
+ export * from "./client"
18
+ export * from "./types"