@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
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Internal transport abstraction for the stream client.
3
+ *
4
+ * `OpenSeaStreamClient` talks only to these interfaces, never to a specific
5
+ * wire protocol. The current implementation speaks Phoenix Channels v2
6
+ * (`./phoenix`), which is what `wss://stream-api.opensea.io/socket` serves.
7
+ *
8
+ * The vocabulary here is deliberately protocol-neutral (subscribe/unsubscribe
9
+ * rather than Phoenix's join/leave) so that a Stream API v2 transport, whose
10
+ * draft protocol is plain JSON frames with `subscribe` / `subscribed` /
11
+ * `event` types and no application-level heartbeat, can be added alongside
12
+ * this one without touching the client or the public event types.
13
+ *
14
+ * Protocol details that are not universal live in the implementation, not
15
+ * here: Phoenix's join refs, reply correlation, and 30s heartbeat are all
16
+ * private to `./phoenix`.
17
+ *
18
+ * These types are deliberately NOT exported from `src/stream/index.ts`.
19
+ * Keeping them internal leaves us free to reshape them once the next stream
20
+ * backend is real. Do not re-export them without a deliberate decision.
21
+ */
22
+
23
+ /** Minimal structural shape of a WebSocket implementation. */
24
+ export interface StreamWebSocket {
25
+ readyState: number
26
+ send(data: string): void
27
+ close(code?: number, reason?: string): void
28
+ onopen: ((event: unknown) => void) | null
29
+ onmessage: ((event: { data: unknown }) => void) | null
30
+ onerror: ((event: unknown) => void) | null
31
+ onclose: ((event: { code?: number; reason?: string }) => void) | null
32
+ }
33
+
34
+ /**
35
+ * A WebSocket constructor. The global `WebSocket` satisfies this, as does the
36
+ * `ws` package, which is only needed on runtimes without a global
37
+ * (Node < 22).
38
+ */
39
+ export type StreamWebSocketConstructor = new (url: string) => StreamWebSocket
40
+
41
+ /** Handler invoked with the raw decoded payload for a subscribed event. */
42
+ export type StreamMessageHandler = (message: unknown) => void
43
+
44
+ /** Options for a single topic subscription. */
45
+ export interface SubscribeOptions {
46
+ /**
47
+ * Restrict the subscription to these event names. Maps to Phoenix join
48
+ * params (`event_types`) today and to the `events` array in the v2 draft.
49
+ */
50
+ eventTypes?: string[]
51
+ }
52
+
53
+ /** Lifecycle callbacks for a subscription request. */
54
+ export interface SubscribeCallbacks {
55
+ /** The server accepted the subscription. */
56
+ onSubscribed?: () => void
57
+ /** The server rejected it, or the request timed out. */
58
+ onSubscribeError?: (reason: unknown) => void
59
+ }
60
+
61
+ /** An active subscription to one topic. */
62
+ export interface StreamSubscription {
63
+ readonly topic: string
64
+ /**
65
+ * Register a handler for an event name on this topic. Returns a function
66
+ * that removes just that handler; the transport unsubscribes from the topic
67
+ * once its last handler is gone.
68
+ */
69
+ on(event: string, handler: StreamMessageHandler): () => void
70
+ /** Unsubscribe from the whole topic, dropping every handler on it. */
71
+ unsubscribe(onUnsubscribed?: () => void): void
72
+ }
73
+
74
+ export interface StreamTransport {
75
+ /** Idempotent. Safe to call when already connected or connecting. */
76
+ connect(): void
77
+ disconnect(onDisconnect?: () => void): void
78
+ isConnected(): boolean
79
+ /** Fully qualified socket URL, including query parameters. */
80
+ endpointUrl(): string
81
+ /** `"ws"` or `"wss"`. */
82
+ protocol(): string
83
+ /** Subscribe to a topic, connecting first if necessary. */
84
+ subscribe(
85
+ topic: string,
86
+ options?: SubscribeOptions,
87
+ callbacks?: SubscribeCallbacks,
88
+ ): StreamSubscription
89
+ /** Register a handler for transport-level errors. */
90
+ onError(handler: (error: unknown) => void): void
91
+ }
@@ -0,0 +1,314 @@
1
+ import type { StreamWebSocketConstructor } from "./transport/types"
2
+
3
+ export type OnClientEvent = <Payload>(
4
+ collection: string,
5
+ eventType: EventType,
6
+ event: BaseStreamMessage<Payload>,
7
+ ) => boolean
8
+
9
+ /**
10
+ * Connection tuning for the stream socket.
11
+ *
12
+ * Replaces the `Partial<SocketConnectOption>` type that `@opensea/stream-js`
13
+ * borrowed from `@types/phoenix`. The options that only ever fed phoenix's
14
+ * longpoll fallback and binary serializer (`sessionStorage`,
15
+ * `longPollFallbackMs`, `binaryType`, `vsn`, `encode`, `decode`) are gone,
16
+ * because neither path is used against the OpenSea stream.
17
+ */
18
+ export type StreamConnectOptions = {
19
+ /**
20
+ * WebSocket implementation. Defaults to the global `WebSocket`, which every
21
+ * browser and Node 22+ provides. Only set this on older runtimes, passing
22
+ * something like the `ws` package.
23
+ */
24
+ transport?: StreamWebSocketConstructor
25
+ /** Extra query parameters to append to the socket URL. */
26
+ params?: Record<string, string>
27
+ /** Milliseconds to wait for a subscription acknowledgement. Default 10000. */
28
+ timeout?: number
29
+ /** Milliseconds between heartbeats. Default 30000. */
30
+ heartbeatIntervalMs?: number
31
+ /** Backoff before reconnect attempt `tries` (1-indexed). */
32
+ reconnectAfterMs?: (tries: number) => number
33
+ }
34
+
35
+ /**
36
+ * OpenSea Stream API configuration object.
37
+ *
38
+ * @param apiKey OpenSea API key. Preferred over `token`, and named to match
39
+ * `OpenSeaAPIConfig.apiKey` used elsewhere in the SDK.
40
+ * @param token Deprecated alias for `apiKey`, kept so code migrating from
41
+ * `@opensea/stream-js` keeps working unchanged.
42
+ * @param network `Network` to use. Defaults to `Network.MAINNET`.
43
+ * @param apiUrl Optional base URL override for the socket.
44
+ * @param connectOptions connection tuning, see `StreamConnectOptions`.
45
+ * @param onError a callback invoked whenever a transport error occurs.
46
+ * @param logLevel `LogLevel` controlling how much the client logs.
47
+ * @param onEvent a callback invoked whenever an event is emitted, useful for
48
+ * metrics or logging. Returning false filters the event so the subscription
49
+ * callback is not invoked.
50
+ */
51
+ export type ClientConfig = {
52
+ network?: Network
53
+ apiUrl?: string
54
+ /** OpenSea API key. Provide either this or `token`. */
55
+ apiKey?: string
56
+ /** @deprecated Use `apiKey` instead. */
57
+ token?: string
58
+ connectOptions?: StreamConnectOptions
59
+ onError?: (error: unknown) => void
60
+ logLevel?: LogLevel
61
+ onEvent?: OnClientEvent
62
+ }
63
+
64
+ export enum Network {
65
+ MAINNET = "mainnet",
66
+ }
67
+
68
+ export enum EventType {
69
+ ITEM_METADATA_UPDATED = "item_metadata_updated",
70
+ ITEM_LISTED = "item_listed",
71
+ ITEM_SOLD = "item_sold",
72
+ ITEM_TRANSFERRED = "item_transferred",
73
+ ITEM_RECEIVED_OFFER = "item_received_offer",
74
+ ITEM_RECEIVED_BID = "item_received_bid",
75
+ ITEM_CANCELLED = "item_cancelled",
76
+ COLLECTION_OFFER = "collection_offer",
77
+ TRAIT_OFFER = "trait_offer",
78
+ ORDER_INVALIDATE = "order_invalidate",
79
+ ORDER_REVALIDATE = "order_revalidate",
80
+ }
81
+
82
+ interface BaseItemMetadataType {
83
+ name: string | null
84
+ image_url: string | null
85
+ animation_url: string | null
86
+ metadata_url: string | null
87
+ }
88
+
89
+ export type BaseItemType<Metadata = BaseItemMetadataType> = {
90
+ nft_id: string
91
+ permalink: string
92
+ metadata: Metadata
93
+ chain: {
94
+ name: string
95
+ }
96
+ }
97
+
98
+ export type Payload = {
99
+ item: BaseItemType
100
+ collection: {
101
+ slug: string
102
+ }
103
+ chain: string
104
+ }
105
+
106
+ export type BaseStreamMessage<Payload> = {
107
+ event_type: string
108
+ version: number
109
+ sent_at: string
110
+ payload: Payload
111
+ }
112
+
113
+ export type Trait = {
114
+ trait_type: string
115
+ value: string | null
116
+ display_type: string | null
117
+ max_value: number | null
118
+ trait_count: number | null
119
+ order: number | null
120
+ }
121
+
122
+ interface ExtendedItemMetadataType extends BaseItemMetadataType {
123
+ description: string | null
124
+ background_color: string | null
125
+ traits: Trait[]
126
+ }
127
+
128
+ export type ItemMetadataUpdatePayload = {
129
+ collection: { slug: string }
130
+ item: BaseItemType<ExtendedItemMetadataType>
131
+ }
132
+
133
+ export type ItemMetadataUpdate = BaseStreamMessage<ItemMetadataUpdatePayload>
134
+
135
+ export type Account = {
136
+ address: string
137
+ }
138
+
139
+ export type PaymentToken = {
140
+ address: string
141
+ decimals: number
142
+ eth_price: string
143
+ name: string
144
+ symbol: string
145
+ usd_price: string
146
+ }
147
+
148
+ export type AssetContractCriteria = {
149
+ address: string
150
+ }
151
+
152
+ export type CollectionIdentifier = {
153
+ slug: string
154
+ }
155
+
156
+ export interface ItemListedEventPayload extends Payload {
157
+ quantity: number
158
+ listing_type: string
159
+ listing_date: string
160
+ expiration_date: string
161
+ maker: Account
162
+ taker: Account
163
+ base_price: string
164
+ payment_token: PaymentToken
165
+ is_private: boolean
166
+ order_hash: string
167
+ event_timestamp: string
168
+ }
169
+
170
+ export type ItemListedEvent = BaseStreamMessage<ItemListedEventPayload>
171
+
172
+ export type Transaction = {
173
+ hash: string
174
+ timestamp: string
175
+ }
176
+
177
+ export interface ItemSoldEventPayload extends Payload {
178
+ quantity: number
179
+ listing_type: string
180
+ closing_date: string
181
+ transaction: Transaction
182
+ maker: Account
183
+ taker: Account
184
+ order_hash: string
185
+ sale_price: string
186
+ payment_token: PaymentToken
187
+ is_private: boolean
188
+ event_timestamp: string
189
+ }
190
+
191
+ export type ItemSoldEvent = BaseStreamMessage<ItemSoldEventPayload>
192
+
193
+ export interface ItemTransferredEventPayload extends Payload {
194
+ from_account: Account
195
+ quantity: number
196
+ to_account: Account
197
+ transaction: Transaction
198
+ event_timestamp: string
199
+ }
200
+
201
+ export type ItemTransferredEvent =
202
+ BaseStreamMessage<ItemTransferredEventPayload>
203
+
204
+ export interface ItemReceivedBidEventPayload extends Payload {
205
+ quantity: number
206
+ created_date: string
207
+ expiration_date: string
208
+ maker: Account
209
+ taker: Account
210
+ order_hash: string
211
+ base_price: string
212
+ payment_token: PaymentToken
213
+ event_timestamp: string
214
+ }
215
+
216
+ export type ItemReceivedBidEvent =
217
+ BaseStreamMessage<ItemReceivedBidEventPayload>
218
+
219
+ export interface ItemReceivedOfferEventPayload extends Payload {
220
+ quantity: number
221
+ created_date: string
222
+ expiration_date: string
223
+ maker: Account
224
+ taker: Account
225
+ order_hash: string
226
+ base_price: string
227
+ payment_token: PaymentToken
228
+ event_timestamp: string
229
+ }
230
+
231
+ export type ItemReceivedOfferEvent =
232
+ BaseStreamMessage<ItemReceivedOfferEventPayload>
233
+
234
+ export interface ItemCancelledEventPayload extends Payload {
235
+ quantity: number
236
+ base_price: string
237
+ expiration_date: string
238
+ maker: Account
239
+ taker: Account
240
+ listing_type: string
241
+ listing_date: string
242
+ transaction: Transaction
243
+ payment_token: PaymentToken
244
+ order_hash: string
245
+ is_private: boolean
246
+ event_timestamp: string
247
+ }
248
+
249
+ export type ItemCancelledEvent = BaseStreamMessage<ItemCancelledEventPayload>
250
+
251
+ export interface CollectionOfferEventPayload extends Payload {
252
+ quantity: number
253
+ created_date: string
254
+ expiration_date: string
255
+ maker: Account
256
+ taker: Account
257
+ base_price: string
258
+ order_hash: string
259
+ payment_token: PaymentToken
260
+ collection_criteria: CollectionIdentifier
261
+ asset_contract_criteria: AssetContractCriteria
262
+ event_timestamp: string
263
+ }
264
+
265
+ export type CollectionOfferEvent =
266
+ BaseStreamMessage<CollectionOfferEventPayload>
267
+
268
+ export type TraitCriteria = {
269
+ trait_type: string
270
+ trait_name: string
271
+ }
272
+
273
+ export interface TraitOfferEventPayload extends Payload {
274
+ quantity: number
275
+ created_date: string
276
+ expiration_date: string
277
+ maker: Account
278
+ taker: Account
279
+ base_price: string
280
+ order_hash: string
281
+ payment_token: PaymentToken
282
+ collection_criteria: CollectionIdentifier
283
+ asset_contract_criteria: AssetContractCriteria
284
+ trait_criteria?: TraitCriteria
285
+ trait_criteria_list?: TraitCriteria[]
286
+ event_timestamp: string
287
+ }
288
+
289
+ export type TraitOfferEvent = BaseStreamMessage<TraitOfferEventPayload>
290
+
291
+ export interface OrderValidationEventPayload {
292
+ event_timestamp: string
293
+ order_hash: string
294
+ protocol_address: string
295
+ chain: {
296
+ name: string
297
+ }
298
+ collection: {
299
+ slug: string
300
+ }
301
+ item: BaseItemType
302
+ }
303
+
304
+ export type OrderValidationEvent =
305
+ BaseStreamMessage<OrderValidationEventPayload>
306
+
307
+ export type Callback<Event> = (event: Event) => unknown
308
+
309
+ export enum LogLevel {
310
+ DEBUG = 20,
311
+ INFO = 30,
312
+ WARN = 40,
313
+ ERROR = 50,
314
+ }
package/src/types.ts CHANGED
@@ -328,4 +328,18 @@ export interface RequestOptions {
328
328
  * await api.post('/path', body, headers, { signal: controller.signal });
329
329
  */
330
330
  signal?: AbortSignal
331
+ /**
332
+ * Whether to recursively rewrite the response's keys from snake_case to
333
+ * camelCase. Defaults to `true`.
334
+ *
335
+ * Set to `false` only for endpoints whose response keys are data rather than
336
+ * field names. `getTraits` returns objects keyed by collection-authored trait
337
+ * names and trait values, so the default rewrite reports a `dark_brown` trait
338
+ * as `darkBrown` and merges two traits that differ only in casing.
339
+ *
340
+ * The return type stays the camelized view, so the caller is responsible for
341
+ * passing a `T` whose keys already match the wire shape. `GetTraitsResponse`
342
+ * qualifies because `Camelize<T>` passes index signatures through unchanged.
343
+ */
344
+ camelizeResponse?: boolean
331
345
  }
@@ -1,5 +1,54 @@
1
+ /** A plain decimal string: optional sign, digits, optional fractional part. */
2
+ const DECIMAL = /^-?(?:\d+(?:\.\d*)?|\.\d+)$/
3
+
4
+ /** Scientific notation, e.g. `1e-8`, `-1.5E+21`. Captures sign, digits, exponent. */
5
+ const SCIENTIFIC = /^(-?)(\d*)(?:\.(\d*))?[eE]([+-]?\d+)$/
6
+
7
+ /**
8
+ * Rewrite scientific notation as a plain decimal string, e.g. `1e-8` →
9
+ * `0.00000001`.
10
+ *
11
+ * Done with string math rather than `Number.prototype.toFixed` so the result is
12
+ * exact. `toFixed` round-trips through a double, which silently corrupts values
13
+ * above 2^53 (`(1e30).toFixed(18)` is off by 19884624838656) and returns
14
+ * exponential notation again at or above 1e21. It also truncates a value
15
+ * smaller than the token's precision to zero, turning a too-small amount into a
16
+ * free order rather than an error.
17
+ *
18
+ * Returns the input unchanged if it is not scientific notation; callers
19
+ * validate the result.
20
+ */
21
+ function expandScientificNotation(str: string): string {
22
+ const match = SCIENTIFIC.exec(str)
23
+ if (!match) {
24
+ return str
25
+ }
26
+
27
+ const [, sign, intDigits, fracDigits = "", exponent] = match
28
+ const digits = `${intDigits}${fracDigits}`
29
+ if (digits.length === 0) {
30
+ return str
31
+ }
32
+
33
+ // Where the decimal point lands once the exponent is applied.
34
+ const pointPosition = intDigits.length + Number(exponent)
35
+
36
+ if (pointPosition <= 0) {
37
+ return `${sign}0.${"0".repeat(-pointPosition)}${digits}`
38
+ }
39
+ if (pointPosition >= digits.length) {
40
+ return `${sign}${digits}${"0".repeat(pointPosition - digits.length)}`
41
+ }
42
+ return `${sign}${digits.slice(0, pointPosition)}.${digits.slice(pointPosition)}`
43
+ }
44
+
1
45
  /**
2
46
  * Parse a decimal string into its base unit representation (e.g. ETH -> wei).
47
+ *
48
+ * Accepts scientific notation from either a number or a string. `String(1e-8)`
49
+ * is `"1e-8"`, so any caller that stringifies an amount before passing it here
50
+ * hits that form.
51
+ *
3
52
  * @param value The decimal value as a string or number (e.g. "1.5")
4
53
  * @param decimals The number of decimal places (e.g. 18 for ETH)
5
54
  * @returns The value in base units as a bigint
@@ -8,13 +57,12 @@ export function parseUnits(
8
57
  value: string | number | bigint,
9
58
  decimals: number,
10
59
  ): bigint {
11
- let str = value.toString()
60
+ const str = expandScientificNotation(value.toString())
12
61
 
13
- // Handle JavaScript scientific notation (e.g. 1e-8 → "0.00000001").
14
- // Note: toFixed has precision limits for very large numbers, but this is
15
- // sufficient for realistic token amounts (up to ~2^53).
16
- if (typeof value === "number" && str.includes("e")) {
17
- str = value.toFixed(decimals)
62
+ // Reject anything that is not a plain decimal, so malformed input fails here
63
+ // with a clear message rather than as a `SyntaxError` out of `BigInt` below.
64
+ if (!DECIMAL.test(str)) {
65
+ throw new Error(`Invalid decimal value: ${value}`)
18
66
  }
19
67
 
20
68
  // Handle negative values
@@ -22,9 +70,6 @@ export function parseUnits(
22
70
  const abs = isNegative ? str.slice(1) : str
23
71
 
24
72
  const [intPart, fracPart = ""] = abs.split(".")
25
- if (abs.split(".").length > 2) {
26
- throw new Error(`Invalid decimal value: ${str}`)
27
- }
28
73
 
29
74
  // Reject excess decimal places to match ethers.parseUnits behavior
30
75
  if (fracPart.length > decimals) {