yoink-sdk
v1.0.4
Published
TypeScript SDK for Yoink bonding curve protocol on Solana - Buy, sell and query tokens with built-in slippage protection
Downloads
42
Maintainers
Readme
Yoink SDK
🚀 Official TypeScript SDK for interacting with the Yoink bonding curve protocol on Solana
🌐 Official Links
🏠 Website: https://yoink.now
🐦 Twitter: @YoinkNow
📚 GitHub: yoinknow/yoink-sdk
📦 NPM: yoink-sdk
✨ Features
- 🔄 Buy & Sell Tokens - Execute trades on custom bonding curves
- 💰 Price Quotes - Get accurate quotes before trading
- 📊 Market Data - Query bonding curve state and statistics
- 🛡️ Slippage Protection - Built-in safeguards against price volatility
- 🔒 Type-Safe - Full TypeScript support with detailed types
- 🌐 Multi-Platform - Works in Node.js and browser environments
- ⚡ Priority Fees - Support for transaction prioritization
📦 Installation
npm install yoink-sdkor
yarn add yoink-sdk🚀 Quick Start
Setup
Create a .env file with your RPC endpoint:
# For testnet (current configuration)
SOLANA_RPC_URL=https://staging-rpc.dev2.eclipsenetwork.xyz
# For Solana mainnet
# SOLANA_RPC_URL=https://api.mainnet-beta.solana.comBasic Usage
import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js";
import { YoinkSDK } from "yoink-sdk";
import { AnchorProvider } from "@coral-xyz/anchor";
import NodeWallet from "@coral-xyz/anchor/dist/cjs/nodewallet";
// Initialize connection and provider
const connection = new Connection(process.env.SOLANA_RPC_URL!);
const wallet = new NodeWallet(Keypair.generate());
const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed" });
// Create SDK instance
const sdk = new YoinkSDK(provider);
// Your token mint address
const mintAddress = new PublicKey("YOUR_TOKEN_MINT_ADDRESS");
// Get bonding curve data
const bondingCurve = await sdk.getBondingCurveAccount(mintAddress);
console.log("Market Cap:", bondingCurve.getMarketCapSOL());
console.log("Price per Token:", bondingCurve.getPricePerToken());
// Get a buy quote
const buyAmount = BigInt(0.1 * LAMPORTS_PER_SOL); // 0.1 SOL
const buyQuote = await sdk.getBuyQuote(mintAddress, buyAmount, BigInt(500)); // 5% slippage
console.log("You will receive:", buyQuote.tokenAmount, "tokens");
// Execute buy
const userKeypair = Keypair.generate(); // Your funded keypair
const buyResult = await sdk.buy(
userKeypair,
mintAddress,
buyAmount,
BigInt(500), // 5% slippage
{
unitLimit: 400000,
unitPrice: 100000,
}
);
if (buyResult.success) {
console.log("Buy successful! Signature:", buyResult.signature);
}API Reference
YoinkSDK
Constructor
constructor(provider?: Provider)Creates a new instance of the Yoink SDK.
Parameters:
provider(optional): Anchor Provider instance. If not provided, uses the default provider from environment.
Example:
const sdk = new YoinkSDK(provider);buy()
async buy(
buyer: Keypair,
mint: PublicKey,
solAmount: bigint,
slippageBasisPoints?: bigint,
priorityFees?: PriorityFee,
commitment?: Commitment,
finality?: Finality
): Promise<TransactionResult>Buy tokens with SOL.
Parameters:
buyer: Keypair of the buyer (must have SOL)mint: PublicKey of the token mint to buysolAmount: Amount of SOL to spend (in lamports)slippageBasisPoints: Slippage tolerance (default: 500 = 5%)priorityFees(optional): Priority fees for transactioncommitment(optional): Transaction commitment level (default: "confirmed")finality(optional): Transaction finality level (default: "confirmed")
Returns: Promise<TransactionResult> with transaction signature and success status
Example:
const result = await sdk.buy(
userKeypair,
mintAddress,
BigInt(0.01 * LAMPORTS_PER_SOL), // 0.01 SOL
BigInt(500), // 5% slippage
{
unitLimit: 400000,
unitPrice: 100000,
}
);sell()
async sell(
seller: Keypair,
mint: PublicKey,
tokenAmount: bigint,
slippageBasisPoints?: bigint,
priorityFees?: PriorityFee,
commitment?: Commitment,
finality?: Finality
): Promise<TransactionResult>Sell tokens for SOL.
Parameters:
seller: Keypair of the seller (must have tokens)mint: PublicKey of the token mint to selltokenAmount: Amount of tokens to sell (in base units with decimals)slippageBasisPoints: Slippage tolerance (default: 500 = 5%)priorityFees(optional): Priority fees for transactioncommitment(optional): Transaction commitment levelfinality(optional): Transaction finality level
Returns: Promise<TransactionResult>
Example:
const result = await sdk.sell(
userKeypair,
mintAddress,
BigInt(1000000 * Math.pow(10, 6)), // 1M tokens with 6 decimals
BigInt(500) // 5% slippage
);getBuyQuote()
async getBuyQuote(
mint: PublicKey,
solAmount: bigint,
slippageBasisPoints?: bigint,
commitment?: Commitment
): Promise<BuyQuote>Get a quote for buying tokens without executing the transaction.
Parameters:
mint: PublicKey of the token mintsolAmount: Amount of SOL to spend (in lamports)slippageBasisPoints: Slippage tolerance (default: 500 = 5%)commitment(optional): Query commitment level
Returns: Promise<BuyQuote> containing:
tokenAmount: Number of tokens you'll receivesolAmount: SOL amount to spendsolAmountWithSlippage: Max SOL with slippage protectionpricePerToken: Average price per token in SOLpriceImpact: Price impact percentage
Example:
const quote = await sdk.getBuyQuote(
mintAddress,
BigInt(0.1 * LAMPORTS_PER_SOL),
BigInt(500)
);
console.log(`You will receive ${quote.tokenAmount} tokens`);
console.log(`Price impact: ${quote.priceImpact}%`);getSellQuote()
async getSellQuote(
mint: PublicKey,
tokenAmount: bigint,
slippageBasisPoints?: bigint,
commitment?: Commitment
): Promise<SellQuote>Get a quote for selling tokens without executing the transaction.
Parameters:
mint: PublicKey of the token minttokenAmount: Amount of tokens to sell (in base units)slippageBasisPoints: Slippage tolerance (default: 500 = 5%)commitment(optional): Query commitment level
Returns: Promise<SellQuote> containing:
tokenAmount: Number of tokens being soldsolAmount: SOL amount you'll receivesolAmountWithSlippage: Min SOL with slippage protectionpricePerToken: Average price per token in SOLpriceImpact: Price impact percentage
Example:
const quote = await sdk.getSellQuote(
mintAddress,
BigInt(1000000 * Math.pow(10, 6)),
BigInt(500)
);
console.log(`You will receive ${Number(quote.solAmount) / LAMPORTS_PER_SOL} SOL`);getBondingCurveAccount()
async getBondingCurveAccount(
mint: PublicKey,
commitment?: Commitment
): Promise<BondingCurveAccount | null>Fetch the bonding curve account data for a token.
Parameters:
mint: PublicKey of the token mintcommitment(optional): Query commitment level
Returns: Promise<BondingCurveAccount | null> - Bonding curve data or null if not found
Example:
const curve = await sdk.getBondingCurveAccount(mintAddress);
if (curve) {
console.log("Virtual SOL Reserves:", curve.virtualSolReserves);
console.log("Virtual Token Reserves:", curve.virtualTokenReserves);
console.log("Market Cap:", curve.getMarketCapSOL());
console.log("Price per Token:", curve.getPricePerToken());
console.log("Is Complete:", curve.complete);
}getGlobalAccount()
async getGlobalAccount(
commitment?: Commitment
): Promise<GlobalAccount>Fetch the global protocol configuration.
Parameters:
commitment(optional): Query commitment level
Returns: Promise<GlobalAccount> - Global configuration data
Example:
const global = await sdk.getGlobalAccount();
console.log("Fee Basis Points:", global.feeBasisPoints);
console.log("Fee Recipient:", global.feeRecipient.toBase58());
console.log("Buybacks Enabled:", global.buybacksEnabled);BondingCurveAccount
The BondingCurveAccount class represents the state of a token's bonding curve.
Properties
virtualTokenReserves: bigint- Virtual token reserves for pricingvirtualSolReserves: bigint- Virtual SOL reserves for pricingrealTokenReserves: bigint- Actual token reserves availablerealSolReserves: bigint- Actual SOL reserves in the curvetokenTotalSupply: bigint- Total token supplycomplete: boolean- Whether the bonding curve is completecreatorFeePool: bigint- Accumulated creator feestreasuryFeePool: bigint- Accumulated treasury feesearlyBirdPool: bigint- Early bird rewards pooltotalBuyers: bigint- Total number of unique buyers
Methods
getMarketCapSOL()
getMarketCapSOL(): bigintCalculate the current market cap in lamports.
Returns: Market cap in lamports
getPricePerToken()
getPricePerToken(): numberGet the current price per token in SOL.
Returns: Price per token as a decimal number
GlobalAccount
The GlobalAccount class represents the global protocol configuration.
Properties
initialized: boolean- Whether the protocol is initializedauthority: PublicKey- Protocol authority addressfeeRecipient: PublicKey- Address receiving platform feesfeeBasisPoints: bigint- Fee percentage in basis points (e.g., 400 = 4%)initialVirtualTokenReserves: bigint- Initial virtual token reserves for new curvesinitialVirtualSolReserves: bigint- Initial virtual SOL reserves for new curvesbuybacksEnabled: boolean- Whether buyback mechanism is enabledearlyBirdEnabled: boolean- Whether early bird rewards are enabledearlyBirdCutoff: bigint- Position cutoff for early bird eligibility
Types
TransactionResult
type TransactionResult = {
signature?: string;
error?: unknown;
results?: VersionedTransactionResponse;
success: boolean;
};BuyQuote
type BuyQuote = {
tokenAmount: bigint;
solAmount: bigint;
solAmountWithSlippage: bigint;
pricePerToken: number;
priceImpact: number;
};SellQuote
type SellQuote = {
tokenAmount: bigint;
solAmount: bigint;
solAmountWithSlippage: bigint;
pricePerToken: number;
priceImpact: number;
};PriorityFee
type PriorityFee = {
unitLimit: number;
unitPrice: number;
};Examples
Example 1: Simple Buy
import { YoinkSDK } from "yoink-sdk";
import { Keypair, LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js";
const sdk = new YoinkSDK(provider);
const buyer = Keypair.generate(); // Make sure this has SOL
const mint = new PublicKey("TOKEN_MINT_ADDRESS");
const result = await sdk.buy(
buyer,
mint,
BigInt(0.1 * LAMPORTS_PER_SOL), // Buy with 0.1 SOL
BigInt(500) // 5% slippage
);
console.log("Success:", result.success);
console.log("Signature:", result.signature);Example 2: Get Quote Before Buying
// First, get a quote
const quote = await sdk.getBuyQuote(
mint,
BigInt(0.1 * LAMPORTS_PER_SOL),
BigInt(500)
);
console.log(`Buying with 0.1 SOL will get you ${quote.tokenAmount} tokens`);
console.log(`Price impact: ${quote.priceImpact.toFixed(2)}%`);
// If the quote looks good, execute the buy
if (quote.priceImpact < 5) {
const result = await sdk.buy(buyer, mint, BigInt(0.1 * LAMPORTS_PER_SOL), BigInt(500));
}Example 3: Monitor Market Data
async function monitorMarket(mint: PublicKey) {
const curve = await sdk.getBondingCurveAccount(mint);
if (!curve) {
console.log("Bonding curve not found");
return;
}
console.log("Market Stats:");
console.log("- Market Cap:", Number(curve.getMarketCapSOL()) / LAMPORTS_PER_SOL, "SOL");
console.log("- Price:", curve.getPricePerToken() * LAMPORTS_PER_SOL, "SOL per token");
console.log("- Tokens Available:", curve.realTokenReserves.toString());
console.log("- SOL Reserves:", Number(curve.realSolReserves) / LAMPORTS_PER_SOL, "SOL");
console.log("- Complete:", curve.complete);
}
// Monitor every 10 seconds
setInterval(() => monitorMarket(mint), 10000);Constants
export const GLOBAL_ACCOUNT_SEED = "global";
export const BONDING_CURVE_SEED = "bonding-curve";
export const HOLDER_STATS_SEED = "holder-stats";
export const DEFAULT_DECIMALS = 6;Error Handling
The SDK provides detailed error information through the TransactionResult type:
const result = await sdk.buy(buyer, mint, amount, slippage);
if (!result.success) {
console.error("Transaction failed:", result.error);
// Check for specific errors
if (result.error instanceof Error) {
if (result.error.message.includes("insufficient funds")) {
console.log("Not enough SOL in wallet");
} else if (result.error.message.includes("slippage")) {
console.log("Price moved too much, try increasing slippage");
}
}
}Building and Publishing
Build the SDK
npm install
npm run buildThis creates three output formats:
dist/esm/- ES Module formatdist/cjs/- CommonJS formatdist/browser/- Browser bundle
Publish to NPM
npm login
npm publishDevelopment
Running the Example
cd example/basic
npm install
# Set up your .env file with SOLANA_RPC_URL
npx ts-node index.tsProgram Information
- Program ID:
9BSxAV9iRuiT3W7kwhFEkmzfoMo7xZTBdFGRF793JRbC - Network: Solana
- Framework: Anchor ^0.30.1
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
ISC
Disclaimer
This software is provided "as is," without warranty of any kind, express or implied. Use at your own risk. The authors take no responsibility for any harm or damage caused by the use of this software.
By using this software, you acknowledge that you have read, understood, and agree to this disclaimer.
Support
For issues, questions, or contributions, please visit our GitHub repository.
For more information about Yoink protocol, visit our website or follow us on Twitter.
Built with ❤️ by the Yoink Team
