opensea-js
Version:
TypeScript SDK for the OpenSea marketplace helps developers build new experiences using NFTs and our marketplace data
435 lines (434 loc) • 24.1 kB
TypeScript
import { Seaport } from "@opensea/seaport-js";
import { OrderComponents } from "@opensea/seaport-js/lib/types";
import { BigNumberish, Overrides, Signer, JsonRpcProvider } from "ethers";
import { OpenSeaAPI } from "./api/api";
import { CollectionOffer, Order } from "./api/types";
import { OrderV2 } from "./orders/types";
import { EventData, EventType, Chain, OpenSeaAPIConfig, AssetWithTokenStandard, AssetWithTokenId } from "./types";
/**
* The OpenSea SDK main class.
* @category Main Classes
*/
export declare class OpenSeaSDK {
/** Provider to use for transactions. */
provider: JsonRpcProvider;
/** Seaport v1.6 client @see {@link https://github.com/ProjectOpenSea/seaport-js} */
seaport_v1_6: Seaport;
/** Logger function to use when debugging */
logger: (arg: string) => void;
/** API instance */
readonly api: OpenSeaAPI;
/** The configured chain */
readonly chain: Chain;
/** Internal cache of decimals for payment tokens to save network requests */
private _cachedPaymentTokenDecimals;
private _emitter;
private _signerOrProvider;
/**
* Create a new instance of OpenSeaSDK.
* @param signerOrProvider Signer or provider to use for transactions. For example:
* `new ethers.providers.JsonRpcProvider('https://mainnet.infura.io')` or
* `new ethers.Wallet(privKey, provider)`
* @param apiConfig configuration options, including `chain`
* @param logger optional function for logging debug strings. defaults to no logging
*/
constructor(signerOrProvider: Signer | JsonRpcProvider, apiConfig?: OpenSeaAPIConfig, logger?: (arg: string) => void);
/**
* Add a listener for events emitted by the SDK.
* @param event The {@link EventType} to listen to.
* @param listener A callback that will accept an object with {@link EventData}\
* @param once Whether the listener should only be called once, or continue listening until removed.
*/
addListener(event: EventType, listener: (data: EventData) => void, once?: boolean): void;
/**
* Remove an event listener by calling `.removeListener()` on an event and listener.
* @param event The {@link EventType} to remove a listener for\
* @param listener The listener to remove
*/
removeListener(event: EventType, listener: (data: EventData) => void): void;
/**
* Remove all event listeners. This should be called when you're unmounting
* a component that listens to events to make UI updates.
* @param event Optional EventType to remove listeners for
*/
removeAllListeners(event?: EventType): void;
/**
* Get the appropriate token address for wrap/unwrap operations.
* For Polygon, use WPOL. For other chains, use getOfferPaymentToken,
* which is the wrapped native asset for the chain.
* @param chain The chain to get the token address for
* @returns The token address for wrap/unwrap operations
*/
getNativeWrapTokenAddress(chain: Chain): string;
/**
* Wrap native asset into wrapped native asset (e.g. ETH into WETH, POL into WPOL).
* Wrapped native assets are needed for making offers.
* @param options
* @param options.amountInEth Amount of native asset to wrap
* @param options.accountAddress Address of the user's wallet containing the native asset
*/
wrapEth({ amountInEth, accountAddress, }: {
amountInEth: BigNumberish;
accountAddress: string;
}): Promise<void>;
/**
* Unwrap wrapped native asset into native asset (e.g. WETH into ETH, WPOL into POL).
* Emits the `UnwrapWeth` event when the transaction is prompted.
* @param options
* @param options.amountInEth How much wrapped native asset to unwrap
* @param options.accountAddress Address of the user's wallet containing the wrapped native asset
*/
unwrapWeth({ amountInEth, accountAddress, }: {
amountInEth: BigNumberish;
accountAddress: string;
}): Promise<void>;
private getAmountWithBasisPointsApplied;
/**
* Build listing order without submitting to API
* @param options Listing parameters
* @returns OrderWithCounter ready for API submission or onchain validation
*/
private _buildListingOrder;
/**
* Build listing order components without submitting to API
* @param options Listing parameters
* @returns OrderComponents ready for onchain validation
*/
private _buildListingOrderComponents;
/**
* Build offer order without submitting to API
* @param options Offer parameters
* @returns OrderWithCounter ready for API submission or onchain validation
*/
private _buildOfferOrder;
/**
* Build offer order components without submitting to API
* @param options Offer parameters
* @returns OrderComponents ready for onchain validation
*/
private _buildOfferOrderComponents;
private getFees;
private isNotMarketplaceFee;
private getNFTItems;
/**
* Create and submit an offer on an asset.
* @param options
* @param options.asset The asset to trade. tokenAddress and tokenId must be defined.
* @param options.accountAddress Address of the wallet making the offer.
* @param options.startAmount Value of the offer in units, not base units e.g. not wei, of the payment token (or WETH if no payment token address specified)
* @param options.quantity The number of assets to bid for (if fungible or semi-fungible). Defaults to 1.
* @param options.domain An optional domain to be hashed and included in the first four bytes of the random salt.
* @param options.salt Arbitrary salt. If not passed in, a random salt will be generated with the first four bytes being the domain hash or empty.
* @param options.expirationTime Expiration time for the order, in UTC seconds
* @param options.paymentTokenAddress ERC20 address for the payment token in the order. If unspecified, defaults to WETH
* @param options.excludeOptionalCreatorFees If true, optional creator fees will be excluded from the offer. Default: true.
* @param options.zone The zone to use for the order. If unspecified, defaults to the chain's signed zone for order protection.
*
* @returns The {@link OrderV2} that was created.
*
* @throws Error if the asset does not contain a token id.
* @throws Error if the accountAddress is not available through wallet or provider.
* @throws Error if the startAmount is not greater than 0.
* @throws Error if paymentTokenAddress is not WETH on anything other than Ethereum mainnet.
*/
createOffer({ asset, accountAddress, startAmount, quantity, domain, salt, expirationTime, paymentTokenAddress, excludeOptionalCreatorFees, zone, }: {
asset: AssetWithTokenId;
accountAddress: string;
startAmount: BigNumberish;
quantity?: BigNumberish;
domain?: string;
salt?: BigNumberish;
expirationTime?: BigNumberish;
paymentTokenAddress?: string;
excludeOptionalCreatorFees?: boolean;
zone?: string;
}): Promise<OrderV2>;
/**
* Create and submit a listing for an asset.
* @param options
* @param options.asset The asset to trade. tokenAddress and tokenId must be defined.
* @param options.accountAddress Address of the wallet making the listing
* @param options.startAmount Value of the listing at the start of the auction in units, not base units e.g. not wei, of the payment token (or WETH if no payment token address specified)
* @param options.endAmount Value of the listing at the end of the auction. If specified, price will change linearly between startAmount and endAmount as time progresses.
* @param options.quantity The number of assets to list (if fungible or semi-fungible). Defaults to 1.
* @param options.domain An optional domain to be hashed and included in the first four bytes of the random salt. This can be used for on-chain order attribution to assist with analytics.
* @param options.salt Arbitrary salt. If not passed in, a random salt will be generated with the first four bytes being the domain hash or empty.
* @param options.listingTime Optional time when the order will become fulfillable, in UTC seconds. Undefined means it will start now.
* @param options.expirationTime Expiration time for the order, in UTC seconds.
* @param options.paymentTokenAddress ERC20 address for the payment token in the order. If unspecified, defaults to ETH
* @param options.buyerAddress Optional address that's allowed to purchase this item. If specified, no other address will be able to take the order, unless its value is the null address.
* @param options.englishAuction If true, the order will be listed as an English auction.
* @param options.excludeOptionalCreatorFees If true, optional creator fees will be excluded from the listing. Default: false.
* @param options.zone The zone to use for the order. For order protection, pass SIGNED_ZONE. If unspecified, defaults to no zone.
* @returns The {@link OrderV2} that was created.
*
* @throws Error if the asset does not contain a token id.
* @throws Error if the accountAddress is not available through wallet or provider.
* @throws Error if the startAmount is not greater than 0.
* @throws Error if paymentTokenAddress is not WETH on anything other than Ethereum mainnet.
*/
createListing({ asset, accountAddress, startAmount, endAmount, quantity, domain, salt, listingTime, expirationTime, paymentTokenAddress, buyerAddress, englishAuction, excludeOptionalCreatorFees, zone, }: {
asset: AssetWithTokenId;
accountAddress: string;
startAmount: BigNumberish;
endAmount?: BigNumberish;
quantity?: BigNumberish;
domain?: string;
salt?: BigNumberish;
listingTime?: number;
expirationTime?: number;
paymentTokenAddress?: string;
buyerAddress?: string;
englishAuction?: boolean;
excludeOptionalCreatorFees?: boolean;
zone?: string;
}): Promise<OrderV2>;
/**
* Create and submit a collection offer.
* @param options
* @param options.collectionSlug Identifier for the collection.
* @param options.accountAddress Address of the wallet making the offer.
* @param options.amount Value of the offer in units, not base units e.g. not wei, of the payment token (or WETH if no payment token address specified).
* @param options.quantity The number of assets to bid for (if fungible or semi-fungible).
* @param options.domain An optional domain to be hashed and included in the first four bytes of the random salt. This can be used for on-chain order attribution to assist with analytics.
* @param options.salt Arbitrary salt. If not passed in, a random salt will be generated with the first four bytes being the domain hash or empty.
* @param options.expirationTime Expiration time for the order, in UTC seconds.
* @param options.paymentTokenAddress ERC20 address for the payment token in the order. If unspecified, defaults to WETH.
* @param options.excludeOptionalCreatorFees If true, optional creator fees will be excluded from the offer. Default: false.
* @param options.offerProtectionEnabled Build the offer on OpenSea's signed zone to provide offer protections from receiving an item which is disabled from trading.
* @param options.traitType If defined, the trait name to create the collection offer for.
* @param options.traitValue If defined, the trait value to create the collection offer for.
* @returns The {@link CollectionOffer} that was created.
*/
createCollectionOffer({ collectionSlug, accountAddress, amount, quantity, domain, salt, expirationTime, paymentTokenAddress, excludeOptionalCreatorFees, offerProtectionEnabled, traitType, traitValue, }: {
collectionSlug: string;
accountAddress: string;
amount: BigNumberish;
quantity: number;
domain?: string;
salt?: BigNumberish;
expirationTime?: number | string;
paymentTokenAddress: string;
excludeOptionalCreatorFees?: boolean;
offerProtectionEnabled?: boolean;
traitType?: string;
traitValue?: string;
}): Promise<CollectionOffer | null>;
/**
* Fulfill a private order for a designated address.
* @param options
* @param options.order The order to fulfill
* @param options.accountAddress Address of the wallet taking the order.
* @param options.domain An optional domain to be hashed and included at the end of fulfillment calldata.
* This can be used for on-chain order attribution to assist with analytics.
* @param options.overrides Transaction overrides, ignored if not set.
* @returns Transaction hash of the order.
*/
private fulfillPrivateOrder;
/**
* Fulfill an order for an asset. The order can be either a listing or an offer.
* @param options
* @param options.order The order to fulfill, a.k.a. "take"
* @param options.accountAddress Address of the wallet taking the offer.
* @param options.recipientAddress The optional address to receive the order's item(s) or currencies. If not specified, defaults to accountAddress.
* @param options.domain An optional domain to be hashed and included at the end of fulfillment calldata. This can be used for on-chain order attribution to assist with analytics.
* @param options.overrides Transaction overrides, ignored if not set.
* @returns Transaction hash of the order.
*
* @throws Error if the accountAddress is not available through wallet or provider.
* @throws Error if the order's protocol address is not supported by OpenSea. See {@link isValidProtocol}.
* @throws Error if attempting to fulfill the order with a recipient address which does not match a private listing.
*/
fulfillOrder({ order, accountAddress, recipientAddress, domain, overrides, }: {
order: OrderV2 | Order;
accountAddress: string;
recipientAddress?: string;
domain?: string;
overrides?: Overrides;
}): Promise<string>;
/**
* Utility function to get the Seaport client based on the address.
* @param protocolAddress The Seaport address.
*/
private getSeaport;
/**
* Cancel orders onchain, preventing them from being fulfilled.
* @param options
* @param options.orders The orders to cancel
* @param options.accountAddress The account address cancelling the orders.
* @param options.domain An optional domain to be hashed and included at the end of fulfillment calldata.
* This can be used for on-chain order attribution to assist with analytics.
* @param options.overrides Transaction overrides, ignored if not set.
* @returns Transaction hash of the order.
*/
private cancelSeaportOrders;
/**
* Cancel an order onchain, preventing it from ever being fulfilled.
* @param options
* @param options.order The order to cancel
* @param options.accountAddress The account address that will be cancelling the order.
* @param options.domain An optional domain to be hashed and included at the end of fulfillment calldata. This can be used for on-chain order attribution to assist with analytics.
*
* @throws Error if the accountAddress is not available through wallet or provider.
* @throws Error if the order's protocol address is not supported by OpenSea. See {@link isValidProtocol}.
*/
cancelOrder({ order, accountAddress, domain, }: {
order: OrderV2;
accountAddress: string;
domain?: string;
}): Promise<void>;
private _getSeaportVersion;
/**
* Get the offerer signature for canceling an order offchain.
* The signature will only be valid if the signer address is the address of the order's offerer.
*/
private _getOffererSignature;
/**
* Offchain cancel an order, offer or listing, by its order hash when protected by the SignedZone.
* Protocol and Chain are required to prevent hash collisions.
* Please note cancellation is only assured if a fulfillment signature was not vended prior to cancellation.
* @param protocolAddress The Seaport address for the order.
* @param orderHash The order hash, or external identifier, of the order.
* @param chain The chain where the order is located.
* @param offererSignature An EIP-712 signature from the offerer of the order.
* If this is not provided, the user associated with the API Key will be checked instead.
* The signature must be a EIP-712 signature consisting of the order's Seaport contract's
* name, version, address, and chain. The struct to sign is `OrderHash` containing a
* single bytes32 field.
* @param useSignerToDeriveOffererSignature Derive the offererSignature from the Ethers signer passed into this sdk.
* @returns The response from the API.
*/
offchainCancelOrder(protocolAddress: string, orderHash: string, chain?: Chain, offererSignature?: string, useSignerToDeriveOffererSignature?: boolean): Promise<import("./api/types").CancelOrderResponse>;
/**
* Returns whether an order is fulfillable.
* An order may not be fulfillable if a target item's transfer function
* is locked for some reason, e.g. an item is being rented within a game
* or trading has been locked for an item type.
* @param options
* @param options.order Order to check
* @param options.accountAddress The account address that will be fulfilling the order
* @returns True if the order is fulfillable, else False.
*
* @throws Error if the order's protocol address is not supported by OpenSea. See {@link isValidProtocol}.
*/
isOrderFulfillable({ order, accountAddress, }: {
order: OrderV2;
accountAddress: string;
}): Promise<boolean>;
/**
* Get an account's balance of any Asset. This asset can be an ERC20, ERC1155, or ERC721.
* @param options
* @param options.accountAddress Account address to check
* @param options.asset The Asset to check balance for. tokenStandard must be set.
* @returns The balance of the asset for the account.
*
* @throws Error if the token standard does not support balanceOf.
*/
getBalance({ accountAddress, asset, }: {
accountAddress: string;
asset: AssetWithTokenStandard;
}): Promise<bigint>;
/**
* Transfer an asset. This asset can be an ERC20, ERC1155, or ERC721.
* @param options
* @param options.asset The Asset to transfer. tokenStandard must be set.
* @param options.amount Amount of asset to transfer. Not used for ERC721.
* @param options.fromAddress The address to transfer from
* @param options.toAddress The address to transfer to
* @param options.overrides Transaction overrides, ignored if not set.
*/
transfer({ asset, amount, fromAddress, toAddress, overrides, }: {
asset: AssetWithTokenStandard;
amount?: BigNumberish;
fromAddress: string;
toAddress: string;
overrides?: Overrides;
}): Promise<void>;
/**
* Instead of signing an off-chain order, this methods allows you to approve an order
* with an on-chain transaction.
* @param order Order to approve
* @param domain An optional domain to be hashed and included at the end of fulfillment calldata. This can be used for on-chain order attribution to assist with analytics.
* @returns Transaction hash of the approval transaction
*
* @throws Error if the accountAddress is not available through wallet or provider.
* @throws Error if the order's protocol address is not supported by OpenSea. See {@link isValidProtocol}.
*/
approveOrder(order: OrderV2, domain?: string): Promise<string>;
/**
* Validates an order onchain using Seaport's validate() method. This submits the order onchain
* and pre-validates the order using Seaport, which makes it cheaper to fulfill since a signature
* is not needed to be verified during fulfillment for the order, but is not strictly required
* and the alternative is orders can be submitted to the API for free instead of sent onchain.
* @param orderComponents Order components to validate onchain
* @param accountAddress Address of the wallet that will pay the gas to validate the order
* @returns Transaction hash of the validation transaction
*
* @throws Error if the accountAddress is not available through wallet or provider.
*/
validateOrderOnchain(orderComponents: OrderComponents, accountAddress: string): Promise<string>;
/**
* Create and validate a listing onchain using Seaport's validate() method. This combines
* order building with onchain validation in a single call.
* @param options Listing parameters
* @returns Transaction hash of the validation transaction
*/
createListingAndValidateOnchain({ asset, accountAddress, startAmount, endAmount, quantity, domain, salt, listingTime, expirationTime, paymentTokenAddress, buyerAddress, englishAuction, excludeOptionalCreatorFees, zone, }: {
asset: AssetWithTokenId;
accountAddress: string;
startAmount: BigNumberish;
endAmount?: BigNumberish;
quantity?: BigNumberish;
domain?: string;
salt?: BigNumberish;
listingTime?: number;
expirationTime?: number;
paymentTokenAddress?: string;
buyerAddress?: string;
englishAuction?: boolean;
excludeOptionalCreatorFees?: boolean;
zone?: string;
}): Promise<string>;
/**
* Create and validate an offer onchain using Seaport's validate() method. This combines
* order building with onchain validation in a single call.
* @param options Offer parameters
* @returns Transaction hash of the validation transaction
*/
createOfferAndValidateOnchain({ asset, accountAddress, startAmount, quantity, domain, salt, expirationTime, paymentTokenAddress, excludeOptionalCreatorFees, zone, }: {
asset: AssetWithTokenId;
accountAddress: string;
startAmount: BigNumberish;
quantity?: BigNumberish;
domain?: string;
salt?: BigNumberish;
expirationTime?: BigNumberish;
paymentTokenAddress?: string;
excludeOptionalCreatorFees?: boolean;
zone?: string;
}): Promise<string>;
/**
* Compute the `basePrice` and `endPrice` parameters to be used to price an order.
* Also validates the expiration time and auction type.
* @param tokenAddress Address of the ERC-20 token to use for trading. Use the null address for ETH.
* @param expirationTime When the auction expires, or 0 if never.
* @param startAmount The base value for the order, in the token's main units (e.g. ETH instead of wei)
* @param endAmount The end value for the order, in the token's main units (e.g. ETH instead of wei)
*/
private _getPriceParameters;
private _dispatch;
/** Get the accounts available from the signer or provider. */
private _getAvailableAccounts;
/**
* Throws an error if an account is not available through the provider.
* @param accountAddress The account address to check is available.
*/
private _requireAccountIsAvailable;
/**
* Wait for a transaction to confirm and log the success or failure.
* @param transactionHash The transaction hash to wait for.
* @param event The event type to log.
* @param description The description of the transaction.
*/
private _confirmTransaction;
}