Skip to content
项目

关于

用于 OpenSea 市场的 TypeScript SDK

开发工具

这些数字如何统计

实测星标增长

24小时
0
7天
0
15天
-1
1个月
-2

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

OpenSea

Version npm Test CI License Docs Discussions

@opensea/sdk

TypeScript SDK for OpenSea. Read and filter the orderbook, create and fulfill listings and offers, swap tokens across chains, and subscribe to marketplace events.

Install

npm install @opensea/sdk viem

Requires Node.js 22.12.0 or newer. viem is a peer dependency of both entry points, since @opensea/seaport-js is built on it. New code should use the viem entry point, @opensea/sdk/viem, which never loads ethers. For a project already on ethers v6, ethers is an optional peer dependency: install it (npm install ethers) and import from the ethers entry point, @opensea/sdk.

Get an API key

For quick experiments, request a free-tier key. It needs no signup and expires after 7 days. In code, call OpenSeaSDK.requestInstantApiKey() (example), or from the shell:

curl -s -X POST https://api.opensea.io/api/v2/auth/keys | jq -r '.api_key'

For production, create a permanent key at opensea.io/settings/developer. These keys don't expire, get higher rate limits, and can be rotated. See the API key docs.

Quick start

Do not ship your API key in frontend code. See Security warning.

import { createPublicClient, http } from "viem";
import { mainnet } from "viem/chains";
import { OpenSeaSDK, Chain } from "@opensea/sdk/viem";

const publicClient = createPublicClient({
  chain: mainnet,
  transport: http("https://eth-mainnet.g.alchemy.com/v2/YOUR_ALCHEMY_API_KEY"),
});
const sdk = new OpenSeaSDK({ publicClient }, { chain: Chain.Mainnet, apiKey: "YOUR_API_KEY" });

To sign, also pass a walletClient (example). Any viem transport works, including WebSocket and injected (custom(window.ethereum)) ones. A walletClient created without an account works too: the SDK acts for the accountAddress each call names, if the wallet exposes it.

With ethers v6, import OpenSeaSDK from @opensea/sdk and pass a JsonRpcProvider or Signer in place of the clients: new OpenSeaSDK(provider, { chain: Chain.Mainnet, apiKey }).

In a browser bundle without ethers installed, import from @opensea/sdk/viem. The root entry's ethers adapter calls require("ethers") only when an ethers-backed OpenSeaSDK is constructed, but some bundlers try to resolve it at build time.

Neither entry point's type declarations reference ethers types, so a TypeScript project without ethers type-checks either one, skipLibCheck or not.

To sign with a managed wallet (Privy, Turnkey, Fireblocks, Bankr) or a raw private key, wrap a @opensea/wallet-adapters adapter in its viem bridge (wallet-adapters 2.1.0 or later) and pass the result as the walletClient (example). Its ethers bridge does the same for the ethers entry point. Orders are signed with the adapter's signTypedData. Fulfillments, approvals and onchain cancels go through its sendTransaction. The public client handles reads and receipts only. Creating listings and offers requires an adapter that supports typed-data signing (wallet.capabilities.signTypedData).

Calling the API

sdk.api groups methods by domain: accounts, assets, chains, collections, drops, events, listings, nfts, offers, orders, tokens, tools (beta), transactions and walletAuth. For example, sdk.api.collections.getCollection(slug) or sdk.api.offers.getAllOffers(...). Search is the one flat method: sdk.api.search(args).

Version 14 removed the older flat methods such as sdk.api.getCollection(slug). Each one maps to the namespaced method of the same name, except four that were renamed; see the API reference.

Optional discovery data

Existing methods accept opt-in data without changing their defaults. api.collections.getCollectionStats(slug, { volumeTimeframe: "seven_days" }) adds volume history; api.collections.getCollectionOfferAggregates(slug, { includeDepth: true }) adds capped two-sided depth. api.nfts.getNFTsByGroup(group, { includeCatalog: true }) requests optional catalog identities. The response omits them before unrestricted public launch or when no identity is available; this option does not bypass lab gating. api.accounts.getAccount(address, { include: ["wallets"] }) expands public registered wallets.

Use api.tokens.getTraderLeaderboard({ timeframe: "seven_days", limit: 20 }) for public rankings based on OpenSea token trades. Feed the response's next value back as cursor, even if the page is short or empty.

Use api.accounts.getNftPositions(address, { state: "OPEN", limit: 10 }) with an API key and a wallet identity token configured on the client. This reads public history for the requested wallet in verified collections. Money values are decimal strings when available. limit caps returned rows, and filters and sorts apply within the most recent 1,000 episodes for the requested state.

Volume history is oldest first. Each bucket has a numeric Unix-seconds time, decimal-string usd, and native currency amount. Missing buckets are omitted, and the current bucket can be incomplete.

api.nfts.getNFTsByCollection keeps its first five positional arguments and accepts listing, price, rarity, numeric-trait and ordering filters as a sixth argument. See the collection NFT parameters. Keep filters and ordering unchanged across cursor pages.

Swap quotes for agents

api.tokens.getSwapQuote accepts singleTransactionOnly and transactionFormat. api.tokens.executeSwap accepts both options and prepares transaction data for external signing and submission.

For self-funded Solana v0 swaps, both methods also accept computeUnitLimit, computeUnitPriceMicroLamports, and jitoTipLamports. Use decimal integer strings for compute prices and tips. A price of "0" disables the priority fee. A tip of "0" requests a route that can run without a canonical tip or bundle. For a positive tip, submit the signed transaction through a Jito bundle and omit singleTransactionOnly. For one-to-one, same-chain Solana swaps, set swapProvider: "jupiter" to require the Jupiter router. Jupiter still selects its downstream venues and programs. If Jupiter cannot build the route, the API returns an error.

The SDK returns camelCase response fields. quote.routes exposes fromQuantity, toQuantity, and nullable minToQuantity as raw token-unit strings. The provider reports the minimum when available. Verify the onchain floor independently. Solana transaction details can include unsigned serializedTransaction, blockhash, lastValidBlockHeight, requiresJitoBundle, and nullable marketplaceFeeTransfer. That field describes the reported OpenSea marketplace fee transfer.

Use an external Solana signer for serialized output, preserve the message bytes, and request a new quote after its block-height expiry.

Response casing

The API uses snake_case. The SDK converts response keys to camelCase, and converts camelCase request bodies and query params to snake_case. You read collection.bannerImageUrl; the wire carries banner_image_url.

@opensea/api-types describes the wire format, so its types are snake_case. Don't use them to annotate a value an SDK method returned. TypeScript only rejects that when the wire type has a required snake_case key somewhere in its tree, so const account: AccountResolveResponse = await sdk.api.accounts.resolveAccount(...) compiles and every snake_case field reads undefined at runtime. Use the SDK's own response type (ResolveAccountResponse), or wrap the wire type in Camelize<T>.

Pass camelizeResponse: false to skip the conversion for one call. Use it when response keys are data rather than field names. getTraits, for example, is keyed by trait names the collection chose, so conversion would turn a dark_brown trait into darkBrown and merge two traits that differ only in casing. Write it as the literal false inline at the call site, or declare the options object as const: api.get, api.post and api.request have an overload for that literal that returns the raw T. A boolean variable, or a const object that widens false to boolean, still skips the conversion at runtime but leaves the declared type as Camelize<T>.

examples/response-casing.ts shows each case, and the type-check proves which ones compile.

Examples

Each example is a standalone script that CI type-checks against the current source.

Example What it shows
instant-api-key.ts Request a free-tier API key and read a collection
viem.ts Construct the SDK from viem public and wallet clients
wallet-adapter-listing.ts Create a listing signed through a @opensea/wallet-adapters adapter
wallet-auth.ts Sign in with SIWE, get a scoped token, call wallet-authenticated endpoints, and revoke
cross-chain-mint.ts Build the transactions to pay on one chain and mint a drop on another
order-actions.ts Get the ordered steps to fulfill a listing on EVM or Solana
token-activity-stats.ts Read precomputed trade count and USD volume for a token
stream-events.ts Subscribe to marketplace events over WebSocket
response-casing.ts Type SDK responses correctly, and skip the camelCase conversion

OpenSeaAuth holds the SIWE session, so keep the same instance until you revoke. See the wallet-auth guide.

The stream client (@opensea/sdk/stream) runs in Node 22+ and browsers with no extra dependencies, and stream events don't count toward your API rate limits. Before version 0.4.0 it was published as @opensea/stream-js. See the migration guide.

When fulfilling on Solana, run actions.steps in order and submit a partially signed transaction or Jito bundle exactly as the response directs. Don't rebuild it or broadcast it through a public RPC.

Documentation

Security warning

Don't use this SDK in frontend code. It needs your API key, and anyone can extract a key embedded in a browser or mobile app, then abuse it or burn through your rate limit.

For a frontend app:

  1. Run your own backend that stores the API key.
  2. Call @opensea/sdk from that backend.
  3. Return what the frontend needs, such as transaction parameters.
  4. Have users sign transactions in the browser with their own wallet (for example, MetaMask).

Changelog

Contributing

Read-only mirror of a private monorepo, updated on each release. Pull requests are welcome, and we bring accepted changes into the monorepo.

Security

Found a vulnerability? Report it through OpenSea's Bugcrowd program at https://bugcrowd.com/engagements/opensea rather than opening a public issue. See SECURITY.md.

探索相关项目

加载中…