@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
@@ -79,10 +79,23 @@ export class CollectionsAPI {
79
79
 
80
80
  /**
81
81
  * Fetch all traits for a collection with their possible values and counts.
82
+ *
83
+ * Opts out of response camelization: this payload is keyed by
84
+ * collection-authored trait names and trait values rather than by field
85
+ * names, so the default rewrite reports a `dark_brown` trait as `darkBrown`
86
+ * and silently merges two traits that differ only in casing. The response's
87
+ * own field names (`categories`, `counts`) are single words with nothing to
88
+ * convert, so opting out is complete rather than a partial workaround.
82
89
  */
83
90
  async getTraits(collectionSlug: string): Promise<GetTraitsResponse> {
84
91
  const path = getTraitsPath(collectionSlug)
85
- const response = await this.fetcher.get<GetTraitsResponse>(path)
92
+ const response = await this.fetcher.get<GetTraitsResponse>(
93
+ path,
94
+ undefined,
95
+ {
96
+ camelizeResponse: false,
97
+ },
98
+ )
86
99
  return response
87
100
  }
88
101
 
@@ -33,14 +33,17 @@ export type HttpMethod = "POST" | "PUT" | "PATCH" | "DELETE"
33
33
  *
34
34
  * Responses are camelized at this boundary — pass the API's snake_case shape
35
35
  * (e.g. an api-types response type) as `T` and the return is the camelCase
36
- * view. See `utils/case.ts`.
36
+ * view. See `utils/case.ts`. Endpoints whose response keys are data rather
37
+ * than field names opt out with {@link RequestOptions.camelizeResponse}.
37
38
  */
38
39
  export interface Fetcher {
39
40
  /**
40
41
  * Generic fetch method for GET requests with automatic rate limit retry
41
42
  * @param apiPath Path to URL endpoint under API
42
43
  * @param query URL query params. Will be used to create a URLSearchParams object.
43
- * @param options Request options like timeout and abort signal.
44
+ * @param options Request options like timeout and abort signal. Includes the
45
+ * {@link RequestOptions.camelizeResponse} opt-out for endpoints
46
+ * whose response keys are data (e.g. trait names).
44
47
  * @returns The camelCase view of the API response.
45
48
  */
46
49
  get<T>(
@@ -400,11 +400,20 @@ export class WalletAuthAPI {
400
400
  )
401
401
  }
402
402
 
403
+ /**
404
+ * `LinkWalletSiwxRequest` is camelCase on the wire. `chainArch` is required, so
405
+ * snake-casing it made every call fail validation, and the nested SIWX `message`
406
+ * keeps camelCase keys the server uses to rebuild the message the wallet signed.
407
+ * Sent verbatim, matching the raw fetch in `auth/siwx.ts` that posts the same
408
+ * operation.
409
+ */
403
410
  linkWallet(body: WalletAuthRequest<"link_wallet_with_siwx">) {
404
411
  return this.fetcher.request<OperationResponse<"link_wallet_with_siwx">>(
405
412
  "POST",
406
413
  "/api/v2/accounts/wallets/siwx",
407
414
  body,
415
+ undefined,
416
+ { snakeizeBody: false },
408
417
  )
409
418
  }
410
419
 
package/src/constants.ts CHANGED
@@ -39,6 +39,14 @@ export const OPENSEA_CONDUIT_ADDRESS_2 =
39
39
  export const OPENSEA_SIGNED_ZONE_V2 =
40
40
  "0x000056f7000000ece9003ca63978907a00ffd100"
41
41
 
42
+ /**
43
+ * Seaport's ConduitController, deployed at the same address on every chain.
44
+ * Resolves a conduit key to the conduit address that pulls tokens on Seaport's
45
+ * behalf, which is the address a buyer approves for an ERC20-priced purchase.
46
+ */
47
+ export const CONDUIT_CONTROLLER_ADDRESS =
48
+ "0x00000000f9490004c11cef243f5400493c00ad63"
49
+
42
50
  // =============================================================================
43
51
  // Alternate Protocol Constants (shared by Gunzilla, Somnia, etc.)
44
52
  // =============================================================================
package/src/index.ts CHANGED
@@ -25,7 +25,7 @@ export * from "./utils"
25
25
  * // Example Setup
26
26
  * ```ts
27
27
  * import { ethers } from 'ethers'
28
- * import { OpenSeaSDK, Chain } from 'opensea-js'
28
+ * import { OpenSeaSDK, Chain } from '@opensea/sdk'
29
29
  * const provider = new ethers.JsonRpcProvider('https://mainnet.infura.io')
30
30
  * const client = new OpenSeaSDK(provider, {
31
31
  * chain: Chain.Mainnet
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Helpers for ERC20-denominated listing fulfillment.
3
+ *
4
+ * When a listing is priced in an ERC20 token instead of the native currency,
5
+ * `transaction.value` is `0` and Seaport pulls the payment from the buyer with
6
+ * `transferFrom`. That only works if the buyer has already approved the spender,
7
+ * so the fulfillment reverts with a bare "execution reverted" when they haven't.
8
+ * These helpers read the payment token and amount out of the API's fulfillment
9
+ * input data so the SDK can check the allowance before spending gas.
10
+ */
11
+
12
+ /** Seaport `ItemType` for an ERC20 item. 0 is native, and anything >= 2 is an NFT. */
13
+ const ITEM_TYPE_ERC20 = 1
14
+
15
+ /**
16
+ * Seaport `BasicOrderRouteType` values where the fulfiller pays with an ERC20
17
+ * token: `ERC20_TO_ERC721` (2) and `ERC20_TO_ERC1155` (3). Routes 0-1 are
18
+ * native-priced listings; routes 4-5 are offer fulfillments, where the fulfiller
19
+ * provides the NFT and the ERC20 comes from the offerer instead.
20
+ */
21
+ const ERC20_PAYMENT_ROUTES = new Set([2, 3])
22
+
23
+ /** A `bytes32(0)` conduit key means Seaport transfers directly, with no conduit. */
24
+ export const ZERO_CONDUIT_KEY = `0x${"0".repeat(64)}`
25
+
26
+ export type Erc20Payment = {
27
+ /** Payment token contract address. */
28
+ token: string
29
+ /** Total amount the fulfiller owes, in the token's base units. */
30
+ amount: bigint
31
+ }
32
+
33
+ type ConsiderationItemLike = {
34
+ itemType?: unknown
35
+ token?: unknown
36
+ startAmount?: unknown
37
+ }
38
+
39
+ /**
40
+ * Coerce a value an RPC adapter may return as a bigint, a decimal string, or a
41
+ * number into a bigint. Returns null for anything else.
42
+ */
43
+ export function toBigInt(value: unknown): bigint | null {
44
+ if (typeof value === "bigint") {
45
+ return value
46
+ }
47
+ if (typeof value === "number" && Number.isInteger(value)) {
48
+ return BigInt(value)
49
+ }
50
+ if (typeof value === "string" && /^\d+$/.test(value.trim())) {
51
+ return BigInt(value.trim())
52
+ }
53
+ return null
54
+ }
55
+
56
+ function toNumber(value: unknown): number | null {
57
+ const asBigInt = toBigInt(value)
58
+ return asBigInt === null ? null : Number(asBigInt)
59
+ }
60
+
61
+ function isRecord(value: unknown): value is Record<string, unknown> {
62
+ return typeof value === "object" && value !== null
63
+ }
64
+
65
+ /**
66
+ * Sum the ERC20 consideration items of a listing, which together are what the
67
+ * fulfiller pays (seller proceeds plus marketplace and creator fees).
68
+ *
69
+ * Returns null unless every consideration item is the same ERC20 token. A native
70
+ * item means the listing is native-priced, an NFT item means this is an offer
71
+ * fulfillment rather than a purchase, and mixed tokens are not something we can
72
+ * express as a single allowance.
73
+ */
74
+ function sumErc20Consideration(consideration: unknown): Erc20Payment | null {
75
+ if (!Array.isArray(consideration) || consideration.length === 0) {
76
+ return null
77
+ }
78
+
79
+ let token: string | null = null
80
+ let total = 0n
81
+
82
+ for (const rawItem of consideration as ConsiderationItemLike[]) {
83
+ if (!isRecord(rawItem)) {
84
+ return null
85
+ }
86
+ const itemType = toNumber(rawItem.itemType)
87
+ if (itemType !== ITEM_TYPE_ERC20) {
88
+ // Native payment, an NFT in the consideration, or an unreadable item type.
89
+ return null
90
+ }
91
+ const itemToken = rawItem.token
92
+ if (typeof itemToken !== "string") {
93
+ return null
94
+ }
95
+ if (token === null) {
96
+ token = itemToken
97
+ } else if (token.toLowerCase() !== itemToken.toLowerCase()) {
98
+ return null
99
+ }
100
+ const amount = toBigInt(rawItem.startAmount)
101
+ if (amount === null) {
102
+ return null
103
+ }
104
+ total += amount
105
+ }
106
+
107
+ return token === null ? null : { token, amount: total }
108
+ }
109
+
110
+ /**
111
+ * Sum the ERC20 payment for a basic order, whose consideration is flattened into
112
+ * `considerationAmount` plus one entry per `additionalRecipients` fee.
113
+ */
114
+ function basicOrderErc20Payment(
115
+ basicOrderParameters: unknown,
116
+ ): Erc20Payment | null {
117
+ if (!isRecord(basicOrderParameters)) {
118
+ return null
119
+ }
120
+
121
+ const basicOrderType = toNumber(basicOrderParameters.basicOrderType)
122
+ if (basicOrderType === null) {
123
+ return null
124
+ }
125
+ // Four order types share each route: full/partial x open/restricted.
126
+ if (!ERC20_PAYMENT_ROUTES.has(Math.floor(basicOrderType / 4))) {
127
+ return null
128
+ }
129
+
130
+ const token = basicOrderParameters.considerationToken
131
+ if (typeof token !== "string") {
132
+ return null
133
+ }
134
+
135
+ let total = toBigInt(basicOrderParameters.considerationAmount)
136
+ if (total === null) {
137
+ return null
138
+ }
139
+
140
+ const additionalRecipients = basicOrderParameters.additionalRecipients
141
+ if (additionalRecipients !== undefined) {
142
+ if (!Array.isArray(additionalRecipients)) {
143
+ return null
144
+ }
145
+ for (const recipient of additionalRecipients) {
146
+ if (!isRecord(recipient)) {
147
+ return null
148
+ }
149
+ const amount = toBigInt(recipient.amount)
150
+ if (amount === null) {
151
+ return null
152
+ }
153
+ total += amount
154
+ }
155
+ }
156
+
157
+ return { token, amount: total }
158
+ }
159
+
160
+ /**
161
+ * Read the ERC20 payment a fulfiller owes from the `inputData` of an OpenSea
162
+ * fulfillment response.
163
+ *
164
+ * Returns null whenever the payment is not a single ERC20 amount we can read
165
+ * with confidence, including native-priced listings and offer fulfillments.
166
+ * Callers must treat null as "no preflight possible" and submit the transaction
167
+ * unchanged, so an unfamiliar response shape can never block a working purchase.
168
+ */
169
+ export function getErc20Payment(inputData: unknown): Erc20Payment | null {
170
+ if (!isRecord(inputData)) {
171
+ return null
172
+ }
173
+
174
+ if ("basicOrderParameters" in inputData) {
175
+ return basicOrderErc20Payment(inputData.basicOrderParameters)
176
+ }
177
+
178
+ const order = isRecord(inputData.advancedOrder)
179
+ ? inputData.advancedOrder
180
+ : isRecord(inputData.order)
181
+ ? inputData.order
182
+ : null
183
+ if (!order || !isRecord(order.parameters)) {
184
+ return null
185
+ }
186
+
187
+ return sumErc20Consideration(order.parameters.consideration)
188
+ }
189
+
190
+ /**
191
+ * Read the fulfiller's conduit key, which decides who the buyer must approve:
192
+ * the resolved conduit for a non-zero key, or Seaport itself for `bytes32(0)`.
193
+ * Returns null when the response does not carry one.
194
+ */
195
+ export function getFulfillerConduitKey(inputData: unknown): string | null {
196
+ if (!isRecord(inputData)) {
197
+ return null
198
+ }
199
+ const direct = inputData.fulfillerConduitKey
200
+ if (typeof direct === "string") {
201
+ return direct
202
+ }
203
+ if (isRecord(inputData.basicOrderParameters)) {
204
+ const fromBasicOrder = inputData.basicOrderParameters.fulfillerConduitKey
205
+ if (typeof fromBasicOrder === "string") {
206
+ return fromBasicOrder
207
+ }
208
+ }
209
+ return null
210
+ }
211
+
212
+ /** Whether a conduit key means "transfer directly from Seaport, no conduit". */
213
+ export function isZeroConduitKey(conduitKey: string | null): boolean {
214
+ if (!conduitKey) {
215
+ return true
216
+ }
217
+ return conduitKey.toLowerCase() === ZERO_CONDUIT_KEY
218
+ }
@@ -0,0 +1,34 @@
1
+ import type {
2
+ CreateOrderAction,
3
+ OrderComponents,
4
+ OrderUseCase,
5
+ } from "@opensea/seaport-js/lib/types"
6
+
7
+ /**
8
+ * Run the approval transactions from a seaport-js create-order use case and
9
+ * return the resulting order components, without asking the wallet to sign.
10
+ *
11
+ * `executeAllActions()` also requests an EIP-712 signature. Callers that
12
+ * validate the order onchain have no use for one, since Seaport's `validate()`
13
+ * takes the transaction sender as proof the offerer approved the order.
14
+ * Requesting it anyway costs an extra wallet prompt for a signature that is
15
+ * discarded, and shuts out contract accounts that cannot produce an offchain
16
+ * signature at all.
17
+ *
18
+ * @param useCase The use case returned by `seaport.createOrder`
19
+ * @returns Order components ready for onchain validation
20
+ *
21
+ * @throws Error if the use case has no create-order action.
22
+ */
23
+ export const executeApprovalsAndGetOrderComponents = async (
24
+ useCase: OrderUseCase<CreateOrderAction>,
25
+ ): Promise<OrderComponents> => {
26
+ await useCase.executeApprovals()
27
+
28
+ const createAction = useCase.actions.find(action => action.type === "create")
29
+ if (!createAction) {
30
+ throw new Error("Seaport create-order use case has no create action")
31
+ }
32
+
33
+ return createAction.orderComponents
34
+ }
@@ -62,6 +62,21 @@ export const constructPrivateListingCounterOrder = (
62
62
  ) {
63
63
  throw new Error("Not all currency items were the same for private order")
64
64
  }
65
+ // The counter order below sums every payment item into a single offer item
66
+ // denominated in the first item's token, so two different ERC-20s would be
67
+ // aggregated as if they were one. Seaport then rejects the match because
68
+ // the offer and consideration components disagree on token, surfacing as an
69
+ // onchain revert rather than as this error.
70
+ if (
71
+ !paymentItems.every(
72
+ item =>
73
+ item.token.toLowerCase() === paymentItems[0].token.toLowerCase(),
74
+ )
75
+ ) {
76
+ throw new Error(
77
+ "Not all currency items were the same for private order: payment items must all use the same token",
78
+ )
79
+ }
65
80
  }
66
81
 
67
82
  const { aggregatedStartAmount, aggregatedEndAmount } = paymentItems.reduce(
package/src/sdk/base.ts CHANGED
@@ -111,7 +111,7 @@ export class BaseOpenSeaSDK {
111
111
  /**
112
112
  * Request a free-tier OpenSea API key without authentication. The returned
113
113
  * key can be passed as `apiKey` into the SDK constructor to bootstrap usage.
114
- * Rate limited to 3 keys per hour per IP; keys expire after 30 days.
114
+ * Keys expire after 7 days.
115
115
  *
116
116
  * @example
117
117
  * ```ts
@@ -412,18 +412,26 @@ export class BaseOpenSeaSDK {
412
412
  return this._fulfillmentManager.approveOrder(order, domain)
413
413
  }
414
414
 
415
- /** Validates an order onchain using Seaport's validate() method. */
415
+ /**
416
+ * Validates an order onchain using Seaport's validate() method, approving it
417
+ * without an offchain signature. Does not post the order to OpenSea.
418
+ */
416
419
  public async validateOrderOnchain(
417
420
  orderComponents: OrderComponents,
418
421
  accountAddress: string,
422
+ protocolAddress?: string,
419
423
  ) {
420
424
  return this._fulfillmentManager.validateOrderOnchain(
421
425
  orderComponents,
422
426
  accountAddress,
427
+ protocolAddress,
423
428
  )
424
429
  }
425
430
 
426
- /** Create and validate a listing onchain. */
431
+ /**
432
+ * Create a listing and validate it onchain instead of signing it offchain.
433
+ * Does not post the listing to OpenSea. Returns a transaction hash.
434
+ */
427
435
  public async createListingAndValidateOnchain(options: {
428
436
  asset: AssetWithTokenId
429
437
  accountAddress: string
@@ -440,7 +448,10 @@ export class BaseOpenSeaSDK {
440
448
  return this._fulfillmentManager.createListingAndValidateOnchain(options)
441
449
  }
442
450
 
443
- /** Create and validate an offer onchain. */
451
+ /**
452
+ * Create an offer and validate it onchain instead of signing it offchain.
453
+ * Does not post the offer to OpenSea. Returns a transaction hash.
454
+ */
444
455
  public async createOfferAndValidateOnchain(options: {
445
456
  asset: AssetWithTokenId
446
457
  accountAddress: string
@@ -478,14 +489,17 @@ export class BaseOpenSeaSDK {
478
489
  return this._cancellationManager.cancelOrders(options)
479
490
  }
480
491
 
481
- /** Cancel an order onchain, preventing it from ever being fulfilled. */
492
+ /**
493
+ * Cancel an order onchain, preventing it from ever being fulfilled.
494
+ * @returns Transaction hash of the cancellation.
495
+ */
482
496
  public async cancelOrder(options: {
483
497
  order?: OrderV2
484
498
  orderHash?: string
485
499
  accountAddress: string
486
500
  protocolAddress?: string
487
501
  domain?: string
488
- }) {
502
+ }): Promise<string> {
489
503
  return this._cancellationManager.cancelOrder(options)
490
504
  }
491
505
 
@@ -27,6 +27,7 @@ export class CancellationManager {
27
27
  * @param options.accountAddress The account address that will be cancelling the order.
28
28
  * @param options.protocolAddress Required when using orderHash. The Seaport protocol address for the order.
29
29
  * @param options.domain An optional domain to be hashed and included at the end of fulfillment calldata. This can be used for onchain order attribution to assist with analytics.
30
+ * @returns Transaction hash of the cancellation.
30
31
  *
31
32
  * @throws Error if neither order nor orderHash is provided.
32
33
  * @throws Error if the accountAddress is not available through wallet or provider.
@@ -44,7 +45,7 @@ export class CancellationManager {
44
45
  accountAddress: string
45
46
  protocolAddress?: string
46
47
  domain?: string
47
- }) {
48
+ }): Promise<string> {
48
49
  // Validate input
49
50
  if (!order && !orderHash) {
50
51
  throw new Error(
@@ -106,6 +107,8 @@ export class CancellationManager {
106
107
  EventType.CancelOrder,
107
108
  "Cancelling order",
108
109
  )
110
+
111
+ return transactionHash
109
112
  }
110
113
 
111
114
  /**