@opensea/sdk 11.8.0 → 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 (51) hide show
  1. package/README.md +45 -13
  2. package/lib/api/api.d.ts +9 -0
  3. package/lib/api/api.js +15 -2
  4. package/lib/api/api.js.map +1 -1
  5. package/lib/api/collections.d.ts +7 -0
  6. package/lib/api/collections.js +10 -1
  7. package/lib/api/collections.js.map +1 -1
  8. package/lib/api/fetcher.d.ts +5 -2
  9. package/lib/index.d.ts +1 -1
  10. package/lib/orders/privateListings.js +8 -0
  11. package/lib/orders/privateListings.js.map +1 -1
  12. package/lib/stream/client.d.ts +67 -0
  13. package/lib/stream/client.js +174 -0
  14. package/lib/stream/client.js.map +1 -0
  15. package/lib/stream/constants.d.ts +3 -0
  16. package/lib/stream/constants.js +8 -0
  17. package/lib/stream/constants.js.map +1 -0
  18. package/lib/stream/helpers.d.ts +1 -0
  19. package/lib/stream/helpers.js +8 -0
  20. package/lib/stream/helpers.js.map +1 -0
  21. package/lib/stream/index.d.ts +17 -0
  22. package/lib/stream/index.js +34 -0
  23. package/lib/stream/index.js.map +1 -0
  24. package/lib/stream/transport/phoenix.d.ts +121 -0
  25. package/lib/stream/transport/phoenix.js +642 -0
  26. package/lib/stream/transport/phoenix.js.map +1 -0
  27. package/lib/stream/transport/types.d.ts +85 -0
  28. package/lib/stream/transport/types.js +24 -0
  29. package/lib/stream/transport/types.js.map +1 -0
  30. package/lib/stream/types.d.ts +269 -0
  31. package/lib/stream/types.js +29 -0
  32. package/lib/stream/types.js.map +1 -0
  33. package/lib/types.d.ts +14 -0
  34. package/lib/utils/units.d.ts +5 -0
  35. package/lib/utils/units.js +48 -9
  36. package/lib/utils/units.js.map +1 -1
  37. package/package.json +9 -8
  38. package/src/api/api.ts +19 -2
  39. package/src/api/collections.ts +14 -1
  40. package/src/api/fetcher.ts +5 -2
  41. package/src/index.ts +1 -1
  42. package/src/orders/privateListings.ts +15 -0
  43. package/src/stream/client.ts +277 -0
  44. package/src/stream/constants.ts +5 -0
  45. package/src/stream/helpers.ts +3 -0
  46. package/src/stream/index.ts +18 -0
  47. package/src/stream/transport/phoenix.ts +815 -0
  48. package/src/stream/transport/types.ts +91 -0
  49. package/src/stream/types.ts +314 -0
  50. package/src/types.ts +14 -0
  51. package/src/utils/units.ts +54 -9
@@ -0,0 +1,85 @@
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
+ /** Minimal structural shape of a WebSocket implementation. */
23
+ export interface StreamWebSocket {
24
+ readyState: number;
25
+ send(data: string): void;
26
+ close(code?: number, reason?: string): void;
27
+ onopen: ((event: unknown) => void) | null;
28
+ onmessage: ((event: {
29
+ data: unknown;
30
+ }) => void) | null;
31
+ onerror: ((event: unknown) => void) | null;
32
+ onclose: ((event: {
33
+ code?: number;
34
+ reason?: string;
35
+ }) => void) | null;
36
+ }
37
+ /**
38
+ * A WebSocket constructor. The global `WebSocket` satisfies this, as does the
39
+ * `ws` package, which is only needed on runtimes without a global
40
+ * (Node < 22).
41
+ */
42
+ export type StreamWebSocketConstructor = new (url: string) => StreamWebSocket;
43
+ /** Handler invoked with the raw decoded payload for a subscribed event. */
44
+ export type StreamMessageHandler = (message: unknown) => void;
45
+ /** Options for a single topic subscription. */
46
+ export interface SubscribeOptions {
47
+ /**
48
+ * Restrict the subscription to these event names. Maps to Phoenix join
49
+ * params (`event_types`) today and to the `events` array in the v2 draft.
50
+ */
51
+ eventTypes?: string[];
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
+ /** An active subscription to one topic. */
61
+ export interface StreamSubscription {
62
+ readonly topic: string;
63
+ /**
64
+ * Register a handler for an event name on this topic. Returns a function
65
+ * that removes just that handler; the transport unsubscribes from the topic
66
+ * once its last handler is gone.
67
+ */
68
+ on(event: string, handler: StreamMessageHandler): () => void;
69
+ /** Unsubscribe from the whole topic, dropping every handler on it. */
70
+ unsubscribe(onUnsubscribed?: () => void): void;
71
+ }
72
+ export interface StreamTransport {
73
+ /** Idempotent. Safe to call when already connected or connecting. */
74
+ connect(): void;
75
+ disconnect(onDisconnect?: () => void): void;
76
+ isConnected(): boolean;
77
+ /** Fully qualified socket URL, including query parameters. */
78
+ endpointUrl(): string;
79
+ /** `"ws"` or `"wss"`. */
80
+ protocol(): string;
81
+ /** Subscribe to a topic, connecting first if necessary. */
82
+ subscribe(topic: string, options?: SubscribeOptions, callbacks?: SubscribeCallbacks): StreamSubscription;
83
+ /** Register a handler for transport-level errors. */
84
+ onError(handler: (error: unknown) => void): void;
85
+ }
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ /**
3
+ * Internal transport abstraction for the stream client.
4
+ *
5
+ * `OpenSeaStreamClient` talks only to these interfaces, never to a specific
6
+ * wire protocol. The current implementation speaks Phoenix Channels v2
7
+ * (`./phoenix`), which is what `wss://stream-api.opensea.io/socket` serves.
8
+ *
9
+ * The vocabulary here is deliberately protocol-neutral (subscribe/unsubscribe
10
+ * rather than Phoenix's join/leave) so that a Stream API v2 transport, whose
11
+ * draft protocol is plain JSON frames with `subscribe` / `subscribed` /
12
+ * `event` types and no application-level heartbeat, can be added alongside
13
+ * this one without touching the client or the public event types.
14
+ *
15
+ * Protocol details that are not universal live in the implementation, not
16
+ * here: Phoenix's join refs, reply correlation, and 30s heartbeat are all
17
+ * private to `./phoenix`.
18
+ *
19
+ * These types are deliberately NOT exported from `src/stream/index.ts`.
20
+ * Keeping them internal leaves us free to reshape them once the next stream
21
+ * backend is real. Do not re-export them without a deliberate decision.
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/stream/transport/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG"}
@@ -0,0 +1,269 @@
1
+ import type { StreamWebSocketConstructor } from "./transport/types";
2
+ export type OnClientEvent = <Payload>(collection: string, eventType: EventType, event: BaseStreamMessage<Payload>) => boolean;
3
+ /**
4
+ * Connection tuning for the stream socket.
5
+ *
6
+ * Replaces the `Partial<SocketConnectOption>` type that `@opensea/stream-js`
7
+ * borrowed from `@types/phoenix`. The options that only ever fed phoenix's
8
+ * longpoll fallback and binary serializer (`sessionStorage`,
9
+ * `longPollFallbackMs`, `binaryType`, `vsn`, `encode`, `decode`) are gone,
10
+ * because neither path is used against the OpenSea stream.
11
+ */
12
+ export type StreamConnectOptions = {
13
+ /**
14
+ * WebSocket implementation. Defaults to the global `WebSocket`, which every
15
+ * browser and Node 22+ provides. Only set this on older runtimes, passing
16
+ * something like the `ws` package.
17
+ */
18
+ transport?: StreamWebSocketConstructor;
19
+ /** Extra query parameters to append to the socket URL. */
20
+ params?: Record<string, string>;
21
+ /** Milliseconds to wait for a subscription acknowledgement. Default 10000. */
22
+ timeout?: number;
23
+ /** Milliseconds between heartbeats. Default 30000. */
24
+ heartbeatIntervalMs?: number;
25
+ /** Backoff before reconnect attempt `tries` (1-indexed). */
26
+ reconnectAfterMs?: (tries: number) => number;
27
+ };
28
+ /**
29
+ * OpenSea Stream API configuration object.
30
+ *
31
+ * @param apiKey OpenSea API key. Preferred over `token`, and named to match
32
+ * `OpenSeaAPIConfig.apiKey` used elsewhere in the SDK.
33
+ * @param token Deprecated alias for `apiKey`, kept so code migrating from
34
+ * `@opensea/stream-js` keeps working unchanged.
35
+ * @param network `Network` to use. Defaults to `Network.MAINNET`.
36
+ * @param apiUrl Optional base URL override for the socket.
37
+ * @param connectOptions connection tuning, see `StreamConnectOptions`.
38
+ * @param onError a callback invoked whenever a transport error occurs.
39
+ * @param logLevel `LogLevel` controlling how much the client logs.
40
+ * @param onEvent a callback invoked whenever an event is emitted, useful for
41
+ * metrics or logging. Returning false filters the event so the subscription
42
+ * callback is not invoked.
43
+ */
44
+ export type ClientConfig = {
45
+ network?: Network;
46
+ apiUrl?: string;
47
+ /** OpenSea API key. Provide either this or `token`. */
48
+ apiKey?: string;
49
+ /** @deprecated Use `apiKey` instead. */
50
+ token?: string;
51
+ connectOptions?: StreamConnectOptions;
52
+ onError?: (error: unknown) => void;
53
+ logLevel?: LogLevel;
54
+ onEvent?: OnClientEvent;
55
+ };
56
+ export declare enum Network {
57
+ MAINNET = "mainnet"
58
+ }
59
+ export declare enum EventType {
60
+ ITEM_METADATA_UPDATED = "item_metadata_updated",
61
+ ITEM_LISTED = "item_listed",
62
+ ITEM_SOLD = "item_sold",
63
+ ITEM_TRANSFERRED = "item_transferred",
64
+ ITEM_RECEIVED_OFFER = "item_received_offer",
65
+ ITEM_RECEIVED_BID = "item_received_bid",
66
+ ITEM_CANCELLED = "item_cancelled",
67
+ COLLECTION_OFFER = "collection_offer",
68
+ TRAIT_OFFER = "trait_offer",
69
+ ORDER_INVALIDATE = "order_invalidate",
70
+ ORDER_REVALIDATE = "order_revalidate"
71
+ }
72
+ interface BaseItemMetadataType {
73
+ name: string | null;
74
+ image_url: string | null;
75
+ animation_url: string | null;
76
+ metadata_url: string | null;
77
+ }
78
+ export type BaseItemType<Metadata = BaseItemMetadataType> = {
79
+ nft_id: string;
80
+ permalink: string;
81
+ metadata: Metadata;
82
+ chain: {
83
+ name: string;
84
+ };
85
+ };
86
+ export type Payload = {
87
+ item: BaseItemType;
88
+ collection: {
89
+ slug: string;
90
+ };
91
+ chain: string;
92
+ };
93
+ export type BaseStreamMessage<Payload> = {
94
+ event_type: string;
95
+ version: number;
96
+ sent_at: string;
97
+ payload: Payload;
98
+ };
99
+ export type Trait = {
100
+ trait_type: string;
101
+ value: string | null;
102
+ display_type: string | null;
103
+ max_value: number | null;
104
+ trait_count: number | null;
105
+ order: number | null;
106
+ };
107
+ interface ExtendedItemMetadataType extends BaseItemMetadataType {
108
+ description: string | null;
109
+ background_color: string | null;
110
+ traits: Trait[];
111
+ }
112
+ export type ItemMetadataUpdatePayload = {
113
+ collection: {
114
+ slug: string;
115
+ };
116
+ item: BaseItemType<ExtendedItemMetadataType>;
117
+ };
118
+ export type ItemMetadataUpdate = BaseStreamMessage<ItemMetadataUpdatePayload>;
119
+ export type Account = {
120
+ address: string;
121
+ };
122
+ export type PaymentToken = {
123
+ address: string;
124
+ decimals: number;
125
+ eth_price: string;
126
+ name: string;
127
+ symbol: string;
128
+ usd_price: string;
129
+ };
130
+ export type AssetContractCriteria = {
131
+ address: string;
132
+ };
133
+ export type CollectionIdentifier = {
134
+ slug: string;
135
+ };
136
+ export interface ItemListedEventPayload extends Payload {
137
+ quantity: number;
138
+ listing_type: string;
139
+ listing_date: string;
140
+ expiration_date: string;
141
+ maker: Account;
142
+ taker: Account;
143
+ base_price: string;
144
+ payment_token: PaymentToken;
145
+ is_private: boolean;
146
+ order_hash: string;
147
+ event_timestamp: string;
148
+ }
149
+ export type ItemListedEvent = BaseStreamMessage<ItemListedEventPayload>;
150
+ export type Transaction = {
151
+ hash: string;
152
+ timestamp: string;
153
+ };
154
+ export interface ItemSoldEventPayload extends Payload {
155
+ quantity: number;
156
+ listing_type: string;
157
+ closing_date: string;
158
+ transaction: Transaction;
159
+ maker: Account;
160
+ taker: Account;
161
+ order_hash: string;
162
+ sale_price: string;
163
+ payment_token: PaymentToken;
164
+ is_private: boolean;
165
+ event_timestamp: string;
166
+ }
167
+ export type ItemSoldEvent = BaseStreamMessage<ItemSoldEventPayload>;
168
+ export interface ItemTransferredEventPayload extends Payload {
169
+ from_account: Account;
170
+ quantity: number;
171
+ to_account: Account;
172
+ transaction: Transaction;
173
+ event_timestamp: string;
174
+ }
175
+ export type ItemTransferredEvent = BaseStreamMessage<ItemTransferredEventPayload>;
176
+ export interface ItemReceivedBidEventPayload extends Payload {
177
+ quantity: number;
178
+ created_date: string;
179
+ expiration_date: string;
180
+ maker: Account;
181
+ taker: Account;
182
+ order_hash: string;
183
+ base_price: string;
184
+ payment_token: PaymentToken;
185
+ event_timestamp: string;
186
+ }
187
+ export type ItemReceivedBidEvent = BaseStreamMessage<ItemReceivedBidEventPayload>;
188
+ export interface ItemReceivedOfferEventPayload extends Payload {
189
+ quantity: number;
190
+ created_date: string;
191
+ expiration_date: string;
192
+ maker: Account;
193
+ taker: Account;
194
+ order_hash: string;
195
+ base_price: string;
196
+ payment_token: PaymentToken;
197
+ event_timestamp: string;
198
+ }
199
+ export type ItemReceivedOfferEvent = BaseStreamMessage<ItemReceivedOfferEventPayload>;
200
+ export interface ItemCancelledEventPayload extends Payload {
201
+ quantity: number;
202
+ base_price: string;
203
+ expiration_date: string;
204
+ maker: Account;
205
+ taker: Account;
206
+ listing_type: string;
207
+ listing_date: string;
208
+ transaction: Transaction;
209
+ payment_token: PaymentToken;
210
+ order_hash: string;
211
+ is_private: boolean;
212
+ event_timestamp: string;
213
+ }
214
+ export type ItemCancelledEvent = BaseStreamMessage<ItemCancelledEventPayload>;
215
+ export interface CollectionOfferEventPayload extends Payload {
216
+ quantity: number;
217
+ created_date: string;
218
+ expiration_date: string;
219
+ maker: Account;
220
+ taker: Account;
221
+ base_price: string;
222
+ order_hash: string;
223
+ payment_token: PaymentToken;
224
+ collection_criteria: CollectionIdentifier;
225
+ asset_contract_criteria: AssetContractCriteria;
226
+ event_timestamp: string;
227
+ }
228
+ export type CollectionOfferEvent = BaseStreamMessage<CollectionOfferEventPayload>;
229
+ export type TraitCriteria = {
230
+ trait_type: string;
231
+ trait_name: string;
232
+ };
233
+ export interface TraitOfferEventPayload extends Payload {
234
+ quantity: number;
235
+ created_date: string;
236
+ expiration_date: string;
237
+ maker: Account;
238
+ taker: Account;
239
+ base_price: string;
240
+ order_hash: string;
241
+ payment_token: PaymentToken;
242
+ collection_criteria: CollectionIdentifier;
243
+ asset_contract_criteria: AssetContractCriteria;
244
+ trait_criteria?: TraitCriteria;
245
+ trait_criteria_list?: TraitCriteria[];
246
+ event_timestamp: string;
247
+ }
248
+ export type TraitOfferEvent = BaseStreamMessage<TraitOfferEventPayload>;
249
+ export interface OrderValidationEventPayload {
250
+ event_timestamp: string;
251
+ order_hash: string;
252
+ protocol_address: string;
253
+ chain: {
254
+ name: string;
255
+ };
256
+ collection: {
257
+ slug: string;
258
+ };
259
+ item: BaseItemType;
260
+ }
261
+ export type OrderValidationEvent = BaseStreamMessage<OrderValidationEventPayload>;
262
+ export type Callback<Event> = (event: Event) => unknown;
263
+ export declare enum LogLevel {
264
+ DEBUG = 20,
265
+ INFO = 30,
266
+ WARN = 40,
267
+ ERROR = 50
268
+ }
269
+ export {};
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LogLevel = exports.EventType = exports.Network = void 0;
4
+ var Network;
5
+ (function (Network) {
6
+ Network["MAINNET"] = "mainnet";
7
+ })(Network || (exports.Network = Network = {}));
8
+ var EventType;
9
+ (function (EventType) {
10
+ EventType["ITEM_METADATA_UPDATED"] = "item_metadata_updated";
11
+ EventType["ITEM_LISTED"] = "item_listed";
12
+ EventType["ITEM_SOLD"] = "item_sold";
13
+ EventType["ITEM_TRANSFERRED"] = "item_transferred";
14
+ EventType["ITEM_RECEIVED_OFFER"] = "item_received_offer";
15
+ EventType["ITEM_RECEIVED_BID"] = "item_received_bid";
16
+ EventType["ITEM_CANCELLED"] = "item_cancelled";
17
+ EventType["COLLECTION_OFFER"] = "collection_offer";
18
+ EventType["TRAIT_OFFER"] = "trait_offer";
19
+ EventType["ORDER_INVALIDATE"] = "order_invalidate";
20
+ EventType["ORDER_REVALIDATE"] = "order_revalidate";
21
+ })(EventType || (exports.EventType = EventType = {}));
22
+ var LogLevel;
23
+ (function (LogLevel) {
24
+ LogLevel[LogLevel["DEBUG"] = 20] = "DEBUG";
25
+ LogLevel[LogLevel["INFO"] = 30] = "INFO";
26
+ LogLevel[LogLevel["WARN"] = 40] = "WARN";
27
+ LogLevel[LogLevel["ERROR"] = 50] = "ERROR";
28
+ })(LogLevel || (exports.LogLevel = LogLevel = {}));
29
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/stream/types.ts"],"names":[],"mappings":";;;AA+DA,IAAY,OAEX;AAFD,WAAY,OAAO;IACjB,8BAAmB,CAAA;AACrB,CAAC,EAFW,OAAO,uBAAP,OAAO,QAElB;AAED,IAAY,SAYX;AAZD,WAAY,SAAS;IACnB,4DAA+C,CAAA;IAC/C,wCAA2B,CAAA;IAC3B,oCAAuB,CAAA;IACvB,kDAAqC,CAAA;IACrC,wDAA2C,CAAA;IAC3C,oDAAuC,CAAA;IACvC,8CAAiC,CAAA;IACjC,kDAAqC,CAAA;IACrC,wCAA2B,CAAA;IAC3B,kDAAqC,CAAA;IACrC,kDAAqC,CAAA;AACvC,CAAC,EAZW,SAAS,yBAAT,SAAS,QAYpB;AAqOD,IAAY,QAKX;AALD,WAAY,QAAQ;IAClB,0CAAU,CAAA;IACV,wCAAS,CAAA;IACT,wCAAS,CAAA;IACT,0CAAU,CAAA;AACZ,CAAC,EALW,QAAQ,wBAAR,QAAQ,QAKnB"}
package/lib/types.d.ts CHANGED
@@ -290,4 +290,18 @@ export interface RequestOptions {
290
290
  * await api.post('/path', body, headers, { signal: controller.signal });
291
291
  */
292
292
  signal?: AbortSignal;
293
+ /**
294
+ * Whether to recursively rewrite the response's keys from snake_case to
295
+ * camelCase. Defaults to `true`.
296
+ *
297
+ * Set to `false` only for endpoints whose response keys are data rather than
298
+ * field names. `getTraits` returns objects keyed by collection-authored trait
299
+ * names and trait values, so the default rewrite reports a `dark_brown` trait
300
+ * as `darkBrown` and merges two traits that differ only in casing.
301
+ *
302
+ * The return type stays the camelized view, so the caller is responsible for
303
+ * passing a `T` whose keys already match the wire shape. `GetTraitsResponse`
304
+ * qualifies because `Camelize<T>` passes index signatures through unchanged.
305
+ */
306
+ camelizeResponse?: boolean;
293
307
  }
@@ -1,5 +1,10 @@
1
1
  /**
2
2
  * Parse a decimal string into its base unit representation (e.g. ETH -> wei).
3
+ *
4
+ * Accepts scientific notation from either a number or a string. `String(1e-8)`
5
+ * is `"1e-8"`, so any caller that stringifies an amount before passing it here
6
+ * hits that form.
7
+ *
3
8
  * @param value The decimal value as a string or number (e.g. "1.5")
4
9
  * @param decimals The number of decimal places (e.g. 18 for ETH)
5
10
  * @returns The value in base units as a bigint
@@ -2,27 +2,66 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.parseUnits = parseUnits;
4
4
  exports.parseEther = parseEther;
5
+ /** A plain decimal string: optional sign, digits, optional fractional part. */
6
+ const DECIMAL = /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
7
+ /** Scientific notation, e.g. `1e-8`, `-1.5E+21`. Captures sign, digits, exponent. */
8
+ const SCIENTIFIC = /^(-?)(\d*)(?:\.(\d*))?[eE]([+-]?\d+)$/;
9
+ /**
10
+ * Rewrite scientific notation as a plain decimal string, e.g. `1e-8` →
11
+ * `0.00000001`.
12
+ *
13
+ * Done with string math rather than `Number.prototype.toFixed` so the result is
14
+ * exact. `toFixed` round-trips through a double, which silently corrupts values
15
+ * above 2^53 (`(1e30).toFixed(18)` is off by 19884624838656) and returns
16
+ * exponential notation again at or above 1e21. It also truncates a value
17
+ * smaller than the token's precision to zero, turning a too-small amount into a
18
+ * free order rather than an error.
19
+ *
20
+ * Returns the input unchanged if it is not scientific notation; callers
21
+ * validate the result.
22
+ */
23
+ function expandScientificNotation(str) {
24
+ const match = SCIENTIFIC.exec(str);
25
+ if (!match) {
26
+ return str;
27
+ }
28
+ const [, sign, intDigits, fracDigits = "", exponent] = match;
29
+ const digits = `${intDigits}${fracDigits}`;
30
+ if (digits.length === 0) {
31
+ return str;
32
+ }
33
+ // Where the decimal point lands once the exponent is applied.
34
+ const pointPosition = intDigits.length + Number(exponent);
35
+ if (pointPosition <= 0) {
36
+ return `${sign}0.${"0".repeat(-pointPosition)}${digits}`;
37
+ }
38
+ if (pointPosition >= digits.length) {
39
+ return `${sign}${digits}${"0".repeat(pointPosition - digits.length)}`;
40
+ }
41
+ return `${sign}${digits.slice(0, pointPosition)}.${digits.slice(pointPosition)}`;
42
+ }
5
43
  /**
6
44
  * Parse a decimal string into its base unit representation (e.g. ETH -> wei).
45
+ *
46
+ * Accepts scientific notation from either a number or a string. `String(1e-8)`
47
+ * is `"1e-8"`, so any caller that stringifies an amount before passing it here
48
+ * hits that form.
49
+ *
7
50
  * @param value The decimal value as a string or number (e.g. "1.5")
8
51
  * @param decimals The number of decimal places (e.g. 18 for ETH)
9
52
  * @returns The value in base units as a bigint
10
53
  */
11
54
  function parseUnits(value, decimals) {
12
- let str = value.toString();
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);
55
+ const str = expandScientificNotation(value.toString());
56
+ // Reject anything that is not a plain decimal, so malformed input fails here
57
+ // with a clear message rather than as a `SyntaxError` out of `BigInt` below.
58
+ if (!DECIMAL.test(str)) {
59
+ throw new Error(`Invalid decimal value: ${value}`);
18
60
  }
19
61
  // Handle negative values
20
62
  const isNegative = str.startsWith("-");
21
63
  const abs = isNegative ? str.slice(1) : str;
22
64
  const [intPart, fracPart = ""] = abs.split(".");
23
- if (abs.split(".").length > 2) {
24
- throw new Error(`Invalid decimal value: ${str}`);
25
- }
26
65
  // Reject excess decimal places to match ethers.parseUnits behavior
27
66
  if (fracPart.length > decimals) {
28
67
  throw new Error(`Too many decimal places: ${fracPart.length} > ${decimals}`);
@@ -1 +1 @@
1
- {"version":3,"file":"units.js","sourceRoot":"","sources":["../../src/utils/units.ts"],"names":[],"mappings":";;AAMA,gCAgCC;AAMD,gCAEC;AA9CD;;;;;GAKG;AACH,SAAgB,UAAU,CACxB,KAA+B,EAC/B,QAAgB;IAEhB,IAAI,GAAG,GAAG,KAAK,CAAC,QAAQ,EAAE,CAAA;IAE1B,oEAAoE;IACpE,yEAAyE;IACzE,wDAAwD;IACxD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACnD,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;IAC/B,CAAC;IAED,yBAAyB;IACzB,MAAM,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;IACtC,MAAM,GAAG,GAAG,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAE3C,MAAM,CAAC,OAAO,EAAE,QAAQ,GAAG,EAAE,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC/C,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,0BAA0B,GAAG,EAAE,CAAC,CAAA;IAClD,CAAC;IAED,mEAAmE;IACnE,I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C,MAAM,GAAG,QAAQ,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CAAC,4BAA4B,QAAQ,CAAC,MAAM,MAAM,QAAQ,EAAE,CAAC,CAAA;IAC9E,CAAC;IACD,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;IACjD,MAAM,QAAQ,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,GAAG,UAAU,CAAA;IAE9C,kCAAkC;IAClC,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;IAC/B,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAA;AACtC,CAAC;AAED;;;GAGG;AACH,SAAgB,UAAU,CAAC,KAA+B;IACxD,OAAO,UAAU,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;AAC9B,CAAC"}
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@opensea/sdk",
3
- "version": "11.8.0",
3
+ "version": "11.9.0",
4
4
  "description": "TypeScript SDK for the OpenSea marketplace helps developers build new experiences using NFTs, tokens, and our marketplace data",
5
5
  "license": "MIT",
6
6
  "author": "OpenSea Developers",
7
7
  "homepage": "https://docs.opensea.io/reference/api-overview",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/ProjectOpenSea/opensea-js.git"
10
+ "url": "git+https://github.com/ProjectOpenSea/opensea-sdk.git"
11
11
  },
12
12
  "bugs": {
13
- "url": "https://github.com/ProjectOpenSea/opensea-js/issues"
13
+ "url": "https://github.com/ProjectOpenSea/opensea-sdk/issues"
14
14
  },
15
15
  "type": "commonjs",
16
16
  "main": "lib/index.js",
@@ -19,6 +19,10 @@
19
19
  "types": "./lib/index.d.ts",
20
20
  "default": "./lib/index.js"
21
21
  },
22
+ "./stream": {
23
+ "types": "./lib/stream/index.d.ts",
24
+ "default": "./lib/stream/index.js"
25
+ },
22
26
  "./viem": {
23
27
  "types": "./lib/viem.d.ts",
24
28
  "default": "./lib/viem.js"
@@ -31,8 +35,6 @@
31
35
  "scripts": {
32
36
  "build": "tsc",
33
37
  "check-types": "tsc -p tsconfig.check.json",
34
- "docs-build": "typedoc",
35
- "docs-build-md": "typedoc --plugin typedoc-plugin-markdown",
36
38
  "format": "biome format --write .",
37
39
  "format:check": "biome format .",
38
40
  "lint": "biome check .",
@@ -62,8 +64,7 @@
62
64
  "@vitest/coverage-v8": "^3.2.4",
63
65
  "concurrently": "^9.2.1",
64
66
  "dotenv": "^17.3.1",
65
- "typedoc": "^0.28.17",
66
- "typedoc-plugin-markdown": "^4.10.0",
67
+ "jsdom": "27.0.0",
67
68
  "typescript": "^6.0.2",
68
69
  "typescript-eslint": "^8.57.0",
69
70
  "viem": "2.23.2",
@@ -85,6 +86,6 @@
85
86
  "typescript"
86
87
  ],
87
88
  "engines": {
88
- "node": ">=20.0.0"
89
+ "node": ">=22.0.0"
89
90
  }
90
91
  }
package/src/api/api.ts CHANGED
@@ -1402,7 +1402,7 @@ export class OpenSeaAPI {
1402
1402
  ? `${this.apiBaseUrl}${apiPath}?${qs}`
1403
1403
  : `${this.apiBaseUrl}${apiPath}`
1404
1404
  const raw = await this._fetch(url, "GET", undefined, undefined, options)
1405
- return camelizeKeysDeep(raw) as Camelize<T>
1405
+ return this.camelizeResponseBody<T>(raw, options)
1406
1406
  },
1407
1407
  { logger: this.logger },
1408
1408
  )
@@ -1447,12 +1447,29 @@ export class OpenSeaAPI {
1447
1447
  const wireBody =
1448
1448
  body == null || !shouldSnakeize ? body : snakeizeKeysDeep(body)
1449
1449
  const raw = await this._fetch(url, method, headers, wireBody, options)
1450
- return camelizeKeysDeep(raw) as Camelize<T>
1450
+ return this.camelizeResponseBody<T>(raw, options)
1451
1451
  },
1452
1452
  { logger: this.logger },
1453
1453
  )
1454
1454
  }
1455
1455
 
1456
+ /**
1457
+ * Camelize a response body unless the caller opted out via
1458
+ * {@link RequestOptions.camelizeResponse}, which endpoints keyed by data
1459
+ * rather than field names (e.g. traits) rely on to keep their keys intact.
1460
+ *
1461
+ * Shared by `get` and `request` so the option cannot silently do nothing on
1462
+ * one verb.
1463
+ */
1464
+ private camelizeResponseBody<T>(
1465
+ raw: unknown,
1466
+ options?: RequestOptions,
1467
+ ): Camelize<T> {
1468
+ return options?.camelizeResponse === false
1469
+ ? (raw as Camelize<T>)
1470
+ : (camelizeKeysDeep(raw) as Camelize<T>)
1471
+ }
1472
+
1456
1473
  private objectToSearchParams(params: object = {}) {
1457
1474
  const urlSearchParams = new URLSearchParams()
1458
1475
 
@@ -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