@opensea/sdk 11.2.0 → 11.4.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.
@@ -0,0 +1,400 @@
1
+ import type {
2
+ OperationRequestBody,
3
+ OperationResponse,
4
+ } from "@opensea/api-types"
5
+ import { getAddress } from "ethers"
6
+ import type { AuthSigner } from "./types"
7
+
8
+ const DEFAULT_AUTH_BASE_URL = "https://auth.opensea.io"
9
+ const DEFAULT_API_BASE_URL = "https://api.opensea.io"
10
+ const DEFAULT_STATEMENT =
11
+ "Click to sign in and accept the OpenSea Terms of Service (https://opensea.io/tos) and Privacy Policy (https://opensea.io/privacy)."
12
+
13
+ export type ChainArch = "EVM" | "SVM" | "BITCOIN"
14
+ export type AccountType = "Ethereum" | "Solana" | "Bitcoin"
15
+
16
+ export interface CreateSiwxMessageOptions {
17
+ address: string
18
+ chainId: number
19
+ nonce: string
20
+ domain?: string
21
+ uri?: string
22
+ version?: "1"
23
+ statement?: string
24
+ issuedAt?: Date
25
+ expirationTime?: Date
26
+ notBefore?: Date
27
+ requestId?: string
28
+ resources?: string[]
29
+ scheme?: string
30
+ chainArch?: ChainArch
31
+ accountType?: AccountType
32
+ }
33
+
34
+ export interface ParseSiwxMessageResult {
35
+ domain: string
36
+ address: string
37
+ statement: string
38
+ uri: string
39
+ version: string
40
+ chainId: string
41
+ nonce: string
42
+ issuedAt: string
43
+ expirationTime?: string
44
+ notBefore?: string
45
+ requestId?: string
46
+ resources?: string[]
47
+ accountType?: AccountType
48
+ }
49
+
50
+ export interface LinkWalletWithSiwxOptions
51
+ extends Omit<CreateSiwxMessageOptions, "address" | "chainId" | "nonce"> {
52
+ authBaseUrl?: string
53
+ apiBaseUrl?: string
54
+ authToken: string
55
+ chainArch: ChainArch
56
+ chainId: number
57
+ }
58
+
59
+ const DOMAIN_REGEX =
60
+ /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}(:[0-9]{1,5})?$/
61
+ const IP_REGEX =
62
+ /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:[0-9]{1,5})?$/
63
+ const LOCALHOST_REGEX = /^localhost(:[0-9]{1,5})?$/
64
+ const NONCE_REGEX = /^[a-zA-Z0-9]{8,}$/
65
+ const SCHEME_REGEX = /^([a-zA-Z][a-zA-Z0-9+-.]*)$/
66
+ const FIELD_PREFIXES = {
67
+ uri: "URI: ",
68
+ version: "Version: ",
69
+ chainId: "Chain ID: ",
70
+ nonce: "Nonce: ",
71
+ issuedAt: "Issued At: ",
72
+ expirationTime: "Expiration Time: ",
73
+ notBefore: "Not Before: ",
74
+ requestId: "Request ID: ",
75
+ } as const
76
+
77
+ type FieldKey = keyof typeof FIELD_PREFIXES
78
+
79
+ /**
80
+ * Translate a chain architecture to the SIWX account type prefix.
81
+ */
82
+ export function chainArchToAccountType(
83
+ chainArch: ChainArch,
84
+ ): AccountType | undefined {
85
+ switch (chainArch) {
86
+ case "EVM":
87
+ return "Ethereum"
88
+ case "SVM":
89
+ return "Solana"
90
+ case "BITCOIN":
91
+ return "Bitcoin"
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Build an EIP-4361/SIWX message for OpenSea wallet linking.
97
+ */
98
+ export function createSiwxMessage(options: CreateSiwxMessageOptions): string {
99
+ const accountType =
100
+ options.accountType ??
101
+ (options.chainArch ? chainArchToAccountType(options.chainArch) : undefined)
102
+ const {
103
+ address,
104
+ chainId,
105
+ domain = "opensea.io",
106
+ expirationTime,
107
+ issuedAt = new Date(),
108
+ nonce,
109
+ notBefore,
110
+ requestId,
111
+ resources,
112
+ scheme,
113
+ uri = "https://opensea.io",
114
+ version = "1",
115
+ } = options
116
+
117
+ validateFields({
118
+ chainId,
119
+ domain,
120
+ nonce,
121
+ scheme,
122
+ statement: options.statement,
123
+ uri,
124
+ version,
125
+ resources,
126
+ })
127
+
128
+ const formattedAddress =
129
+ accountType === "Ethereum" ? getAddress(address) : address
130
+ const origin = scheme ? `${scheme}://${domain}` : domain
131
+ const statement = options.statement ? `${options.statement}\n` : ""
132
+ const accountTypePrefix = accountType ? `${accountType} ` : ""
133
+ const prefix = `${origin} wants you to sign in with your ${accountTypePrefix}account:\n${formattedAddress}\n\n${statement}`
134
+
135
+ let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}\nNonce: ${nonce}\nIssued At: ${issuedAt.toISOString()}`
136
+ if (expirationTime) {
137
+ suffix += `\nExpiration Time: ${expirationTime.toISOString()}`
138
+ }
139
+ if (notBefore) {
140
+ suffix += `\nNot Before: ${notBefore.toISOString()}`
141
+ }
142
+ if (requestId) {
143
+ suffix += `\nRequest ID: ${requestId}`
144
+ }
145
+ if (resources && resources.length > 0) {
146
+ suffix += "\nResources:"
147
+ for (const resource of resources) {
148
+ suffix += `\n- ${resource}`
149
+ }
150
+ }
151
+
152
+ return `${prefix}\n${suffix}`
153
+ }
154
+
155
+ /**
156
+ * Parse a SIWX message into the JSON body expected by the wallet-link API.
157
+ */
158
+ export function parseSiwxMessage(message: string): ParseSiwxMessageResult {
159
+ const lines = message.split("\n")
160
+ const domainMatch =
161
+ /^(?<domain>[^ ]+) wants you to sign in with your (?:(?<accountType>Ethereum|Solana|Bitcoin) )?account:$/.exec(
162
+ lines[0] ?? "",
163
+ )
164
+ const addressMatch = /^(?<address>.+)$/.exec(lines[1] ?? "")
165
+ if (!domainMatch || !addressMatch) {
166
+ throw new Error("Invalid SIWX message")
167
+ }
168
+ if (domainMatch.groups == null || addressMatch.groups == null) {
169
+ throw new Error("Invalid SIWX message")
170
+ }
171
+ const { domain, accountType } = domainMatch.groups
172
+ const { address } = addressMatch.groups
173
+
174
+ const fields: Record<FieldKey, string> = {
175
+ uri: "",
176
+ version: "",
177
+ chainId: "",
178
+ nonce: "",
179
+ issuedAt: "",
180
+ expirationTime: "",
181
+ notBefore: "",
182
+ requestId: "",
183
+ }
184
+ const resources: string[] = []
185
+
186
+ let firstFieldLineIndex = lines.length
187
+ for (let i = 2; i < lines.length; i += 1) {
188
+ const line = lines[i]
189
+ for (const key of Object.keys(FIELD_PREFIXES) as FieldKey[]) {
190
+ const prefix = FIELD_PREFIXES[key]
191
+ if (fields[key] === "" && line.startsWith(prefix)) {
192
+ fields[key] = line.slice(prefix.length)
193
+ firstFieldLineIndex = Math.min(firstFieldLineIndex, i)
194
+ }
195
+ }
196
+ if (line === "Resources:") {
197
+ firstFieldLineIndex = Math.min(firstFieldLineIndex, i)
198
+ for (let j = i + 1; j < lines.length; j += 1) {
199
+ const resourceLine = lines[j]
200
+ if (resourceLine.startsWith("- ")) {
201
+ resources.push(resourceLine.slice(2))
202
+ }
203
+ }
204
+ break
205
+ }
206
+ }
207
+
208
+ const statementLines = lines.slice(2, firstFieldLineIndex)
209
+ while (statementLines.length > 0 && statementLines[0] === "") {
210
+ statementLines.shift()
211
+ }
212
+ while (statementLines.length > 0 && statementLines.at(-1) === "") {
213
+ statementLines.pop()
214
+ }
215
+
216
+ return {
217
+ domain,
218
+ address,
219
+ statement: statementLines.join("\n"),
220
+ uri: fields.uri,
221
+ version: fields.version,
222
+ chainId: fields.chainId,
223
+ nonce: fields.nonce,
224
+ issuedAt: fields.issuedAt,
225
+ ...(fields.expirationTime
226
+ ? {
227
+ expirationTime: fields.expirationTime,
228
+ }
229
+ : {}),
230
+ ...(fields.notBefore
231
+ ? {
232
+ notBefore: fields.notBefore,
233
+ }
234
+ : {}),
235
+ ...(fields.requestId
236
+ ? {
237
+ requestId: fields.requestId,
238
+ }
239
+ : {}),
240
+ ...(resources.length > 0
241
+ ? {
242
+ resources,
243
+ }
244
+ : {}),
245
+ ...(accountType
246
+ ? {
247
+ accountType: accountType as AccountType,
248
+ }
249
+ : {}),
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Request a single-use nonce from the auth service.
255
+ */
256
+ export async function requestSiwxNonce(
257
+ authBaseUrl = DEFAULT_AUTH_BASE_URL,
258
+ ): Promise<string> {
259
+ const response = await fetch(`${stripTrailingSlash(authBaseUrl)}/api/nonce`, {
260
+ method: "GET",
261
+ headers: { Accept: "application/json" },
262
+ })
263
+ if (!response.ok) {
264
+ throw new Error(
265
+ `Auth server error (${response.status}): ${response.statusText}`,
266
+ )
267
+ }
268
+ const data = (await response.json()) as { nonce: string }
269
+ return data.nonce
270
+ }
271
+
272
+ /**
273
+ * Fetch, sign, and submit a wallet-link request.
274
+ */
275
+ export async function linkWalletWithSiwx(
276
+ signer: AuthSigner,
277
+ options: LinkWalletWithSiwxOptions,
278
+ ): Promise<OperationResponse<"link_wallet_with_siwx">> {
279
+ if (
280
+ typeof options.authToken !== "string" ||
281
+ options.authToken.trim() === ""
282
+ ) {
283
+ throw new Error("authToken is required to link a wallet")
284
+ }
285
+
286
+ const authBaseUrl = stripTrailingSlash(
287
+ options.authBaseUrl ?? DEFAULT_AUTH_BASE_URL,
288
+ )
289
+ const apiBaseUrl = stripTrailingSlash(
290
+ options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
291
+ )
292
+ const nonce = await requestSiwxNonce(authBaseUrl)
293
+ const address = await signer.getAddress()
294
+ const message = createSiwxMessage({
295
+ address,
296
+ chainArch: options.chainArch,
297
+ chainId: options.chainId,
298
+ nonce,
299
+ domain: options.domain,
300
+ uri: options.uri,
301
+ version: options.version,
302
+ statement: options.statement ?? DEFAULT_STATEMENT,
303
+ issuedAt: options.issuedAt,
304
+ expirationTime: options.expirationTime,
305
+ notBefore: options.notBefore,
306
+ requestId: options.requestId,
307
+ resources: options.resources,
308
+ scheme: options.scheme,
309
+ })
310
+ const signature = await signer.signMessage(message)
311
+ const payload: OperationRequestBody<"link_wallet_with_siwx"> = {
312
+ message: parseSiwxMessage(message),
313
+ signature,
314
+ chainArch: options.chainArch,
315
+ }
316
+
317
+ const response = await fetch(`${apiBaseUrl}/api/v2/accounts/wallets/siwx`, {
318
+ method: "POST",
319
+ headers: {
320
+ Authorization: `Bearer ${options.authToken}`,
321
+ "Content-Type": "application/json",
322
+ },
323
+ body: JSON.stringify(payload),
324
+ })
325
+ if (!response.ok) {
326
+ const body = await response.text().catch(() => "")
327
+ throw new Error(
328
+ `Wallet link failed (${response.status}): ${body || response.statusText}`,
329
+ )
330
+ }
331
+ return response.json() as Promise<OperationResponse<"link_wallet_with_siwx">>
332
+ }
333
+
334
+ function validateFields({
335
+ chainId,
336
+ domain,
337
+ nonce,
338
+ scheme,
339
+ statement,
340
+ uri,
341
+ version,
342
+ resources,
343
+ }: {
344
+ chainId: number
345
+ domain: string
346
+ nonce: string
347
+ scheme?: string
348
+ statement?: string
349
+ uri: string
350
+ version: string
351
+ resources?: string[]
352
+ }) {
353
+ if (chainId !== Math.floor(chainId)) {
354
+ throw new Error("Chain ID must be a whole number")
355
+ }
356
+ if (
357
+ !(
358
+ DOMAIN_REGEX.test(domain) ||
359
+ IP_REGEX.test(domain) ||
360
+ LOCALHOST_REGEX.test(domain)
361
+ )
362
+ ) {
363
+ throw new Error(`Invalid domain: ${domain}`)
364
+ }
365
+ if (!NONCE_REGEX.test(nonce)) {
366
+ throw new Error(`Invalid nonce: ${nonce}`)
367
+ }
368
+ if (scheme && !SCHEME_REGEX.test(scheme)) {
369
+ throw new Error(`Invalid scheme: ${scheme}`)
370
+ }
371
+ if (!isUri(uri)) {
372
+ throw new Error(`Invalid uri: ${uri}`)
373
+ }
374
+ if (version !== "1") {
375
+ throw new Error(`Invalid version: ${version}`)
376
+ }
377
+ if (statement?.includes("\n")) {
378
+ throw new Error("Statement must not include newlines")
379
+ }
380
+ if (resources) {
381
+ for (const resource of resources) {
382
+ if (!isUri(resource)) {
383
+ throw new Error(`Invalid resource URI: ${resource}`)
384
+ }
385
+ }
386
+ }
387
+ }
388
+
389
+ function isUri(value: string): boolean {
390
+ try {
391
+ new URL(value)
392
+ return true
393
+ } catch {
394
+ return false
395
+ }
396
+ }
397
+
398
+ function stripTrailingSlash(value: string): string {
399
+ return value.replace(/\/$/, "")
400
+ }
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ import { OpenSeaOAuth } from "./auth/oauth"
4
4
  import { OpenSeaSDK } from "./sdk"
5
5
 
6
6
  export * from "./api/types"
7
+ export * from "./api/walletAuth"
7
8
  export * from "./auth"
8
9
  export * from "./auth/oauth"
9
10
  export * from "./auth/oauth-types"
package/src/scopes.ts CHANGED
@@ -12,9 +12,11 @@ import type { AuthScope } from "@opensea/api-types"
12
12
  export const OPENSEA_SCOPES = {
13
13
  READ_ELIGIBILITY: "read:eligibility",
14
14
  READ_FAVORITES: "read:favorites",
15
- READ_REWARDS: "read:rewards",
15
+ WRITE_FAVORITES: "write:favorites",
16
16
  WRITE_ORDERS: "write:orders",
17
17
  WRITE_DROPS: "write:drops",
18
+ WRITE_COLLECTIONS: "write:collections",
19
+ WRITE_PROFILE: "write:profile",
18
20
  WRITE_WALLETS: "write:wallets",
19
21
  } as const satisfies Record<string, AuthScope>
20
22
 
@@ -55,6 +55,11 @@ export const getChainId = (chain: Chain): string => {
55
55
  * @returns The token address for offers
56
56
  */
57
57
  export const getOfferPaymentToken = (chain: Chain) => {
58
+ if (chain === Chain.Solana || chain === Chain.Hyperliquid) {
59
+ throw new Error(
60
+ `Chain ${chain} is not supported for OpenSea Seaport offers`,
61
+ )
62
+ }
58
63
  switch (chain) {
59
64
  case Chain.Mainnet:
60
65
  return "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" // WETH
@@ -99,13 +104,8 @@ export const getOfferPaymentToken = (chain: Chain) => {
99
104
  return "0x046ede9564a72571df6f5e44d0405360c0f4dcab" // WSOMI
100
105
  case Chain.Monad:
101
106
  return "0x3bd359c1119da7da1d913d1c4d2b7c461115433a" // WMON
102
- // Chains without Seaport deployment
103
107
  case Chain.Robinhood:
104
- case Chain.Solana:
105
- case Chain.Hyperliquid:
106
- throw new Error(
107
- `Chain ${chain} is not supported for OpenSea Seaport offers`,
108
- )
108
+ return "0x0bd7d308f8e1639fab988df18a8011f41eacad73" // WETH
109
109
  default: {
110
110
  const exhaustiveChain: never = chain
111
111
  throw new Error(`Unknown offer currency for ${exhaustiveChain}`)
@@ -119,6 +119,11 @@ export const getOfferPaymentToken = (chain: Chain) => {
119
119
  * @returns The token address for listings
120
120
  */
121
121
  export const getListingPaymentToken = (chain: Chain) => {
122
+ if (chain === Chain.Solana || chain === Chain.Hyperliquid) {
123
+ throw new Error(
124
+ `Chain ${chain} is not supported for OpenSea Seaport listings`,
125
+ )
126
+ }
122
127
  switch (chain) {
123
128
  case Chain.Mainnet:
124
129
  case Chain.Soneium:
@@ -155,13 +160,8 @@ export const getListingPaymentToken = (chain: Chain) => {
155
160
  return "0x0000000000000000000000000000000000000000" // GUN
156
161
  case Chain.AnimeChain:
157
162
  return "0x0000000000000000000000000000000000000000" // ANIME
158
- // Chains without Seaport deployment
159
163
  case Chain.Robinhood:
160
- case Chain.Solana:
161
- case Chain.Hyperliquid:
162
- throw new Error(
163
- `Chain ${chain} is not supported for OpenSea Seaport listings`,
164
- )
164
+ return "0x0000000000000000000000000000000000000000" // ETH
165
165
  default: {
166
166
  const exhaustiveChain: never = chain
167
167
  throw new Error(`Unknown listing currency for ${exhaustiveChain}`)
@@ -181,6 +181,7 @@ export const getDefaultConduit = (
181
181
  case Chain.Abstract:
182
182
  case Chain.HyperEVM:
183
183
  case Chain.Monad:
184
+ case Chain.Robinhood:
184
185
  return {
185
186
  key: OPENSEA_CONDUIT_KEY_2,
186
187
  address: OPENSEA_CONDUIT_ADDRESS_2,
package/src/viem.ts CHANGED
@@ -40,6 +40,7 @@ import {
40
40
  // Re-export everything from the main entry point
41
41
  export { OpenSeaAPI } from "./api/api"
42
42
  export * from "./api/types"
43
+ export * from "./api/walletAuth"
43
44
  export * from "./auth"
44
45
  export * from "./constants"
45
46
  export * from "./orders/types"