@opensea/sdk 10.5.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/lib/api/accounts.js +12 -8
  2. package/lib/api/accounts.js.map +1 -1
  3. package/lib/api/api.d.ts +16 -10
  4. package/lib/api/api.js +42 -18
  5. package/lib/api/api.js.map +1 -1
  6. package/lib/api/collections.js +7 -15
  7. package/lib/api/collections.js.map +1 -1
  8. package/lib/api/fetcher.d.ts +35 -5
  9. package/lib/api/listings.js +3 -3
  10. package/lib/api/listings.js.map +1 -1
  11. package/lib/api/nfts.d.ts +1 -1
  12. package/lib/api/nfts.js +2 -5
  13. package/lib/api/nfts.js.map +1 -1
  14. package/lib/api/offers.d.ts +11 -0
  15. package/lib/api/offers.js +14 -11
  16. package/lib/api/offers.js.map +1 -1
  17. package/lib/api/orders.d.ts +16 -1
  18. package/lib/api/orders.js +17 -3
  19. package/lib/api/orders.js.map +1 -1
  20. package/lib/api/tokens.d.ts +2 -2
  21. package/lib/api/tokens.js +1 -1
  22. package/lib/api/tokens.js.map +1 -1
  23. package/lib/api/types.d.ts +196 -356
  24. package/lib/api/types.js +2 -1
  25. package/lib/api/types.js.map +1 -1
  26. package/lib/orders/types.d.ts +2 -2
  27. package/lib/orders/utils.d.ts +53 -13
  28. package/lib/orders/utils.js +33 -50
  29. package/lib/orders/utils.js.map +1 -1
  30. package/lib/sdk/base.d.ts +11 -4
  31. package/lib/sdk/base.js +4 -4
  32. package/lib/sdk/base.js.map +1 -1
  33. package/lib/sdk/cancellation.d.ts +3 -1
  34. package/lib/sdk/cancellation.js +12 -6
  35. package/lib/sdk/cancellation.js.map +1 -1
  36. package/lib/sdk/fulfillment.js +7 -4
  37. package/lib/sdk/fulfillment.js.map +1 -1
  38. package/lib/sdk/orders.js +1 -1
  39. package/lib/sdk/orders.js.map +1 -1
  40. package/lib/types.d.ts +22 -122
  41. package/lib/types.js.map +1 -1
  42. package/lib/utils/case.d.ts +63 -0
  43. package/lib/utils/case.js +83 -0
  44. package/lib/utils/case.js.map +1 -0
  45. package/lib/utils/utils.d.ts +0 -1
  46. package/lib/utils/utils.js +0 -1
  47. package/lib/utils/utils.js.map +1 -1
  48. package/package.json +2 -2
  49. package/src/api/accounts.ts +14 -8
  50. package/src/api/api.ts +60 -25
  51. package/src/api/collections.ts +7 -21
  52. package/src/api/fetcher.ts +41 -6
  53. package/src/api/listings.ts +3 -3
  54. package/src/api/nfts.ts +3 -7
  55. package/src/api/offers.ts +17 -10
  56. package/src/api/orders.ts +29 -5
  57. package/src/api/tokens.ts +2 -2
  58. package/src/api/types.ts +265 -399
  59. package/src/orders/types.ts +2 -2
  60. package/src/orders/utils.ts +57 -79
  61. package/src/sdk/base.ts +4 -4
  62. package/src/sdk/cancellation.ts +16 -6
  63. package/src/sdk/fulfillment.ts +7 -6
  64. package/src/sdk/orders.ts +1 -1
  65. package/src/types.ts +33 -120
  66. package/src/utils/case.ts +150 -0
  67. package/src/utils/utils.ts +0 -1
  68. package/lib/utils/converters.d.ts +0 -37
  69. package/lib/utils/converters.js +0 -137
  70. package/lib/utils/converters.js.map +0 -1
  71. package/src/utils/converters.ts +0 -145
@@ -70,7 +70,7 @@ export type OrderV2 = {
70
70
 
71
71
  export type FulfillmentDataResponse = {
72
72
  protocol: string
73
- fulfillment_data: FulfillmentData
73
+ fulfillmentData: FulfillmentData
74
74
  }
75
75
 
76
76
  type FulfillmentData = {
@@ -83,7 +83,7 @@ type Transaction = {
83
83
  chain: number
84
84
  to: string
85
85
  value: string
86
- input_data:
86
+ inputData:
87
87
  | {
88
88
  // For fulfillAdvancedOrder
89
89
  advancedOrder: AdvancedOrder
@@ -6,9 +6,18 @@ import type { ProtocolData } from "./types"
6
6
 
7
7
  export const DEFAULT_SEAPORT_CONTRACT_ADDRESS = CROSS_CHAIN_SEAPORT_V1_6_ADDRESS
8
8
 
9
+ /**
10
+ * Build the POST /api/v2/offers body for a collection offer.
11
+ *
12
+ * The OpenSea OpenAPI spec uses mixed casing here: the outer envelope
13
+ * (`protocol_address`, `protocol_data`) is snake_case, but the Seaport
14
+ * `parameters` inside `protocol_data` and `numericTraits` inside `criteria`
15
+ * keep their camelCase keys on the wire. Emit the body in exact wire shape
16
+ * so callers can pass `snakeizeBody: false`.
17
+ */
9
18
  export const getPostCollectionOfferPayload = (
10
19
  collectionSlug: string,
11
- protocol_data: ProtocolData,
20
+ protocolData: ProtocolData,
12
21
  chain: Chain,
13
22
  traitType?: string,
14
23
  traitValue?: string,
@@ -18,27 +27,32 @@ export const getPostCollectionOfferPayload = (
18
27
  const payload = {
19
28
  criteria: {
20
29
  collection: { slug: collectionSlug },
30
+ } as {
31
+ collection: { slug: string }
32
+ traits?: Array<{ type: string; value: string }>
33
+ trait?: { type: string; value: string }
34
+ numericTraits?: Array<{ type: string; min?: number; max?: number }>
21
35
  },
22
- protocol_data,
36
+ protocol_data: protocolData,
23
37
  protocol_address: getSeaportAddress(chain),
24
38
  }
25
39
 
26
- // Prioritize traits array if provided
27
40
  if (traits && traits.length > 0) {
28
- ;(payload.criteria as any).traits = traits
41
+ payload.criteria.traits = traits
29
42
  } else if (traitType && traitValue) {
30
- // Fallback to single trait for backward compatibility
31
- ;(payload.criteria as any).trait = {
32
- type: traitType,
33
- value: traitValue,
34
- }
43
+ payload.criteria.trait = { type: traitType, value: traitValue }
35
44
  }
36
45
  if (numericTraits && numericTraits.length > 0) {
37
- ;(payload.criteria as any).numericTraits = numericTraits
46
+ payload.criteria.numericTraits = numericTraits
38
47
  }
39
48
  return payload
40
49
  }
41
50
 
51
+ /**
52
+ * Build the POST /api/v2/offers/build body. Same mixed-casing rules as
53
+ * {@link getPostCollectionOfferPayload}: outer `protocol_address` and
54
+ * `offer_protection_enabled` are snake_case, `numericTraits` stays camelCase.
55
+ */
42
56
  export const getBuildCollectionOfferPayload = (
43
57
  offererAddress: string,
44
58
  quantity: number,
@@ -54,26 +68,24 @@ export const getBuildCollectionOfferPayload = (
54
68
  offerer: offererAddress,
55
69
  quantity,
56
70
  criteria: {
57
- collection: {
58
- slug: collectionSlug,
59
- },
71
+ collection: { slug: collectionSlug },
72
+ } as {
73
+ collection: { slug: string }
74
+ traits?: Array<{ type: string; value: string }>
75
+ trait?: { type: string; value: string }
76
+ numericTraits?: Array<{ type: string; min?: number; max?: number }>
60
77
  },
61
78
  protocol_address: getSeaportAddress(chain),
62
79
  offer_protection_enabled: offerProtectionEnabled,
63
80
  }
64
81
 
65
- // Prioritize traits array if provided
66
82
  if (traits && traits.length > 0) {
67
- ;(payload.criteria as any).traits = traits
83
+ payload.criteria.traits = traits
68
84
  } else if (traitType && traitValue) {
69
- // Fallback to single trait for backward compatibility
70
- ;(payload.criteria as any).trait = {
71
- type: traitType,
72
- value: traitValue,
73
- }
85
+ payload.criteria.trait = { type: traitType, value: traitValue }
74
86
  }
75
87
  if (numericTraits && numericTraits.length > 0) {
76
- ;(payload.criteria as any).numericTraits = numericTraits
88
+ payload.criteria.numericTraits = numericTraits
77
89
  }
78
90
  return payload
79
91
  }
@@ -85,7 +97,7 @@ export const getFulfillmentDataPath = (side: OrderSide) => {
85
97
 
86
98
  export const getFulfillListingPayload = (
87
99
  fulfillerAddress: string,
88
- order_hash: string,
100
+ orderHash: string,
89
101
  protocolAddress: string,
90
102
  chain: Chain,
91
103
  assetContractAddress?: string,
@@ -95,53 +107,35 @@ export const getFulfillListingPayload = (
95
107
  includeOptionalCreatorFees: boolean = false,
96
108
  ) => {
97
109
  const payload: {
98
- listing: {
99
- hash: string
100
- chain: Chain
101
- protocol_address: string
102
- }
103
- fulfiller: {
104
- address: string
105
- }
106
- consideration?: {
107
- asset_contract_address: string
108
- token_id: string
109
- }
110
- units_to_fill: string
110
+ listing: { hash: string; chain: Chain; protocolAddress: string }
111
+ fulfiller: { address: string }
112
+ consideration?: { assetContractAddress: string; tokenId: string }
113
+ unitsToFill: string
111
114
  recipient?: string
112
- include_optional_creator_fees: boolean
115
+ includeOptionalCreatorFees: boolean
113
116
  } = {
114
117
  listing: {
115
- hash: order_hash,
118
+ hash: orderHash,
116
119
  chain,
117
- protocol_address: protocolAddress,
120
+ protocolAddress,
118
121
  },
119
- fulfiller: {
120
- address: fulfillerAddress,
121
- },
122
- units_to_fill: unitsToFill,
123
- include_optional_creator_fees: includeOptionalCreatorFees,
122
+ fulfiller: { address: fulfillerAddress },
123
+ unitsToFill,
124
+ includeOptionalCreatorFees,
124
125
  }
125
126
 
126
- // Add consideration for criteria listings if needed
127
127
  if (assetContractAddress && tokenId) {
128
- payload.consideration = {
129
- asset_contract_address: assetContractAddress,
130
- token_id: tokenId,
131
- }
128
+ payload.consideration = { assetContractAddress, tokenId }
132
129
  }
133
-
134
- // Add optional recipient for listings
135
130
  if (recipientAddress) {
136
131
  payload.recipient = recipientAddress
137
132
  }
138
-
139
133
  return payload
140
134
  }
141
135
 
142
136
  export const getFulfillOfferPayload = (
143
137
  fulfillerAddress: string,
144
- order_hash: string,
138
+ orderHash: string,
145
139
  protocolAddress: string,
146
140
  chain: Chain,
147
141
  assetContractAddress?: string,
@@ -150,40 +144,24 @@ export const getFulfillOfferPayload = (
150
144
  includeOptionalCreatorFees: boolean = false,
151
145
  ) => {
152
146
  const payload: {
153
- offer: {
154
- hash: string
155
- chain: Chain
156
- protocol_address: string
157
- }
158
- fulfiller: {
159
- address: string
160
- }
161
- consideration?: {
162
- asset_contract_address: string
163
- token_id: string
164
- }
165
- units_to_fill: string
166
- include_optional_creator_fees: boolean
147
+ offer: { hash: string; chain: Chain; protocolAddress: string }
148
+ fulfiller: { address: string }
149
+ consideration?: { assetContractAddress: string; tokenId: string }
150
+ unitsToFill: string
151
+ includeOptionalCreatorFees: boolean
167
152
  } = {
168
153
  offer: {
169
- hash: order_hash,
154
+ hash: orderHash,
170
155
  chain,
171
- protocol_address: protocolAddress,
156
+ protocolAddress,
172
157
  },
173
- fulfiller: {
174
- address: fulfillerAddress,
175
- },
176
- units_to_fill: unitsToFill,
177
- include_optional_creator_fees: includeOptionalCreatorFees,
158
+ fulfiller: { address: fulfillerAddress },
159
+ unitsToFill,
160
+ includeOptionalCreatorFees,
178
161
  }
179
162
 
180
- // Add consideration for criteria offers (e.g., collection offers)
181
163
  if (assetContractAddress && tokenId) {
182
- payload.consideration = {
183
- asset_contract_address: assetContractAddress,
184
- token_id: tokenId,
185
- }
164
+ payload.consideration = { assetContractAddress, tokenId }
186
165
  }
187
-
188
166
  return payload
189
167
  }
package/src/sdk/base.ts CHANGED
@@ -115,8 +115,8 @@ export class BaseOpenSeaSDK {
115
115
  *
116
116
  * @example
117
117
  * ```ts
118
- * const { api_key } = await OpenSeaSDK.requestInstantApiKey()
119
- * const sdk = new OpenSeaSDK(provider, { apiKey: api_key })
118
+ * const { apiKey } = await OpenSeaSDK.requestInstantApiKey()
119
+ * const sdk = new OpenSeaSDK(provider, { apiKey })
120
120
  * ```
121
121
  *
122
122
  * @param apiBaseUrl Optional base URL override (defaults to mainnet).
@@ -386,12 +386,12 @@ export class BaseOpenSeaSDK {
386
386
  listings: options.listings.map(l => ({
387
387
  hash: l.hash,
388
388
  chain: l.chain,
389
- protocol_address: l.protocolAddress,
389
+ protocolAddress: l.protocolAddress,
390
390
  })),
391
391
  fulfiller: { address: options.fulfillerAddress },
392
392
  payment: {
393
393
  chain: options.paymentChain,
394
- token_address: options.paymentTokenAddress,
394
+ tokenAddress: options.paymentTokenAddress,
395
395
  },
396
396
  ...(options.recipientAddress
397
397
  ? { recipient: options.recipientAddress }
@@ -75,9 +75,14 @@ export class CancellationManager {
75
75
  protocolAddress,
76
76
  this.context.chain,
77
77
  )
78
- requireValidProtocol(fetchedOrder.protocol_address)
79
- effectiveProtocolAddress = fetchedOrder.protocol_address
80
- orderComponents = fetchedOrder.protocol_data.parameters
78
+ if (!fetchedOrder.protocolAddress || !fetchedOrder.protocolData) {
79
+ throw new Error(
80
+ `Order ${orderHash} is missing protocolAddress or protocolData — cannot cancel.`,
81
+ )
82
+ }
83
+ requireValidProtocol(fetchedOrder.protocolAddress)
84
+ effectiveProtocolAddress = fetchedOrder.protocolAddress
85
+ orderComponents = fetchedOrder.protocolData.parameters
81
86
  this.context.dispatch(EventType.CancelOrder, {
82
87
  order: fetchedOrder,
83
88
  accountAddress,
@@ -209,9 +214,14 @@ export class CancellationManager {
209
214
 
210
215
  // Extract OrderComponents from the fetched orders
211
216
  orderComponents = fetchedOrders.map(fetched => {
212
- requireValidProtocol(fetched.protocol_address)
213
- effectiveProtocolAddress = fetched.protocol_address
214
- return fetched.protocol_data.parameters
217
+ if (!fetched.protocolAddress || !fetched.protocolData) {
218
+ throw new Error(
219
+ `Order ${fetched.orderHash} is missing protocolAddress or protocolData — cannot cancel.`,
220
+ )
221
+ }
222
+ requireValidProtocol(fetched.protocolAddress)
223
+ effectiveProtocolAddress = fetched.protocolAddress
224
+ return fetched.protocolData.parameters
215
225
  })
216
226
 
217
227
  // Dispatch event for the first fetched order
@@ -135,12 +135,13 @@ export class FulfillmentManager {
135
135
  }): Promise<string> {
136
136
  await this.context.requireAccountIsAvailable(accountAddress)
137
137
 
138
- const protocolAddress =
139
- (order as OrderV2).protocolAddress ?? (order as Order).protocol_address
138
+ const protocolAddress = order.protocolAddress
139
+ if (!protocolAddress) {
140
+ throw new Error("Order protocol address is required")
141
+ }
140
142
  requireValidProtocol(protocolAddress)
141
143
 
142
- const orderHash =
143
- (order as OrderV2).orderHash ?? (order as Order).order_hash
144
+ const orderHash = order.orderHash
144
145
 
145
146
  const side =
146
147
  (order as OrderV2).side ??
@@ -180,8 +181,8 @@ export class FulfillmentManager {
180
181
  )
181
182
 
182
183
  // Use the transaction data returned by the API
183
- const transaction = fulfillmentData.fulfillment_data.transaction
184
- const inputData = transaction.input_data
184
+ const transaction = fulfillmentData.fulfillmentData.transaction
185
+ const inputData = transaction.inputData
185
186
 
186
187
  // Extract function name and build parameters array in correct order
187
188
  const rawFunctionName = transaction.function.split("(")[0]
package/src/sdk/orders.ts CHANGED
@@ -83,7 +83,7 @@ export class OrdersManager {
83
83
  ): CreateInputItem[] {
84
84
  return nfts.map((nft, index) => ({
85
85
  itemType: getAssetItemType(
86
- nft.token_standard.toUpperCase() as TokenStandard,
86
+ nft.tokenStandard.toUpperCase() as TokenStandard,
87
87
  ),
88
88
  token: remapSharedStorefrontAddress(nft.contract),
89
89
  identifier: nft.identifier ?? undefined,
package/src/types.ts CHANGED
@@ -1,6 +1,17 @@
1
- import type { ChainIdentifier } from "@opensea/api-types"
1
+ import type {
2
+ AccountResponse,
3
+ Fee as ApiFee,
4
+ PricingCurrencies as ApiPricingCurrencies,
5
+ Rarity as ApiRarity,
6
+ SocialMediaAccount as ApiSocialMediaAccount,
7
+ ChainIdentifier,
8
+ CollectionDetailedResponse,
9
+ CollectionStatsResponse,
10
+ PaymentToken,
11
+ } from "@opensea/api-types"
2
12
  import type { Listing, Offer } from "./api/types"
3
13
  import type { OrderV2 } from "./orders/types"
14
+ import type { Camelize } from "./utils/case"
4
15
 
5
16
  /**
6
17
  * Numeric type for amounts (replaces ethers BigNumberish).
@@ -199,11 +210,7 @@ export enum SafelistStatus {
199
210
  * Collection fees
200
211
  * @category API Models
201
212
  */
202
- export interface Fee {
203
- fee: number
204
- recipient: string
205
- required: boolean
206
- }
213
+ export type Fee = Camelize<ApiFee>
207
214
 
208
215
  /**
209
216
  * Generic Blockchain Asset.
@@ -240,143 +247,49 @@ export interface AssetWithTokenStandard extends Asset {
240
247
  tokenStandard: TokenStandard
241
248
  }
242
249
 
243
- interface OpenSeaCollectionStatsIntervalData {
244
- interval: "one_day" | "seven_day" | "thirty_day"
245
- volume: number
246
- sales: number
247
- }
248
-
249
250
  /**
250
- * OpenSea Collection Stats
251
+ * OpenSea Collection Stats — sourced from api-types `CollectionStatsResponse`.
251
252
  * @category API Models
252
253
  */
253
- export interface OpenSeaCollectionStats {
254
- total: {
255
- volume: number
256
- sales: number
257
- num_owners: number
258
- floor_price: number
259
- floor_price_symbol: string
260
- }
261
- intervals: OpenSeaCollectionStatsIntervalData[]
262
- }
254
+ export type OpenSeaCollectionStats = Camelize<CollectionStatsResponse>
263
255
 
264
- export interface RarityStrategy {
265
- strategyId: string
266
- strategyVersion: string
267
- calculatedAt: string
268
- maxRank: number
269
- tokensScored: number
270
- }
256
+ /**
257
+ * Rarity strategy for a collection. Camelized from api-types `Rarity`.
258
+ * @category API Models
259
+ */
260
+ export type RarityStrategy = Camelize<ApiRarity>
271
261
 
272
262
  /**
273
- * OpenSea collection metadata.
263
+ * OpenSea collection metadata. Camelized from api-types `CollectionDetailedResponse`.
274
264
  * @category API Models
275
265
  */
276
- export interface OpenSeaCollection {
277
- /** Name of the collection */
278
- name: string
279
- /** The identifier (slug) of the collection */
280
- collection: string
281
- /** Description of the collection */
282
- description: string
283
- /** Image for the collection */
284
- imageUrl: string
285
- /** Banner image for the collection */
286
- bannerImageUrl: string
287
- /** Owner address of the collection */
288
- owner: string
289
- /** The collection's safelist status */
290
- safelistStatus: SafelistStatus
291
- /** The category of the collection */
292
- category: string
293
- /** If the collection is disabled */
294
- isDisabled: boolean
295
- /** If the collection is NSFW (not safe for work) */
296
- isNSFW: boolean
297
- /** If trait offers are enabled */
298
- traitOffersEnabled: boolean
299
- /** If collection offers are enabled */
300
- collectionOffersEnabled: boolean
301
- /** The OpenSea url for the collection */
302
- openseaUrl: string
303
- /** The project url for the collection */
304
- projectUrl: string
305
- /** The wiki url for the collection */
306
- wikiUrl: string
307
- /** The discord url for the collection */
308
- discordUrl: string
309
- /** The telegram url for the collection */
310
- telegramUrl: string
311
- /** The twitter username for the collection */
312
- twitterUsername: string
313
- /** The instagram username for the collection */
314
- instagramUsername: string
315
- /** The contracts for the collection */
316
- contracts: { address: string; chain: Chain }[]
317
- /** Accounts allowed to edit this collection */
318
- editors: string[]
319
- /** The fees for the collection */
320
- fees: Fee[]
321
- /** The rarity strategy for the collection */
322
- rarity: RarityStrategy | null
323
- /** Pricing currencies for listings and offers in this collection */
324
- pricingCurrencies?: PricingCurrencies
325
- /** The total supply of the collection (minted minus burned) */
326
- totalSupply: number
327
- /** The number of unique items in the collection */
328
- uniqueItemCount: number
329
- /** The created date of the collection */
330
- createdDate: string
331
- /** When defined, the zone required for orders for the collection */
332
- requiredZone?: string
333
- }
266
+ export type OpenSeaCollection = Camelize<CollectionDetailedResponse>
334
267
 
335
268
  /**
336
- * Full annotated Fungible Token spec with OpenSea metadata
269
+ * Full annotated Fungible Token spec with OpenSea metadata.
270
+ * Sourced from api-types `PaymentToken`.
271
+ * @category API Models
337
272
  */
338
- export interface OpenSeaPaymentToken {
339
- name: string
340
- symbol: string
341
- decimals: number
342
- address: string
343
- chain: Chain
344
- imageUrl?: string
345
- ethPrice?: string
346
- usdPrice?: string
347
- }
273
+ export type OpenSeaPaymentToken = Camelize<PaymentToken>
348
274
 
349
275
  /**
350
276
  * Pricing currencies for a collection, defining default currencies for listings and offers.
277
+ * Sourced from api-types `PricingCurrencies`.
351
278
  * @category API Models
352
279
  */
353
- export interface PricingCurrencies {
354
- listingCurrency?: OpenSeaPaymentToken
355
- offerCurrency?: OpenSeaPaymentToken
356
- }
280
+ export type PricingCurrencies = Camelize<ApiPricingCurrencies>
357
281
 
358
282
  /**
359
- * OpenSea Account
283
+ * OpenSea Account. Sourced from api-types `AccountResponse`.
360
284
  * @category API Models
361
285
  */
362
- export interface OpenSeaAccount {
363
- address: string
364
- username: string
365
- profileImageUrl: string
366
- bannerImageUrl: string
367
- website: string
368
- socialMediaAccounts: SocialMediaAccount[]
369
- bio: string
370
- joinedDate: string
371
- }
286
+ export type OpenSeaAccount = Camelize<AccountResponse>
287
+
372
288
  /**
373
- * Social media account
289
+ * Social media account. Sourced from api-types `SocialMediaAccount`.
374
290
  * @category API Models
375
291
  */
376
- export interface SocialMediaAccount {
377
- platform: string
378
- username: string
379
- }
292
+ export type SocialMediaAccount = Camelize<ApiSocialMediaAccount>
380
293
 
381
294
  /**
382
295
  * Enhanced Error type for rate limit errors that includes retry-after information
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Recursively camelizes object keys (snake_case → camelCase). Walks plain
3
+ * objects and arrays. Leaves non-plain values (strings, numbers, Date, etc.)
4
+ * untouched.
5
+ *
6
+ * `is_nsfw` → `isNsfw`. Multi-underscore segments capitalize each subsequent
7
+ * word: `total_original_consideration_items` → `totalOriginalConsiderationItems`.
8
+ *
9
+ * Used by the API fetcher to expose camelCase responses to SDK consumers
10
+ * regardless of the snake_case wire format. Pair with the {@link Camelize}
11
+ * type-level mapper so the type system reflects the runtime shape.
12
+ */
13
+ export function camelizeKeysDeep<T>(value: T): Camelize<T> {
14
+ return walk(value) as Camelize<T>
15
+ }
16
+
17
+ function walk(value: unknown): unknown {
18
+ if (Array.isArray(value)) {
19
+ return value.map(walk)
20
+ }
21
+ if (isPlainObject(value)) {
22
+ const out: Record<string, unknown> = {}
23
+ for (const [key, v] of Object.entries(value)) {
24
+ out[snakeToCamel(key)] = walk(v)
25
+ }
26
+ return out
27
+ }
28
+ return value
29
+ }
30
+
31
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
32
+ if (typeof value !== "object" || value === null) return false
33
+ const proto = Object.getPrototypeOf(value)
34
+ return proto === Object.prototype || proto === null
35
+ }
36
+
37
+ function snakeToCamel(key: string): string {
38
+ // No underscore → preserve as-is. Skips the regex when not needed (common case).
39
+ if (!key.includes("_")) return key
40
+ return key.replace(/_([a-z0-9])/g, (_, ch: string) => ch.toUpperCase())
41
+ }
42
+
43
+ /**
44
+ * Recursively snakeizes object keys (camelCase → snake_case). Walks plain
45
+ * objects and arrays. Leaves non-plain values (strings, numbers, Date, etc.)
46
+ * untouched.
47
+ *
48
+ * The inverse of {@link camelizeKeysDeep}. Used by the fetcher to convert
49
+ * camelCase request bodies and query params back to the snake_case wire
50
+ * format the API expects.
51
+ *
52
+ * **Acronym caveat:** every uppercase character emits its own underscore, so
53
+ * acronym-style keys are split between letters: `URL` → `url`,
54
+ * `userID` → `user_i_d`, `NFTContract` → `n_f_t_contract`. This is deliberate
55
+ * (the roundtrip with `camelizeKeysDeep` is consistent under generic rules)
56
+ * but consumers calling `snakeizeKeysDeep` directly should avoid PascalCase
57
+ * acronyms in key names — use `userId` / `nftContract` instead.
58
+ */
59
+ export function snakeizeKeysDeep<T>(value: T): Snakeize<T> {
60
+ return walkSnake(value) as Snakeize<T>
61
+ }
62
+
63
+ function walkSnake(value: unknown): unknown {
64
+ if (Array.isArray(value)) {
65
+ return value.map(walkSnake)
66
+ }
67
+ if (isPlainObject(value)) {
68
+ const out: Record<string, unknown> = {}
69
+ for (const [key, v] of Object.entries(value)) {
70
+ out[camelToSnake(key)] = walkSnake(v)
71
+ }
72
+ return out
73
+ }
74
+ return value
75
+ }
76
+
77
+ function camelToSnake(key: string): string {
78
+ // Position-0 guard: don't emit a leading underscore for the first uppercase
79
+ // character. Otherwise PascalCase or acronym keys (`URL`, `MyKey`) would
80
+ // gain a spurious leading `_` (`_u_r_l`, `_my_key`).
81
+ return key.replace(/[A-Z]/g, (ch, i) =>
82
+ i === 0 ? ch.toLowerCase() : `_${ch.toLowerCase()}`,
83
+ )
84
+ }
85
+
86
+ /**
87
+ * Maps a camelCase string literal to snake_case at the type level.
88
+ * `"isNsfw"` → `"is_nsfw"`. The inverse of {@link Camelize}.
89
+ *
90
+ * Position 0 is special-cased so that PascalCase or acronym keys (`"URL"`,
91
+ * `"MyKey"`) don't gain a leading underscore — this mirrors the runtime
92
+ * {@link camelToSnake} behavior.
93
+ */
94
+ type CamelToSnakeInner<S extends string> =
95
+ S extends `${infer Head}${infer Tail}`
96
+ ? Head extends Uppercase<Head>
97
+ ? `_${Lowercase<Head>}${CamelToSnakeInner<Tail>}`
98
+ : `${Head}${CamelToSnakeInner<Tail>}`
99
+ : S
100
+
101
+ type CamelToSnake<S extends string> = S extends `${infer Head}${infer Tail}`
102
+ ? Head extends Uppercase<Head>
103
+ ? `${Lowercase<Head>}${CamelToSnakeInner<Tail>}`
104
+ : `${Head}${CamelToSnakeInner<Tail>}`
105
+ : S
106
+
107
+ /**
108
+ * Recursively rewrites object keys from camelCase to snake_case. The inverse
109
+ * of {@link Camelize}.
110
+ */
111
+ export type Snakeize<T> = T extends Date
112
+ ? T
113
+ : T extends Array<infer U>
114
+ ? Array<Snakeize<U>>
115
+ : T extends object
116
+ ? {
117
+ [K in keyof T as K extends string ? CamelToSnake<K> : K]: Snakeize<
118
+ T[K]
119
+ >
120
+ }
121
+ : T
122
+
123
+ // ─── Type-level mapper ─────────────────────────────────────────────────────
124
+
125
+ /**
126
+ * Maps a snake_case string literal to camelCase at the type level.
127
+ * `"is_nsfw"` → `"isNsfw"`.
128
+ */
129
+ type SnakeToCamel<S extends string> = S extends `${infer Head}_${infer Tail}`
130
+ ? `${Head}${Capitalize<SnakeToCamel<Tail>>}`
131
+ : S
132
+
133
+ /**
134
+ * Recursively rewrites object keys from snake_case to camelCase. Preserves
135
+ * arrays, primitives, and non-plain objects (Date, etc.).
136
+ *
137
+ * SDK consumers see camelCase types even though api-types ships snake_case —
138
+ * the runtime {@link camelizeKeysDeep} keeps shapes in sync.
139
+ */
140
+ export type Camelize<T> = T extends Date
141
+ ? T
142
+ : T extends Array<infer U>
143
+ ? Array<Camelize<U>>
144
+ : T extends object
145
+ ? {
146
+ [K in keyof T as K extends string ? SnakeToCamel<K> : K]: Camelize<
147
+ T[K]
148
+ >
149
+ }
150
+ : T