Package Exports
- @solsdk/tokenflow_sdk
Readme
@solsdk/tokenflow_sdk SDK
Overview
@solsdk/tokenflow_sdk SDK is a robust and secure toolkit for interacting with decentralized applications on the Solana blockchain. It provides a simple and type-safe interface for creating, buying, and selling tokens, as well as subscribing to on-chain events. Designed for developers who value reliability, security, and best practices, @solsdk/tokenflow_sdk SDK streamlines Solana token operations for both beginners and professionals.
Features
- Create, buy, and sell tokens with a single call
- Full support for Solana's latest standards
- Event subscription for real-time updates (createEvent, tradeEvent, completeEvent, setGlobalCfgEvent)
- Strict TypeScript typings (no
any, no type assertions) - Bonding curve configuration management
- Automatic metadata upload to IPFS
- Priority fee support for faster transaction processing
- Follows KISS, DRY, YAGNI, SOLID, and other best practices
- Actively maintained and open to contributions
Installation
npm install @solsdk/tokenflow_sdk
# or
yarn add @solsdk/tokenflow_sdk
# or
pnpm add @solsdk/tokenflow_sdkImports
The SDK provides multiple import options for different use cases:
Main SDK Class
import { HappyPumpSDK } from "@solsdk/tokenflow_sdk";Types and Interfaces
import type {
CreateTokenMetadata,
PriorityFee,
TransactionResult,
CreateEvent,
TradeEvent,
CompleteEvent,
SetGlobalCfgEvent,
} from "@solsdk/tokenflow_sdk";Utility Functions
import {
calculateWithSlippageBuy,
calculateWithSlippageSell,
buildVersionedTx,
sendTx,
getTxDetails,
} from "@solsdk/tokenflow_sdk";Constants
import {
DEFAULT_DECIMALS,
DEFAULT_COMMITMENT,
DEFAULT_FINALITY,
GLOBAL_ACCOUNT_SEED,
MINT_AUTHORITY_SEED,
BONDING_CURVE_SEED,
METADATA_SEED,
} from "@solsdk/tokenflow_sdk";Account Classes
import { GlobalAccount, BondingCurveAccount, AMM } from "@solsdk/tokenflow_sdk";Event Processing Functions
import {
toCreateEvent,
toTradeEvent,
toCompleteEvent,
toSetGlobalCfgEvent,
} from "@solsdk/tokenflow_sdk";Quick Start
- Create a
.envfile and set your Solana RPC URL (see.env.examplefor reference). - Fund your test account with at least 0.004 SOL.
Example Usage
import dotenv from "dotenv";
import {
Connection,
Keypair,
LAMPORTS_PER_SOL,
PublicKey,
} from "@solana/web3.js";
import { HappyPumpSDK } from "@solsdk/tokenflow_sdk";
import { AnchorProvider } from "@coral-xyz/anchor";
import NodeWallet from "@coral-xyz/anchor/dist/cjs/nodewallet";
dotenv.config();
const SLIPPAGE_BASIS_POINTS = 500n; // Default slippage
const getProvider = () => {
if (!process.env.SOLANA_RPC_URL) {
throw new Error("Please set SOLANA_RPC_URL in your .env file");
}
const connection = new Connection(process.env.SOLANA_RPC_URL);
const wallet = new NodeWallet(new Keypair());
return new AnchorProvider(connection, wallet, { commitment: "finalized" });
};
const main = async () => {
const provider = getProvider();
const sdk = new HappyPumpSDK(provider);
const creator = Keypair.generate();
const mint = Keypair.generate();
const tradeAuthority = Keypair.generate(); // Optional trade authority
// Create a file blob for the token image
const imageFile = new Blob(
[
/* your image data */
],
{ type: "image/png" }
);
// Example: Create and buy a new token
const tokenMetadata = {
name: "EXAMPLE",
symbol: "EXMPL",
description: "Example token for demonstration",
file: imageFile, // Must be a Blob object
twitter: "https://twitter.com/example", // Optional
telegram: "https://t.me/example", // Optional
website: "https://example.com", // Optional
};
const result = await sdk.createAndBuy(
creator,
mint,
tokenMetadata,
BigInt(0.0001 * LAMPORTS_PER_SOL),
SLIPPAGE_BASIS_POINTS,
tradeAuthority, // Optional
{
unitLimit: 250_000,
unitPrice: 250_000,
}
);
if (result.success) {
console.log("Token created and purchased successfully!");
console.log("Transaction signature:", result.signature);
} else {
console.error("Operation failed:", result.error);
}
};
main();API Reference
Core Methods
create
Creates a new token without purchasing it.
async create(
creator: Keypair,
mint: Keypair,
createTokenMetadata: CreateTokenMetadata,
tradeAuthority?: Keypair,
priorityFees?: PriorityFee,
commitment?: Commitment,
finality?: Finality
): Promise<TransactionResult>createAndBuy
Creates a new token and immediately purchases it.
async createAndBuy(
creator: Keypair,
mint: Keypair,
createTokenMetadata: CreateTokenMetadata,
buyAmountSol: bigint,
slippageBasisPoints: bigint = 500n,
tradeAuthority?: Keypair,
priorityFees?: PriorityFee,
commitment?: Commitment,
finality?: Finality
): Promise<TransactionResult>buy
Purchases tokens for a given mint.
async buy(
buyer: Keypair,
mint: Keypair,
buyAmountSol: bigint,
slippageBasisPoints: bigint = 500n,
tradeAuthority?: Keypair,
priorityFees?: PriorityFee,
commitment?: Commitment,
finality?: Finality
): Promise<TransactionResult>sell
Sells a specified amount of tokens.
async sell(
seller: Keypair,
mint: Keypair,
sellTokenAmount: bigint,
slippageBasisPoints: bigint = 500n,
priorityFees?: PriorityFee,
commitment?: Commitment,
finality?: Finality
): Promise<TransactionResult>setBondingCurveCfg
Configures bonding curve settings for a token.
async setBondingCurveCfg(
user: Keypair,
mint: PublicKey,
tradeAuthority: PublicKey,
priorityFees?: PriorityFee,
commitment?: Commitment,
finality?: Finality
): Promise<TransactionResult>Account Management
getGlobalAccount
Retrieves the global account configuration.
async getGlobalAccount(commitment?: Commitment): Promise<GlobalAccount>getBondingCurveAccount
Retrieves bonding curve account data for a specific mint.
async getBondingCurveAccount(
mint: PublicKey,
commitment?: Commitment
): Promise<BondingCurveAccount | undefined>getBondingCurvePDA
Generates the Program Derived Address for a bonding curve.
getBondingCurvePDA(mint: PublicKey): PublicKeyEvent Subscription
Subscribe to on-chain events for real-time updates.
// Available event types: 'createEvent', 'tradeEvent', 'completeEvent', 'setGlobalCfgEvent'
const eventId = sdk.addEventListener("tradeEvent", (event, slot, signature) => {
console.log("Trade event:", event, slot, signature);
console.log("Token amount:", event.tokenAmount);
console.log("SOL amount:", event.solAmount);
console.log("Is buy:", event.isBuy);
});
// Subscribe to token creation events
const createEventId = sdk.addEventListener(
"createEvent",
(event, slot, signature) => {
console.log("New token created:", event.name, event.symbol);
console.log("Mint address:", event.mint.toString());
}
);
// Subscribe to bonding curve completion events
const completeEventId = sdk.addEventListener(
"completeEvent",
(event, slot, signature) => {
console.log("Bonding curve completed for mint:", event.mint.toString());
}
);
// To remove listeners:
sdk.removeEventListener(eventId);
sdk.removeEventListener(createEventId);
sdk.removeEventListener(completeEventId);Types and Interfaces
CreateTokenMetadata
Metadata structure for creating new tokens.
type CreateTokenMetadata = {
name: string;
symbol: string;
description: string;
file: Blob; // Image file as Blob object
twitter?: string; // Optional Twitter URL
telegram?: string; // Optional Telegram URL
website?: string; // Optional website URL
};PriorityFee
Priority fee configuration for faster transaction processing.
type PriorityFee = {
unitLimit: number; // Compute unit limit
unitPrice: number; // Price per compute unit in micro-lamports
};TransactionResult
Result object returned by all transaction methods.
type TransactionResult = {
signature?: string; // Transaction signature if successful
error?: unknown; // Error object if failed
results?: VersionedTransactionResponse; // Full transaction response
success: boolean; // Whether transaction succeeded
};Event Types
CreateEvent
type CreateEvent = {
name: string;
symbol: string;
uri: string;
mint: PublicKey;
bondingCurve: PublicKey;
user: PublicKey;
tradeAuthority?: PublicKey;
timestamp: number;
virtualTokenReserves: bigint;
virtualSolReserves: bigint;
realTokenReserves: bigint;
realSolReserves: bigint;
};TradeEvent
type TradeEvent = {
mint: PublicKey;
solAmount: bigint;
tokenAmount: bigint;
isBuy: boolean;
user: PublicKey;
timestamp: number;
virtualSolReserves: bigint;
virtualTokenReserves: bigint;
realSolReserves: bigint;
realTokenReserves: bigint;
};CompleteEvent
type CompleteEvent = {
user: PublicKey;
mint: PublicKey;
bondingCurve: PublicKey;
timestamp: number;
};Utility Functions
The SDK exports several utility functions for common operations:
calculateWithSlippageBuy
Calculates buy amount with slippage protection.
function calculateWithSlippageBuy(amount: bigint, basisPoints: bigint): bigint;calculateWithSlippageSell
Calculates sell amount with slippage protection.
function calculateWithSlippageSell(amount: bigint, basisPoints: bigint): bigint;buildVersionedTx
Builds a versioned transaction from instructions.
function buildVersionedTx(
connection: Connection,
payer: PublicKey,
instructions: TransactionInstruction[],
commitment?: Commitment
): Promise<VersionedTransaction>;sendTx
Sends a transaction with proper error handling.
function sendTx(
connection: Connection,
instructions: TransactionInstruction[],
payer: PublicKey,
signers: Keypair[],
priorityFees?: PriorityFee,
commitment?: Commitment,
finality?: Finality
): Promise<TransactionResult>;Constants
The SDK exports several useful constants:
// Program seeds
export const GLOBAL_ACCOUNT_SEED = "global";
export const MINT_AUTHORITY_SEED = "mint-authority";
export const BONDING_CURVE_SEED = "bonding-curve";
export const METADATA_SEED = "metadata";
// Default values
export const DEFAULT_DECIMALS = 6;
export const DEFAULT_COMMITMENT = "finalized";
export const DEFAULT_FINALITY = "finalized";Complete Usage Examples
Creating a Token Only
import { HappyPumpSDK } from "@solsdk/tokenflow_sdk";
import { Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
const creator = Keypair.generate();
const mint = Keypair.generate();
const imageFile = new Blob(
[
/* image data */
],
{ type: "image/png" }
);
const metadata = {
name: "My Token",
symbol: "MTK",
description: "A sample token",
file: imageFile,
website: "https://mytoken.com",
};
const result = await sdk.create(
creator,
mint,
metadata,
undefined, // No trade authority
{ unitLimit: 200_000, unitPrice: 200_000 }
);Buying Existing Tokens
const buyer = Keypair.generate();
const mintKeypair = Keypair.fromSecretKey(/* existing mint secret key */);
const result = await sdk.buy(
buyer,
mintKeypair,
BigInt(0.001 * LAMPORTS_PER_SOL), // Buy with 0.001 SOL
300n, // 3% slippage
undefined, // No trade authority
{ unitLimit: 150_000, unitPrice: 150_000 }
);Selling Tokens
const seller = Keypair.generate();
const mintKeypair = Keypair.fromSecretKey(/* mint secret key */);
const tokenAmount = BigInt(1000000); // Amount of tokens to sell
const result = await sdk.sell(
seller,
mintKeypair,
tokenAmount,
500n, // 5% slippage
{ unitLimit: 150_000, unitPrice: 150_000 }
);Security & Best Practices
Type Safety
- All operations are strictly type-checked with TypeScript
- No use of
anyor type assertions in the SDK - Comprehensive type definitions for all parameters and return values
Transaction Security
- Always validate transaction results using the
successproperty - Handle errors gracefully using the
errorproperty inTransactionResult - Use appropriate slippage settings to protect against MEV attacks
- Set reasonable priority fees to ensure transaction inclusion
Key Management
- Never expose private keys in client-side code
- Use environment variables for sensitive configuration
- Generate new keypairs for testing, never reuse production keys
File Handling
- Always pass image files as
Blobobjects toCreateTokenMetadata - Validate file types and sizes before uploading
- The SDK automatically uploads metadata to IPFS
Best Practices
- Use appropriate commitment levels (
finalizedfor production) - Monitor transaction confirmations using the returned signatures
- Implement proper error handling for network failures
- Test thoroughly on devnet before mainnet deployment
- Follow Solana's official documentation and standards
Performance Optimization
- Reuse SDK instances when possible
- Use batch operations for multiple transactions
- Set appropriate compute unit limits in priority fees
- Monitor and adjust slippage based on market conditions
Contributing
Contributions are welcome! Please open an issue or submit a pull request to discuss improvements or new features.
License
MIT
Disclaimer
This software is provided "as is," without warranty of any kind, express or implied. Use at your own risk. The authors are not responsible for any damages or losses resulting from the use of this software. By using this SDK, you acknowledge that you have read and understood this disclaimer.
By following this guide, you can quickly integrate @solsdk/tokenflow_sdk SDK into your Solana projects and benefit from a secure, developer-friendly toolkit for token operations and event handling.