### Install Tensorswap SDK
Source: https://github.com/tensor-foundation/tensorswap-sdk/blob/main/README.md
Instructions for installing the Tensorswap SDK using either npm or yarn package managers.
```bash
# yarn
yarn add @tensor-oss/tensorswap-sdk
# npm
npm install @tensor-oss/tensorswap-sdk
```
--------------------------------
### Build Tensorswap SDK from Source
Source: https://github.com/tensor-foundation/tensorswap-sdk/blob/main/README.md
Steps to clone the Tensorswap SDK repository, install dependencies, and build the JavaScript files using yarn.
```bash
git clone https://github.com/tensor-hq/tensorswap-sdk.git
cd tensorswap-sdk/
yarn
# Build JS files
yarn tsc
```
--------------------------------
### Tensorswap SDK Example: Compute Price and Trade NFTs (TypeScript)
Source: https://github.com/tensor-foundation/tensorswap-sdk/blob/main/README.md
Example demonstrating how to use the Tensorswap SDK in TypeScript to compute the taker price for buying or selling NFTs, and then execute buy or sell transactions. It requires setting up an AnchorProvider and initializing the TensorSwapSDK and TensorWhitelistSDK.
```typescript
const { AnchorProvider, Wallet } = require("@project-serum/anchor");
const { Connection, Keypair, PublicKey, Transaction } = require("@solana/web3.js");
const {
TensorSwapSDK,
TensorWhitelistSDK,
computeTakerPrice,
TakerSide,
castPoolConfigAnchor,
findWhitelistPDA,
} = require("@tensor-oss/tensorswap-sdk");
const conn = new Connection("https://api.mainnet-beta.solana.com");
const provider = new AnchorProvider(conn, new Wallet(Keypair.generate()));
const swapSdk = new TensorSwapSDK({ provider });
const wlSdk = new TensorWhitelistSDK({ provider });
// ========= Compute current price (Buy + sell)
// Fetch the pool PDA for its settings.
const pool = await swapSdk.fetchPool(new PublicKey("
"));
const config = castPoolConfigAnchor(pool.config);
const price = computeTakerPrice({
takerSide: TakerSide.Buy, // or TakerSide.Sell for selling
extraNFTsSelected: 0,
// These fields can be extracted from the pool object above.
config,
takerSellCount: pool.takerSellCount,
takerBuyCount: pool.takerBuyCount,
maxTakerSellCount: pool.maxTakerSellCount,
statsTakerSellCount: pool.stats.takerSellCount,
slippage: , // add optional slippage: in case pool updates on-chain
});
// ========= Buying
{
const {
tx: { ixs },
} = await swapSdk.buyNft({
// Whitelist PDA address where name = tensor slug (see TensorWhitelistSDK.nameToBuffer)
whitelist,
// NFT Mint address
nftMint,
// Buyer ATA account (destination)
nftBuyerAcc,
// owner of NFT (in pool PDA)
owner,
// buyer
buyer,
// PoolConfig object: construct from pool PDA
config,
// max price buyer is willing to pay (add ~0.1% for exponential pools b/c of rounding differences)
// see `computeTakerPrice` above to get the current price
maxPrice
});
const buyTx = new Transaction(...ixs);
}
// ========= Selling
// uuid = Tensor collection ID (see "Collection UUID" API endpoint below)
const uuid = "..."
// Remove "-" symbols from uuid, so it's within the 32 seed length limit. Additionally convert the uuid to a Uint8Array
const uuidArray = Buffer.from(uuid.replaceAll("-", "")).toJSON().data;
// Finding the PDA address
const wlAddr = findWhitelistPDA({uuid: uuidArray})[0];
// Step 1: Prepare the mint proof PDA (if required).
{
const wl = await wlSdk.fetchWhitelist(wlAddr);
// Proof is only required if rootHash is NOT a 0 array, o/w not necessary!
if(JSON.stringify(wl.rootHash) !== JSON.stringify(Array(32).fill(0))) {
// Off-chain merkle proof (see "Mint Proof" API endpoint below).
const proof = ...;
const {
tx: { ixs },
} = await wlSdk.initUpdateMintProof({
// User signing the tx (the seller)
user,
whitelist: wlAddr,
// (NFT) Mint address
mint,
proof,
});
const proofTx = new Transaction(...ixs);
}
}
// Step 2: Send sell tx.
{
const {
tx: { ixs },
} = await swapSdk.sellNft({
type: "token", // or 'trade' for a trade pool
whitelist: wlAddr,
// NFT Mint address
nftMint,
// Token account holding seller's mint
nftSellerAcc,
// owner of NFT (in pool PDA)
owner,
// seller
seller,
// PoolConfig object: construct from pool PDA
config,
// min price seller is willing to receive (sub ~0.1% for exponential pools b/c of rounding differences)
// see `computeTakerPrice` above to get the current price
minPrice,
});
const sellTx = new Transaction(...ixs);
}
// ========= TODO: initPool / closePool / editPool / withdrawNft / depositNft / withdrawSol / depositSol
```
--------------------------------
### Install Tensor Tensorswap SDK using npm or yarn
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
This snippet shows how to add the TensorSwap SDK to your project using either yarn or npm package managers. Ensure you have Node.js and a package manager installed.
```bash
# Using yarn
yarn add @tensor-oss/tensorswap-sdk
# Using npm
npm install @tensor-oss/tensorswap-sdk
```
--------------------------------
### Initialize a TensorSwap Liquidity Pool in TypeScript
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Creates a new liquidity pool for a specified NFT collection whitelist using the TensorSwap SDK. This involves setting pool parameters like type, curve, starting price, and order type, then constructing and sending a transaction.
```typescript
import { AnchorProvider, BN, Wallet } from "@coral-xyz/anchor";
import { LAMPORTS_PER_SOL, PublicKey, Transaction } from "@solana/web3.js";
import {
TensorSwapSDK,
CurveTypeAnchor,
PoolTypeAnchor,
OrderType,
} from "@tensor-oss/tensorswap-sdk";
const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed" });
const swapSdk = new TensorSwapSDK({ provider });
const whitelist = new PublicKey("YOUR_WHITELIST_ADDRESS");
const initPoolResult = await swapSdk.initPool({
owner: wallet.publicKey,
whitelist,
config: {
poolType: PoolTypeAnchor.Token, // Collection-wide bid
curveType: CurveTypeAnchor.Exponential,
startingPrice: new BN(0.1 * LAMPORTS_PER_SOL),
delta: new BN(100), // 1% price change
mmCompoundFees: true,
mmFeeBps: null,
},
maxTakerSellCount: 10, // Max NFTs to buy
isCosigned: false,
orderType: OrderType.Standard,
});
const tx = new Transaction().add(...initPoolResult.tx.ixs);
// Sign and send transaction
```
--------------------------------
### Initialize TensorSwap, Whitelist, and Bid SDKs in TypeScript
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Initializes the main SDK components for interacting with TensorSwap, TensorWhitelist, and TensorBid protocols. Requires an Anchor provider, which is set up with a Solana connection, wallet, and commitment level.
```typescript
import { AnchorProvider, Wallet } from "@coral-xyz/anchor";
import { Connection, Keypair } from "@solana/web3.js";
import { TensorSwapSDK, TensorWhitelistSDK, TensorBidSDK } from "@tensor-oss/tensorswap-sdk";
const connection = new Connection("https://api.mainnet-beta.solana.com");
const wallet = new Wallet(Keypair.generate());
const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed" });
// Initialize SDKs
const swapSdk = new TensorSwapSDK({ provider });
const whitelistSdk = new TensorWhitelistSDK({ provider });
const bidSdk = new TensorBidSDK({ provider });
```
--------------------------------
### Place Bid on NFT with TensorBid SDK (TypeScript)
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Place a bid on a specific NFT mint address using the TensorBid SDK. This involves providing the bidder's public key, NFT mint, bid amount in lamports, and an expiration time. It also shows how to cancel a bid.
```typescript
import { BN } from "@coral-xyz/anchor";
import { PublicKey, LAMPORTS_PER_SOL, Transaction } from "@solana/web3.js";
import { TensorBidSDK } from "@tensor-oss/tensorswap-sdk";
const bidSdk = new TensorBidSDK({ provider });
const nftMint = new PublicKey("NFT_MINT_ADDRESS");
// Place bid
const bidResult = await bidSdk.bid({
bidder: wallet.publicKey,
nftMint,
lamports: new BN(2 * LAMPORTS_PER_SOL), // Bid 2 SOL
expireIn: new BN(7 * 24 * 60 * 60), // Expire in 7 days (seconds)
margin: null, // Optional: use margin account
});
const bidTx = new Transaction().add(...bidResult.tx.ixs);
// Cancel bid
const cancelResult = await bidSdk.cancelBid({
bidder: wallet.publicKey,
nftMint,
});
const cancelTx = new Transaction().add(...cancelResult.tx.ixs);
```
--------------------------------
### Buy NFT from Pool using TypeScript
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Purchases an NFT from a pool with slippage protection. Requires pool address, NFT mint, buyer's associated token account, owner, buyer public key, pool configuration, maximum price (calculated with slippage), token program, metadata, and optional royalty percentage. Returns transaction instructions.
```typescript
import { PublicKey, Transaction } from "@solana/web3.js";
import { getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID } from "@solana/spl-token";
import { TensorSwapSDK, castPoolConfigAnchor, computeTakerPrice, TakerSide } from "@tensor-oss/tensorswap-sdk";
const poolAddress = new PublicKey("POOL_ADDRESS");
const nftMint = new PublicKey("NFT_MINT_ADDRESS");
// Fetch pool to get current config
const pool = await swapSdk.fetchPool(poolAddress);
const config = castPoolConfigAnchor(pool.config);
// Calculate current buy price with slippage
const currentPrice = computeTakerPrice({
takerSide: TakerSide.Buy,
extraNFTsSelected: 0,
config,
takerSellCount: pool.takerSellCount,
takerBuyCount: pool.takerBuyCount,
maxTakerSellCount: pool.maxTakerSellCount,
statsTakerSellCount: pool.stats.takerSellCount,
statsTakerBuyCount: pool.stats.takerBuyCount,
slippage: 0.01, // 1% slippage
marginated: pool.margin !== null,
});
const buyerAta = getAssociatedTokenAddressSync(nftMint, wallet.publicKey);
const buyResult = await swapSdk.buyNft({
whitelist: pool.whitelist,
nftMint,
nftBuyerAcc: buyerAta,
owner: pool.owner,
buyer: wallet.publicKey,
config: pool.config,
maxPrice: new BN(currentPrice.round().toString()),
tokenProgram: TOKEN_PROGRAM_ID,
meta: nftMetadata,
optionalRoyaltyPct: 100, // Pay full royalties
});
const tx = new Transaction().add(...buyResult.tx.ixs);
```
--------------------------------
### Buy Single Listing
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Purchase a single NFT from an existing listing on TensorSwap.
```APIDOC
## POST /api/buySingleListing
### Description
Purchase an NFT from a single listing.
### Method
POST
### Endpoint
/api/buySingleListing
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **nftMint** (PublicKey) - Required - The mint address of the NFT to buy.
- **nftBuyerAcc** (PublicKey) - Required - The buyer's associated token account for the NFT.
- **owner** (PublicKey) - Required - The public key of the original lister.
- **buyer** (PublicKey) - Required - The public key of the buyer.
- **maxPrice** (BN) - Required - The maximum price the buyer is willing to pay, in lamports.
- **tokenProgram** (PublicKey) - Required - The token program ID.
- **meta** (object) - Required - NFT metadata object.
- **optionalRoyaltyPct** (number) - Optional - The royalty percentage to apply.
### Request Example
```typescript
{
"nftMint": "NFT_MINT_ADDRESS",
"nftBuyerAcc": "BUYER_ATA_ADDRESS",
"owner": "LISTING_OWNER_ADDRESS",
"buyer": "BUYER_PUBLIC_KEY",
"maxPrice": "5100000000", // Example: 5.1 SOL in lamports
"tokenProgram": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
"meta": { ... }, // NFT metadata details
"optionalRoyaltyPct": 100
}
```
### Response
#### Success Response (200)
- **tx** (object) - An object containing the transaction instructions.
#### Response Example
```json
{
"tx": {
"ixs": [
// Transaction instruction objects
]
}
}
```
```
--------------------------------
### Manage Single NFT Listing using TypeScript
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Handles listing, editing, and delisting individual NFTs at a fixed price. Requires owner, NFT mint, source/destination accounts, price, token program, and metadata. Returns transaction instructions for each operation.
```typescript
import { BN } from "@coral-xyz/anchor";
import { LAMPORTS_PER_SOL, Transaction } from "@solana/web3.js";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
// List NFT
const listResult = await swapSdk.list({
owner: wallet.publicKey,
nftMint,
nftSource: sellerNftAccount,
price: new BN(5 * LAMPORTS_PER_SOL), // List for 5 SOL
tokenProgram: TOKEN_PROGRAM_ID,
meta: nftMetadata,
});
const listTx = new Transaction().add(...listResult.tx.ixs);
// Edit listing price
const editResult = await swapSdk.editSingleListing({
owner: wallet.publicKey,
nftMint,
price: new BN(4.5 * LAMPORTS_PER_SOL), // New price
});
const editTx = new Transaction().add(...editResult.tx.ixs);
// Delist NFT
const delistResult = await swapSdk.delist({
owner: wallet.publicKey,
nftMint,
nftDest: sellerNftAccount, // Return destination
tokenProgram: TOKEN_PROGRAM_ID,
meta: nftMetadata,
});
const delistTx = new Transaction().add(...delistResult.tx.ixs);
```
--------------------------------
### Accept Bid on NFT with TensorBid SDK (TypeScript)
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Accept an existing bid to sell an NFT using the TensorBid SDK. This function requires the bidder's public key, seller's public key, NFT mint, bid amount, token program ID, seller's NFT account, NFT metadata, and optional royalty percentage.
```typescript
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
const takeBidResult = await bidSdk.takeBid({
bidder: bidderPublicKey, // The person who placed the bid
seller: wallet.publicKey,
nftMint,
lamports: new BN(2 * LAMPORTS_PER_SOL), // Bid amount
tokenProgram: TOKEN_PROGRAM_ID,
nftSellerAcc: sellerNftAccount,
meta: nftMetadata,
authData: null,
optionalRoyaltyPct: 100,
});
const tx = new Transaction().add(...takeBidResult.tx.ixs);
```
--------------------------------
### Sell NFT to Pool using TypeScript
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Sells an NFT into a Token or Trade pool. Requires pool details, NFT mint and seller account, owner, seller public key, pool configuration, minimum price (calculated with slippage), token program, metadata, and optional royalty percentage. Returns transaction instructions.
```typescript
import { PublicKey, Transaction } from "@solana/web3.js";
import { TensorSwapSDK, TakerSide, computeTakerPrice } from "@tensor-oss/tensorswap-sdk";
// Calculate minimum sell price
const sellPrice = computeTakerPrice({
takerSide: TakerSide.Sell,
extraNFTsSelected: 0,
config,
takerSellCount: pool.takerSellCount,
takerBuyCount: pool.takerBuyCount,
maxTakerSellCount: pool.maxTakerSellCount,
statsTakerSellCount: pool.stats.takerSellCount,
statsTakerBuyCount: pool.stats.takerBuyCount,
slippage: 0.01,
marginated: pool.margin !== null,
});
const sellResult = await swapSdk.sellNft({
type: "token", // or "trade" for trade pools
whitelist: pool.whitelist,
nftMint,
nftSellerAcc: sellerNftAccount,
owner: pool.owner,
seller: wallet.publicKey,
config: pool.config,
minPrice: new BN(sellPrice.round().toString()),
tokenProgram: TOKEN_PROGRAM_ID,
meta: nftMetadata,
optionalRoyaltyPct: 100,
});
const tx = new Transaction().add(...sellResult.tx.ixs);
```
--------------------------------
### Manage Margin Accounts with TypeScript
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Code for creating and managing shared escrow (margin) accounts for capital-efficient trading. This includes initializing, depositing to, attaching/detaching pools from, withdrawing from, and closing margin accounts.
```typescript
import { TensorSwapSDK } from "@tensor-oss/tensorswap-sdk";
// Initialize margin account
const initMarginResult = await swapSdk.initMarginAcc({
owner: wallet.publicKey,
name: TensorSwapSDK.uuidToBuffer("my-margin-account"),
});
const initTx = new Transaction().add(...initMarginResult.tx.ixs);
const marginNr = initMarginResult.marginNr;
// Deposit to margin account
const depositMarginResult = await swapSdk.depositMarginAcc({
marginNr,
owner: wallet.publicKey,
amount: new BN(10 * LAMPORTS_PER_SOL),
});
// Attach pool to margin account
const attachResult = await swapSdk.attachPoolMargin({
config: poolConfig,
marginNr,
owner: wallet.publicKey,
whitelist,
});
// Detach pool from margin
const detachResult = await swapSdk.detachPoolMargin({
config: poolConfig,
marginNr,
owner: wallet.publicKey,
whitelist,
amount: new BN(0), // Amount to move back to pool escrow
});
// Withdraw from margin account
const withdrawMarginResult = await swapSdk.withdrawMarginAcc({
marginNr,
owner: wallet.publicKey,
amount: new BN(5 * LAMPORTS_PER_SOL),
});
// Close margin account
const closeMarginResult = await swapSdk.closeMarginAcc({
marginNr,
owner: wallet.publicKey,
});
```
--------------------------------
### Margin Account Management
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Create and manage shared escrow (margin) accounts for capital-efficient trading.
```APIDOC
## POST /api/margin-account
### Description
Create and manage shared escrow (margin) accounts for capital-efficient trading across multiple pools.
### Method
POST
### Endpoint
/api/margin-account
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **action** (string) - Required - The action to perform: 'init', 'deposit', 'attach', 'detach', 'withdraw', 'close'.
- **owner** (PublicKey) - Required - The public key of the owner.
- **marginNr** (number) - Required for actions other than 'init' - The margin account number.
- **name** (Buffer) - Required for 'init' - The name of the margin account (UUID buffer).
- **amount** (BN) - Required for 'deposit' and 'withdraw' - The amount in lamports.
- **config** (object) - Required for 'attach' and 'detach' - The pool configuration.
- **whitelist** (PublicKey) - Required for 'attach' and 'detach' - The whitelist address.
### Request Example
```typescript
// Initialize margin account
const initMarginResult = await swapSdk.initMarginAcc({
owner: wallet.publicKey,
name: TensorSwapSDK.uuidToBuffer("my-margin-account")
});
// Deposit to margin account
const depositMarginResult = await swapSdk.depositMarginAcc({
marginNr: initMarginResult.marginNr,
owner: wallet.publicKey,
amount: new BN(10 * LAMPORTS_PER_SOL)
});
// Attach pool to margin account
const attachResult = await swapSdk.attachPoolMargin({
config: poolConfig,
marginNr: initMarginResult.marginNr,
owner: wallet.publicKey,
whitelist: whitelistAddress
});
// Detach pool from margin
const detachResult = await swapSdk.detachPoolMargin({
config: poolConfig,
marginNr: initMarginResult.marginNr,
owner: wallet.publicKey,
whitelist: whitelistAddress,
amount: new BN(0)
});
// Withdraw from margin account
const withdrawMarginResult = await swapSdk.withdrawMarginAcc({
marginNr: initMarginResult.marginNr,
owner: wallet.publicKey,
amount: new BN(5 * LAMPORTS_PER_SOL)
});
// Close margin account
const closeMarginResult = await swapSdk.closeMarginAcc({
marginNr: initMarginResult.marginNr,
owner: wallet.publicKey
});
```
### Response
#### Success Response (200)
- **tx** (object) - An object containing the transaction instructions.
- **marginNr** (number) - The margin account number (returned on initialization).
#### Response Example
```json
{
"tx": {
"ixs": [
// Transaction instruction objects
]
},
"marginNr": 1 // Example margin account number
}
```
```
--------------------------------
### TensorBid - Accept/Take Bid
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Accept an existing bid to sell an NFT.
```APIDOC
## POST /api/tensorbid/take-bid
### Description
Sell an NFT to accept an existing bid.
### Method
POST
### Endpoint
/api/tensorbid/take-bid
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **bidder** (PublicKey) - Required - The public key of the bidder.
- **seller** (PublicKey) - Required - The public key of the seller.
- **nftMint** (PublicKey) - Required - The mint address of the NFT being sold.
- **lamports** (BN) - Required - The bid amount in lamports.
- **tokenProgram** (PublicKey) - Required - The token program ID.
- **nftSellerAcc** (PublicKey) - Required - The seller's account for the NFT.
- **meta** (object) - Required - NFT metadata object.
- **authData** (object | null) - Optional - Authorization data.
- **optionalRoyaltyPct** (number) - Optional - The royalty percentage to apply.
### Request Example
```typescript
const takeBidResult = await bidSdk.takeBid({
bidder: bidderPublicKey,
seller: wallet.publicKey,
nftMint: "NFT_MINT_ADDRESS",
lamports: new BN(2 * LAMPORTS_PER_SOL), // Bid amount
tokenProgram: TOKEN_PROGRAM_ID,
nftSellerAcc: sellerNftAccount,
meta: nftMetadata,
authData: null,
optionalRoyaltyPct: 100
});
```
### Response
#### Success Response (200)
- **tx** (object) - An object containing the transaction instructions.
#### Response Example
```json
{
"tx": {
"ixs": [
// Transaction instruction objects
]
}
}
```
```
--------------------------------
### Manage NFT Collection Whitelists with Merkle Trees
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Create and manage collection whitelists using Merkle trees for NFT verification. This involves generating UUIDs, creating Merkle trees from collection mints, initializing the whitelist with the Merkle root, and generating proofs for individual NFTs.
```typescript
import { PublicKey } from "@solana/web3.js";
import { TensorWhitelistSDK } from "@tensor-oss/tensorswap-sdk";
const whitelistSdk = new TensorWhitelistSDK({ provider });
// Generate UUID for whitelist
const uuid = whitelistSdk.genWhitelistUUID();
const uuidBuffer = TensorWhitelistSDK.uuidToBuffer(uuid);
// Create Merkle tree from collection mints
const collectionMints = [
new PublicKey("MINT_1"),
new PublicKey("MINT_2"),
new PublicKey("MINT_3"),
];
const { tree, root, proofs } = TensorWhitelistSDK.createTreeForMints(collectionMints);
// Initialize whitelist with Merkle root
const initWhitelistResult = await whitelistSdk.initUpdateWhitelist({
uuid: uuidBuffer,
rootHash: root,
name: TensorWhitelistSDK.nameToBuffer("My Collection"),
voc: null, // Optional: Verified On-Chain collection address
fvc: null, // Optional: First Verified Creator address
});
const tx = new Transaction().add(...initWhitelistResult.tx.ixs);
// Initialize mint proof for selling/depositing
const mintProof = proofs.find((p) => p.mint.equals(nftMint));
const mintProofResult = await whitelistSdk.initUpdateMintProof({
user: wallet.publicKey,
mint: nftMint,
whitelist: initWhitelistResult.whitelistPda,
proof: mintProof.proof,
});
const proofTx = new Transaction().add(...mintProofResult.tx.ixs);
```
--------------------------------
### TensorBid - Place Bid
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Place a bid on a specific NFT mint address using the TensorBid SDK.
```APIDOC
## POST /api/tensorbid/place-bid
### Description
Place a bid on a specific NFT mint address.
### Method
POST
### Endpoint
/api/tensorbid/place-bid
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **bidder** (PublicKey) - Required - The public key of the bidder.
- **nftMint** (PublicKey) - Required - The mint address of the NFT to bid on.
- **lamports** (BN) - Required - The amount of SOL to bid, in lamports.
- **expireIn** (BN) - Required - The expiration time of the bid in seconds.
- **margin** (PublicKey | null) - Optional - The margin account to use for the bid.
### Request Example
```typescript
const bidResult = await bidSdk.bid({
bidder: wallet.publicKey,
nftMint: "NFT_MINT_ADDRESS",
lamports: new BN(2 * LAMPORTS_PER_SOL), // Bid 2 SOL
expireIn: new BN(7 * 24 * 60 * 60), // Expire in 7 days (seconds)
margin: null // Optional: use margin account
});
```
### Response
#### Success Response (200)
- **tx** (object) - An object containing the transaction instructions.
#### Response Example
```json
{
"tx": {
"ixs": [
// Transaction instruction objects
]
}
}
```
```
```APIDOC
## DELETE /api/tensorbid/cancel-bid
### Description
Cancel an existing bid on an NFT.
### Method
DELETE
### Endpoint
/api/tensorbid/cancel-bid
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **bidder** (PublicKey) - Required - The public key of the bidder.
- **nftMint** (PublicKey) - Required - The mint address of the NFT for which the bid is being cancelled.
### Request Example
```typescript
const cancelResult = await bidSdk.cancelBid({
bidder: wallet.publicKey,
nftMint: "NFT_MINT_ADDRESS"
});
```
### Response
#### Success Response (200)
- **tx** (object) - An object containing the transaction instructions.
#### Response Example
```json
{
"tx": {
"ixs": [
// Transaction instruction objects
]
}
}
```
```
--------------------------------
### Fetch On-Chain Account Data with TensorSwap SDK
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Fetches on-chain account data for TensorSwap pools, listings, and global state. Requires the TensorSwapSDK and relevant PDAs. Outputs include pool owner, NFT counts, listing prices, margin account details, and global fee configurations.
```typescript
import { PublicKey } from "@solana/web3.js";
import { TensorSwapSDK, findPoolPDA, findSingleListingPDA } from "@tensor-oss/tensorswap-sdk";
// Fetch pool data
const pool = await swapSdk.fetchPool(poolAddress);
console.log("Pool owner:", pool.owner.toString());
console.log("NFTs held:", pool.nftsHeld);
console.log("Taker sell count:", pool.takerSellCount);
console.log("Taker buy count:", pool.takerBuyCount);
// Fetch single listing
const [listingPda] = findSingleListingPDA({ nftMint });
const listing = await swapSdk.fetchSingleListing(listingPda);
console.log("Listing price:", listing.price.toString());
console.log("Listing owner:", listing.owner.toString());
// Fetch margin account
const marginAccount = await swapSdk.fetchMarginAccount(marginPda);
console.log("Pools attached:", marginAccount.poolsAttached);
// Fetch TSwap global state
const [tswapPda] = findTSwapPDA({});
const tswap = await swapSdk.fetchTSwap(tswapPda);
console.log("Fee BPS:", tswap.config.feeBps);
```
--------------------------------
### Buy Single NFT Listing with TypeScript
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Purchase a single NFT from a listing using the TensorSwap SDK. This function requires NFT mint address, buyer's ATA, listing owner, buyer's public key, maximum price, token program ID, NFT metadata, and an optional royalty percentage.
```typescript
const buyListingResult = await swapSdk.buySingleListing({
nftMint,
nftBuyerAcc: buyerAta,
owner: listingOwner, // Original lister
buyer: wallet.publicKey,
maxPrice: new BN(5.1 * LAMPORTS_PER_SOL), // Max willing to pay
tokenProgram: TOKEN_PROGRAM_ID,
meta: nftMetadata,
optionalRoyaltyPct: 100,
});
const tx = new Transaction().add(...buyListingResult.tx.ixs);
```
--------------------------------
### Deposit NFT into Pool using TypeScript
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Adds an NFT to an NFT or Trade pool for selling. Requires owner, whitelist, NFT mint and source accounts, token program ID, pool configuration (type, curve, price, delta, fees), and NFT metadata. Returns transaction instructions.
```typescript
import { PublicKey, Transaction } from "@solana/web3.js";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
const nftMint = new PublicKey("NFT_MINT_ADDRESS");
const nftSource = new PublicKey("YOUR_NFT_TOKEN_ACCOUNT");
const depositNftResult = await swapSdk.depositNft({
owner: wallet.publicKey,
whitelist,
nftMint,
nftSource,
tokenProgram: TOKEN_PROGRAM_ID,
config: {
poolType: PoolTypeAnchor.NFT,
curveType: CurveTypeAnchor.Exponential,
startingPrice: new BN(0.1 * LAMPORTS_PER_SOL),
delta: new BN(100),
mmCompoundFees: true,
mmFeeBps: null,
},
// pNFT metadata (fetch using @metaplex-foundation/js)
meta: nftMetadata,
});
const tx = new Transaction().add(...depositNftResult.tx.ixs);
```
--------------------------------
### Price Calculation Utilities
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Utilities to calculate current prices and required amounts for pool operations.
```APIDOC
## GET /api/price-utilities
### Description
Calculate current prices and required amounts for pool operations.
### Method
GET
### Endpoint
/api/price-utilities
### Parameters
#### Path Parameters
None
#### Query Parameters
- **poolAddress** (PublicKey) - Required - The address of the pool.
- **takerSide** (TakerSide) - Required - The side of the taker (Buy or Sell).
- **extraNFTsSelected** (number) - Optional - Number of extra NFTs selected.
#### Request Body
None
### Request Example
```typescript
// To get display price:
const displayPrice = await swapSdk.computeTakerDisplayPrice({
takerSide: TakerSide.Buy,
extraNFTsSelected: 0,
config: poolConfig,
takerSellCount: pool.takerSellCount,
takerBuyCount: pool.takerBuyCount,
maxTakerSellCount: pool.maxTakerSellCount,
statsTakerSellCount: pool.stats.takerSellCount,
statsTakerBuyCount: pool.stats.takerBuyCount,
marginated: pool.margin !== null
});
// To calculate how many NFTs can be bought with X SOL:
const { allowedCount, totalAmount, initialPrice } = await swapSdk.computeMakerAmountCount({
desired: { total: new BN(10 * LAMPORTS_PER_SOL) }, // e.g., 10 SOL
maxCountWhenInfinite: 1000,
takerSide: TakerSide.Sell,
extraNFTsSelected: 0,
config: poolConfig,
takerSellCount: pool.takerSellCount,
takerBuyCount: pool.takerBuyCount,
maxTakerSellCount: pool.maxTakerSellCount,
statsTakerSellCount: pool.stats.takerSellCount,
statsTakerBuyCount: pool.stats.takerBuyCount,
marginated: pool.margin !== null
});
```
### Response
#### Success Response (200)
- **displayPrice** (BigNumber | null) - The display price for UI purposes.
- **allowedCount** (number) - The number of NFTs that can be bought.
- **totalAmount** (BN) - The total amount required for the purchase.
- **initialPrice** (BN) - The initial price for the purchase.
#### Response Example
```json
{
"displayPrice": "1500000000", // Example: 1.5 SOL in lamports
"allowedCount": 5,
"totalAmount": "7500000000", // Example: 7.5 SOL in lamports
"initialPrice": "1500000000" // Example: 1.5 SOL in lamports
}
```
```
--------------------------------
### Calculate Pool Prices and Amounts with TypeScript
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Utilities to calculate current prices and required amounts for NFT pool operations. It uses functions like `computeTakerPrice`, `computeTakerDisplayPrice`, and `computeMakerAmountCount` from the TensorSwap SDK. Dependencies include `@tensor-oss/tensorswap-sdk` and `big.js`.
```typescript
import {
computeTakerPrice,
computeTakerDisplayPrice,
computeMakerAmountCount,
castPoolConfigAnchor,
TakerSide,
} from "@tensor-oss/tensorswap-sdk";
import Big from "big.js";
const pool = await swapSdk.fetchPool(poolAddress);
const config = castPoolConfigAnchor(pool.config);
// Get display price (no slippage - for UI)
const displayPrice = computeTakerDisplayPrice({
takerSide: TakerSide.Buy,
extraNFTsSelected: 0,
config,
takerSellCount: pool.takerSellCount,
takerBuyCount: pool.takerBuyCount,
maxTakerSellCount: pool.maxTakerSellCount,
statsTakerSellCount: pool.stats.takerSellCount,
statsTakerBuyCount: pool.stats.takerBuyCount,
marginated: pool.margin !== null,
});
console.log("Current price:", displayPrice?.div(1e9).toString(), "SOL");
// Calculate how many NFTs can be bought with X SOL
const solBalance = new BN(10 * LAMPORTS_PER_SOL);
const { allowedCount, totalAmount, initialPrice } = computeMakerAmountCount({
desired: { total: solBalance },
maxCountWhenInfinite: 1000,
takerSide: TakerSide.Sell,
extraNFTsSelected: 0,
config,
takerSellCount: pool.takerSellCount,
takerBuyCount: pool.takerBuyCount,
maxTakerSellCount: pool.maxTakerSellCount,
statsTakerSellCount: pool.stats.takerSellCount,
statsTakerBuyCount: pool.stats.takerBuyCount,
marginated: pool.margin !== null,
});
console.log(`Can buy ${allowedCount} NFTs for ${totalAmount.toString()} lamports`);
```
--------------------------------
### WNS (Wen New Standard) NFT Operations with TensorSwap SDK
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Trade WNS NFTs using the TensorSwap SDK, which includes support for royalty distributions. This allows for listing, buying, and selling WNS NFTs with integrated royalty handling.
```typescript
import { PublicKey } from "@solana/web3.js";
const collectionMint = new PublicKey("WNS_COLLECTION_MINT");
// List WNS NFT
const wnsListResult = await swapSdk.wnsList({
nftMint,
nftSource: sellerNftAccount,
owner: wallet.publicKey,
price: new BN(2 * LAMPORTS_PER_SOL),
collectionMint,
});
// Buy WNS NFT from listing
const wnsBuyResult = await swapSdk.wnsBuySingleListing({
nftMint,
nftBuyerAcc: buyerAta,
owner: listingOwner,
buyer: wallet.publicKey,
maxPrice: new BN(2.1 * LAMPORTS_PER_SOL),
collectionMint,
});
// Sell WNS NFT to pool
const wnsSellResult = await swapSdk.wnsSellNft({
type: "token",
whitelist,
nftMint,
nftSellerAcc: sellerNftAccount,
owner: poolOwner,
seller: wallet.publicKey,
config: poolConfig,
minPrice: new BN(1.9 * LAMPORTS_PER_SOL),
collectionMint,
});
```
--------------------------------
### Fetch Tensor Collection Whitelist PDA
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Find the whitelist PDA address for a Tensor collection using its UUID. This function takes a collection UUID, converts it to a buffer, and then uses `findWhitelistPDA` to derive the Program Derived Address.
```typescript
import { findWhitelistPDA } from "@tensor-oss/tensorswap-sdk";
// Collection UUID from Tensor API (remove dashes)
const collectionUuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
const uuidArray = Buffer.from(collectionUuid.replaceAll("-", "")).toJSON().data;
// Find whitelist PDA
const [whitelistPda] = findWhitelistPDA({ uuid: uuidArray });
// Fetch whitelist account
const whitelist = await whitelistSdk.fetchWhitelist(whitelistPda);
console.log("Whitelist verified:", whitelist.verified);
console.log("Root hash:", whitelist.rootHash);
```
--------------------------------
### Parse TensorSwap Transaction Instructions
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Decodes and parses TensorSwap instructions from raw Solana transactions. Utilizes TensorSwapSDK to extract instruction names, pool configurations, SOL amounts, and fees. Requires a Solana Connection object and a transaction signature.
```typescript
import { Connection, PublicKey } from "@solana/web3.js";
import { TensorSwapSDK } from "@tensor-oss/tensorswap-sdk";
const connection = new Connection("https://api.mainnet-beta.solana.com");
const txSignature = "YOUR_TX_SIGNATURE";
const tx = await connection.getTransaction(txSignature, {
maxSupportedTransactionVersion: 0,
});
if (tx) {
const parsedIxs = swapSdk.parseIxs(tx);
for (const ix of parsedIxs) {
console.log("Instruction:", ix.ix.name);
// Get pool config from instruction
const poolConfig = swapSdk.getPoolConfig(ix);
if (poolConfig) {
console.log("Pool type:", poolConfig.poolType);
}
// Get SOL amount from instruction
const solAmount = swapSdk.getSolAmount(ix);
if (solAmount) {
console.log("SOL amount:", solAmount.toString());
}
// Get fees from instruction
const fees = swapSdk.getFeeAmount(ix);
if (fees) {
console.log("Fees:", fees.toString());
}
}
}
```
--------------------------------
### Configure TensorSwap Pool Settings in TypeScript
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Defines different pool configurations for TensorSwap, including Token, NFT, and Trade pools, each with specific curve types (Linear/Exponential) and pricing parameters. These configurations are crucial for setting up AMM behavior.
```typescript
import { BN } from "@coral-xyz/anchor";
import { LAMPORTS_PER_SOL } from "@solana/web3.js";
import { CurveTypeAnchor, PoolTypeAnchor, PoolConfigAnchor } from "@tensor-oss/tensorswap-sdk";
// Token Pool - Collection-wide bid pool (buys NFTs)
const tokenPoolConfig: PoolConfigAnchor = {
poolType: PoolTypeAnchor.Token,
curveType: CurveTypeAnchor.Linear,
startingPrice: new BN(1 * LAMPORTS_PER_SOL), // 1 SOL starting bid
delta: new BN(0.1 * LAMPORTS_PER_SOL), // 0.1 SOL decrease per buy
mmCompoundFees: false,
mmFeeBps: null,
};
// NFT Pool - Listing pool (sells NFTs on a curve)
const nftPoolConfig: PoolConfigAnchor = {
poolType: PoolTypeAnchor.NFT,
curveType: CurveTypeAnchor.Exponential,
startingPrice: new BN(2 * LAMPORTS_PER_SOL), // 2 SOL starting price
delta: new BN(500), // 5% increase per sale (500 basis points)
mmCompoundFees: false,
mmFeeBps: null,
};
// Trade Pool - Two-sided market maker pool (buys and sells)
const tradePoolConfig: PoolConfigAnchor = {
poolType: PoolTypeAnchor.Trade,
curveType: CurveTypeAnchor.Exponential,
startingPrice: new BN(1.5 * LAMPORTS_PER_SOL),
delta: new BN(200), // 2% spread
mmCompoundFees: true, // Reinvest fees
mmFeeBps: 150, // 1.5% market maker fee
};
```
--------------------------------
### Token-2022 NFT Operations with TensorSwap SDK
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Perform NFT operations for Token-2022 NFTs, including listing, buying, and selling. Supports transfer hooks for custom logic during transfers and integrates with the TensorSwap marketplace.
```typescript
import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token";
// List Token-2022 NFT
const listT22Result = await swapSdk.listT22({
nftMint,
nftSource: sellerNftAccount,
owner: wallet.publicKey,
price: new BN(3 * LAMPORTS_PER_SOL),
transferHook: {
program: transferHookProgramId, // Optional transfer hook
remainingAccounts: [], // Additional accounts for hook
},
});
// Buy Token-2022 NFT from pool
const buyT22Result = await swapSdk.buyNftT22({
whitelist,
nftMint,
nftBuyerAcc: buyerAta,
owner: poolOwner,
buyer: wallet.publicKey,
config: poolConfig,
maxPrice: new BN(3.1 * LAMPORTS_PER_SOL),
});
// Sell Token-2022 NFT to pool
const sellT22Result = await swapSdk.sellNftT22({
type: "token",
whitelist,
nftMint,
nftSellerAcc: sellerNftAccount,
owner: poolOwner,
seller: wallet.publicKey,
config: poolConfig,
minPrice: new BN(2.9 * LAMPORTS_PER_SOL),
});
```
--------------------------------
### Withdraw SOL from Pool using TypeScript
Source: https://context7.com/tensor-foundation/tensorswap-sdk/llms.txt
Removes SOL from a Token or Trade pool. Requires the owner's public key, whitelist, the amount of lamports to withdraw, and the pool configuration. Returns transaction instructions to be added to a Solana transaction.
```typescript
const withdrawResult = await swapSdk.withdrawSol({
owner: wallet.publicKey,
whitelist,
lamports: new BN(2 * LAMPORTS_PER_SOL), // Withdraw 2 SOL
config: poolConfig, // Same config used to create pool
});
const tx = new Transaction().add(...withdrawResult.tx.ixs);
```