index/classes/LaunchpadSDK.md
Constructors
Constructor
new LaunchpadSDK(
config):LaunchpadSDK
Parameters
| Parameter | Type |
|---|---|
config | LaunchpadSDKConfig |
Returns
LaunchpadSDK
launchpad sdk config
Address Management
getAddress()
getAddress():
AddressFormat
Gets the authenticated user's address in backend format
Returns the wallet address formatted for backend API calls. The backend expects addresses in the format "eth|{40-hex-chars}" without the standard "0x" prefix.
Returns
AddressFormat
The address in eth|{40-hex-chars} format required by the backend
Since
1.0.0
Throws
ValidationError if wallet is not configured
Examples
Get backend address format
const sdk = new LaunchpadSDK({ wallet });
const backendAddress = sdk.getAddress();
console.log(backendAddress); // "eth|742d35Cc6634C0532925a3b8D0Ea2c76f94C31C0"
Use in API calls
const address = sdk.getAddress();
const pools = await sdk.launchpad.fetchPools({
creatorAddress: address,
pageSize: 10
});
See
getEthereumAddress - Get standard Ethereum address format
get address format
getEthereumAddress()
getEthereumAddress():
string
Gets the authenticated user's Ethereum address in standard format
Returns the wallet address in standard Ethereum format with "0x" prefix. This is the format typically used in frontend displays and external tools.
Returns
string
Standard Ethereum address with 0x prefix
Since
1.0.0
Throws
ValidationError if wallet is not configured
Examples
Display user address
const sdk = new LaunchpadSDK({ wallet });
const ethAddress = sdk.getEthereumAddress();
console.log(`User: ${ethAddress}`); // "User: 0x742d35Cc6634C0532925a3b8D0Ea2c76f94C31C0"
Address consistency check
const ethAddr = sdk.getEthereumAddress();
const backendAddr = sdk.getAddress();
// Verify they represent the same address
const ethHex = stripHexPrefix(ethAddr);
const backendHex = backendAddr.replace('eth|', '');
console.log('Same address:', ethHex.toLowerCase() === backendHex.toLowerCase());
See
getAddress - Get backend-compatible address format
get ethereum address
AIModeration
ai moderation
getAIModeration()
getAIModeration(
options):Promise<GetAIModerationResult>
Get AI moderation for a specific content flag (overseer only).
Retrieves the AI moderation results for flagged content, including:
- Recommendation (NO_ACTION, REVIEW_REQUIRED, DELETE_CONTENT, BAN_USER)
- Confidence score (0-1)
- Detected categories with individual confidence scores
- Summary and reasoning for the recommendation
- Tiered analysis metadata (tier used, escalation info, token usage)
Requires either Admin API key or JWT with overseer status.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetAIModerationOptions | Options including flagId |
Returns
Promise<GetAIModerationResult>
AI moderation data
Throws
ConfigurationError if neither admin API key nor JWT is configured
Throws
Error if moderation not found (404)
Since
6.15.0
Example
const { moderation } = await sdk.getAIModeration({ flagId: 123 });
console.log('Status:', moderation.status);
console.log('Recommendation:', moderation.recommendation);
console.log('Confidence:', moderation.confidence);
// Tiered analysis info
if (moderation.analysisTier) {
console.log('Tier used:', moderation.analysisTier);
console.log('Escalated:', moderation.escalatedFromQuick);
}
get ai moderation result options
getAIModerationSettings()
getAIModerationSettings():
Promise<GetAIModerationSettingsResult>
Get current AI moderation settings (overseer only).
Returns configuration for AI-powered content moderation including:
- Whether AI moderation is enabled
- Moderation mode (DISABLED, ADVISORY)
- Provider configuration
- Tiered analysis settings (frames, resolution, escalation threshold)
Requires either Admin API key or JWT with overseer status.
Returns
Promise<GetAIModerationSettingsResult>
AI moderation settings
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
6.15.0
Example
const { settings } = await sdk.getAIModerationSettings();
console.log('AI enabled:', settings.enabled);
console.log('Mode:', settings.mode);
console.log('Tiered analysis:', settings.tieredAnalysisEnabled);
console.log('Quick scan frames:', settings.quickScanFrames);
get ai moderation settings result
getAIModerationStatus()
getAIModerationStatus():
Promise<GetAIModerationStatusResult>
Get AI system status (overseer only).
Returns the current status of the AI moderation system:
- Whether AI is enabled globally
- Current mode (DISABLED, ADVISORY)
- Provider availability (e.g., Claude API accessible)
Useful for checking if AI moderation is operational before triggering moderation for flagged content.
Requires either Admin API key or JWT with overseer status.
Returns
Promise<GetAIModerationStatusResult>
AI system status
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
6.15.0
Example
const { status } = await sdk.getAIModerationStatus();
console.log('AI enabled:', status.enabled);
console.log('Provider available:', status.providerAvailable);
// Only trigger moderation if system is operational
if (status.enabled && status.providerAvailable) {
await sdk.triggerAIModeration({ flagId: 123 });
}
get ai moderation status result
triggerAIModeration()
triggerAIModeration(
options):Promise<TriggerAIModerationResult>
Trigger AI moderation for a content flag (overseer only).
Queues flagged content for AI moderation. Moderation runs asynchronously - use getAIModeration() to poll for results or listen for the AI_MODERATION_COMPLETE WebSocket event.
For video content with tiered analysis enabled:
- Quick scan runs first (5 frames at 480px)
- If concerns found, detailed scan runs (20 frames at 640px)
Requires either Admin API key or JWT with overseer status.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | TriggerAIModerationOptions | Options including flagId |
Returns
Promise<TriggerAIModerationResult>
Queued status and message
Throws
ConfigurationError if neither admin API key nor JWT is configured
Throws
Error if flag not found (404) or moderation already exists (400)
Since
6.15.0
Example
const result = await sdk.triggerAIModeration({ flagId: 123 });
console.log('Queued:', result.queued);
// Poll for results
let moderation;
while (!moderation || moderation.status === 'PROCESSING') {
await new Promise(r => setTimeout(r, 1000));
const result = await sdk.getAIModeration({ flagId: 123 });
moderation = result.moderation;
}
console.log('Done:', moderation.recommendation);
trigger ai moderation result options
updateAIModerationSettings()
updateAIModerationSettings(
options):Promise<UpdateAIModerationSettingsResult>
Update AI moderation settings (overseer only).
Configure AI-powered content moderation behavior. Only provided fields will be updated.
Requires either Admin API key or JWT with overseer status.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | UpdateAIModerationSettingsOptions | Settings to update |
Returns
Promise<UpdateAIModerationSettingsResult>
Updated AI moderation settings
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
6.15.0
Examples
Enable AI moderation in advisory mode
const { settings } = await sdk.updateAIModerationSettings({
enabled: true,
mode: 'ADVISORY'
});
Change provider
const { settings } = await sdk.updateAIModerationSettings({
provider: 'claude'
});
update ai moderation settings result options
Authentication
ensureValidToken()
ensureValidToken(
thresholdMs?):Promise<string>
Ensure we have a valid token, refreshing if necessary.
Call this before making authenticated requests to ensure the token won't expire mid-request. Will:
- Throw if not authenticated at all
- Re-login if token is expired
- Refresh if token expires within threshold
- Return current token if still valid
Parameters
| Parameter | Type | Description |
|---|---|---|
thresholdMs? | number | Refresh threshold in milliseconds (default: 5 minutes) |
Returns
Promise<string>
Current access token
Throws
Error if not authenticated and can't refresh
Since
5.2.0
Example
Before critical operation
const token = await sdk.ensureValidToken();
// Token is guaranteed valid for at least 5 more minutes
await criticalStreamingOperation();
ensure valid token threshold ms
getAccessToken()
getAccessToken():
string|null
Get the current JWT access token.
Returns the raw token string for use in custom requests or debugging. Returns null if not authenticated.
Returns
string | null
Access token string, or null if not authenticated
Since
5.2.0
Example
Use token in custom request
const token = sdk.getAccessToken();
if (token) {
const headers = { 'Authorization': `Bearer ${token}` };
// Use headers in custom fetch call
}
get access token
getSession()
getSession():
Promise<SessionInfo>
Get current session information from the backend.
Returns session details including:
- Authenticated address
- Token issued time
- Token expiration time
Returns
Promise<SessionInfo>
Session info with address and timestamps
Throws
Error if not authenticated
Since
5.2.0
Example
View session details
const session = await sdk.getSession();
console.log(`Logged in as: ${session.address}`);
console.log(`Session expires: ${session.expiresAt}`);
get session info
isAuthenticated()
isAuthenticated():
boolean
Check if user is authenticated with valid JWT.
Returns true if:
- A JWT token exists
- The token has not expired
Returns
boolean
true if authenticated with non-expired token
Since
5.2.0
Example
Check authentication status
if (!sdk.isAuthenticated()) {
await sdk.login();
}
// Now proceed with authenticated operations
is authenticated
login()
login():
Promise<LoginResponse>
Login with wallet signature to get JWT token.
This authenticates the user with the backend by:
- Generating a message with timestamp: "Sign in to Launchpad t:{timestamp}"
- Signing the message with the configured wallet
- Sending the signature to the backend for verification
- Storing the returned JWT token for authenticated requests
Required before calling JWT-protected endpoints:
startStream(),stopStream(),resetStreamKey(),getRecordingDownload(),deleteRecording()addSimulcastTarget(),removeSimulcastTarget()sendChatMessage()(REST API)
Returns
Promise<LoginResponse>
Login response with accessToken and expiration
Throws
Error if wallet is not configured
Throws
Error if signature fails
Since
5.2.0
Examples
Basic login
const { accessToken, expiresIn, address } = await sdk.login();
console.log(`Logged in as ${address}`);
console.log(`Token expires in ${expiresIn}s`);
Login before streaming
// Authenticate first
await sdk.login();
// Now streaming methods work
const stream = await sdk.startStream('mytoken');
login response start stream stop reset key get recording download delete add simulcast target remove send chat message
loginWithDevBypass()
loginWithDevBypass(
address):Promise<LoginResponse>
Log in as address without a signature: the backend's development bypass, accepted by
non-production deployments only. Session handling as in loginWithSignature.
Parameters
| Parameter | Type |
|---|---|
address | string |
Returns
Promise<LoginResponse>
Since
9.0.0
login with dev bypass response
loginWithSignature()
loginWithSignature(
request):Promise<LoginResponse>
Log in with a signature the caller made: a browser wallet signs the login message
(Sign in to Launchpad t:<ms>, JWT_CONSTANTS) itself, so an SDK built with only a
signer has nothing to sign it with. publicKey registers a client| alias's key.
With an app session the login asks for a cookie session (the refresh token becomes an httpOnly
cookie and is absent from the answer) and nothing is stored in the SDK: hand the answer to the
session. Without one the tokens are stored as login stores them. A failure is an
AuthError carrying the backend's statusCode.
Parameters
| Parameter | Type |
|---|---|
request | LoginRequest |
Returns
Promise<LoginResponse>
Since
9.0.0
Example
const message = `Sign in to Launchpad t:${Date.now()}`;
const signature = await provider.signMessage(message);
const { accessToken, refreshExpiresIn } = await sdk.loginWithSignature({ address, message, signature });
login with signature response public key auth error status code request
logout()
logout(
options?):Promise<void>
Logout and clear the JWT token.
Clears the client-side JWT and optionally revokes all active sessions on the server. Future calls to JWT-protected endpoints will fail until login() is called again.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | { accessToken?: string | null; allDevices?: boolean; } | Optional logout configuration |
options.accessToken? | string | null | - |
options.allDevices? | boolean | If true, revokes all active sessions server-side (requires valid JWT) |
Returns
Promise<void>
Promise that resolves when logout is complete
Since
5.2.0
Examples
Clean logout
// ... do work ...
await sdk.logout();
console.log('Logged out');
Logout from all devices
await sdk.logout({ allDevices: true });
console.log('Logged out from all devices');
With an app session the logout always reaches the server (POST /auth/logout, the cookie
naming the session to revoke), carries options.accessToken as its bearer when given, and
throws an AuthError (with the backend's statusCode) when it fails.
access token all devices auth error status code
refreshToken()
refreshToken():
Promise<LoginResponse>
Refresh the current JWT token.
Use this to get a new token before the current one expires. The token is automatically refreshed during requests if it will expire within 5 minutes.
Returns
Promise<LoginResponse>
Refresh response with new accessToken
Throws
Error if not authenticated (call login() first)
Since
5.2.0
Example
Manual token refresh
if (sdk.shouldRefreshToken()) {
const { accessToken, expiresIn } = await sdk.refreshToken();
console.log(`Token refreshed, expires in ${expiresIn}s`);
}
refresh token login response
shouldRefreshToken()
shouldRefreshToken(
thresholdMs?):boolean
Check if token should be refreshed.
Returns true if token exists and will expire within the threshold. Default threshold is 5 minutes.
Parameters
| Parameter | Type | Description |
|---|---|---|
thresholdMs? | number | Custom threshold in milliseconds (default: 5 minutes) |
Returns
boolean
true if refresh is recommended
Since
5.2.0
Example
Check before long operation
// Ensure token won't expire during operation
if (sdk.shouldRefreshToken(10 * 60 * 1000)) { // 10 minutes
await sdk.refreshToken();
}
await performLongOperation();
should refresh token threshold ms
Bridge
bridgeIn()
bridgeIn(
params):Promise<BridgeTransaction>
Bridge tokens from an external chain to GalaChain.
Initiates a cross-chain transfer from Ethereum or Solana to GalaChain. The transfer will burn wrapped tokens on the source chain and unlock tokens on GalaChain.
Parameters
| Parameter | Type | Description |
|---|---|---|
params | BridgeInParams | Bridge in parameters |
Returns
Promise<BridgeTransaction>
Promise resolving to transaction details
Throws
Error if wallet is not configured
Throws
Error if token is not bridgeable from the source chain
Since
4.0.16
Example
Bridge GALA from Ethereum to GalaChain
const result = await sdk.bridgeIn({
tokenId: 'GALA|Unit|none|none',
amount: '100',
sourceChain: 'Ethereum',
});
console.log(`Transaction: ${result.transactionHash}`);
bridge in transaction params
bridgeOut()
bridgeOut(
params):Promise<BridgeTransaction>
Bridge tokens from GalaChain to an external chain.
Initiates a cross-chain transfer from GalaChain to Ethereum or Solana. The transfer will lock tokens on GalaChain and mint wrapped tokens on the destination chain.
Parameters
| Parameter | Type | Description |
|---|---|---|
params | BridgeOutParams | Bridge out parameters |
Returns
Promise<BridgeTransaction>
Promise resolving to transaction details
Throws
Error if wallet is not configured
Throws
Error if token is not bridgeable to the destination chain
Throws
Error if recipient address is invalid
Since
4.0.16
Example
Bridge GALA to Ethereum
const result = await sdk.bridgeOut({
tokenId: 'GALA|Unit|none|none',
amount: '100',
destinationChain: 'Ethereum',
recipientAddress: '0x1234...abcd',
});
console.log(`Transaction: ${result.transactionHash}`);
bridge out transaction params
estimateBridgeFee()
estimateBridgeFee(
params):Promise<BridgeFeeEstimate>
Estimate bridge fees for a cross-chain transfer.
Calculates the expected fees for bridging tokens from GalaChain to an external chain (Ethereum or Solana).
Parameters
| Parameter | Type | Description |
|---|---|---|
params | EstimateBridgeFeeParams | Fee estimation parameters |
Returns
Promise<BridgeFeeEstimate>
Promise resolving to fee estimate with breakdown
Throws
Error if wallet is not configured
Throws
Error if token is not bridgeable to the destination chain
Since
4.0.16
Example
Estimate fee for bridging GALA to Ethereum
// the fee does not depend on the amount bridged
const fee = await sdk.estimateBridgeFee({
tokenId: 'GALA|Unit|none|none',
destinationChain: 'Ethereum',
});
console.log(`Fee: ${fee.estimatedFeeInGala} GALA`);
estimate bridge fee params
fetchAllBridgeableTokensByNetwork()
fetchAllBridgeableTokensByNetwork(
network):Promise<FetchBridgeableTokensResult>
Fetch ALL bridgeable tokens for a network with auto-pagination
Automatically handles pagination to retrieve all tokens bridgeable to the specified network. Returns cached data if available; fetches from API otherwise.
Parameters
| Parameter | Type | Description |
|---|---|---|
network | BridgeableNetwork | Target network ('ETHEREUM' or 'SOLANA') |
Returns
Promise<FetchBridgeableTokensResult>
Promise resolving to all bridgeable tokens for the network
Throws
NetworkError if DEX API is unavailable
Since
3.33.0
Example
Fetch all Ethereum-bridgeable tokens
const result = await sdk.fetchAllBridgeableTokensByNetwork('ETHEREUM');
console.log(`Total: ${result.tokenCount} tokens`);
result.tokens.forEach(t => {
console.log(`${t.symbol}: ${t.ethereumContractAddress}`);
});
fetch all bridgeable tokens by network result
fetchAllTokensBridgeableToEthereum()
fetchAllTokensBridgeableToEthereum():
Promise<FetchBridgeableTokensResult>
Fetch all tokens bridgeable to Ethereum
Convenience method for fetching Ethereum-bridgeable tokens. Returns cached data if available; fetches from API otherwise.
Returns
Promise<FetchBridgeableTokensResult>
Promise resolving to all Ethereum-bridgeable tokens
Throws
NetworkError if DEX API is unavailable
Since
3.33.0
Example
Get Ethereum-bridgeable tokens
const result = await sdk.fetchAllTokensBridgeableToEthereum();
console.log('Ethereum-bridgeable tokens:');
result.tokens.forEach(t => {
console.log(` ${t.symbol}: ${t.ethereumContractAddress}`);
});
fetch all tokens bridgeable to ethereum result
fetchAllTokensBridgeableToSolana()
fetchAllTokensBridgeableToSolana():
Promise<FetchBridgeableTokensResult>
Fetch all tokens bridgeable to Solana
Convenience method for fetching Solana-bridgeable tokens. Returns cached data if available; fetches from API otherwise.
Returns
Promise<FetchBridgeableTokensResult>
Promise resolving to all Solana-bridgeable tokens
Throws
NetworkError if DEX API is unavailable
Since
3.33.0
Example
Get Solana-bridgeable tokens
const result = await sdk.fetchAllTokensBridgeableToSolana();
console.log('Solana-bridgeable tokens:');
result.tokens.forEach(t => {
console.log(` ${t.symbol}: ${t.solanaContractAddress}`);
});
fetch all tokens bridgeable to solana result
fetchBridgeableTokensByNetwork()
fetchBridgeableTokensByNetwork(
options):Promise<FetchBridgeableTokensResult>
Fetch bridgeable tokens for a specific network with pagination
Queries the DEX API to discover which tokens can be bridged to the specified network. Results are cached permanently for the SDK lifetime (bridgeable tokens never change).
Parameters
| Parameter | Type | Description |
|---|---|---|
options | FetchBridgeableTokensOptions | Fetch options including network and pagination |
Returns
Promise<FetchBridgeableTokensResult>
Promise resolving to paginated bridgeable tokens
Throws
NetworkError if DEX API is unavailable
Since
3.33.0
Example
Paginated fetch for Ethereum
const result = await sdk.fetchBridgeableTokensByNetwork({
network: 'ETHEREUM',
pageSize: 100
});
console.log(`Found ${result.tokenCount} Ethereum-bridgeable tokens`);
fetch bridgeable tokens by network result options
getBridgeStatus()
getBridgeStatus(
transactionHash):Promise<BridgeStatus>
Get the status of a bridge transaction.
Checks the current status of a cross-chain bridge transaction.
Parameters
| Parameter | Type | Description |
|---|---|---|
transactionHash | string | Transaction hash to check (one GalaConnect status read, any chain) |
Returns
Promise<BridgeStatus>
Promise resolving to bridge status
Since
4.0.16
Example
Check bridge status
const status = await sdk.getBridgeStatus('0x1234...abcd');
console.log(`Status: ${status.status}`);
get bridge status transaction hash
getSupportedBridgeTokens()
getSupportedBridgeTokens():
Promise<{supportedChains:string[];tokens:BridgeToken[];totalCount:number; }>
Get list of tokens supported for bridging.
Returns the static list of tokens that can be bridged between GalaChain and external chains.
Returns
Promise<{ supportedChains: string[]; tokens: BridgeToken[]; totalCount: number; }>
Promise resolving to supported bridge tokens
Since
4.0.16
Example
Get supported tokens
const tokens = await sdk.getSupportedBridgeTokens();
tokens.tokens.forEach(t => {
console.log(`${t.symbol}: ${t.supportedChains.join(', ')}`);
});
get supported bridge tokens chains token total count
isTokenBridgeableToEthereum()
isTokenBridgeableToEthereum(
tokenId):Promise<IsTokenBridgeableResult>
Check if a token is bridgeable to Ethereum
Convenience method for checking Ethereum bridgeability. Returns contract address if token is bridgeable.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenId | TokenId | Token identifier (pipe-delimited string or TokenClassKey object) |
Returns
Promise<IsTokenBridgeableResult>
Promise resolving to bridgeability check result
Throws
NetworkError if DEX API is unavailable
Throws
ValidationError if tokenId format is invalid
Since
3.33.0
Example
Check if GWETH is bridgeable to Ethereum
// Pipe-delimited format
const result = await sdk.isTokenBridgeableToEthereum('Token|Unit|GWETH|eth:0x...');
console.log(`Bridgeable: ${result.isBridgeable}`);
// Or TokenClassKey object
const result = await sdk.isTokenBridgeableToEthereum({
collection: 'Token', category: 'Unit', type: 'GWETH', additionalKey: 'eth:0x...'
});
is token bridgeable to ethereum id result
isTokenBridgeableToNetwork()
isTokenBridgeableToNetwork(
options):Promise<IsTokenBridgeableResult>
Check if a token is bridgeable to a specific network
Returns bridgeability status and contract address if available. Uses cached data for efficient lookups; fetches from API if not cached.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | IsTokenBridgeableOptions | Token identifier and target network |
Returns
Promise<IsTokenBridgeableResult>
Promise resolving to bridgeability check result
Throws
NetworkError if DEX API is unavailable
Throws
ValidationError if tokenId format is invalid
Since
3.33.0
Examples
Check GALA bridgeability with pipe-delimited format
const result = await sdk.isTokenBridgeableToNetwork({
tokenId: 'GALA|Unit|none|none',
network: 'ETHEREUM'
});
if (result.isBridgeable) {
console.log(`GALA contract: ${result.contractAddress}`);
}
Check with TokenClassKey object
const result = await sdk.isTokenBridgeableToNetwork({
tokenId: { collection: 'Token', category: 'Unit', type: 'GALA', additionalKey: 'none' },
network: 'SOLANA'
});
is token bridgeable to network result options
isTokenBridgeableToSolana()
isTokenBridgeableToSolana(
tokenId):Promise<IsTokenBridgeableResult>
Check if a token is bridgeable to Solana
Convenience method for checking Solana bridgeability. Returns contract address if token is bridgeable.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenId | TokenId | Token identifier (pipe-delimited string or TokenClassKey object) |
Returns
Promise<IsTokenBridgeableResult>
Promise resolving to bridgeability check result
Throws
NetworkError if DEX API is unavailable
Throws
ValidationError if tokenId format is invalid
Since
3.33.0
Example
Check if GALA is bridgeable to Solana
// Pipe-delimited format
const result = await sdk.isTokenBridgeableToSolana('GALA|Unit|none|none');
console.log(`Bridgeable: ${result.isBridgeable}`);
// Or TokenClassKey object
const result = await sdk.isTokenBridgeableToSolana({
collection: 'Token', category: 'Unit', type: 'GALA', additionalKey: 'none'
});
is token bridgeable to solana id result
Cache Management
clearCache()
clearCache(
tokenName?):void
Clear token caches
Clears cached token data. Can clear a specific launchpad token or all caches. When clearing all (no tokenName provided), also clears bridgeable and wrappable token caches. Useful for testing or when you need to force a fresh fetch of token data.
Note: Caches automatically warm from fetchPools/fetchBridgeableTokens/fetchWrappableTokens calls and persist across the entire SDK/MCP session lifetime.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName? | string | Optional launchpad token name to clear (clears all caches if not provided) |
Returns
void
Since
3.9.2
Examples
Clear specific launchpad token
sdk.clearCache('anime'); // Clear only anime token metadata
Clear all caches (launchpad metadata + bridgeable + wrappable tokens)
sdk.clearCache(); // Clear all cached token data
clear cache token name
flushAllCache()
flushAllCache(
confirm):Promise<FlushResult>
Flush ALL Launchpad cache (Nuclear Option).
Clears ALL cached data across the entire Launchpad platform including:
- All user profile data
- All token data (chat, recordings, holders, prices)
- All overseer/moderator access data
- All ban status data
- Site configuration cache
WARNING: This will cause a temporary performance hit across the entire platform as all data needs to be re-fetched from the database.
Requires Admin API key OR JWT as existing Overseer. Safety feature: Requires confirm=true to prevent accidental usage.
Parameters
| Parameter | Type | Description |
|---|---|---|
confirm | true | Must be true to proceed (safety confirmation) |
Returns
Promise<FlushResult>
Flush result with count and duration
Throws
ValidationError if confirm is not true
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
8.x.0
Example
Flush all cache (dangerous!)
const result = await sdk.flushAllCache(true);
console.log(`Flushed ALL ${result.flushedCount} cache entries in ${result.duration}ms`);
flush all cache result
flushCacheByAddress()
flushCacheByAddress(
address):Promise<FlushResult>
Flush all cache entries for a wallet address.
Clears cached data associated with the specified address including:
- User profile data (profile:data:, profile:stats:)
- Overseer status
- Owned tokens list
- Ban status (global and per-token)
Requires Admin API key OR JWT as existing Overseer.
Parameters
| Parameter | Type | Description |
|---|---|---|
address | string | Wallet address to flush cache for (eth|... or 0x... format) |
Returns
Promise<FlushResult>
Flush result with count and duration
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
8.x.0
Example
Flush cache for a user
const result = await sdk.flushCacheByAddress('eth|abc123...');
console.log(`Flushed ${result.flushedCount} cache entries in ${result.duration}ms`);
flush cache by address result
flushCacheByToken()
flushCacheByToken(
tokenName):Promise<FlushResult>
Flush all cache entries for a token.
Clears cached data associated with the specified token including:
- Stream chat messages and pinned messages
- Recordings list
- Holders data and rankings
- Token ban status
- Price data (GALA and USD)
Requires Admin API key OR JWT as existing Overseer.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to flush cache for |
Returns
Promise<FlushResult>
Flush result with count and duration
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
8.x.0
Example
Flush cache for a token
const result = await sdk.flushCacheByToken('MYTOKEN');
console.log(`Flushed ${result.flushedCount} cache entries in ${result.duration}ms`);
flush cache by token name result
flushWalletAliasCache()
flushWalletAliasCache(
address?):Promise<FlushResult>
Flush wallet-alias cache entries.
Clears the cached eth| → client| alias resolution for the given address, or ALL wallet-alias entries if no address is provided.
Use this when a user's login returns a stale eth| address even though
they have a client| alias on GalaChain. After flushing, the next login
will re-resolve the alias from the GalaChain public-key contract.
Requires Admin API key OR JWT as existing Overseer.
Parameters
| Parameter | Type | Description |
|---|---|---|
address? | string | Optional. Wallet address (eth| or 0x format) to flush. If omitted, ALL wallet-alias entries are flushed. |
Returns
Promise<FlushResult>
Flush result with count and duration
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
8.x.0
Examples
Flush alias for a single address
const result = await sdk.flushWalletAliasCache('eth|dc1783...');
console.log(`Flushed ${result.flushedCount} alias entries in ${result.duration}ms`);
Flush all wallet alias entries
const result = await sdk.flushWalletAliasCache();
console.log(`Flushed ${result.flushedCount} alias entries in ${result.duration}ms`);
flush wallet alias cache result
getCacheInfo()
getCacheInfo():
object
Get token metadata cache information
Returns statistics about all token caches including:
- Launchpad token metadata cache (totalTokens, cacheSize, oldestEntry)
- Bridgeable token cache (bridgeableTokens - by network)
- Wrappable token cache (wrappableTokens - count and timestamp)
Caches persist for the entire SDK/MCP server lifetime and accumulate data across conversations for optimal performance.
Returns
object
Cache statistics object with launchpad, bridgeable, and wrappable token stats
| Name | Type |
|---|---|
bridgeableTokens? | object |
bridgeableTokens.ETHEREUM | number |
bridgeableTokens.SOLANA | number |
bridgeableTokens.total | number |
cacheSize | number |
oldestEntry | number |
totalTokens | number |
wrappableTokens? | object |
wrappableTokens.isPopulated | boolean |
wrappableTokens.lastFetchedAt | number | null |
wrappableTokens.tokenCount | number |
Since
3.9.2
Example
const cacheInfo = sdk.getCacheInfo();
console.log(`Launchpad tokens: ${cacheInfo.totalTokens}`);
console.log(`Cache size: ${cacheInfo.cacheSize} bytes`);
console.log(`Bridgeable ETH: ${cacheInfo.bridgeableTokens?.ETHEREUM ?? 0}`);
console.log(`Bridgeable SOL: ${cacheInfo.bridgeableTokens?.SOLANA ?? 0}`);
console.log(`Wrappable tokens: ${cacheInfo.wrappableTokens?.tokenCount ?? 0}`);
get cache info bridgeable tokens size oldest entry total wrappable is populated last fetched at token count
Calculations
calculateBuyAmount()
calculateBuyAmount(
options):Promise<AmountCalculationResult>
Calculate buy amount for a token purchase with automatic mode selection
Flexible calculation method that automatically routes to either local (instant, client-side) or external (real-time, GalaChain) calculation based on available parameters. Defaults to external calculation for guaranteed accuracy unless currentSupply is provided.
Supports two calculation types:
- type: 'native' - Calculate tokens received for a given GALA amount
- type: 'exact' - Calculate GALA needed to buy a specific token amount
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CalculateBuyAmountOptions | Calculation options with required tokenName and amount |
Returns
Promise<AmountCalculationResult>
Promise
Throws
If tokenName or amount is invalid
Throws
If external calculation fails
Since
1.0.0
Examples
Calculate tokens from GALA (external mode)
const result = await sdk.calculateBuyAmount({
tokenName: 'anime',
amount: '100', // 100 GALA
type: 'native'
});
console.log('Tokens you will receive:', result.amount);
console.log('Transaction fee:', result.transactionFee);
Calculate GALA needed for tokens (external mode)
const result = await sdk.calculateBuyAmount({
tokenName: 'anime',
amount: '1000', // 1000 tokens
type: 'exact'
});
console.log('GALA needed:', result.amount);
console.log('Fees:', result.transactionFee, result.gasFee);
Performance-optimized with local calculation
// Fetch supply once, reuse for multiple calculations
const poolDetails = await sdk.fetchPoolDetailsForCalculation('anime');
const calc1 = await sdk.calculateBuyAmount({
tokenName: 'anime',
amount: '100',
type: 'native',
currentSupply: poolDetails.currentSupply // Enables instant local calculation
});
const calc2 = await sdk.calculateBuyAmount({
tokenName: 'anime',
amount: '500',
type: 'native',
currentSupply: poolDetails.currentSupply // Reuse same supply
});
calculate buy amount calculation result options
calculateInitialBuyAmount()
calculateInitialBuyAmount(
nativeTokenQuantity):Promise<AmountCalculationResult>
Calculate initial buy amount for pre-mint token launches
Calculates the number of tokens that will be received when purchasing during the token launch pre-buy phase. This is used internally during token creation with the preBuyQuantity parameter.
The pre-mint phase uses the same exponential bonding curve formula but starts from zero supply, providing the best possible price for early supporters.
Parameters
| Parameter | Type | Description |
|---|---|---|
nativeTokenQuantity | string | Amount of GALA to spend during pre-buy (decimal string) |
Returns
Promise<AmountCalculationResult>
Promise
Throws
If nativeTokenQuantity is invalid or negative
Throws
If API request fails
Since
1.0.0
Examples
Calculate pre-buy tokens
const result = await sdk.calculateInitialBuyAmount('100');
console.log('Tokens from 100 GALA pre-buy:', result.amount);
console.log('Transaction fee:', result.transactionFee);
console.log('Starting supply:', result.currentSupply); // Should be "0"
Validate pre-buy before launch
// Check what you'll receive before launching token
const preBuyAmount = '50'; // 50 GALA
const calc = await sdk.calculateInitialBuyAmount(preBuyAmount);
console.log(`Pre-buying with ${preBuyAmount} GALA will give you ${calc.amount} tokens`);
// Now launch with this pre-buy amount
const launch = await sdk.launchToken({
tokenName: 'mytoken',
tokenSymbol: 'MTK',
tokenDescription: 'My token',
preBuyQuantity: preBuyAmount
});
calculate initial buy amount native token quantity calculation result
calculateSellAmount()
calculateSellAmount(
options):Promise<AmountCalculationResult>
Calculate sell amount for a token sale with automatic mode selection
Flexible calculation method that automatically routes to either local (instant, client-side) or external (real-time, GalaChain) calculation based on available parameters. Defaults to external calculation for guaranteed accuracy unless currentSupply and RBC fees are provided.
Supports two calculation types:
- type: 'exact' - Calculate GALA received for selling a specific token amount
- type: 'native' - Calculate tokens needed to receive a specific GALA amount
Includes reverse bonding curve (RBC) fee calculation that scales with token supply.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CalculateSellAmountOptions | Calculation options with required tokenName and amount |
Returns
Promise<AmountCalculationResult>
Promise
Throws
If tokenName or amount is invalid
Throws
If external calculation fails
Since
1.0.0
Examples
Calculate GALA from selling tokens (external mode)
const result = await sdk.calculateSellAmount({
tokenName: 'anime',
amount: '500', // 500 tokens
type: 'exact'
});
console.log('GALA you will receive:', result.amount);
console.log('Reverse bonding fee:', result.reverseBondingCurveFee);
console.log('Transaction fee:', result.transactionFee);
Calculate tokens needed for GALA (external mode)
const result = await sdk.calculateSellAmount({
tokenName: 'anime',
amount: '50', // 50 GALA desired
type: 'native'
});
console.log('Tokens to sell:', result.amount);
console.log('Total fees deducted:', result.totalFees);
Performance-optimized with local calculation
// Fetch pool details once, reuse for multiple calculations
const poolDetails = await sdk.fetchPoolDetailsForCalculation('anime');
const calc1 = await sdk.calculateSellAmount({
tokenName: 'anime',
amount: '500',
type: 'exact',
currentSupply: poolDetails.currentSupply,
reverseBondingCurveMaxFeeFactor: poolDetails.reverseBondingCurveMaxFeeFactor,
reverseBondingCurveMinFeeFactor: poolDetails.reverseBondingCurveMinFeeFactor
});
// Instant local calculation - no network calls
calculate sell amount calculation result options
Chat
deleteChatMessage()
deleteChatMessage(
id):Promise<void>
Delete a chat message.
Supports both JWT and API key authentication. Authorization: message author, pool owner, or MANAGE_CHAT permission.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | Message ID to delete (format: chat-{timestamp}-{uuid}) |
Returns
Promise<void>
Throws
ValidationError if ID format is invalid
Throws
ConfigurationError if neither JWT nor API key is configured
Since
6.2.0
Example
Delete a chat message
await sdk.deleteChatMessage('chat-1734445623456-550e8400-e29b-41d4-a716-446655440000');
console.log('Message deleted');
delete chat message
disableChat()
disableChat(
tokenName):Promise<ChatStatusResponse>
Disable chat for a specific token.
Supports dual authentication:
- Admin (API key): Sets ADMIN_DISABLED - owner locked out
- Owner (JWT): Sets DISABLED - owner can re-enable
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
Promise<ChatStatusResponse>
Promise resolving with enabled status and detailed status
Throws
Error if neither admin API key nor JWT is configured
Since
5.1.0
Since
5.4.0 - Added dual-auth support (Admin API key OR JWT owner)
disable chat token name status response
enableChat()
enableChat(
tokenName):Promise<ChatStatusResponse>
Enable chat for a specific token.
Supports dual authentication:
- Admin (API key): Sets ENABLED - clears lock, owner regains control
- Owner (JWT): Sets ENABLED - fails with 403 if ADMIN_DISABLED
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
Promise<ChatStatusResponse>
Promise resolving with enabled status and detailed status
Throws
Error if neither admin API key nor JWT is configured
Throws
Error (403) if owner tries to enable when ADMIN_DISABLED
Since
5.1.0
Since
5.4.0 - Added dual-auth support (Admin API key OR JWT owner)
enable chat token name status response
getChatMessages()
getChatMessages(
options):Promise<GetChatMessagesResult>
Get chat messages with optional filtering.
Public endpoint - no authentication required. At least one of tokenName or userAddress must be provided.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetChatMessagesOptions | Query options including tokenName/userAddress and pagination |
Returns
Promise<GetChatMessagesResult>
Paginated list of chat messages
Throws
ValidationError if no filter is provided or options are invalid
Since
6.2.0
Examples
Get chat messages for a token
const { messages, meta } = await sdk.getChatMessages({ tokenName: 'anime' });
console.log(`Found ${meta.totalItems} messages`);
messages.forEach(msg => {
console.log(`${msg.userProfile?.fullName}: ${msg.content}`);
});
Get chat messages by a user
const result = await sdk.getChatMessages({
userAddress: 'eth|123...',
pageSize: 50
});
get chat messages result options
getChatStatus()
getChatStatus(
tokenName):Promise<ChatStatusResponse>
The chat status of a token (GET /live/:tokenName/chat, public): whether chat is on, why it is
off (reason: 'global' or 'token') and the slow-mode interval (slowModeSeconds, 0 = off).
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name |
Returns
Promise<ChatStatusResponse>
The token's chat status
Throws
ValidationError if the token name is invalid
Since
9.0.0
Example
const status = await sdk.getChatStatus('mytoken');
if (!status.enabled) console.log('Chat is off:', status.reason);
console.log('Slow mode:', status.slowModeSeconds ?? 0, 's');
get chat status token name response slow mode seconds
getPinnedChatMessage()
getPinnedChatMessage(
tokenName):Promise<GetPinnedMessageResult>
Get the currently pinned chat message for a token (v6.x.0+)
Retrieves the pinned message for a token's chat if one exists.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
Promise<GetPinnedMessageResult>
Pinned message details or null if no message is pinned
Throws
If token name is invalid
Since
6.x.0
Example
Get pinned message
const pinned = await sdk.getPinnedChatMessage('mytoken');
if (pinned) {
console.log('Pinned message:', pinned.content);
console.log('Pinned by:', pinned.pinnedBy);
}
get pinned chat message token name result
pinChatMessage()
pinChatMessage(
tokenName,messageId):Promise<GetPinnedMessageResult>
Pin a chat message for a token (v6.x.0+)
Pins a message to the top of the chat for this token. Requires admin or manager access.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
messageId | string | ID of the message to pin |
Returns
Promise<GetPinnedMessageResult>
The token's pinned message as read back after the pin. pinnedMessage is null when
another moderator unpinned it between the two requests.
Throws
If token name or message ID is invalid
Throws
If user is not authorized to pin messages
Since
6.x.0
Example
Pin a message
const result = await sdk.pinChatMessage('mytoken', 'msg123');
console.log('Message pinned:', result.pinnedMessage?.messageId);
pin chat message token name id get pinned result
sendChatMessage()
sendChatMessage(
options):Promise<CreateChatMessageResult>
Send a chat message.
Requires JWT authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CreateChatMessageOptions | Send options including tokenName and content |
Returns
Promise<CreateChatMessageResult>
The created chat message
Throws
ValidationError if token name or content is invalid
Throws
ConfigurationError if JWT is not configured
Since
6.2.0
Example
Send a chat message
const result = await sdk.sendChatMessage({
tokenName: 'anime',
content: 'Hello everyone!'
});
console.log('Message sent:', result.message.id);
send chat message create result options
setSlowMode()
setSlowMode(
tokenName,slowModeSeconds):Promise<{slowModeSeconds:number;tokenName:string; }>
Set slow mode interval for a token's chat (v8.x.0+)
Throttles users to one message per N seconds. Enforcement is server-side (Redis-backed). Set to 0 to disable slow mode.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
slowModeSeconds | number | Interval in seconds (0 = disabled, max 600) |
Returns
Promise<{ slowModeSeconds: number; tokenName: string; }>
Updated slow mode setting
Throws
If token name is invalid or seconds out of range
Since
8.x.0
Examples
Set 30-second slow mode
await sdk.setSlowMode('mytoken', 30);
Disable slow mode
await sdk.setSlowMode('mytoken', 0);
set slow mode token name seconds
unpinChatMessage()
unpinChatMessage(
tokenName):Promise<UnpinMessageResult>
Unpin the currently pinned chat message for a token (v6.x.0+)
Removes the pinned message from a token's chat. Requires admin or manager access.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
Promise<UnpinMessageResult>
Throws
If token name is invalid
Throws
If user is not authorized to unpin messages
Since
6.x.0
Example
Unpin a message
await sdk.unpinChatMessage('mytoken');
console.log('Message unpinned');
unpin chat message token name result
updateChatMessage()
updateChatMessage(
id,options):Promise<UpdateChatMessageResult>
Update a chat message.
Requires JWT authentication. Only the message author can update.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | Message ID to update (format: chat-{timestamp}-{uuid}) |
options | UpdateChatMessageOptions | Update options including new content |
Returns
Promise<UpdateChatMessageResult>
The updated chat message
Throws
ValidationError if ID or content is invalid
Throws
ConfigurationError if JWT is not configured
Since
6.2.0
Example
Update a chat message
const result = await sdk.updateChatMessage(
'chat-1734445623456-550e8400-e29b-41d4-a716-446655440000',
{ content: 'Updated message' }
);
console.log('Updated:', result.message.updatedAt);
update chat message result options
Comments
createComment()
createComment(
options):Promise<CreateCommentResult>
Create a new comment on a token pool.
Requires JWT authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CreateCommentOptions | Create options including tokenName and content |
Returns
Promise<CreateCommentResult>
The created comment
Throws
ValidationError if token name or content is invalid
Throws
ConfigurationError if JWT is not configured
Since
6.2.0
Example
Create a comment
const result = await sdk.createComment({
tokenName: 'mytoken',
content: 'This is a great project!'
});
console.log('Created comment ID:', result.comment.id);
create comment result options
deleteComment()
deleteComment(
id):Promise<DeleteCommentResult>
Delete a comment.
Requires authentication (JWT or API key). Authorization: comment author, pool creator, moderator with MANAGE_COMMENTS permission, or overseer.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | Message ID of the comment to delete |
Returns
Promise<DeleteCommentResult>
Success indicator
Throws
ValidationError if ID is invalid
Throws
ConfigurationError if neither JWT nor API key is configured
Since
6.2.0
Example
Delete a comment
await sdk.deleteComment('msg-1234567890123-abc...');
console.log('Comment deleted');
delete comment result
getComments()
getComments(
options):Promise<CommentsResult>
Get comments with optional filtering.
Public endpoint - no authentication required. At least one of tokenName or userAddress must be provided.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetCommentsOptions | Query options including tokenName/userAddress and pagination |
Returns
Promise<CommentsResult>
Paginated list of comments
Throws
ValidationError if no filter is provided or options are invalid
Since
6.2.0
Examples
Get comments for a token
const { messages, meta } = await sdk.getComments({ tokenName: 'mytoken' });
console.log(`Page ${meta.currentPage} of ${meta.totalPages}`);
messages.forEach(comment => {
console.log(`${comment.userProfile?.fullName}: ${comment.content}`);
});
Get comments by a user
const result = await sdk.getComments({
userAddress: 'eth|123...',
pageSize: 20
});
get comments result options
updateComment()
updateComment(
id,options):Promise<UpdateCommentResult>
Update a comment.
Requires JWT authentication. Only the comment author can update.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | Message ID of the comment to update |
options | UpdateCommentOptions | Update options including new content |
Returns
Promise<UpdateCommentResult>
The updated comment
Throws
ValidationError if ID or content is invalid
Throws
ConfigurationError if JWT is not configured
Since
6.2.0
Example
Update a comment
const result = await sdk.updateComment('msg-1234567890123-abc...', {
content: 'Updated comment content'
});
console.log('Updated at:', result.comment.updatedAt);
update comment result options
Configuration
getConfig()
getConfig():
LaunchpadSDKConfigResponse
Gets the current SDK configuration
Returns a copy of the SDK configuration with sensitive data removed. The wallet instance is excluded for security reasons.
Includes the GalaChain gas fee (fixed at 1 GALA) which is applied to all blockchain transactions.
Returns
SDK configuration object including:
- environment: Current environment (
stageorprod) - gasFee: GalaChain gas fee (fixed at "1" GALA)
- slippageToleranceFactor: Effective slippage tolerance
- calculateAmountMode: Calculation mode (local or external)
- Base URLs and other configuration settings
Since
1.0.0
Examples
Inspect SDK configuration
const sdk = new LaunchpadSDK({
wallet,
baseUrl: 'https://api.example.com',
timeout: 45000,
debug: true
});
const config = sdk.getConfig();
console.log('Base URL:', config.baseUrl);
console.log('Timeout:', config.timeout);
console.log('Debug mode:', config.debug);
console.log('Gas Fee:', config.gasFee); // "1" GALA
// wallet property is not included for security
Configuration validation
const config = sdk.getConfig();
if (config.debug) {
console.log('Debug mode is enabled - detailed logging active');
}
if (config.timeout < 30000) {
console.warn('Timeout is quite low, consider increasing for stability');
}
get config launchpad sdk response
getPlatformConfig()
getPlatformConfig():
Promise<PlatformConfig>
Get current platform configuration.
Public endpoint - no authentication required.
Returns global platform settings affecting all tokens and streams:
- Whether streaming is enabled globally
- Whether chat is enabled globally
- Whether comments are enabled globally
- Whether webhooks are enabled globally
Returns
Promise<PlatformConfig>
Current platform configuration
Since
7.3.0
Example
Get platform configuration
const config = await sdk.getPlatformConfig();
if (!config.streamingEnabled) {
console.log('Platform streaming is disabled');
}
if (!config.chatEnabled) {
console.log('Platform chat is disabled');
}
get platform config
getRestrictedNames()
getRestrictedNames():
Promise<GetRestrictedNamesResult>
Get the restricted token names content (Overseer only).
Returns a newline-separated list of restricted words that cannot be used in token names.
Requires JWT authentication with overseer role.
Returns
Promise<GetRestrictedNamesResult>
Promise
Since
7.0.0
Example
const result = await sdk.getRestrictedNames();
if (result.success) {
const words = result.data.content.split('\n').filter(w => w.trim());
console.log('Restricted words:', words);
}
get restricted names result
updatePlatformConfig()
updatePlatformConfig(
options):Promise<PlatformConfig>
Update platform configuration.
Requires JWT authentication with admin or overseer role.
Performs a partial update - only provide fields to change. Other fields remain unchanged.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | UpdatePlatformConfigOptions | Configuration fields to update |
Returns
Promise<PlatformConfig>
Updated platform configuration
Throws
ValidationError if options are invalid or missing
Throws
ConfigurationError if JWT auth is not configured
Throws
Error if user is not authorized (not admin or overseer)
Since
7.3.0
Examples
Disable streaming platform-wide
const updated = await sdk.updatePlatformConfig({
streamingEnabled: false
});
console.log('Streaming disabled globally');
Disable multiple features
const updated = await sdk.updatePlatformConfig({
streamingEnabled: false,
chatEnabled: false,
commentsEnabled: false
});
update platform config options
updateRestrictedNames()
updateRestrictedNames(
request):Promise<UpdateRestrictedNamesResult>
Update the restricted token names content (Overseer only).
Replaces the entire list with newline-separated words. Contains offensive words - not exposed publicly.
Requires JWT authentication with overseer role.
Parameters
| Parameter | Type | Description |
|---|---|---|
request | UpdateRestrictedNamesRequest | Request containing newline-separated content |
Returns
Promise<UpdateRestrictedNamesResult>
Promise
Throws
If content is not provided
Since
7.0.0
Example
const result = await sdk.updateRestrictedNames({
content: 'scam\nrug\nfake\nfraud\n...'
});
if (result.success) {
console.log('Restricted names updated');
}
update restricted names result request
ContentReactions
content reactions
addContentReaction()
addContentReaction(
options):Promise<AddContentReactionResult>
Add a reaction to a pool message (chat or comment).
Requires JWT or API key authentication. Adding the same reaction type again is a no-op (idempotent). Users can have multiple different reaction types on the same message.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | AddContentReactionOptions | Options including messageId and reactionType |
Returns
Promise<AddContentReactionResult>
Updated reaction data and whether reaction was newly created
Throws
ValidationError if parameters are invalid
Throws
ConfigurationError if authentication is not configured
Since
5.12.0
Example
Add a heart reaction
const result = await sdk.addContentReaction({
messageId: 'msg-1703443200000-a1b2c3d4e5f6789012345678901234ab',
reactionType: 'heart'
});
console.log('Created:', result.created);
console.log('Total reactions:', result.data.totalCount);
add content reaction result options
addReactionToChatMessage()
addReactionToChatMessage(
options):Promise<AddContentReactionResult>
Add a reaction to a chat message.
Convenience wrapper for addContentReaction specifically for chat messages.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | AddContentReactionOptions | Options including messageId and reactionType |
Returns
Promise<AddContentReactionResult>
Updated reaction data
Since
5.12.0
Example
Add a fire reaction to a chat message
await sdk.addReactionToChatMessage({
messageId: 'msg-1703443200000-a1b2c3d4e5f6789012345678901234ab',
reactionType: 'fire'
});
add reaction to chat message content result options
addReactionToComment()
addReactionToComment(
options):Promise<AddContentReactionResult>
Add a reaction to a comment.
Convenience wrapper for addContentReaction specifically for comments.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | AddContentReactionOptions | Options including messageId and reactionType |
Returns
Promise<AddContentReactionResult>
Updated reaction data
Since
5.12.0
Example
Add a thumbs_up reaction to a comment
await sdk.addReactionToComment({
messageId: 'msg-1703443200000-a1b2c3d4e5f6789012345678901234ab',
reactionType: 'thumbs_up'
});
add reaction to comment content result options
removeContentReaction()
removeContentReaction(
options):Promise<RemoveContentReactionResult>
Remove a reaction from a pool message.
Requires JWT or API key authentication. Only the user who created the reaction can remove it.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | RemoveContentReactionOptions | Options including messageId and reactionType |
Returns
Promise<RemoveContentReactionResult>
Success indicator
Throws
ValidationError if parameters are invalid
Throws
ConfigurationError if authentication is not configured
Since
5.12.0
Example
Remove a heart reaction
await sdk.removeContentReaction({
messageId: 'msg-1703443200000-a1b2c3d4e5f6789012345678901234ab',
reactionType: 'heart'
});
remove content reaction result options
removeReactionFromChatMessage()
removeReactionFromChatMessage(
options):Promise<RemoveContentReactionResult>
Remove a reaction from a chat message.
Convenience wrapper for removeContentReaction specifically for chat messages.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | RemoveContentReactionOptions | Options including messageId and reactionType |
Returns
Promise<RemoveContentReactionResult>
Success indicator
Since
5.12.0
Example
Remove a fire reaction from a chat message
await sdk.removeReactionFromChatMessage({
messageId: 'msg-1703443200000-a1b2c3d4e5f6789012345678901234ab',
reactionType: 'fire'
});
remove reaction from chat message content result options
removeReactionFromComment()
removeReactionFromComment(
options):Promise<RemoveContentReactionResult>
Remove a reaction from a comment.
Convenience wrapper for removeContentReaction specifically for comments.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | RemoveContentReactionOptions | Options including messageId and reactionType |
Returns
Promise<RemoveContentReactionResult>
Success indicator
Since
5.12.0
Example
Remove a thumbs_up reaction from a comment
await sdk.removeReactionFromComment({
messageId: 'msg-1703443200000-a1b2c3d4e5f6789012345678901234ab',
reactionType: 'thumbs_up'
});
remove reaction from comment content result options
Events
getEventStats()
getEventStats():
Promise<EventStats>
Aggregate event statistics (GET /v1/events/stats). Admin API key or Overseer JWT.
Returns
Promise<EventStats>
Event totals, today's count, unique users and tokens, and the count per event type
Throws
ConfigurationError if neither an admin API key nor a JWT is configured
Since
9.0.0
Example
const stats = await sdk.getEventStats();
console.log(stats.totalEvents, stats.eventsByType);
get event stats
queryEvents()
queryEvents(
options?):Promise<QueryEventsResult>
One page of stored events (GET /v1/events). Admin API key or Overseer JWT. Paging is offset
style (page, limit 1..100), not a cursor.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | QueryEventsOptions | Filters (user, token, event types, dates, search), paging and sorting |
Returns
Promise<QueryEventsResult>
{ data, pagination: { page, limit, total, totalPages } }
Throws
ValidationError for an out-of-range limit / page or an unknown sort, preset or source
Throws
ConfigurationError if neither an admin API key nor a JWT is configured
Since
9.0.0
Example
const page = await sdk.queryEvents({ tokenName: 'anime', eventTypes: ['token_buy'], page: 1, limit: 50 });
console.log(page.pagination.total, page.data[0]?.eventType);
query events result options total pages
External Calculations
calculateBuyAmountExternal()
calculateBuyAmountExternal(
options):Promise<AmountCalculationResult>
Calculate buy amount using external GalaChain call
Makes a network request to GalaChain to calculate buy amounts. Always returns fresh calculations based on current blockchain state. Use when you want guaranteed accuracy but don't mind network latency.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | { amount: string; tokenName: string; type: "native" | "exact"; } | Buy amount calculation options |
options.amount | string | - |
options.tokenName | string | - |
options.type | "native" | "exact" | - |
Returns
Promise<AmountCalculationResult>
Promise
Deprecated
Use getTradeQuote() instead — it uses the backend-proxy for instant
calculations without a direct GalaChain call. The swap backend has removed direct
chain quote endpoints in favour of the backend-proxy approach.
Throws
NetworkError if API request fails
Since
3.8.0
calculate buy amount external calculation result token name get trade quote
calculateSellAmountExternal()
calculateSellAmountExternal(
options):Promise<AmountCalculationResult>
Calculate sell amount using external GalaChain call
Makes a network request to GalaChain to calculate sell amounts. Always returns fresh calculations based on current blockchain state. Use when you want guaranteed accuracy but don't mind network latency.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | { amount: string; tokenName: string; type: "native" | "exact"; } | Sell amount calculation options |
options.amount | string | - |
options.tokenName | string | - |
options.type | "native" | "exact" | - |
Returns
Promise<AmountCalculationResult>
Promise
Deprecated
Use getTradeQuote() instead — it uses the backend-proxy for instant
calculations without a direct GalaChain call. The swap backend has removed direct
chain quote endpoints in favour of the backend-proxy approach.
Throws
NetworkError if API request fails
Since
3.8.0
calculate sell amount external calculation result token name get trade quote
Flags
actionFlag()
actionFlag(
options):Promise<ActionFlagResult>
Take action on a flag.
Actions available:
- DELETE_CONTENT: Remove the flagged content
- BAN_USER: Ban the reported user from the token
- DELETE_AND_BAN: Both delete content and ban user
Parameters
| Parameter | Type | Description |
|---|---|---|
options | ActionFlagOptions | Action options |
Returns
Promise<ActionFlagResult>
Updated flag data with action taken
Throws
Error if not authorized, flag not found, or action invalid
Since
5.8.0
Examples
Delete the flagged content
const result = await sdk.actionFlag({
flagId: 123,
action: FlagAction.DELETE_CONTENT,
});
Delete content and ban user
const result = await sdk.actionFlag({
flagId: 123,
action: FlagAction.DELETE_AND_BAN,
});
action flag result options
createFlag()
createFlag(
options):Promise<CreateFlagResult>
Create a content flag/report.
Two-tier system:
- Chat/Comment: reason and details are optional (one-click flag)
- Stream: reason is required (modal flow)
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CreateFlagOptions | Flag creation options |
Returns
Promise<CreateFlagResult>
Created flag data
Throws
Error if not authenticated or validation fails
Since
5.8.0
Examples
One-click flag on chat message
const result = await sdk.createFlag({
tokenName: 'mytoken',
contentType: ContentType.CHAT_MESSAGE,
contentId: 'msg-123',
reportedUserAddress: 'eth|abc...',
});
Stream report with required reason
const result = await sdk.createFlag({
tokenName: 'mytoken',
contentType: ContentType.STREAM,
contentId: 'stream-456',
reportedUserAddress: 'eth|abc...',
reason: FlagReason.INAPPROPRIATE_CONTENT,
details: 'Explicit content',
});
create flag result options
dismissFlag()
dismissFlag(
options):Promise<DismissFlagResult>
Dismiss a flag (no action taken).
Marks the flag as reviewed but takes no action on the content.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | DismissFlagOptions | Dismiss options |
Returns
Promise<DismissFlagResult>
Updated flag data
Throws
Error if not authorized or flag not found
Since
5.8.0
Example
Dismiss a flag
const result = await sdk.dismissFlag({ flagId: 123 });
console.log(result.flag.status); // 'DISMISSED'
dismiss flag result options
listFlags()
listFlags(
options):Promise<FlagListResult>
List flags for a token with pagination and filtering.
Authorization varies by content type:
- CHAT_MESSAGE/COMMENT: Owner or Moderator (JWT) can view
- STREAM: Admin API key only
Parameters
| Parameter | Type | Description |
|---|---|---|
options | ListFlagsOptions | List options with filters |
Returns
Promise<FlagListResult>
Paginated list of flags
Throws
Error if not authorized
Since
5.8.0
Examples
List pending flags
const result = await sdk.listFlags({
tokenName: 'mytoken',
status: FlagStatus.PENDING,
});
console.log(`Found ${result.flags.length} pending flags`);
List flags with pagination
const result = await sdk.listFlags({
tokenName: 'mytoken',
contentType: ContentType.CHAT_MESSAGE,
pageSize: 50,
});
list flags flag result options
listGlobalFlags()
listGlobalFlags(
options?):Promise<FlagListResult>
List flags globally across all tokens (Overseer only).
Returns paginated flags matching filter criteria across the platform. Requires OVERSEER role for access.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | ListGlobalFlagsOptions | Filter and pagination options |
Returns
Promise<FlagListResult>
Paginated list of flags
Throws
Error if not authorized as overseer
Since
6.2.0
list global flags flag result options
Health
getHealth()
getHealth():
Promise<HealthCheckResponse>
The launchpad backend's dependency health (GET /health). Public: no Authorization header.
A critical dependency being down answers HTTP 503, which throws a NetworkError.
Returns
Promise<HealthCheckResponse>
Overall status and the state of each dependency
Since
9.0.0
Example
const health = await sdk.getHealth();
console.log(health.status, health.database?.status, health.redis?.status);
get health check response network error
Local Calculations
calculateBuyAmountLocal()
calculateBuyAmountLocal(
options):Promise<AmountCalculationResult>
Calculate buy amount locally using bonding curve formula
Performs instant client-side calculation without network calls to GalaChain. Uses exponential bonding curve mathematics to calculate GALA costs or token amounts. Requires the current token supply to perform accurate calculations.
This method enables instant price quotes and real-time calculations without API rate limits or network latency. Perfect for building responsive UIs that show live pricing as users adjust their trade amounts.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CalculateBuyAmountLocalOptions | Local calculation options with currentSupply |
Returns
Promise<AmountCalculationResult>
Promise
Throws
ValidationError if parameters are invalid
Since
3.8.0
Examples
Calculate GALA needed to buy 1000 tokens
const result = await sdk.calculateBuyAmountLocal({
tokenName: 'mytoken',
amount: '1000',
type: 'exact',
currentSupply: '500000'
});
console.log('GALA needed:', result.amount);
console.log('Transaction fee:', result.transactionFee);
Calculate tokens received for 100 GALA
const result = await sdk.calculateBuyAmountLocal({
tokenName: 'mytoken',
amount: '100',
type: 'native',
currentSupply: '500000'
});
console.log('Tokens received:', result.amount);
calculate buy amount local calculation result options
calculateSellAmountLocal()
calculateSellAmountLocal(
options):Promise<AmountCalculationResult>
Calculate sell amount locally using bonding curve formula
Performs instant client-side calculation without network calls to GalaChain. Uses exponential bonding curve mathematics to calculate GALA received or tokens needed. Requires the current token supply to perform accurate calculations.
This method enables instant price quotes and real-time calculations without API rate limits or network latency. Includes reverse bonding curve fee calculation that scales with supply.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CalculateSellAmountLocalOptions | Local calculation options with currentSupply |
Returns
Promise<AmountCalculationResult>
Promise
Throws
ValidationError if parameters are invalid
Since
3.8.0
Examples
Calculate GALA received when selling 500 tokens
const result = await sdk.calculateSellAmountLocal({
tokenName: 'mytoken',
amount: '500',
type: 'exact',
currentSupply: '500000'
});
console.log('GALA received:', result.amount);
console.log('Reverse bonding fee:', result.reverseBondingCurveFee);
console.log('Transaction fee:', result.transactionFee);
Calculate tokens needed to receive 50 GALA
const result = await sdk.calculateSellAmountLocal({
tokenName: 'mytoken',
amount: '50',
type: 'native',
currentSupply: '500000'
});
console.log('Tokens to sell:', result.amount);
calculate sell amount local calculation result options
Main SDK
fetchAllReferrals()
fetchAllReferrals(
options?):Promise<AllReferralsResult>
Fetch all referrals for a wallet address (auto-paginated)
Automatically fetches all pages and returns the complete list of referrals. Use this when you need all referral data without manual pagination.
Wallet requirement: If no address is provided, uses the SDK wallet address. You can optionally pass any wallet address to fetch their referrals.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | Omit<FetchReferralsOptions, "page" | "limit"> | Optional fetch parameters |
Returns
Promise<AllReferralsResult>
Promise
Throws
If wallet not configured and no address provided
Throws
If DEX API request fails
Since
4.0.23
Examples
Fetch all referrals
const result = await sdk.fetchAllReferrals();
console.log(`Total referrals: ${result.total}`);
// Calculate total rewards
const totalRewards = result.referrals.reduce((sum, ref) => {
const galaRewards = ref.rewards.filter(r => r.tokenClassKey.collection === 'GALA');
return sum + galaRewards.reduce((s, r) => s + r.quantity, 0);
}, 0);
console.log(`Total GALA earned from referrals: ${totalRewards}`);
Fetch all referrals for a specific address
const result = await sdk.fetchAllReferrals({
address: 'client|689e38a801386ddc6fca8c9f'
});
fetch all referrals result options
fetchGalaBalance()
fetchGalaBalance(
address?):Promise<TokenBalanceResult|null>
Fetch GALA token balance for a wallet address
Retrieves the current GALA token balance for a specified wallet address or the authenticated user's wallet if no address is provided. Returns complete balance information including token quantity, token metadata, and collection details from GalaChain.
Supports both address formats:
- Standard Ethereum format:
0x...(64 hex characters after 0x prefix) - Backend format:
eth|...(full GalaChain address format)
Parameters
| Parameter | Type | Description |
|---|---|---|
address? | string | Optional wallet address in 0x... or eth|... format. Defaults to current SDK wallet address. |
Returns
Promise<TokenBalanceResult | null>
Promise
Throws
If wallet is not configured and no address is provided
Throws
If GalaChain query fails or network connection is unavailable
Since
4.0.4-beta.0
Examples
Fetch balance for authenticated wallet
const balance = await sdk.fetchGalaBalance();
console.log(`Your GALA balance: ${balance.quantity}`);
Fetch balance for specific address
const address = 'eth|742d35Cc6634C0532925a3b8D0Ea2c76f94C31C0';
const balance = await sdk.fetchGalaBalance(address);
console.log(`Balance: ${balance.quantity} GALA`);
Fetch and format balance
const balance = await sdk.fetchGalaBalance();
const formattedBalance = (BigInt(balance.quantity) / BigInt(10 ** 8)).toString();
console.log(`GALA: ${formattedBalance}`);
fetch gala balance token result
fetchLaunchpadFee()
fetchLaunchpadFee():
Promise<number>
Fetch the current launchpad fee via backend proxy (cached 1 hour).
Same value as fetchLaunchTokenFee() (which delegates here) — no chain call.
Returns
Promise<number>
Promise resolving to the fee amount in GALA (number)
Since
9.1.0
Example
const fee = await sdk.fetchLaunchpadFee();
console.log(`Current launchpad fee: ${fee} GALA`);
fetch launchpad fee launch token
fetchProfile()
fetchProfile(
address?):Promise<PublicUserProfile>
Fetch user profile information by wallet address
GET /v1/users/:address (public, no authentication): name, profile image, bio, aggregated stats
and the four badge ladders. An address with no profile row still answers a profile (fullName,
profileImage and bio are null).
Supports both address formats:
- Standard Ethereum format:
0x...(64 hex characters after 0x prefix) - Backend format:
eth|...(full GalaChain address format)
Parameters
| Parameter | Type | Description |
|---|---|---|
address? | string | Optional wallet address in 0x... or eth|... format. Defaults to current SDK wallet address. |
Returns
Promise<PublicUserProfile>
The public profile (the data of the backend's envelope)
Throws
If wallet is not configured and no address is provided
Throws
If launchpad API request fails, or answers a body that is not a profile
Since
4.0.4-beta.0
Since
9.0.0 - typed PublicUserProfile (it returned the whole { data } envelope as unknown)
Examples
Fetch current user's profile
const profile = await sdk.fetchProfile();
console.log(`User: ${profile.fullName}, tokens created: ${profile.stats.tokensCreated}`);
Fetch profile for specific address
const profile = await sdk.fetchProfile('eth|742d35Cc6634C0532925a3b8D0Ea2c76f94C31C0');
console.log(`Profile owner: ${profile.fullName}`);
fetch profile public user full name image
fetchReferrals()
fetchReferrals(
options?):Promise<ReferralsResult>
Fetch referrals for a wallet address with pagination
Returns a paginated list of users who signed up using this wallet's referral link, including relationship level, join date, and rewards earned from each referral.
Wallet requirement: If no address is provided, uses the SDK wallet address. You can optionally pass any wallet address to fetch their referrals.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | FetchReferralsOptions | Optional fetch parameters |
Returns
Promise<ReferralsResult>
Promise
Throws
If wallet not configured and no address provided
Throws
If DEX API request fails
Since
4.0.23
Examples
Fetch first page of referrals
const result = await sdk.fetchReferrals();
console.log(`Found ${result.referrals.length} referrals`);
result.referrals.forEach(ref => {
console.log(`${ref.walletAddress} joined ${ref.joined}, level ${ref.relationshipLevel}`);
});
Fetch with pagination
const page2 = await sdk.fetchReferrals({ pageSize: 20 });
if (page2.hasMore) {
console.log('More pages available');
}
Fetch referrals for a specific address
const referrals = await sdk.fetchReferrals({
address: 'eth|1234567890abcdef...',
sortDir: 'asc'
});
fetch referrals result options
fetchReferralsSummary()
fetchReferralsSummary(
options?):Promise<ReferralsSummaryResult>
Fetch referral summary statistics for a wallet address
Returns aggregate counts and reward totals for the referral program without listing individual referrals. Perfect for dashboard displays and quick overviews.
Wallet requirement: If no address is provided, uses the SDK wallet address. You can optionally pass any wallet address to fetch their summary.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | FetchReferralsSummaryOptions | Optional fetch parameters |
Returns
Promise<ReferralsSummaryResult>
Promise
Throws
If wallet not configured and no address provided
Throws
If address format is invalid
Throws
If DEX API request fails or returns unexpected format
Since
4.0.23
Examples
Fetch referral summary for current wallet
const summary = await sdk.fetchReferralsSummary();
console.log(`Total referrals: ${summary.referralCount}`);
console.log(`Total rewards: ${summary.rewardTotals.total} GALA`);
console.log(`Past month: ${summary.rewardTotals.pastMonth} GALA`);
console.log(`Past day: ${summary.rewardTotals.pastDay} GALA`);
Fetch summary for a specific address
const summary = await sdk.fetchReferralsSummary({
address: 'eth|1234567890abcdef...'
});
fetch referrals summary result options
fetchReferralUrl()
fetchReferralUrl():
Promise<ReferralUrlResult>
Fetch the current user's referral URL
Retrieves the unique referral URL for the authenticated wallet from the DEX API platform. The referral URL can be shared to earn referral rewards when new users sign up through the link.
Requires wallet configuration - the wallet address is used to identify the user and fetch their unique referral code.
Returns
Promise<ReferralUrlResult>
Promise
Throws
If wallet is not configured
Throws
If DEX API request fails
Since
4.0.18
Examples
Fetch and share referral URL
const result = await sdk.fetchReferralUrl();
console.log('Share this link:', result.url);
// Example: https://connect.gala.com/?r=69026333c58ce14673aa97e0
Use in a referral program UI
const { url } = await sdk.fetchReferralUrl();
// Copy to clipboard
await navigator.clipboard.writeText(url);
console.log('Referral URL copied!');
fetch referral url result
fetchSaleDetails()
fetchSaleDetails(
tokenName):Promise<SaleDetailsResult>
Fetch sale details (supply, status) for a token via backend proxy (cached 10 seconds).
Uses tokenName; the backend resolves the vaultAddress internally.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (e.g. 'anime') |
Returns
Promise<SaleDetailsResult>
Promise resolving to sale details including supply, quantities, and status
Since
9.1.0
Example
const details = await sdk.fetchSaleDetails('anime');
console.log(`Supply: ${details.sellingTokenQuantity} / ${details.maxSupply}`);
console.log(`Status: ${details.saleStatus}`);
fetch sale details token name result
getPremintQuote()
getPremintQuote(
amount):Promise<AmountCalculationResult>
Calculate a pre-mint token output for a given GALA amount (supply = 0 assumed).
Used during the token creation flow. The backend assumes supply = 0 and computes via local bonding curve math — no chain call required.
Parameters
| Parameter | Type | Description |
|---|---|---|
amount | string | GALA amount to spend (as a decimal string, e.g. '100') |
Returns
Promise<AmountCalculationResult>
Promise resolving to amount calculation result with fees
Since
9.1.0
Example
const quote = await sdk.getPremintQuote('500');
console.log(`Initial purchase will yield: ${quote.amount} tokens`);
console.log(`Transaction fee: ${quote.transactionFee} GALA`);
get premint quote amount calculation result
getTradeQuote()
getTradeQuote(
params):Promise<AmountCalculationResult>
Calculate a trade quote via the backend using local bonding curve math (no chain call).
Instant alternative to calculateBuyAmountExternal() / calculateSellAmountExternal().
The backend uses its local bonding curve math — no GalaChain network request.
Parameters
| Parameter | Type | Description |
|---|---|---|
params | TradeQuoteParams | Quote parameters |
Returns
Promise<AmountCalculationResult>
Promise resolving to amount calculation result with fees
Since
9.1.0
Example
Buy: how many tokens for 100 GALA?
const quote = await sdk.getTradeQuote({
tokenName: 'anime',
amount: '100',
type: 'NATIVE',
method: 'IN',
});
console.log(`You will receive: ${quote.amount} tokens`);
console.log(`Fee: ${quote.reverseBondingCurveFee} GALA`);
get trade quote amount calculation result calculate buy external sell params
updateProfile()
updateProfile(
data):Promise<void>
Update user profile information for a wallet address
Updates public profile metadata for a wallet, including display name and profile image. Only the wallet owner can update their own profile. Changes take effect immediately after successful submission to the launchpad server.
Requires a JWT (the backend updates the user of the token). Only the fields given are sent:
an omitted field is left as it is, profileImage: '' clears the image.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | UpdateProfileData | Profile update data (at least one of fullName and profileImage) |
Returns
Promise<void>
Promise
Throws
If the address or name is invalid or nothing is given
Throws
If launchpad API request fails
Since
4.0.4-beta.0
Examples
Update profile name and image
await sdk.updateProfile({
address: sdk.getAddress(),
fullName: 'John Crypto',
profileImage: 'https://example.com/profile-pic.png'
});
console.log('Profile updated successfully!');
Update only name
await sdk.updateProfile({
address: sdk.getAddress(),
fullName: 'Jane Blockchain'
});
Clear profile image
await sdk.updateProfile({
address: sdk.getAddress(),
profileImage: '' // Clear image
});
update profile image data
uploadProfileImage()
uploadProfileImage(
options):Promise<string>
Upload a profile image for the logged-in user (POST /v1/users/me/image)
Takes the image as a browser File or a Node.js Buffer and answers the URL it is served from.
The backend uploads for the user of the session JWT, so the route needs no address and no wallet:
it works on an SDK configured with a signer and a wallet address (and a session, or after
login()). An address that is given is validated and only names the multipart file.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | UploadProfileImageOptions | Profile image upload options |
Returns
Promise<string>
Promise
Throws
If the address is not a valid address
Throws
If there is no session or logged-in token
Throws
If upload request fails (the backend's answer is kept: its size limit, 400 for a bad format)
Since
4.0.4-beta.0
Since
9.0.0 - needs no wallet and no address (it threw "Wallet is required" on a signer-plus-address SDK)
Example
Upload a profile image
const imageUrl = await sdk.uploadProfileImage({ file: imageBuffer });
console.log(`Profile image uploaded: ${imageUrl}`);
upload profile image options
uploadTokenImage()
uploadTokenImage(
options):Promise<string>
Upload a token image (POST /v1/tokens/:tokenName/image)
Takes the image as a browser File or a Node.js Buffer and answers the URL it is served from.
The route needs only the logged-in session's bearer: it works on an SDK configured with a signer
and a wallet address (and a session, or after login()), with no wallet. The token must be
the caller's to manage; the backend answers 403 otherwise.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | UploadImageByTokenNameOptions | { tokenName, options: { file } } |
Returns
Promise<string>
Promise
Throws
If tokenName is invalid or the file is not an image
Throws
If there is no session or logged-in token
Throws
If upload request fails (the backend's answer is kept: its size limit, 403, 404)
Since
4.0.4-beta.0
Since
9.0.0 - needs no wallet (it threw "Wallet is required" on a signer-plus-address SDK)
Example
Upload an image
const imageUrl = await sdk.uploadTokenImage({
tokenName: 'mytoken',
options: { file: imageBuffer }
});
console.log(`Image uploaded: ${imageUrl}`);
upload token image name by options
Messages
createMessage()
createMessage<
T>(options):Promise<CreateMessageResult<T>>
Create a new message (chat or comment).
Requires JWT authentication.
Type Parameters
| Type Parameter |
|---|
T extends MessageType |
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CreateMessageOptions<T> | Create options including type, tokenName, and content |
Returns
Promise<CreateMessageResult<T>>
The created message
Throws
ValidationError if options are invalid
Throws
ConfigurationError if JWT is not configured
Since
7.0.0
Examples
Create a chat message
const result = await sdk.createMessage({
type: 'CHAT_MESSAGE',
tokenName: 'anime',
content: 'Hello world!'
});
console.log('Created message ID:', result.message.messageId);
Create a comment
const result = await sdk.createMessage({
type: 'COMMENT',
tokenName: 'anime',
content: 'Great project!'
});
create message result type options
deleteMessage()
deleteMessage(
id):Promise<DeleteMessageResult>
Delete a message.
Requires authentication (JWT or API key). Authorization: message author, token owner, moderator, or admin.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | Message ID to delete |
Returns
Promise<DeleteMessageResult>
Success indicator
Throws
ValidationError if ID is invalid
Throws
ConfigurationError if neither JWT nor API key is configured
Since
7.0.0
Example
Delete a message
await sdk.deleteMessage('msg-1234567890123-abc...');
console.log('Message deleted');
delete message result
fetchMessages()
fetchMessages(
options):Promise<FetchMessagesResult>
Fetch messages with optional filtering by type, token, or user.
Unified endpoint for all message types (CHAT and COMMENT). Public endpoint - no authentication required. At least one of type, tokenName, or userAddress must be provided.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | FetchMessagesOptions | Query options including type/tokenName/userAddress and pagination |
Returns
Promise<FetchMessagesResult>
Paginated list of messages
Throws
ValidationError if no filter is provided or options are invalid
Since
7.0.0
Examples
Get chat messages for a token
const { messages, pageInfo } = await sdk.fetchMessages({
type: 'CHAT_MESSAGE',
tokenName: 'anime'
});
console.log(`Found ${pageInfo.totalCount} chat messages`);
Get comments for a token
const { messages, pageInfo } = await sdk.fetchMessages({
type: 'COMMENT',
tokenName: 'anime'
});
Get all messages from a user with pagination
const result = await sdk.fetchMessages({
userAddress: 'eth|123...',
pageSize: 20,
cursor: 'next_cursor'
});
fetch messages result options
getMessageStats()
getMessageStats():
Promise<MessageStats>
Get platform-wide message statistics.
Requires admin API key or overseer JWT (AdminOrOverseerGuard).
Returns aggregated message metrics including:
- Total message count
- Today's message count
- Unique users and tokens
- Message counts by type (CHAT_MESSAGE, COMMENT)
Returns
Promise<MessageStats>
Platform-wide message statistics
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
9.1.0
Example
Get message statistics
const stats = await sdk.getMessageStats();
console.log('Total messages:', stats.totalMessages);
console.log('Today:', stats.todayMessages);
console.log('Unique users:', stats.uniqueUsers);
console.log('Unique tokens:', stats.uniqueTokens);
console.log('By type:', stats.messagesByType);
get message stats
getPinnedMessage()
getPinnedMessage(
tokenName):Promise<PinnedMessageResult>
Get the currently pinned message for a token.
Public endpoint - no authentication required.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to get pinned message for |
Returns
Promise<PinnedMessageResult>
The pinned message or null if none
Since
7.0.0
Example
Get pinned message
const result = await sdk.getPinnedMessage('anime');
if (result.message) {
console.log('Pinned:', result.message.content);
} else {
console.log('No message pinned');
}
get pinned message token name result
pinMessage()
pinMessage(
id):Promise<PinMessageResult>
Pin a message.
Requires JWT authentication with owner or moderator role. Only one message can be pinned per token at a time.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | Message ID to pin |
Returns
Promise<PinMessageResult>
Success indicator
Throws
ValidationError if ID is invalid
Throws
ConfigurationError if JWT is not configured
Since
7.0.0
Example
Pin a message
await sdk.pinMessage('msg-1234567890123-abc...');
console.log('Message pinned');
pin message result
unpinMessage()
unpinMessage(
id):Promise<PinMessageResult>
Unpin a message.
Requires JWT authentication with owner or moderator role.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | Message ID to unpin |
Returns
Promise<PinMessageResult>
Success indicator
Throws
ValidationError if ID is invalid
Throws
ConfigurationError if JWT is not configured
Since
7.0.0
Example
Unpin a message
await sdk.unpinMessage('msg-1234567890123-abc...');
console.log('Message unpinned');
unpin message pin result
updateMessage()
updateMessage<
T>(id,options):Promise<UpdateMessageResult<T>>
Update a message's content.
Requires JWT authentication. Only the message author can update.
Type Parameters
| Type Parameter | Default type |
|---|---|
T extends MessageType | MessageType |
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | Message ID to update |
options | UpdateMessageOptions<T> | Update options including new content |
Returns
Promise<UpdateMessageResult<T>>
The updated message
Throws
ValidationError if ID or content is invalid
Throws
ConfigurationError if JWT is not configured
Since
7.0.0
Example
Update a message
const result = await sdk.updateMessage('msg-1234567890123-abc...', {
content: 'Updated message content',
type: 'COMMENT'
});
console.log('Updated at:', result.message.updatedAt);
update message result type options
Moderation
createBan()
createBan(
options):Promise<CreateBanResult>
Create a ban for a user on a token.
Bans a user from participating in chat, comments, and reactions for the specified token. Can be temporary (with duration) or permanent.
Supports dual authentication:
- Admin (API key): Can ban any user on any token
- Owner (JWT): Can ban users on their own token
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CreateBanOptions | Ban creation options |
Returns
Promise<CreateBanResult>
Promise resolving to the created ban
Throws
Error if neither admin API key nor JWT is configured
Since
5.5.0
Examples
Ban a user permanently
const result = await sdk.createBan({
tokenName: 'mytoken',
userAddress: 'eth|abc123...',
reason: 'Spam',
});
console.log(`Banned: ${result.ban.userAddress}`);
Ban a user for 24 hours
const result = await sdk.createBan({
tokenName: 'mytoken',
userAddress: 'eth|abc123...',
reason: 'Warning for inappropriate content',
durationSeconds: 86400, // 24 hours
});
console.log(`Expires: ${result.ban.expiresAt}`);
create ban result options
createGlobalBan()
createGlobalBan(
options):Promise<CreateGlobalBanResult>
Create a global user ban (bans user from all tokens on the platform).
Global bans prevent a user from accessing any token, participating in streams, chat, or comments across the entire platform.
Requires admin API key or Overseer JWT authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CreateGlobalBanOptions | Global ban creation options |
Returns
Promise<CreateGlobalBanResult>
Promise resolving to created ban data
Throws
ValidationError if options are invalid
Throws
ConfigurationError if admin API key or JWT is not configured
Since
6.x.0
Examples
Permanent global ban
const result = await sdk.createGlobalBan({
userAddress: 'eth|123...',
reason: 'Serious platform violation'
});
console.log('User globally banned:', result.ban.userAddress);
Temporary global ban (7 days)
const result = await sdk.createGlobalBan({
userAddress: 'eth|123...',
reason: 'Spam across multiple streams',
durationSeconds: 604800 // 7 days
});
console.log('Ban expires:', result.ban.expiresAt);
create global ban result options
getActiveModerators()
getActiveModerators(
tokenName):Promise<object[]>
Get the roster of active (already-accepted) moderators for a token.
There is no dedicated "active moderators" endpoint - a moderator's invite record IS their moderator record. This lists invites for the token with status 'CLAIMED', which is exactly the set of currently-active moderators (a PENDING invite has not been accepted yet; REVOKED/EXPIRED are no longer active).
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token to fetch the moderator roster for |
Returns
Promise<object[]>
Active moderators, with the invite's role, claimedBy address, and claimedAt date
Since
7.1.0
get active moderators token name
getActiveUsers()
getActiveUsers(
options):Promise<ActiveUsersResult>
Get active users for a token.
Returns a list of users currently viewing or participating in a stream. Can filter by viewer type (all viewers or only chat participants).
Returns up to 1000 users. If more are connected, the truncated flag
will be true.
Supports dual authentication:
- Admin (API key): Can get users for any token
- Owner (JWT): Can get users for their own token
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetActiveUsersOptions | Active users options |
Returns
Promise<ActiveUsersResult>
Promise resolving to active users list
Throws
Error if neither admin API key nor JWT is configured
Since
5.5.0
Examples
Get all viewers
const result = await sdk.getActiveUsers({
tokenName: 'mytoken',
type: 'viewers',
});
console.log(`${result.total} viewers online`);
if (result.truncated) {
console.log('More than 1000 users, list truncated');
}
Search for a specific user
const result = await sdk.getActiveUsers({
tokenName: 'mytoken',
type: 'chat_participants',
search: 'alice', // Filter by address or name
});
get active users result options
getBanStatus()
getBanStatus(
options):Promise<BanStatusResult>
Get ban status for a specific user on a token.
Checks if a user is currently banned and returns ban details if so.
Supports dual authentication:
- Admin (API key): Can check any user on any token
- Owner (JWT): Can check users on their own token
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetBanStatusOptions | Status check options |
Returns
Promise<BanStatusResult>
Promise resolving to ban status
Throws
Error if neither admin API key nor JWT is configured
Since
5.5.0
Example
Check if user is banned
const status = await sdk.getBanStatus({
tokenName: 'mytoken',
userAddress: 'eth|abc123...',
});
if (status.banned) {
console.log(`Banned for: ${status.ban?.reason}`);
console.log(`Expires: ${status.ban?.expiresAt ?? 'permanent'}`);
}
get ban status result options
getGlobalBan()
getGlobalBan(
options):Promise<GlobalBanStatusResult>
Get global ban status for a specific user.
Requires admin API key or Overseer JWT authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetGlobalBanOptions | Global ban status options |
Returns
Promise<GlobalBanStatusResult>
Promise resolving to ban status (banned or not) with ban data if applicable
Throws
ValidationError if options are invalid
Throws
ConfigurationError if admin API key or JWT is not configured
Since
6.x.0
Example
const status = await sdk.getGlobalBan({
userAddress: 'eth|123...'
});
if (status.banned) {
console.log('User is globally banned');
console.log('Reason:', status.ban?.reason);
console.log('Expires:', status.ban?.expiresAt ?? 'permanent');
}
get global ban status result options
listBans()
listBans(
options):Promise<BanListResult>
List all bans for a token.
Returns a paginated list of banned users with their profile information, ban reasons, and expiration times.
Supports dual authentication:
- Admin (API key): Can list bans for any token
- Owner (JWT): Can list bans for their own token
Parameters
| Parameter | Type | Description |
|---|---|---|
options | ListBansOptions | List options including pagination and filters |
Returns
Promise<BanListResult>
Promise resolving to paginated ban list
Throws
Error if neither admin API key nor JWT is configured
Since
5.5.0
Examples
List all bans
const result = await sdk.listBans({ tokenName: 'mytoken' });
console.log(`Total bans: ${result.pageInfo.totalCount}`);
result.bans.forEach(ban => {
console.log(`${ban.userAddress}: ${ban.reason}`);
});
Search bans by user
const result = await sdk.listBans({
tokenName: 'mytoken',
search: 'alice', // Search by address or name
pageSize: 20,
});
list bans ban result options
listGlobalBans()
listGlobalBans(
options?):Promise<GlobalBanListResult>
List all global user bans on the platform.
Returns paginated results with user profile information. Supports filtering by user address or name.
Requires admin API key or Overseer JWT authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | ListGlobalBansOptions | List options with optional pagination and filters |
Returns
Promise<GlobalBanListResult>
Promise resolving to paginated list of global bans
Throws
ValidationError if options are invalid
Throws
ConfigurationError if admin API key or JWT is not configured
Since
6.x.0
Examples
Get first page of global bans
const result = await sdk.listGlobalBans({
pageSize: 20
});
console.log('Total global bans:', result.pageInfo.totalCount);
result.items.forEach(ban => {
console.log(`${ban.userAddress}: ${ban.reason}`);
});
Search for banned user
const result = await sdk.listGlobalBans({
userAddress: 'eth|123...',
pageSize: 10
});
list global bans ban result options
removeBan()
removeBan(
options):Promise<RemoveBanResult>
Remove a ban for a user on a token.
Unbans a user, allowing them to participate in chat, comments, and reactions again.
Supports dual authentication:
- Admin (API key): Can unban any user on any token
- Owner (JWT): Can unban users on their own token
Parameters
| Parameter | Type | Description |
|---|---|---|
options | RemoveBanOptions | Ban removal options |
Returns
Promise<RemoveBanResult>
Promise resolving to removal confirmation
Throws
Error if neither admin API key nor JWT is configured
Throws
Error (404) if ban not found
Since
5.5.0
Example
Unban a user
const result = await sdk.removeBan({
tokenName: 'mytoken',
userAddress: 'eth|abc123...',
});
console.log(`Unbanned: ${result.removed}`);
remove ban result options
removeGlobalBan()
removeGlobalBan(
options):Promise<RemoveGlobalBanResult>
Remove a global user ban.
Requires admin API key or Overseer JWT authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | RemoveGlobalBanOptions | Global ban removal options |
Returns
Promise<RemoveGlobalBanResult>
Promise resolving to removal confirmation
Throws
ValidationError if options are invalid
Throws
ConfigurationError if admin API key or JWT is not configured
Throws
Error if ban not found
Since
6.x.0
Example
const result = await sdk.removeGlobalBan({
userAddress: 'eth|123...'
});
console.log('Global ban removed:', result.removed);
remove global ban result options
NFT Collections
claimNftCollection()
claimNftCollection(
params):Promise<ClaimCollectionResult>
Claim an NFT collection name
Parameters
| Parameter | Type | Description |
|---|---|---|
params | ClaimCollectionParams | Collection claim parameters |
Returns
Promise<ClaimCollectionResult>
Claim result with transaction ID
claim nft collection result params
createNftTokenClass()
createNftTokenClass(
params):Promise<CreateTokenClassResult>
Create a token class within an NFT collection
Parameters
| Parameter | Type | Description |
|---|---|---|
params | CreateTokenClassParams | Token class creation parameters |
Returns
Promise<CreateTokenClassResult>
Creation result with transaction ID
create nft token class result params
estimateNftMintFee()
estimateNftMintFee(
params):Promise<string>
Estimate minting fee for NFTs via DryRun
Parameters
| Parameter | Type | Description |
|---|---|---|
params | EstimateMintFeeParams | Mint parameters (collection, type, category, quantity, owner) |
Returns
Promise<string>
Estimated fee in GALA
estimate nft mint fee params
estimateNftOperationFees()
estimateNftOperationFees(
params):NftFeeEstimate
Calculate total fees for multiple NFT operations
Parameters
| Parameter | Type | Description |
|---|---|---|
params | EstimateNftFeesParams | Operations to estimate (claimCollection, createTokenClasses count) |
Returns
Fee breakdown with total
estimate nft operation fees fee params
fetchNftBalances()
fetchNftBalances(
ownerAddress,collectionFilter?):Promise<NftBalance[]>
Fetch NFT balances for an owner
Parameters
| Parameter | Type | Description |
|---|---|---|
ownerAddress | string | Owner wallet address |
collectionFilter? | string | Optional collection name to filter by |
Returns
Promise<NftBalance[]>
List of NFT balances
fetch nft balances owner address collection filter balance
fetchNftCollections()
fetchNftCollections(
walletAddress):Promise<NftCollectionAuthorization[]>
Fetch all NFT collections authorized to a user
Parameters
| Parameter | Type | Description |
|---|---|---|
walletAddress | string | Wallet address to fetch collections for |
Returns
Promise<NftCollectionAuthorization[]>
List of authorized collections
fetch nft collections wallet address collection authorization
fetchNftTokenClasses()
fetchNftTokenClasses(
params):Promise<NftTokenClassWithSupply[]>
Fetch token classes for a collection
Parameters
| Parameter | Type | Description |
|---|---|---|
params | FetchTokenClassesParams | Query parameters (collection, type, category) |
Returns
Promise<NftTokenClassWithSupply[]>
List of token classes with supply info
fetch nft token classes class with supply params
getNftCollectionClaimFee()
getNftCollectionClaimFee():
string
Get the fee to claim an NFT collection
Returns
string
Fee amount in GALA as string ("10000")
get nft collection claim fee
getNftTokenClassCreateFee()
getNftTokenClassCreateFee():
string
Get the fee to create a token class
Returns
string
Fee amount in GALA as string ("1000")
get nft token class create fee
isNftCollectionAvailable()
isNftCollectionAvailable(
collectionName):Promise<boolean>
Check if an NFT collection name is available
Parameters
| Parameter | Type | Description |
|---|---|---|
collectionName | string | Collection name to check |
Returns
Promise<boolean>
True if available, false if already claimed
is nft collection available name
mintNft()
mintNft(
params):Promise<MintNftResult>
Mint NFTs from a token class
Parameters
| Parameter | Type | Description |
|---|---|---|
params | MintNftParams | Minting parameters |
Returns
Promise<MintNftResult>
Minting result with transaction ID
mint nft result params
OEmbed
getHomeOEmbed()
getHomeOEmbed(
options?):Promise<GetHomeOEmbedJsonResult>
Get oEmbed metadata for the home page.
Returns oEmbed JSON data featuring the top/live token for social media previews.
Public endpoint - no authentication required.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | GetHomeOEmbedOptions | Optional parameters |
Returns
Promise<GetHomeOEmbedJsonResult>
oEmbed data with featured token info
Since
9.0.0
Example
Get home page oEmbed
const { oembed } = await sdk.getHomeOEmbed();
console.log('Site:', oembed.provider_name);
console.log('Featured:', oembed.featuredToken);
get home embed json result options
getPoolOEmbed()
getPoolOEmbed(
options):Promise<GetPoolOEmbedJsonResult>
Get oEmbed metadata for a pool/token page.
Returns oEmbed JSON data for a token's buy/sell page, including live stream status if applicable.
Public endpoint - no authentication required.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetPoolOEmbedOptions | Options with tokenName |
Returns
Promise<GetPoolOEmbedJsonResult>
oEmbed data with token info and live status
Throws
ValidationError if tokenName is missing or invalid
Since
9.0.0
Example
Get pool oEmbed
const { oembed } = await sdk.getPoolOEmbed({ tokenName: 'anime' });
console.log('Token:', oembed.tokenName);
console.log('Symbol:', oembed.symbol);
console.log('Live:', oembed.isLive);
get pool embed json result options
getProfileOEmbed()
getProfileOEmbed(
options):Promise<GetProfileOEmbedJsonResult>
Get oEmbed metadata for a user profile page.
Returns oEmbed JSON data for a user's profile including stats.
Public endpoint - no authentication required.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetProfileOEmbedOptions | Options with address |
Returns
Promise<GetProfileOEmbedJsonResult>
oEmbed data with user stats
Throws
ValidationError if address is missing or invalid
Since
9.0.0
Example
Get profile oEmbed
const { oembed } = await sdk.getProfileOEmbed({ address: 'eth|123...' });
console.log('User:', oembed.displayName);
console.log('Tokens created:', oembed.tokensCreated);
console.log('Volume:', oembed.totalVolumeGala);
get profile embed json result options
Other
launchpad
readonlylaunchpad:LaunchpadWrites
v6 launchpad write surface.
launchpad writes
DEFAULT_CALCULATE_AMOUNT_MODE
readonlystaticDEFAULT_CALCULATE_AMOUNT_MODE:"local"|"external"
Default calculation mode for all amount calculations - 'local' for instant client-side bonding curve calculations
default calculate amount mode
DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY
readonlystaticDEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:10000000
Default maximum total supply for launchpad tokens (10,000,000) - Used when token-specific maxSupply not provided
default launchpad token max supply
DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR
readonlystaticDEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:0.01=0.01
Default reverse bonding curve fee slippage factor (1%) - Applied to maxAcceptableReverseBondingCurveFee
default max acceptable reverse bonding curve fee slippage
DEFAULT_SLIPPAGE_TOLERANCE_FACTOR
readonlystaticDEFAULT_SLIPPAGE_TOLERANCE_FACTOR:0.15=0.15
Default slippage tolerance factor (15%) - Higher for volatile bonding curve tokens
default slippage tolerance factor
events
Get Signature
get events():
EventsBatcherService
Access the events tracking service for batching and flushing events
Lazy-initialized on first access.
Since
8.2.0
Returns
EventsBatcherService instance
events batcher service
burnTokens()
burnTokens(
data):Promise<BurnTokensResult>
Permanently burn (destroy) tokens on GalaChain
⚠️ WARNING: THIS OPERATION IS IRREVERSIBLE!
Once tokens are burned, they are permanently destroyed and cannot be recovered. The burned tokens are removed from circulation, reducing total supply.
Supports batch burning of multiple token types in a single transaction.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | BurnTokensData | Burn tokens parameters |
Returns
Promise<BurnTokensResult>
BurnTokensResult with transaction details and burned token info
Examples
Burn a single token by name
const result = await sdk.burnTokens({
tokens: [{ tokenName: 'anime', amount: '1000' }]
});
console.log('Burned:', result.burned);
Burn multiple tokens in one transaction
const result = await sdk.burnTokens({
tokens: [
{ tokenName: 'anime', amount: '500' },
{ tokenName: 'dragon', amount: '250' }
]
});
console.log('Burned:', result.burned.length, 'token types');
Burn by tokenId
const result = await sdk.burnTokens({
tokens: [{
tokenId: 'Token|Unit|ANIME|client:abc123',
amount: '1000'
}]
});
Throws
When token cannot be found, insufficient balance, or burn fails
Throws
When wallet is not configured
burn tokens result data
calculateBuyAmountForGraduation()
calculateBuyAmountForGraduation(
tokenNameOrOptions):Promise<GraduationCalculationResult>
Calculate buy amount needed to graduate a token pool
Convenience method that fetches pool details and calculates the exact
cost to buy all remaining tokens. Returns GraduationCalculationResult
which includes remainingTokens (the token quantity to buy).
Performance optimization: Provide currentSupply to avoid fetching pool details twice.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenNameOrOptions | string | CalculateBuyAmountForGraduationOptions | Token name string OR CalculateBuyAmountForGraduationOptions object |
Returns
Promise<GraduationCalculationResult>
Promise
Throws
ValidationError if token not found or already graduated
Examples
Basic usage
const result = await sdk.calculateBuyAmountForGraduation('mytoken');
console.log('Tokens to buy:', result.remainingTokens); // Token quantity
console.log('GALA required:', result.amount); // GALA cost
Performance-optimized with reused pool details
import { CALCULATION_MODES } from '@gala-chain/launchpad-sdk';
const poolDetails = await sdk.fetchPoolDetailsForCalculation('anime');
const result = await sdk.calculateBuyAmountForGraduation({
tokenName: 'anime',
calculateAmountMode: CALCULATION_MODES.LOCAL,
currentSupply: poolDetails.currentSupply
});
calculate buy amount for graduation token name or options calculation result remaining tokens
claimModeratorInvite()
claimModeratorInvite(
options):Promise<ClaimModeratorInviteResult>
Claim a moderator invite.
Claims an invite using the code from a magic link URL. The authenticated user's wallet becomes the moderator for the token with the specified role.
Requires JWT authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | ClaimModeratorInviteOptions | Claim options including the invite code |
Returns
Promise<ClaimModeratorInviteResult>
The token that was added to the user's moderated tokens
Example
const result = await sdk.claimModeratorInvite({
inviteCode: 'abc123def456...'
});
console.log('Now moderating:', result.token.tokenName);
console.log('Role:', result.token.role);
Since
5.7.0
claim moderator invite result options
convertTokenNameToTokenClassKey()
convertTokenNameToTokenClassKey(
tokenName):Promise<GalaChainTokenClassKey>
Convert token name to TokenClassKey (explicit alias for resolveTokenClassKey)
convert token name to class key gala chain
CRITICAL: TokenClassKey is NOT Derivable from TokenName!
This is an explicit alias emphasizing that resolution is REQUIRED - never guess.
The relationship between token name and TokenClassKey is NOT PREDICTABLE:
tokenName: "anime"does NOT meantype: "ANIME"(could be "ANM", "ANIM", etc.)- The
additionalKeycontains the creator's ETH address - impossible to guess
ALWAYS use this method. Never construct TokenClassKey manually from a token name.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to convert (e.g., 'anime', 'dragon') |
Returns
Promise<GalaChainTokenClassKey>
Promise
Example
// ✅ CORRECT - Always use this method
const tokenClassKey = await sdk.convertTokenNameToTokenClassKey('anime');
// Returns: { collection: "Token", category: "Unit", type: "ANM", additionalKey: "eth:0x..." }
// ❌ WRONG - Never do this!
const tokenClassKey = {
collection: "Token",
category: "Unit",
type: "ANIME", // WRONG! Might be "ANM" or anything
additionalKey: "???" // IMPOSSIBLE to guess!
};
Throws
When token name cannot be resolved
token class key name additional gala chain
createApiKey()
createApiKey(
options):Promise<CreateApiKeyResponse>
Create a new API key.
CRITICAL: The rawKey in the response is ONLY shown once!
Store it securely immediately - it cannot be retrieved again.
API keys enable delegation of specific permissions to third-party services or automated systems without sharing full account access.
Requires JWT authentication - call sdk.login() first.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CreateApiKeyOptions | API key creation options |
Returns
Promise<CreateApiKeyResponse>
Created API key with raw key (shown only once)
Throws
ValidationError if options are invalid
Throws
ConfigurationError if JWT auth is not configured
Example
// Create a moderator key for chat management
const result = await sdk.createApiKey({
role: 'MODERATOR',
description: 'Twitch chat bot integration',
tokenNames: ['mytoken', 'othertoken']
});
// CRITICAL: Save this immediately!
console.log('API Key:', result.rawKey);
// Format: glp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Create an owner key for full access to all tokens
const ownerKey = await sdk.createApiKey({
role: 'OWNER',
description: 'Production automation',
delegateAllTokens: true,
expiresAt: '2025-12-31T23:59:59Z'
});
Since
5.6.0
create api key response raw options
createModeratorInvite()
createModeratorInvite(
options):Promise<CreateModeratorInviteResult>
Create a moderator invite for a token.
Creates a magic link invite that can be shared with someone to grant them moderator access to the specified token. The recipient claims the invite after logging in, and their wallet becomes linked as a moderator.
Requires JWT authentication - must be the token owner.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CreateModeratorInviteOptions | Create invite options including tokenName, role, and optional description/expiration |
Returns
Promise<CreateModeratorInviteResult>
The created invite including the magic link URL
Example
const result = await sdk.createModeratorInvite({
tokenName: 'mytoken',
role: 'MODERATOR',
description: 'John - Friday evening shows'
});
console.log('Share this link:', result.invite.inviteUrl);
Since
5.7.0
create moderator invite result options
emitBalanceUpdated()
emitBalanceUpdated(
userAddress,tokenName,payload):Promise<void>
Emit a balance update to a specific user (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
userAddress | string |
tokenName | string |
payload | BalanceUpdatedPayload |
Returns
Promise<void>
emit balance updated user address token name payload
emitChatMessage()
emitChatMessage(
tokenName,payload):Promise<void>
Emit chat message event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | ChatMessagePayload |
Returns
Promise<void>
emit chat message token name payload
emitChatStatus()
emitChatStatus(
tokenName,payload):Promise<void>
Emit chat status event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | ChatStatusPayload |
Returns
Promise<void>
emit chat status token name payload
emitFeatureStatus()
emitFeatureStatus(
payload):Promise<void>
Emit feature status changed event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
payload | FeatureStatusPayload |
Returns
Promise<void>
emit feature status payload
emitModeratorAdded()
emitModeratorAdded(
tokenName,payload):Promise<void>
Emit moderator added event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | ModeratorAddedPayload |
Returns
Promise<void>
emit moderator added token name payload
emitModeratorRemoved()
emitModeratorRemoved(
tokenName,payload):Promise<void>
Emit moderator removed event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | ModeratorRemovedPayload |
Returns
Promise<void>
emit moderator removed token name payload
emitSiteConfigChanged()
emitSiteConfigChanged(
payload):Promise<void>
Emit site configuration changed event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
payload | SiteConfigChangedPayload |
Returns
Promise<void>
emit site config changed payload
emitStreamCountdown()
emitStreamCountdown(
tokenName,payload):Promise<void>
Emit stream countdown event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | StreamCountdownPayload |
Returns
Promise<void>
emit stream countdown token name payload
emitStreamStatus()
emitStreamStatus(
tokenName,payload):Promise<void>
Emit stream status change event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | StreamStatusPayload |
Returns
Promise<void>
emit stream status token name payload
emitTokenBanned()
emitTokenBanned(
tokenName,payload):Promise<void>
Emit token banned event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | TokenBannedPayload |
Returns
Promise<void>
emit token banned name payload
emitTokenUnbanned()
emitTokenUnbanned(
tokenName,payload):Promise<void>
Emit token unbanned event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | TokenUnbannedPayload |
Returns
Promise<void>
emit token unbanned name payload
emitTypingIndicator()
emitTypingIndicator(
tokenName,payload):Promise<void>
Emit typing indicator event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | TypingIndicatorPayload |
Returns
Promise<void>
emit typing indicator token name payload
emitUserProfileUpdated()
emitUserProfileUpdated(
userAddress,payload):Promise<void>
Emit user profile updated event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
userAddress | string |
payload | UserProfileUpdatedPayload |
Returns
Promise<void>
emit user profile updated address payload
emitViewerCount()
emitViewerCount(
tokenName,payload):Promise<void>
Emit viewer count update event (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | ViewerCountPayload |
Returns
Promise<void>
emit viewer count token name payload
fetchAvailableBalance()
fetchAvailableBalance(
options):Promise<AvailableBalanceResult|null>
Fetch available (unlocked, not in-use) balance for a token
Returns the portion of balance that is not locked or in use. Requires tokenId (not tokenName) for accurate calculations with lock details.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | FetchTokenBalanceOptions | Balance query options |
Returns
Promise<AvailableBalanceResult | null>
Promise<AvailableBalanceResult | null> Available balance details or null if no balance
Example
const available = await sdk.fetchAvailableBalance({
address: sdk.getAddress(),
tokenId: 'GALA|Unit|none|none'
});
if (available) {
console.log('Total:', available.totalQuantity);
console.log('Available:', available.availableQuantity);
}
fetch available balance result token options
fetchClientFlags()
fetchClientFlags():
Promise<GetClientFlagsResult>
Get client feature flags.
Returns feature flag overrides for the native mobile app. No authentication required (public endpoint).
Returns
Promise<GetClientFlagsResult>
Client feature flags
Example
const { flags } = await sdk.fetchClientFlags();
console.log('Push notifications:', flags.PUSH_NOTIFICATIONS);
console.log('Dark mode:', flags.DARK_MODE);
console.log('DEX trading:', flags.DEX_TRADING);
fetch client flags get result
fetchEthereumWalletAllBalances()
fetchEthereumWalletAllBalances(
address?):Promise<EthereumWalletBalanceResult>
Fetch all supported token balances on Ethereum for a wallet.
Returns native ETH balance plus all supported ERC-20 token balances in a single call: GALA, GWETH, GUSDC, GUSDT, GWTRX, GWBTC
This method fetches all balances in parallel (7 RPC calls).
For checking a single token, use fetchEthereumWalletTokenBalance() (more efficient).
Parameters
| Parameter | Type | Description |
|---|---|---|
address? | string | Ethereum address (0x format). Defaults to configured wallet address. |
Returns
Promise<EthereumWalletBalanceResult>
Complete balance breakdown including native ETH and all supported tokens
Throws
Error if Ethereum bridge is not configured
Examples
Fetch all balances for configured wallet
const balances = await sdk.fetchEthereumWalletAllBalances();
console.log(`ETH: ${balances.native.quantity}`);
console.log(`GALA: ${balances.tokens.find(t => t.symbol === 'GALA')?.quantity}`);
Fetch all balances for specific address
const balances = await sdk.fetchEthereumWalletAllBalances('0x742d35Cc6634C0532925a3b8D0Ea2c76f94C31C0');
for (const token of balances.tokens) {
console.log(`${token.symbol}: ${token.quantity}`);
}
fetch ethereum wallet all balances balance result token
fetchEthereumWalletNativeBalance()
fetchEthereumWalletNativeBalance(
address?):Promise<ExternalChainBalance>
Fetch native ETH balance on Ethereum.
Efficient method for checking ETH balance only (1 RPC call).
Use fetchEthereumWalletAllBalances() for complete portfolio view.
Parameters
| Parameter | Type | Description |
|---|---|---|
address? | string | Ethereum address (0x format). Defaults to configured wallet. |
Returns
Promise<ExternalChainBalance>
Native ETH balance with metadata
Throws
Error if Ethereum bridge is not configured
Example
Check ETH balance (for gas fees)
const eth = await sdk.fetchEthereumWalletNativeBalance();
console.log(`ETH for gas: ${eth.quantity}`);
fetch ethereum wallet native balance external chain all balances
fetchEthereumWalletTokenBalance()
fetchEthereumWalletTokenBalance(
symbol,address?):Promise<ExternalChainBalance>
Fetch a single ERC-20 token balance on Ethereum.
Efficient method for checking a specific token balance (1 RPC call).
Use fetchEthereumWalletAllBalances() for complete portfolio view.
Parameters
| Parameter | Type | Description |
|---|---|---|
symbol | string | Token symbol (GALA, GWETH, GUSDC, GUSDT, GWTRX, GWBTC) |
address? | string | Ethereum address (0x format). Defaults to configured wallet. |
Returns
Promise<ExternalChainBalance>
Single token balance with metadata
Throws
Error if Ethereum bridge is not configured or token is not supported
Examples
Check GALA balance on Ethereum
const gala = await sdk.fetchEthereumWalletTokenBalance('GALA');
console.log(`GALA on Ethereum: ${gala.quantity}`);
Check specific address
const gusdc = await sdk.fetchEthereumWalletTokenBalance('GUSDC', '0x742d35Cc...');
console.log(`GUSDC: ${gusdc.quantity} (${gusdc.decimals} decimals)`);
fetch ethereum wallet token balance external chain all balances
fetchLaunchTokenFee()
fetchLaunchTokenFee():
Promise<number>
Fetch the current launchpad token launch fee
Returns the GALA fee amount required to launch a new token.
This fee is dynamic and may vary based on network conditions.
Call this before launching a token to ensure you have sufficient balance.
Served by the launchpad backend (GET /v1/trading/fee, cached 1 hour); identical to
LaunchpadSDK.fetchLaunchpadFee.
Returns
Promise<number>
Promise
Throws
Network errors from connection failures or timeouts
Throws
If the backend returns an error response
Example
const fee = await sdk.fetchLaunchTokenFee();
console.log(`Token launch fee: ${fee} GALA`);
// Check if wallet has sufficient balance
const balance = await sdk.fetchGalaBalance();
if (parseFloat(balance.quantity) >= fee) {
console.log('Sufficient balance to launch token');
}
fetch launch token fee
fetchLockedBalance()
fetchLockedBalance(
options):Promise<LockedBalanceResult|null>
Fetch only locked balance for a token
Returns focused information about locked tokens including lock details. Requires tokenId (not tokenName) as lock details are only available from GalaChain.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | FetchTokenBalanceOptions | Balance query options (must include tokenId, not tokenName) |
Returns
Promise<LockedBalanceResult | null>
Promise<LockedBalanceResult | null> Locked balance details or null if no balance
Throws
Error if tokenName is provided (lock details require tokenId)
Example
const locked = await sdk.fetchLockedBalance({
address: sdk.getAddress(),
tokenId: 'GALA|Unit|none|none'
});
if (locked) {
console.log('Locked quantity:', locked.lockedQuantity);
locked.lockedHolds.forEach(hold => {
console.log(`Lock by ${hold.lockAuthority}: ${hold.quantity}`);
});
}
fetch locked balance result token options
fetchNotificationPreferences()
fetchNotificationPreferences():
Promise<GetNotificationPreferencesResult>
Get notification preferences for the authenticated user.
Returns the current push notification preference settings.
Authentication: Requires JWT auth (call sdk.login() first).
Returns
Promise<GetNotificationPreferencesResult>
Current notification preferences
Example
const { preferences } = await sdk.fetchNotificationPreferences();
console.log('Trades:', preferences.tradesEnabled);
console.log('Streams:', preferences.streamsEnabled);
console.log('Chat:', preferences.chatEnabled);
console.log('System:', preferences.systemEnabled);
fetch notification preferences get result
fetchPoolDetails()
fetchPoolDetails(
tokenName):Promise<PoolDetailsData>
Fetch pool details for a token - returns complete bonding curve pool state
Delegates to fetchPoolDetailsForCalculation for normalized fee factors and computed values, then enriches with full pool data from the launchpad backend.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to fetch pool details for |
Returns
Promise<PoolDetailsData>
Promise
fetch pool details token name data
fetchSolanaWalletAllBalances()
fetchSolanaWalletAllBalances(
address?):Promise<SolanaWalletBalanceResult>
Fetch all supported token balances on Solana for a wallet.
Returns native SOL balance plus all supported SPL token balances in a single call: GALA, GSOL
This method fetches all balances in parallel (3 RPC calls).
For checking a single token, use fetchSolanaWalletTokenBalance() (more efficient).
Parameters
| Parameter | Type | Description |
|---|---|---|
address? | string | Solana address (base58 format). Defaults to configured wallet address. |
Returns
Promise<SolanaWalletBalanceResult>
Complete balance breakdown including native SOL and all supported tokens
Throws
Error if Solana bridge is not configured
Examples
Fetch all balances for configured wallet
const balances = await sdk.fetchSolanaWalletAllBalances();
console.log(`SOL: ${balances.native.quantity}`);
console.log(`GALA: ${balances.tokens.find(t => t.symbol === 'GALA')?.quantity}`);
Fetch all balances for specific address
const balances = await sdk.fetchSolanaWalletAllBalances('7dMM...base58address');
for (const token of balances.tokens) {
console.log(`${token.symbol}: ${token.quantity}`);
}
fetch solana wallet all balances balance result token
fetchSolanaWalletNativeBalance()
fetchSolanaWalletNativeBalance(
address?):Promise<ExternalChainBalance>
Fetch native SOL balance on Solana.
Efficient method for checking SOL balance only (1 RPC call).
Use fetchSolanaWalletAllBalances() for complete portfolio view.
Parameters
| Parameter | Type | Description |
|---|---|---|
address? | string | Solana address (base58 format). Defaults to configured wallet. |
Returns
Promise<ExternalChainBalance>
Native SOL balance with metadata
Throws
Error if Solana bridge is not configured
Example
Check SOL balance (for transaction fees)
const sol = await sdk.fetchSolanaWalletNativeBalance();
console.log(`SOL for fees: ${sol.quantity}`);
fetch solana wallet native balance external chain all balances
fetchSolanaWalletTokenBalance()
fetchSolanaWalletTokenBalance(
symbol,address?):Promise<ExternalChainBalance>
Fetch a single SPL token balance on Solana.
Efficient method for checking a specific token balance (1 RPC call).
Use fetchSolanaWalletAllBalances() for complete portfolio view.
Parameters
| Parameter | Type | Description |
|---|---|---|
symbol | string | Token symbol (GALA, GSOL) |
address? | string | Solana address (base58 format). Defaults to configured wallet. |
Returns
Promise<ExternalChainBalance>
Single token balance with metadata
Throws
Error if Solana bridge is not configured or token is not supported
Example
Check GALA balance on Solana
const gala = await sdk.fetchSolanaWalletTokenBalance('GALA');
console.log(`GALA on Solana: ${gala.quantity}`);
fetch solana wallet token balance external chain all balances
fetchTokenBalance()
fetchTokenBalance(
options):Promise<TokenBalanceResult|null>
Fetch token balance from GalaChain (published tokens) or DEX API (launchpad tokens)
This method queries either the GalaChain gateway directly for published tokens or the DEX API for launchpad tokens, providing reliable results.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | FetchTokenBalanceOptions | Token balance options with flexible token identification |
Returns
Promise<TokenBalanceResult | null>
Promise<TokenBalanceResult | null>
Example
// Using string format
const galaBalance = await sdk.fetchTokenBalance({
address: sdk.getAddress(),
tokenId: "GALA|Unit|none|none"
});
// Using TokenClassKey object
const tokenClass = await sdk.resolveTokenClassKey('unicorn');
const unicornBalance = await sdk.fetchTokenBalance({
address: sdk.getAddress(),
tokenClassKey: tokenClass
});
// Using TokenInstanceKey object
const unicornBalance2 = await sdk.fetchTokenBalance({
address: sdk.getAddress(),
tokenId: {
collection: "Token",
category: "Unit",
type: "UNI",
additionalKey: "eth:9401b171307bE656f00F9e18DF756643FD3a91dE",
instance: "0"
}
});
// Using token name for convenience
const unicornBalance3 = await sdk.fetchTokenBalance({
address: sdk.getAddress(),
tokenName: "unicorn"
});
fetch token balance result options
fetchTokenDetails()
fetchTokenDetails(
tokenId):Promise<GalaChainTokenDetails>
Fetch comprehensive token details from GalaChain
Reads the token's GalaChain token class (symbol, decimals, name, image, description, network, contract address).
Supports flexible token identification using either string or object format:
- String:
'GUSDC|Unit|none|eth:0x...'(pipe-delimited) - Object:
{ collection, category, type, additionalKey }
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenId | TokenId | Token identifier in flexible format |
Returns
Promise<GalaChainTokenDetails>
Promise
Examples
String format
const details = await sdk.fetchTokenDetails('GUSDC|Unit|none|none');
console.log(details.symbol); // 'GUSDC'
console.log(details.decimals); // 6
console.log(details.network); // the token's network
console.log(details.image); // 'https://...'
Object format
const details = await sdk.fetchTokenDetails({
collection: 'GUSDC',
category: 'Unit',
type: 'none',
additionalKey: 'none'
});
Throws
If tokenId format is invalid
Throws
If API request fails or token not found
fetch token details id gala chain additional key
fetchTokenPrice()
fetchTokenPrice(
params):Promise<TokenSpotPrice>
Fetch a launchpad token's USD spot price.
- A token still on its bonding curve: GALA's USD price divided by the tokens 1 GALA buys (the launchpad backend's bonding-curve calculation).
- A graduated token: its USD price on the swap backend.
Only launchpad tokens (by name) are priced here. Any token by class key, and GALA itself, is
priced by gswap-sdk: gSwap.market.getPrice('GALA|Unit|none|none').
Parameters
| Parameter | Type | Description |
|---|---|---|
params | FetchTokenSpotPriceParams | The launchpad token's name |
Returns
Promise<TokenSpotPrice>
Promise
Example
const price = await sdk.fetchTokenPrice({ tokenName: 'galadog' });
console.log(`${price.symbol}: $${price.price.toFixed(6)}`);
Throws
ValidationError if tokenName is missing or empty, or a tokenId is given
Throws
NetworkError if the calculation or a price read fails
fetch token price spot get params name id
fetchTokensCreated()
fetchTokensCreated(
options?):Promise<UserTokenListResult>
Fetch tokens created by the current user with optional filtering
Retrieves a paginated list of tokens created by the authenticated user. Uses backend search, then applies exact tokenName matching to the returned page.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | FetchTokensCreatedOptions | Token list options with filtering support |
Returns
Promise<UserTokenListResult>
Promise
Example
// Fetch all created tokens with pagination
const myTokens = await sdk.fetchTokensCreated({ pageSize: 20 });
// Exact match for a specific created token (most efficient)
const myToken = await sdk.fetchTokensCreated({ tokenName: 'mytoken', pageSize: 1 });
// Fuzzy search through created tokens
const testTokens = await sdk.fetchTokensCreated({ search: 'test', pageSize: 10 });
Remarks
- Use
tokenNamefor exact lookups when you know the token name (fastest) - Use
searchfor discovery when exploring your created tokens searchis applied by the backend;tokenNameis matched locally- If both are supplied, the returned page must satisfy both filters
fetch tokens created user token list result options name
fetchTokensHeld()
fetchTokensHeld(
options?):Promise<UserTokenListResult>
Fetch tokens held by user with optional filtering
Retrieves a paginated list of tokens held by the authenticated user. Uses backend search and exact tokenName filters for holdings.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | FetchTokensHeldOptions | Token list options with filtering support |
Returns
Promise<UserTokenListResult>
Promise
Example
// Fetch all tokens with pagination
const allTokens = await sdk.fetchTokensHeld({ pageSize: 20 });
// Exact match for a specific token (most efficient)
const anime = await sdk.fetchTokensHeld({ tokenName: 'anime', pageSize: 1 });
// Fuzzy search for exploration
const dragons = await sdk.fetchTokensHeld({ search: 'dragon', pageSize: 10 });
Remarks
- Use
tokenNamefor exact lookups when you know the token name (fastest) - Use
searchfor discovery when exploring available tokens - Both filters are applied by the backend
- Passing both parameters together is discouraged
fetch tokens held user token list result options name
getApiKey()
getApiKey(
id):Promise<ApiKeyData>
Get a single API key by ID.
Returns the API key metadata. Raw key is never included.
Requires JWT authentication - call sdk.login() first.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | number | API key ID |
Returns
Promise<ApiKeyData>
API key data
Throws
ValidationError if ID is invalid
Throws
ConfigurationError if JWT auth is not configured
Throws
Error if API key not found (404)
Example
const key = await sdk.getApiKey(123);
console.log(`Key ${key.keyPrefix}: ${key.role}`);
console.log(`Description: ${key.description}`);
console.log(`Delegate all tokens: ${key.delegateAllTokens}`);
console.log(`Token names: ${key.tokenNames.join(', ')}`);
Since
5.6.0
get api key data
getApiKeyRoles()
getApiKeyRoles():
string[]
Get all valid API key roles.
Returns the list of available roles for API keys. Useful for UI dropdowns or validation.
Returns
string[]
Array of valid role strings
Example
const roles = sdk.getApiKeyRoles();
console.log('Available roles:', roles);
// ['MODERATOR', 'TECHNICAL_PRODUCER', 'MANAGER', 'OWNER']
Since
5.6.0
get api key roles
getBundlerTransactionResult()
getBundlerTransactionResult(
transactionId):Promise<ApiResponse<unknown>>
Get bundle transaction result
Returns a lightweight status check for a bundle transaction via HTTP (not WebSocket). Useful for checking transaction status when WebSocket monitoring times out or to get a definitive answer on transaction state.
Response format: { id: string, method: string, status: string }
Parameters
| Parameter | Type | Description |
|---|---|---|
transactionId | string | Transaction ID from buy(), sell(), or launchToken() |
Returns
Promise<ApiResponse<unknown>>
Promise with transaction result containing id, method, and status
Example
// Check status of a transaction
const result = await sdk.getBundlerTransactionResult('3c7d9f79-a496-4794-abaf-d6bd13473ff7');
console.log('Status:', result.data.status); // "COMPLETED", "FAILED", "PENDING", "PROCESSING"
console.log('Method:', result.data.method); // "SellExactToken", "BuyWithNative", etc.
get bundler transaction result id api response
getConnectedClients()
getConnectedClients(
options?):Promise<ConnectedClientsResponse>
Get list of currently connected WebSocket clients (admin/overseer only)
Parameters
| Parameter | Type |
|---|---|
options? | GetConnectedClientsOptions |
Returns
Promise<ConnectedClientsResponse>
get connected clients response options
getEthereumTransactionStatus()
getEthereumTransactionStatus(
transactionHash):Promise<EthereumTransactionStatus>
Get the status of an Ethereum transaction by hash.
Queries Ethereum RPC directly using getTransactionReceipt() and getTransaction().
Use this to verify if a bridge or any Ethereum transaction succeeded after submission.
Status values:
pending- Transaction in mempool, not yet minedconfirmed- Mined with <12 confirmationsfinalized- Mined with 12+ confirmations (practical finality)not_found- Transaction hash not found on networkfailed- Transaction mined but reverted
Performance: Single synchronous RPC call sequence (no WebSocket required).
Parameters
| Parameter | Type | Description |
|---|---|---|
transactionHash | string | Ethereum transaction hash (0x + 64 hex characters) |
Returns
Promise<EthereumTransactionStatus>
Transaction status with confirmation details
Throws
Error if Ethereum bridge is not configured or hash format invalid
Examples
Check bridge transaction status
const bridgeResult = await sdk.bridgeOut({
tokenId: 'GALA|Unit|none|none',
amount: '100',
destinationChain: 'Ethereum',
recipientAddress: '0x1234...',
});
const status = await sdk.getEthereumTransactionStatus(bridgeResult.transactionHash);
console.log(`Status: ${status.status}`);
console.log(`Confirmations: ${status.confirmations}`);
if (status.status === 'finalized') {
console.log('Transaction is final (12+ confirmations)');
}
Polling pattern for finality
async function waitForFinality(txHash: string, maxAttempts = 30) {
for (let i = 0; i < maxAttempts; i++) {
const status = await sdk.getEthereumTransactionStatus(txHash);
if (status.status === 'finalized') return status;
if (status.status === 'failed') throw new Error(status.error);
await new Promise(r => setTimeout(r, 15000)); // ~15s per block
}
throw new Error('Transaction finality timeout');
}
get ethereum transaction status hash receipt not found
getModeratedTokens()
getModeratedTokens(
options?):Promise<ModeratedTokensResult>
Get all tokens the current user moderates.
Returns a paginated list of tokens where the authenticated user has claimed a moderator invite and has active access. Used for the /studio dashboard.
Requires JWT authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | BasePaginationOptions | Optional pagination options |
Returns
Promise<ModeratedTokensResult>
Paginated list of moderated tokens
Example
const result = await sdk.getModeratedTokens({ pageSize: 20 });
console.log('Moderating', result.pageInfo.totalCount, 'tokens');
for (const token of result.tokens) {
console.log(`- ${token.tokenName} (${token.role})`);
}
Since
5.7.0
get moderated tokens result base pagination options
getModeratorInviteByCode()
getModeratorInviteByCode(
inviteCode):Promise<PublicInviteInfo>
Get invite details by code (public endpoint).
Returns public information about an invite for the claim page. This is used by the frontend to display invite details before the user logs in to claim.
No authentication required.
Parameters
| Parameter | Type | Description |
|---|---|---|
inviteCode | string | The invite code from the magic link URL |
Returns
Promise<PublicInviteInfo>
Public invite information
Example
const info = await sdk.getModeratorInviteByCode('abc123def456...');
console.log(`Invited to moderate ${info.tokenName} as ${info.role}`);
console.log(`Invited by: ${info.invitedBy.fullName || info.invitedBy.address}`);
Since
5.7.0
get moderator invite by code public info
getOnlineOverseers()
getOnlineOverseers():
Promise<{clients:ConnectedClient[];count:number; }>
Get list of currently online overseers/admins
Returns
Promise<{ clients: ConnectedClient[]; count: number; }>
get online overseers connected client
getOnlineUsers()
getOnlineUsers(
userAddresses):Promise<{clients:object[];offline:string[];online:string[]; }>
Batch check which users from a list are currently online
Parameters
| Parameter | Type | Description |
|---|---|---|
userAddresses | string[] | Array of user wallet addresses (required, non-empty) |
Returns
Promise<{ clients: object[]; offline: string[]; online: string[]; }>
Object with online/offline arrays and client details
Throws
ConfigurationError if userAddresses is empty or invalid
Throws
NetworkError if API request fails
get online users user addresses
getSolanaTransactionStatus()
getSolanaTransactionStatus(
signature):Promise<SolanaTransactionStatus>
Get the status of a Solana transaction by signature.
This method queries the Solana RPC directly using getSignatureStatuses, which doesn't require WebSockets and works in Node.js environments. Use this to verify airdrop or bridge transactions after submission.
Requirements:
- Solana private key must be configured (
solanaPrivateKeyin config)
Parameters
| Parameter | Type | Description |
|---|---|---|
signature | string | Base58-encoded Solana transaction signature (87-88 characters) |
Returns
Promise<SolanaTransactionStatus>
Transaction status with:
- confirmed: Whether transaction has been successfully processed on-chain
- status: Confirmation level ('confirmed' | 'finalized' | 'processed' | 'not_found' | 'failed')
- slot: Block slot number (present when transaction is found)
- error: Error details if transaction failed
Throws
Error if Solana bridge not configured or signature format is invalid
Examples
Check airdrop status
const signature = await sdk.requestSolanaDevnetAirdrop(1);
// Wait a moment for transaction to propagate
await new Promise(r => setTimeout(r, 2000));
const status = await sdk.getSolanaTransactionStatus(signature);
if (status.confirmed) {
console.log(`Confirmed at slot ${status.slot}, level: ${status.status}`);
} else if (status.status === 'not_found') {
console.log('Transaction not yet visible, try again');
} else if (status.status === 'failed') {
console.log(`Transaction failed: ${status.error}`);
}
Polling pattern for confirmation
async function waitForConfirmation(signature: string, maxAttempts = 30) {
for (let i = 0; i < maxAttempts; i++) {
const status = await sdk.getSolanaTransactionStatus(signature);
if (status.confirmed) return status;
if (status.status === 'failed') throw new Error(status.error);
await new Promise(r => setTimeout(r, 2000));
}
throw new Error('Transaction confirmation timeout');
}
get solana transaction status private key
getTokenViewers()
getTokenViewers(
tokenName,options?):Promise<{authenticatedCount:number;clients:ConnectedClient[];count:number; }>
Get list of users currently viewing a specific token
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name |
options? | { authenticated?: boolean; limit?: number; } | Optional filtering options |
options.authenticated? | boolean | - |
options.limit? | number | - |
Returns
Promise<{ authenticatedCount: number; clients: ConnectedClient[]; count: number; }>
get token viewers name authenticated count connected client
getWalletProvider()
getWalletProvider():
WalletProvider|undefined
Returns the configured wallet provider (if any)
Returns
WalletProvider | undefined
The wallet provider or undefined if not configured
get wallet provider
graduateToken()
graduateToken(
options):Promise<TradeResult>
Graduate a token pool by buying all remaining tokens
Convenience method that combines calculateBuyAmountForGraduation + buy to graduate a token in a single call with WebSocket confirmation.
Performance optimization: Provide currentSupply to avoid fetching pool details twice.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GraduateTokenOptions | Graduation options with tokenName and optional slippage protection |
Returns
Promise<TradeResult>
Promise
Throws
ValidationError if token already graduated or parameters invalid
Examples
Basic usage
const result = await sdk.graduateToken({
tokenName: 'mytoken',
slippageToleranceFactor: 0.01
});
console.log('Graduation complete!');
console.log('Total cost:', result.totalFees);
Performance-optimized with reused pool details
import { CALCULATION_MODES } from '@gala-chain/launchpad-sdk';
const poolDetails = await sdk.fetchPoolDetailsForCalculation('anime');
const result = await sdk.graduateToken({
tokenName: 'anime',
calculateAmountMode: CALCULATION_MODES.LOCAL,
currentSupply: poolDetails.currentSupply,
slippageToleranceFactor: 0.01
});
graduate token trade result options
isUserOnline()
isUserOnline(
userAddress):Promise<{connectedAt?:string;online:boolean;rooms?:string[];socketId?:string; }>
Check if a specific user is currently online
Parameters
| Parameter | Type | Description |
|---|---|---|
userAddress | string | User's wallet address (required, non-empty) |
Returns
Promise<{ connectedAt?: string; online: boolean; rooms?: string[]; socketId?: string; }>
Online status with socket ID and rooms if connected
Throws
ConfigurationError if userAddress is empty
Throws
NetworkError if API request fails
is user online address connected at socket id
listApiKeys()
listApiKeys(
options?):Promise<ApiKeyListResponse>
List all API keys for the authenticated user.
Returns paginated list of API keys. Raw keys are never included - they are only shown once at creation time.
Requires JWT authentication - call sdk.login() first.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | ListApiKeysOptions | Optional pagination options |
Returns
Promise<ApiKeyListResponse>
Paginated list of API keys
Throws
ConfigurationError if JWT auth is not configured
Example
// List all API keys
const result = await sdk.listApiKeys();
console.log(`Total keys: ${result.pageInfo.totalCount}`);
for (const key of result.apiKeys) {
console.log(`${key.keyPrefix} - ${key.role} - ${key.description}`);
console.log(` Last used: ${key.lastUsedAt || 'Never'}`);
console.log(` Expires: ${key.expiresAt || 'Never'}`);
}
// Paginate through keys (cursor-based)
if (result.pageInfo.hasNextPage) {
const page2 = await sdk.listApiKeys({
cursor: result.pageInfo.endCursor ?? undefined,
pageSize: 10
});
}
Since
5.6.0
list api keys key response options
listModeratorInvites()
listModeratorInvites(
options):Promise<ModeratorInviteListResult>
List moderator invites.
Returns a paginated list of moderator invites. Behavior depends on tokenName:
- With tokenName: Returns invites for that specific token (verifies ownership)
- Without tokenName: Returns ALL invites created by the authenticated user across all tokens
Requires JWT authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | ListModeratorInvitesOptions | List options including optional tokenName, status filter, and pagination |
Returns
Promise<ModeratorInviteListResult>
Paginated list of invites
Example
// Get all invites across all tokens
const allInvites = await sdk.listModeratorInvites({});
// Get invites for a specific token
const result = await sdk.listModeratorInvites({ tokenName: 'mytoken' });
console.log('Total invites:', result.pageInfo.totalCount);
// Filter by status
const pending = await sdk.listModeratorInvites({
tokenName: 'mytoken',
status: 'PENDING'
});
Since
5.7.0
list moderator invites invite result options
lockTokens()
lockTokens(
data):Promise<LockTokensResult>
Lock tokens on GalaChain (batch operation)
Supports locking multiple token types in a single transaction. Places holds on tokens, preventing them from being transferred until unlocked. Useful for staking, escrow, vesting, or other hold scenarios.
The lock operation creates a hold that can only be released by the lock authority (defaults to the caller's address if not specified).
Parameters
| Parameter | Type | Description |
|---|---|---|
data | LockTokensData | Lock tokens parameters |
Returns
Promise<LockTokensResult>
LockTokensResult with transaction ID and locked token details
Examples
Lock a single token
const result = await sdk.lockTokens({
tokens: [{ tokenName: 'anime', amount: '1000' }]
});
console.log('Tokens locked:', result.locked);
Lock multiple tokens with different settings
const result = await sdk.lockTokens({
tokens: [
{ tokenName: 'anime', amount: '500', lockAuthority: 'eth|1234...' },
{ tokenName: 'dragon', amount: '250', expires: Date.now() + 86400000, name: 'vesting-lock' }
]
});
Throws
When validation fails or lock operation is rejected
Throws
When wallet is not configured
lock tokens result data
registerPushToken()
registerPushToken(
params):Promise<RegisterPushTokenResult>
Register a push notification device token.
Associates a push token (FCM or APNs) with the authenticated user. If the token already exists, it updates the associated device info.
Authentication: Requires JWT auth (call sdk.login() first).
Parameters
| Parameter | Type | Description |
|---|---|---|
params | RegisterPushTokenParams | Registration parameters (token, platform, optional deviceId) |
Returns
Promise<RegisterPushTokenResult>
Registration result
Example
const result = await sdk.registerPushToken({
token: 'fcm-device-token-abc123',
platform: 'android',
deviceId: 'pixel-7-main',
});
console.log('Registered:', result.registered);
register push token result params
requestSolanaDevnetAirdrop()
requestSolanaDevnetAirdrop(
amount?,address?):Promise<string>
Request SOL airdrop from Solana devnet faucet.
Only available in stage environment (Solana devnet) for testing purposes. Will throw an error if called in production environment.
Parameters
| Parameter | Type | Description |
|---|---|---|
amount? | number | Amount of SOL to request (default: 1, max: 2 per request) |
address? | string | Optional recipient Solana address (defaults to configured wallet) |
Returns
Promise<string>
Transaction signature
Throws
Error if not in stage environment, Solana not configured, or airdrop fails
Examples
Airdrop 1 SOL to configured wallet
const signature = await sdk.requestSolanaDevnetAirdrop();
console.log(`Airdrop complete: ${signature}`);
Airdrop specific amount to another address
const signature = await sdk.requestSolanaDevnetAirdrop(0.5, 'SomeAddress...');
request solana devnet airdrop
resolveTokenClassKey()
resolveTokenClassKey(
tokenName):Promise<GalaChainTokenClassKey>
Resolve token class key from token name
Public method to resolve a token name to its TokenClassKey object for caching or optimization patterns. Uses the same resolution logic as transferToken internally.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to resolve (e.g., 'unicorn', 'tinyevil') |
Returns
Promise<GalaChainTokenClassKey>
Promise
Example
const tokenClassKey = await sdk.resolveTokenClassKey('unicorn');
// Returns: {
// collection: "Token",
// category: "Unit",
// type: "UNI",
// additionalKey: "eth:9401b171307bE656f00F9e18DF756643FD3a91dE"
// }
// Can be cached and used later for direct operations
await sdk.transferToken({
to: 'eth|...',
tokenId: tokenClassKey, // Direct, no lookup
amount: '1'
});
await sdk.fetchTokenBalance({
address: sdk.getAddress(),
tokenClassKey: tokenClassKey // Same object format
});
Throws
When token name cannot be resolved
resolve token class key name gala chain
revokeApiKey()
revokeApiKey(
id):Promise<void>
Revoke an API key.
This performs a soft delete - the key becomes immediately unusable but is retained for audit purposes.
Requires JWT authentication - call sdk.login() first.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | number | API key ID to revoke |
Returns
Promise<void>
Throws
ValidationError if ID is invalid
Throws
ConfigurationError if JWT auth is not configured
Throws
Error if API key not found (404)
Example
// Revoke a compromised key
await sdk.revokeApiKey(123);
console.log('API key revoked');
// Key is now unusable
// Attempts to use it will fail with 401 Unauthorized
Since
5.6.0
revoke api key
revokeModeratorInvite()
revokeModeratorInvite(
inviteId):Promise<void>
Revoke a moderator invite.
Revokes an invite by ID, preventing it from being claimed. If already claimed, the moderator loses access to the token.
Requires JWT authentication - must be the token owner.
Parameters
| Parameter | Type | Description |
|---|---|---|
inviteId | number | The ID of the invite to revoke |
Returns
Promise<void>
Example
await sdk.revokeModeratorInvite(123);
console.log('Invite revoked');
Since
5.7.0
revoke moderator invite id
sell()
sell(
options):Promise<TradeResult>
Sell tokens with confirmation
Executes a sell order on the bonding curve and waits for blockchain confirmation, returning complete trade details including actual amounts traded and fees paid.
trade result
Token Format
Use simple tokenName (e.g., "anime"), NOT full TokenClassKey format.
This method is for bonding curve tokens only (pre-graduation). For DEX trading
of graduated tokens, use @gala-chain/gswap-sdk (new GSwap({ signer }).swaps.swap()) with full TokenClassKey format.
// ✅ CORRECT - Simple token name
await sdk.sell({ tokenName: 'anime', amount: '100', type: 'tokens', ... });
// ❌ WRONG - Do NOT use TokenClassKey format
await sdk.sell({ tokenName: 'Token|Unit|ANIME|...' }); // Error!
Parameters
| Parameter | Type | Description |
|---|---|---|
options | SellTokenOptions | Sell options with required tokenName and expectedAmount |
Returns
Promise<TradeResult>
Promise
Since
3.0.0 - Now returns TradeResult instead of basic response
Example
const result = await sdk.sell({
tokenName: 'mytoken',
amount: '500',
type: 'exact',
expectedAmount: '50',
slippageToleranceFactor: 0.05
});
console.log('Sold tokens:', result.inputAmount);
console.log('Received GALA:', result.outputAmount);
console.log('Fees paid:', result.totalFees);
token name sell options trade result
setWalletProvider()
setWalletProvider(
provider):void
Sets or updates the wallet provider for authentication
Use this method to dynamically configure wallet authentication after SDK initialization. This is the preferred method for browser wallet integrations.
Parameters
| Parameter | Type | Description |
|---|---|---|
provider | WalletProvider | undefined | The wallet provider to set (or undefined to clear) |
Returns
void
Example
import { ExternalWalletProvider, detectWallets } from '@gala-chain/gala-core-sdk/providers';
// Detect available wallets
const { wallets } = await detectWallets();
// Create provider from detected wallet
const provider = new ExternalWalletProvider(wallets[0].provider);
await provider.connect();
// Set on SDK
sdk.setWalletProvider(provider);
set wallet provider
transferGala()
transferGala(
data):Promise<GalaChainTransferReceipt>
Transfer GALA tokens between wallets
Transfers GALA tokens from the authenticated wallet to another wallet using GalaChain with EIP-712 signature authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | TransferGalaData | Transfer data including recipient address and amount |
Returns
Promise<GalaChainTransferReceipt>
PromisetransactionId
(x-transaction-id header) and optional blockNumber (x-block-number)
Example
// Transfer 1 GALA to another wallet
const { transactionId, blockNumber } = await sdk.transferGala({
recipientAddress: 'eth|1234567890abcdef1234567890abcdef12345678',
amount: '1' // 1 GALA in decimal format
});
console.log('GALA transfer successful!');
console.log('Transaction ID:', transactionId, 'block:', blockNumber);
// mainnet explorer: https://chainmeter.net/tx/index.html?tx=${transactionId}
transfer gala chain receipt data transaction id block number
transferToken()
transferToken(
data):Promise<GalaChainTransferReceipt>
Transfer launchpad tokens between wallets
Transfers launchpad tokens from the authenticated wallet to another wallet using GalaChain with EIP-712 signature authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | TransferTokenData | Transfer data including recipient address, token name, and amount |
Returns
Promise<GalaChainTransferReceipt>
PromisetransactionId + optional blockNumber
Example
// Transfer 100 TINYEVIL tokens to another wallet
const { transactionId, blockNumber } = await sdk.transferToken({
to: 'eth|9876543210fedcba9876543210fedcba98765432',
tokenName: 'tinyevil',
amount: '100' // Amount in decimal format
});
console.log('Token transfer successful!');
console.log('Transaction ID:', transactionId, 'block:', blockNumber);
transfer token gala chain receipt data transaction id block number
unlockTokens()
unlockTokens(
data):Promise<UnlockTokensResult>
Unlock previously locked tokens on GalaChain (batch operation)
Supports unlocking multiple token types in a single transaction. Releases token holds, making them available for transfer again. Must be signed by the lock authority (the address that locked the tokens or was designated as lock authority during the lock operation).
Parameters
| Parameter | Type | Description |
|---|---|---|
data | UnlockTokensData | Unlock tokens parameters |
Returns
Promise<UnlockTokensResult>
UnlockTokensResult with transaction ID and unlocked token details
Examples
Unlock a single token
const result = await sdk.unlockTokens({
tokens: [{ tokenName: 'anime', amount: '1000' }]
});
console.log('Tokens unlocked:', result.unlocked);
Unlock multiple tokens
const result = await sdk.unlockTokens({
tokens: [
{ tokenName: 'anime', amount: '500' },
{ tokenName: 'dragon', amount: '250', name: 'vesting-lock' }
]
});
Throws
When validation fails or unlock operation is rejected
Throws
When wallet is not configured
unlock tokens result data
unregisterPushToken()
unregisterPushToken(
token):Promise<UnregisterPushTokenResult>
Unregister a push notification device token.
Deactivates a push token so the device no longer receives notifications.
Authentication: Requires JWT auth (call sdk.login() first).
Parameters
| Parameter | Type | Description |
|---|---|---|
token | string | The push token to unregister |
Returns
Promise<UnregisterPushTokenResult>
Unregistration result
Example
const result = await sdk.unregisterPushToken('fcm-device-token-abc123');
console.log('Unregistered:', result.unregistered);
unregister push token result
updateApiKey()
updateApiKey(
id,options):Promise<ApiKeyData>
Update an API key's metadata and permissions.
Cannot change the key itself, only metadata and permissions. At least one field must be provided.
Requires JWT authentication - call sdk.login() first.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | number | API key ID |
options | UpdateApiKeyOptions | Fields to update |
Returns
Promise<ApiKeyData>
Updated API key data
Throws
ValidationError if ID or options are invalid
Throws
ConfigurationError if JWT auth is not configured
Throws
Error if API key not found (404)
Example
// Update description
await sdk.updateApiKey(123, {
description: 'Updated description'
});
// Upgrade role and extend expiration
await sdk.updateApiKey(123, {
role: 'MANAGER',
expiresAt: '2026-12-31T23:59:59Z'
});
// Switch from specific tokens to all tokens
await sdk.updateApiKey(123, {
delegateAllTokens: true
});
Since
5.6.0
update api key data options
updateModeratorInvite()
updateModeratorInvite(
options):Promise<UpdateModeratorInviteResult>
Update a moderator invite's role and/or description (owner only).
Parameters
| Parameter | Type | Description |
|---|---|---|
options | UpdateModeratorInviteOptions | Update options including inviteId, optional role, and optional description |
Returns
Promise<UpdateModeratorInviteResult>
The updated invite
Example
const result = await sdk.updateModeratorInvite({
inviteId: 123,
description: 'John - handles Friday evening streams'
});
console.log('Updated description:', result.invite.description);
Since
5.0.4-beta.60
update moderator invite result options
updateModeratorInviteRole()
updateModeratorInviteRole(
options):Promise<UpdateInviteRoleResult>
Update the role of a moderator invite.
Changes the role granted by the invite. For claimed invites, the moderator's effective permissions change immediately (enforced at runtime).
Requires JWT authentication - must be the token owner.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | UpdateInviteRoleOptions | Update options including inviteId and new role |
Returns
Promise<UpdateInviteRoleResult>
The updated invite
Example
const result = await sdk.updateModeratorInviteRole({
inviteId: 123,
role: 'MANAGER'
});
console.log('Updated role:', result.invite.role);
Since
5.7.0
update moderator invite role result options
updateNotificationPreferences()
updateNotificationPreferences(
params):Promise<UpdateNotificationPreferencesResult>
Update notification preferences for the authenticated user.
Partial update - only provided fields are modified, others remain unchanged.
Authentication: Requires JWT auth (call sdk.login() first).
Parameters
| Parameter | Type | Description |
|---|---|---|
params | UpdateNotificationPreferencesParams | Preference fields to update |
Returns
Promise<UpdateNotificationPreferencesResult>
Updated notification preferences
Example
// Disable chat notifications only
const { preferences } = await sdk.updateNotificationPreferences({
chatEnabled: false,
});
console.log('Chat now:', preferences.chatEnabled); // false
update notification preferences result params
Overseer
claimOverseerInvite()
claimOverseerInvite(
inviteCode):Promise<{invite:OverseerInviteWithUrl; }>
Claim an overseer invite.
The authenticated user's wallet becomes an overseer with global access to ALL tokens on the platform.
Requires JWT authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
inviteCode | string | The invite code from the magic link URL |
Returns
Promise<{ invite: OverseerInviteWithUrl; }>
The claimed invite data
Throws
ValidationError if invite code is invalid or invite already claimed/revoked/expired
Throws
ConfigurationError if JWT is not configured
Since
5.9.0
Example
Claim an invite
const result = await sdk.claimOverseerInvite('abc123def456...');
console.log('Now an overseer! Status:', result.invite.status);
claim overseer invite code with url
createOverseerDirect()
createOverseerDirect(
options):Promise<{overseer:Overseer; }>
Create an overseer directly (bypassing invite flow).
This directly promotes a user to overseer status without requiring them to claim an invite. A synthetic invite record is created for audit trail.
Use this when you need to promote someone programmatically without requiring their interaction (e.g., CLI admin tools, automated tests).
Requires Admin API key OR JWT as existing Overseer.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | CreateOverseerDirectOptions | The options for creating the overseer |
Returns
Promise<{ overseer: Overseer; }>
The created overseer record
Throws
ValidationError if address format is invalid
Throws
ConfigurationError if neither auth method is available
Throws
Error if user is already an overseer (400)
Since
8.3.0
Example
Promote a user to overseer
const result = await sdk.createOverseerDirect({
userAddress: 'eth|1234567890abcdef1234567890abcdef12345678',
description: 'Platform team - John'
});
console.log('Overseer created:', result.overseer.userAddress);
create overseer direct options
createOverseerInvite()
createOverseerInvite(
options?):Promise<{invite:OverseerInviteWithUrl; }>
Create an overseer invite.
Overseers have global platform access with MANAGER-level permissions across ALL tokens (current and future). This is different from moderators who have token-scoped access.
Requires Admin API key OR JWT as existing Overseer.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | CreateOverseerInviteOptions | Optional description and expiration settings |
Returns
Promise<{ invite: OverseerInviteWithUrl; }>
Created invite data including the invite URL
Throws
ConfigurationError if neither auth method is available
Throws
ValidationError if parameters are invalid
Since
5.9.0
Examples
Create an invite with description
const result = await sdk.createOverseerInvite({
description: 'John - Platform Support Team',
});
console.log('Share this link:', result.invite.inviteUrl);
Create invite with expiration
const result = await sdk.createOverseerInvite({
description: 'Temporary access',
expiresAt: '2025-12-31T23:59:59Z',
});
create overseer invite with url options
getBanStats()
getBanStats():
Promise<BanStatsResponse>
Get ban stats for the overseer banned users tab
Returns
Promise<BanStatsResponse>
Ban counts
Since
8.x.0
get ban stats response
getFlagStats()
getFlagStats():
Promise<FlagStatsResponse>
Get flag stats for the content flags tab
Returns
Promise<FlagStatsResponse>
Flag counts by status
Since
8.x.0
get flag stats response
getInviteStats()
getInviteStats():
Promise<InviteStatsResponse>
Get invite stats for the overseer invites tab
Returns
Promise<InviteStatsResponse>
Invite counts by status
Since
8.x.0
get invite stats response
getMyOverseerStatus()
getMyOverseerStatus():
Promise<OverseerStatusResponse>
Check own overseer status.
Returns whether the authenticated user is currently an active overseer and their details if so.
Requires JWT authentication.
Returns
Promise<OverseerStatusResponse>
Overseer status including details if active
Throws
ConfigurationError if JWT is not configured
Since
5.9.0
Example
Check your overseer status
const status = await sdk.getMyOverseerStatus();
if (status.isOverseer) {
console.log('You are an overseer!');
console.log('Access granted:', status.overseer?.createdAt);
} else {
console.log('You are not an overseer');
}
get my overseer status response
getOverseerInviteByCode()
getOverseerInviteByCode(
inviteCode):Promise<PublicOverseerInviteInfo>
Get overseer invite details by code.
This is a public endpoint used by the frontend claim page to display invite information before the user logs in to claim.
Parameters
| Parameter | Type | Description |
|---|---|---|
inviteCode | string | The invite code from the magic link URL |
Returns
Promise<PublicOverseerInviteInfo>
Public invite information (description, status, inviter info)
Throws
ValidationError if invite code format is invalid
Throws
Error if invite not found (404)
Since
5.9.0
Example
Get invite info before claiming
const info = await sdk.getOverseerInviteByCode('abc123def456...');
console.log(`Invited by: ${info.invitedBy.fullName || info.invitedBy.address}`);
console.log(`Status: ${info.status}`);
get overseer invite by code public info
getOverseerSummary()
getOverseerSummary():
Promise<OverseerSummaryResponse>
Get platform summary for CCTV dashboard.
Returns quick counts for the overseer monitoring dashboard:
- Active streams (pools with live streams)
- Total viewers across all active streams
- Pending content flags awaiting review
- Total pools on the platform
Returns
Promise<OverseerSummaryResponse>
Platform summary with counts
Throws
ConfigurationError if neither auth method is available
Since
5.10.0
Example
Get platform summary
const summary = await sdk.getOverseerSummary();
console.log(`Active streams: ${summary.activeStreams}`);
console.log(`Total viewers: ${summary.totalViewers}`);
console.log(`Pending flags: ${summary.pendingFlags}`);
console.log(`Total pools: ${summary.totalPools}`);
console.log(`Graduated pools: ${summary.graduatedPools}`);
get overseer summary response
getOverseerUserSummary()
getOverseerUserSummary(
address):Promise<UserSummaryResponse>
Get comprehensive user summary (Admin/Overseer only - v6.x.0+)
Retrieves full profile, activity metrics, and ban status for a specific user. Useful for overseer dashboard user detail pages.
Requires either Admin API key or JWT with overseer status.
Parameters
| Parameter | Type | Description |
|---|---|---|
address | string | User wallet address |
Returns
Promise<UserSummaryResponse>
User profile with detailed activity metrics and ban status
Throws
ConfigurationError if neither admin API key nor JWT is configured
Throws
ValidationError if address format is invalid
Since
6.x.0
Example
Get user summary
const summary = await sdk.getOverseerUserSummary('eth|abc123...');
console.log(`User: ${summary.profile?.fullName}`);
console.log(`Flags: ${summary.stats.flagsReceived}`);
console.log(`Global ban: ${summary.stats.globalBan}`);
get overseer user summary response
getTokenBanStats()
getTokenBanStats():
Promise<TokenBanStatsResponse>
Get token ban stats for the overseer delisted tokens tab
Returns
Promise<TokenBanStatsResponse>
Token ban counts
Since
8.x.0
get token ban stats response
getUserStats()
getUserStats():
Promise<UserStatsResponse>
Get user stats for the overseer users management tab
Returns
Promise<UserStatsResponse>
User counts (total, flagged, banned)
Since
8.x.0
get user stats response
listOverseerInvites()
listOverseerInvites(
options?):Promise<PaginatedOverseerInvites>
List all overseer invites.
Requires Admin API key OR JWT as existing Overseer.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | ListOverseerInvitesOptions | Optional filter and pagination options |
Returns
Promise<PaginatedOverseerInvites>
Paginated list of invites
Throws
ConfigurationError if neither auth method is available
Since
5.9.0
Examples
List all invites
const result = await sdk.listOverseerInvites();
console.log(`Total invites: ${result.pageInfo.totalCount}`);
Filter by status with pagination
const result = await sdk.listOverseerInvites({
status: 'PENDING',
pageSize: 10,
});
list overseer invites paginated options
listOverseers()
listOverseers(
options?):Promise<PaginatedOverseers>
List all overseers.
Requires Admin API key OR JWT as existing Overseer.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | ListOverseersOptions | Optional filter and pagination options |
Returns
Promise<PaginatedOverseers>
Paginated list of overseers
Throws
ConfigurationError if neither auth method is available
Since
5.9.0
Examples
List all overseers
const result = await sdk.listOverseers();
console.log(`Total overseers: ${result.pageInfo.totalCount}`);
Filter by status
const active = await sdk.listOverseers({
status: 'ACTIVE',
});
list overseers paginated options
listOverseerUsers()
listOverseerUsers(
options?):Promise<UsersListResponse>
List users with activity metrics (Admin/Overseer only - v6.x.0+)
Lists all platform users with their activity metrics including comments posted, messages sent, trades, and trading volume.
Requires either Admin API key or JWT with overseer status.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | ListUsersOptions | List options including search, sorting, and pagination |
Returns
Promise<UsersListResponse>
Paginated list of users with activity metrics
Throws
ConfigurationError if neither admin API key nor JWT is configured
Throws
ValidationError if options are invalid
Since
6.x.0
Examples
List users with pagination
const result = await sdk.listOverseerUsers({ pageSize: 20 });
result.items.forEach(user => {
console.log(`${user.fullName}: ${user.flagsReceived} flags`);
});
Search and sort
const result = await sdk.listOverseerUsers({
search: 'alice',
sortBy: 'activity',
sortOrder: 'desc',
pageSize: 10
});
list overseer users response options
revokeOverseer()
revokeOverseer(
address):Promise<void>
Revoke an overseer's access.
This revokes the overseer's global platform access.
Requires Admin API key OR JWT as existing Overseer.
Parameters
| Parameter | Type | Description |
|---|---|---|
address | string | The wallet address of the overseer to revoke |
Returns
Promise<void>
Throws
ValidationError if address format is invalid
Throws
ConfigurationError if neither auth method is available
Throws
Error if overseer not found (404)
Since
5.9.0
Example
Revoke an overseer
await sdk.revokeOverseer('eth|1234567890abcdef...');
console.log('Overseer access revoked');
revoke overseer
revokeOverseerInvite()
revokeOverseerInvite(
inviteId):Promise<void>
Revoke an overseer invite.
This revokes the invite, preventing it from being claimed. If the invite was already claimed, the overseer loses access.
Requires Admin API key OR JWT as existing Overseer.
Parameters
| Parameter | Type | Description |
|---|---|---|
inviteId | number | The ID of the invite to revoke |
Returns
Promise<void>
Throws
ValidationError if invite ID is invalid
Throws
ConfigurationError if neither auth method is available
Throws
Error if invite not found (404)
Since
5.9.0
Example
Revoke an invite
await sdk.revokeOverseerInvite(123);
console.log('Invite revoked');
revoke overseer invite id
PlatformStats
platform stats
getPlatformStats()
getPlatformStats():
Promise<GetPlatformStatsResult>
Get platform-wide statistics.
Returns aggregated platform metrics including:
- GALA trading volume over 1h, 24h, 7d
- Total number of tokens on the platform
Caching: Backend caches stats for 3 minutes.
Public endpoint - no authentication required.
Returns
Promise<GetPlatformStatsResult>
Platform statistics
Since
9.0.0
Example
Get platform stats
const { stats } = await sdk.getPlatformStats();
// Display volume in millions
console.log(`24h Volume: ${(stats.galaVolume24h / 1_000_000).toFixed(2)}M GALA`);
// Display token count
console.log(`${stats.totalTokens} tokens on platform`);
// Display timestamp
const updated = new Date(stats.timestamp);
console.log(`Last updated: ${updated.toLocaleString()}`);
get platform stats result
Pool Information
fetchAllPools()
fetchAllPools(
options?):Promise<PoolsResult>
Fetch all available pools with automatic pagination
Convenience method that fetches all available pools by automatically handling pagination through cursor-based iteration.
Cache Warming: Maintains the same opportunistic cache warming as fetchPools(), caching immutable token metadata for all returned pools to enable instant local calculations.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | Omit<FetchPoolsOptions, "cursor" | "pageSize"> | Optional filters (type, tokenName, search) |
Returns
Promise<PoolsResult>
Promise
Since
3.11.0
Examples
Fetch all recent pools
const all = await sdk.fetchAllPools({ type: 'recent' });
console.log(`Fetched ${all.items.length} total pools`);
console.log(`Total available: ${all.total}`);
Fetch all pools matching search
const dragons = await sdk.fetchAllPools({ search: 'dragon' });
console.log(`Found ${dragons.items.length} dragon tokens`);
Cache warming demonstration
// Fetch all pools - automatically warms cache for all tokens
const all = await sdk.fetchAllPools();
// Check cache statistics
const cacheInfo = sdk.getCacheInfo();
console.log(`Cached ${cacheInfo.totalTokens} tokens from ${all.items.length} pools`);
// All subsequent calculations are instant (no network calls)
const calculations = await Promise.all(
all.items.slice(0, 10).map(pool =>
sdk.calculateBuyAmountLocal({
tokenName: pool.tokenName,
amount: '100',
type: 'native',
currentSupply: '500000'
})
)
);
console.log('Calculated 10 prices instantly using cached metadata');
fetch all pools result options page size
fetchPoolDetailsForCalculation()
fetchPoolDetailsForCalculation(
tokenName):Promise<{currentSupply:string;maxSupply:string;remainingTokens:string;reverseBondingCurveMaxFeeFactor:number;reverseBondingCurveMinFeeFactor:number;reverseBondingCurveNetFeeFactor:number; }>
Fetch optimized pool details for local calculations
Retrieves essential pool parameters needed for bonding curve calculations:
- Current supply (computed with full precision)
- Reverse bonding curve fee factors (normalized to numbers)
- Net fee factor (max - min, for convenience)
- Remaining tokens available in the pool
This method is more efficient than fetchPoolDetails() as it returns only
the fields needed for calculations, with automatic normalization applied.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to fetch pool details for |
Returns
Promise<{ currentSupply: string; maxSupply: string; remainingTokens: string; reverseBondingCurveMaxFeeFactor: number; reverseBondingCurveMinFeeFactor: number; reverseBondingCurveNetFeeFactor: number; }>
Promise with calculation-optimized pool details
Throws
If token not found or vault address invalid
Throws
If GalaChain client not configured
Throws
If API request fails
Since
3.8.0
Examples
Basic usage
const details = await sdk.fetchPoolDetailsForCalculation('mytoken');
console.log('Current supply:', details.currentSupply);
console.log('Remaining tokens:', details.remainingTokens);
console.log('Max fee factor:', details.reverseBondingCurveMaxFeeFactor);
console.log('Min fee factor:', details.reverseBondingCurveMinFeeFactor);
console.log('Net fee factor:', details.reverseBondingCurveNetFeeFactor);
Use with local calculations
// Fetch pool details once
const details = await sdk.fetchPoolDetailsForCalculation('mytoken');
// Use in multiple local calculations without additional API calls
const buyCalc = await sdk.calculateBuyAmountLocal({
tokenName: 'mytoken',
amount: '100',
type: 'native',
currentSupply: details.currentSupply
});
const sellCalc = await sdk.calculateSellAmountLocal({
tokenName: 'mytoken',
amount: '50',
type: 'exact',
currentSupply: details.currentSupply,
reverseBondingCurveMaxFeeFactor: details.reverseBondingCurveMaxFeeFactor,
reverseBondingCurveMinFeeFactor: details.reverseBondingCurveMinFeeFactor
});
Check graduation status
const details = await sdk.fetchPoolDetailsForCalculation('mytoken');
console.log(`Tokens available: ${details.remainingTokens}`);
if (parseFloat(details.remainingTokens) === 0) {
console.log('Pool is graduated!');
} else {
console.log(`Need to buy ${details.remainingTokens} more tokens to graduate`);
}
fetch pool details for calculation token name current supply max remaining tokens reverse bonding curve fee factor min net
fetchPools()
fetchPools(
options?):Promise<PoolsResult>
Fetch pools with optional filters
Automatically warms the token metadata cache with RBC fees and vault addresses from the pools response for optimal performance in local calculations.
Cache Warming: This method opportunistically caches immutable token metadata (reverse bonding curve fees, vault addresses) for every pool returned. This enables instant local calculations without additional API calls.
Options are those GET /v1/tokens accepts: type RECENT / POPULAR / RECORDINGS /
SECONDS_STREAMED and streamStatus IDLE / ACTIVE / DISABLED (any case), pageSize 1 to 100
(default 10); anything else is a ValidationError before a request is made.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | FetchPoolsOptions | Optional filters for pool fetching |
Returns
Promise<PoolsResult>
Promise
Since
1.0.0
Examples
Basic pool fetching
const result = await sdk.fetchPools({ type: 'RECENT', pageSize: 20 });
console.log(`Fetched ${result.items.length} pools`);
console.log(`Total pools: ${result.total}`);
Cache warming demonstration
// Before fetching - cache is empty
let cacheInfo = sdk.getCacheInfo();
console.log('Cached tokens:', cacheInfo.totalTokens); // 0
// Fetch pools - automatically warms cache
await sdk.fetchPools({ pageSize: 20 });
// After fetching - cache is warmed
cacheInfo = sdk.getCacheInfo();
console.log('Cached tokens:', cacheInfo.totalTokens); // 20
// Now local calculations are instant (no network calls)
const calc = await sdk.calculateBuyAmountLocal({
tokenName: 'mytoken',
amount: '100',
type: 'native',
currentSupply: '500000'
});
console.log('Instant result:', calc.amount); // <1ms, used cached RBC fees
Performance optimization with cache
// Warm cache once
await sdk.fetchPools({ type: 'popular', pageSize: 50 });
// All subsequent calculations for these tokens are instant
const tokens = ['token1', 'token2', 'token3'];
const calculations = await Promise.all(
tokens.map(token =>
sdk.calculateBuyAmountLocal({
tokenName: token,
amount: '1000',
type: 'exact',
currentSupply: '1000000'
})
)
);
// All 3 calculations complete in <5ms total (no network calls)
fetch pools result stream status page size validation error options
isTokenGraduated()
isTokenGraduated(
tokenName):Promise<boolean>
Check if a token pool is graduated
Convenience method that fetches pool details and returns just the graduation status. A token is considered graduated when all tokens in the bonding curve pool have been purchased, transitioning the token to full DEX trading.
This method checks the pool's saleStatus field - pools with status 'Completed'
are considered graduated.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to check graduation status for |
Returns
Promise<boolean>
Promise
Throws
ValidationError if token not found or vault address invalid
Throws
ConfigurationError if GalaChain client not configured
Throws
NetworkError if API request fails
Since
3.8.0
Examples
Check if a token has graduated
const isGraduated = await sdk.isTokenGraduated('anime');
if (isGraduated) {
console.log('Token has graduated to DEX trading!');
} else {
console.log('Token is still in bonding curve phase');
}
Use in conditional logic
const graduated = await sdk.isTokenGraduated('mytoken');
if (graduated) {
// Use DEX API for graduated token
await sdk.swapOnDex(...);
} else {
// Use bonding curve for non-graduated token
await sdk.buy(...);
}
is token graduated name sale status
Pools
getPoolRealtimeState()
getPoolRealtimeState(
tokenName):Promise<{chatConfig:TokenConfigData|null;chatConfigError?:string;holderCount: {count:number;totalBalance:string; } |null;holderCountError?:string;price:TokenSpotPrice|null;priceError?:string;recentTrades:TradesQueryResult|null;recentTradesError?:string;tokenName:string; }>
Get a combined real-time snapshot of a pool: holder count, chat/comments config, recent trades, and current price - fetched in parallel from their real underlying endpoints.
There is no single backend endpoint for this; each field comes from a separate real
fetch. A field that fails independently is reported as null with its error message
rather than failing the whole call - a temporary price-feed hiccup should not hide an
otherwise-successful holder count and trade history.
There is no platform data for "stream status" (ACTIVE/IDLE/DISABLED) as a standalone concept separate from the chat config, and no "active moderators" summary beyond getActiveModerators() - this returns only fields with a real, single-token data source.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token to fetch a snapshot for |
Returns
Promise<{ chatConfig: TokenConfigData | null; chatConfigError?: string; holderCount: { count: number; totalBalance: string; } | null; holderCountError?: string; price: TokenSpotPrice | null; priceError?: string; recentTrades: TradesQueryResult | null; recentTradesError?: string; tokenName: string; }>
Combined snapshot; any field that failed to fetch is null with an error message
Since
7.1.0
get pool realtime state token name chat config data error holder count total balance spot price recent trades query result
getTokenConfig()
getTokenConfig(
tokenName):Promise<TokenConfigData>
Get the current token configuration, including chat/comments enabled status.
Reads the same record updateTokenConfig() writes - there is no dedicated chat-status endpoint. Chat status is included in the token's general config record.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to fetch configuration for |
Returns
Promise<TokenConfigData>
The token's current configuration
Since
7.1.0
get token config name data
updateTokenConfig()
updateTokenConfig(
tokenName,config):Promise<void>
Update token configuration (chat/comments enabled status).
Requires JWT authentication with owner or admin role.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to configure |
config | UpdateTokenConfigOptions | Configuration options |
Returns
Promise<void>
Promise
Throws
ValidationError if options are invalid
Throws
ConfigurationError if JWT is not configured
Since
7.0.0
Examples
Disable chat for a token
await sdk.updateTokenConfig('anime', { chatEnabled: false });
Enable comments for a token
await sdk.updateTokenConfig('anime', { commentsEnabled: true });
Update messaging and comments
await sdk.updateTokenConfig('anime', {
chatEnabled: true,
commentsEnabled: false
});
Update social links
await sdk.updateTokenConfig('anime', {
websiteUrl: 'https://anime.example.com',
twitterUrl: 'https://twitter.com/animeproject',
telegramUrl: 'https://t.me/animegroup',
discordUrl: 'https://discord.gg/anime'
});
Update streaming configuration
await sdk.updateTokenConfig('anime', {
streamingEnabled: true,
streamLanguage: 'en',
nextLiveStreamAt: '2026-02-01T18:00:00Z'
});
update token config name options
Real-time Monitoring
subscribeToTokenCreations()
subscribeToTokenCreations(
callback,options?): () =>void
Subscribe to real-time token creation broadcasts
Listens to WebSocket broadcasts for ALL token creations globally. Provides real-time notifications with ~1-2 second latency (vs 15-30s polling).
Architecture: The backend broadcasts transaction confirmation events to ALL connected Socket.IO clients. This listener captures "CreateSale" events which indicate token creation.
Key Difference from onLaunchpadTokenCreation():
subscribeToTokenCreations()- WebSocket broadcasts (instant, <2s latency)onLaunchpadTokenCreation()- REST API polling (slow, 15-30s latency)
Connection Management:
- If WebSocket is already connected, listener is registered immediately
- If not connected, automatically initiates connection with 3-second timeout
- Connection failures are logged and can be handled via error callback
Cleanup Function:
- Safe to call multiple times (idempotent)
- Removes listener and cleans up tracking state
- Returns immediately if listener was never registered
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (token) => void | Called when any token is created |
options? | { creatorFilter?: string; onError?: (error) => void; } | Optional filtering and error handling |
options.creatorFilter? | string | Only receive tokens from specific creator address |
options.onError? | (error) => void | Called if WebSocket connection fails |
Returns
Cleanup function to stop listening - safe to call multiple times
() => void
Since
4.1.0
Throws
Error if WebSocket service not initialized
Examples
Basic usage - listen to all token creations
const cleanup = sdk.subscribeToTokenCreations((token) => {
console.log(`Token created: ${token.tokenName} by ${token.creatorAddress}`);
});
// Stop listening when done
cleanup();
Filter to specific creator
const cleanup = sdk.subscribeToTokenCreations(
(token) => console.log(`My token: ${token.tokenName}`),
{
creatorFilter: sdk.getAddress(),
onError: (error) => console.error('Connection failed:', error)
}
);
Monitor for competitor tokens with error handling
const cleanup = sdk.subscribeToTokenCreations(
(token) => {
console.log(`New token: ${token.tokenName} - ${token.symbol}`);
// Could trigger automatic buy/analysis
},
{
onError: (error) => {
console.error('Real-time monitoring failed:', error);
// Fallback to polling
}
}
);
subscribe to token creations on launchpad creation creator filter error
Resource Management
cleanup()
cleanup():
Promise<void>
Cleanup SDK resources and connections
Releases WebSocket references and performs cleanup of SDK resources. Should be called when the SDK instance is no longer needed to prevent memory leaks and ensure proper resource management.
Returns
Promise<void>
Since
2.1.0
Examples
Basic cleanup
const sdk = new LaunchpadSDK({ wallet });
// Use SDK for operations...
await sdk.launchToken({...});
// Cleanup when done
await sdk.cleanup();
Cleanup in application shutdown
process.on('SIGINT', async () => {
console.log('Shutting down...');
await sdk.cleanup();
process.exit(0);
});
cleanupAll()
staticcleanupAll(debug?):void
Cleanup all SDK instances and shared resources
Forces cleanup of all shared WebSocket connections and resources across all SDK instances. Use this for application-wide cleanup or testing teardown.
Parameters
| Parameter | Type | Description |
|---|---|---|
debug? | boolean | Enable debug logging |
Returns
void
Since
2.1.0
Examples
Application shutdown
// Cleanup all SDK instances and shared resources
LaunchpadSDK.cleanupAll(true);
Test cleanup
afterEach(() => {
// Ensure clean state between tests
LaunchpadSDK.cleanupAll();
});
cleanup all
Streaming
addSimulcastTarget()
addSimulcastTarget(
options):Promise<AddSimulcastTargetResult>
Add a simulcast target to a stream.
Configure the stream to rebroadcast to an external platform.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | AddSimulcastTargetOptions | Simulcast target configuration |
Returns
Promise<AddSimulcastTargetResult>
Promise resolving to the new target
Throws
Error if wallet is not configured
Since
5.1.0
Example
Add YouTube simulcast
const { target } = await sdk.addSimulcastTarget({
tokenName: 'mytoken',
platform: 'youtube',
streamKey: 'xxxx-xxxx-xxxx-xxxx',
url: 'rtmp://a.rtmp.youtube.com/live2',
});
console.log(`Added target: ${target.id}`);
add simulcast target result options
deleteRecording()
deleteRecording(
tokenName,assetId):Promise<void>
Delete a recording.
Permanently removes a recording. This action cannot be undone.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
assetId | string | Recording asset ID |
Returns
Promise<void>
Promise resolving when deleted
Throws
Error if wallet is not configured
Since
5.1.0
delete recording token name asset id
disableStream()
disableStream(
tokenName):Promise<{enabled:boolean;tokenName:string; }>
Disable streaming for a specific token (Admin only).
Prevents new streams from being started for this token. Existing active streams will continue until they end.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
Promise<{ enabled: boolean; tokenName: string; }>
Promise resolving when disabled
Throws
Error if admin API key is not configured
Since
5.1.0
Admin
Requires streamAdminApiKey configuration
disable stream token name
enableStream()
enableStream(
tokenName):Promise<{enabled:boolean;tokenName:string; }>
Enable streaming for a specific token (Admin only).
Re-enables streaming capability for a previously disabled token.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
Promise<{ enabled: boolean; tokenName: string; }>
Promise resolving when enabled
Throws
Error if admin API key is not configured
Since
5.1.0
Admin
Requires streamAdminApiKey configuration
enable stream token name
getAvailableRoles()
getAvailableRoles():
Promise<AvailableRolesResponse>
Get all available roles and permissions for token delegation.
Returns reference data about the role system, including:
- All available roles (OWNER, MANAGER, TECHNICAL_PRODUCER, MODERATOR)
- Role descriptions and hierarchy levels
- Permissions assigned to each role
- Complete list of all available permissions
This is static reference data - it doesn't change per user or token.
Returns
Promise<AvailableRolesResponse>
Promise resolving to available roles and permissions
Since
5.10.0
Example
Get available roles
const { roles, permissions } = await sdk.getAvailableRoles();
// List all roles
roles.forEach(role => {
console.log(`${role.name} (level ${role.level}): ${role.description}`);
console.log(' Permissions:', role.permissions.join(', '));
});
// Build a role selector dropdown
const roleOptions = roles.map(role => ({
value: role.name,
label: role.description,
level: role.level,
}));
get available roles response
getGlobalStreamingStatus()
getGlobalStreamingStatus():
Promise<GlobalStreamingStatus>
Get global streaming status.
Returns platform-wide streaming status including maintenance windows.
Returns
Promise<GlobalStreamingStatus>
Promise resolving to global streaming status
Since
5.1.0
Example
Check if streaming is available
const status = await sdk.getGlobalStreamingStatus();
if (!status.enabled) {
console.log(`Streaming disabled: ${status.reason ?? 'maintenance'}`);
}
get global streaming status
getRecordingDownload()
getRecordingDownload(
tokenName,assetId):Promise<RecordingDownloadResult>
Get download URL for a recording.
Returns a signed URL for downloading a specific recording. URLs are typically valid for a limited time.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
assetId | string | Recording asset ID |
Returns
Promise<RecordingDownloadResult>
Promise resolving to download URL
Throws
Error if wallet is not configured
Since
5.1.0
Example
Download a recording
const result = await sdk.getRecordingDownload('mytoken', 'asset-123');
console.log(`Download: ${result.downloadUrl}`);
console.log(`Expires: ${result.expiresAt}`);
get recording download token name asset id result
getSimulcastTargets()
getSimulcastTargets(
tokenName):Promise<SimulcastTargetsResult>
Get simulcast targets for a stream.
Returns list of configured simulcast destinations (YouTube, Twitch, etc.).
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
Promise<SimulcastTargetsResult>
Promise resolving to simulcast targets
Since
5.1.0
Example
Check simulcast configuration
const { targets } = await sdk.getSimulcastTargets('mytoken');
targets.forEach(t => {
console.log(`${t.passthrough ?? t.url}: ${t.status}`);
});
get simulcast targets token name result
getStreamCredentials()
getStreamCredentials(
tokenName):Promise<StreamCredentials>
Get stream credentials (key and URL).
Returns the current stream key and RTMP URL for streaming.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
Promise<StreamCredentials>
Promise resolving to stream credentials
Since
6.13.0
Example
Get stream credentials
const creds = await sdk.getStreamCredentials('mytoken');
console.log(`Stream Key: ${creds.streamKey}`);
console.log(`RTMPS URL: ${creds.rtmpsUrl}`);
console.log(`Playback ID: ${creds.playbackId}`);
get stream credentials token name
getStreamRecordings()
getStreamRecordings(
options):Promise<RecordingsResult>
Get recordings for a stream.
Returns list of available recordings from past streams.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | FetchRecordingsOptions | Pagination options |
Returns
Promise<RecordingsResult>
Promise resolving to recordings list
Since
5.1.0
Example
List recordings
const { recordings, total } = await sdk.getStreamRecordings({ tokenName: 'mytoken' });
recordings.forEach(rec => {
console.log(`${rec.createdAt}: ${rec.duration}s - ${rec.status}`);
});
get stream recordings result fetch options
getStreamRole()
getStreamRole(
options):Promise<StreamRoleResponse>
Get the authenticated user's role for a token's stream.
Returns the user's effective role based on:
- Token ownership (OWNER role)
- Claimed moderator invite (MANAGER, TECHNICAL_PRODUCER, or MODERATOR)
- No access (null role)
This enables the frontend Studio page to detect permissions and show the appropriate UI based on the user's role.
Authentication: Optional JWT - returns null role if not authenticated.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetStreamRoleOptions | GetStreamRoleOptions with tokenName |
Returns
Promise<StreamRoleResponse>
Promise resolving to StreamRoleResponse with role, isOwner flag, source, and inviteScope
Since
5.7.0
Example
Check stream access
const roleInfo = await sdk.getStreamRole({ tokenName: 'mytoken' });
if (roleInfo.role === null) {
console.log('No access to this stream');
} else if (roleInfo.isOwner) {
console.log('You are the token owner');
} else {
console.log(`You have ${roleInfo.role} access via ${roleInfo.source}`);
}
// Use role for permission checks
const canStream = ['OWNER', 'MANAGER', 'TECHNICAL_PRODUCER'].includes(roleInfo.role ?? '');
const canModerate = ['OWNER', 'MANAGER', 'MODERATOR'].includes(roleInfo.role ?? '');
get stream role response options
getTokenAccess()
getTokenAccess(
options):Promise<TokenAccessResult>
Check if the authenticated user has Studio access for a token.
Returns comprehensive access information combining:
- Token ownership check (OWNER role)
- Claimed moderator invite (MANAGER, TECHNICAL_PRODUCER, MODERATOR)
- Platform overseer status (global access)
This is used by the frontend to determine whether to show the "Click to Studio" link on the buy-sell page.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetTokenAccessOptions | Options with tokenName |
Returns
Promise<TokenAccessResult>
Promise resolving to access info with role, permissions, and flags
Since
5.11.0
Example
Check Studio access
const access = await sdk.getTokenAccess({ tokenName: 'mytoken' });
if (!access.hasAccess) {
console.log('No Studio access for this token');
} else {
console.log(`Access via: ${access.accessSource}`);
console.log(`Role: ${access.role}`);
console.log('Permissions:', access.permissions);
if (access.permissions.canStream) {
console.log('User can start/stop streams');
}
if (access.permissions.canModerate) {
console.log('User can moderate chat');
}
}
get token access result options
removeSimulcastTarget()
removeSimulcastTarget(
tokenName,targetId):Promise<void>
Remove a simulcast target from a stream.
Stops rebroadcasting to the specified platform.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
targetId | string | Simulcast target ID |
Returns
Promise<void>
Promise resolving when removed
Throws
Error if wallet is not configured
Since
5.1.0
remove simulcast target token name id
resetStreamKey()
resetStreamKey(
tokenName):Promise<ResetStreamKeyResult>
Reset the stream key for a token.
Generates a new stream key, invalidating the previous one. Use this if the stream key has been compromised.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
Promise<ResetStreamKeyResult>
Promise resolving to new stream credentials
Throws
Error if wallet is not configured
Since
5.1.0
Example
Reset compromised stream key
const newCreds = await sdk.resetStreamKey('mytoken');
console.log(`New Stream Key: ${newCreds.streamKey}`);
console.log(`Reset at: ${newCreds.resetAt}`);
reset stream key token name result
setGlobalStreamingEnabled()
setGlobalStreamingEnabled(
enabled):Promise<GlobalStreamingStatus>
Enable or disable streaming globally (Admin only).
Controls platform-wide streaming capability.
Parameters
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | Whether streaming should be enabled |
Returns
Promise<GlobalStreamingStatus>
Promise resolving when updated
Throws
Error if admin API key is not configured
Since
5.1.0
Admin
Requires streamAdminApiKey configuration
set global streaming enabled status
setNextLiveStreamCountdown()
setNextLiveStreamCountdown(
tokenName,nextLiveStreamAt):Promise<void>
Set the next live stream countdown time (v6.x.0+)
Convenience method that sets a scheduled time for the next live stream. The frontend can display a countdown timer based on this time.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
nextLiveStreamAt | string | Date | null | Scheduled stream time (ISO 8601 string, Date, or null to clear) |
Returns
Promise<void>
Throws
If token name or date is invalid
Since
6.x.0
Example
Set countdown
await sdk.setNextLiveStreamCountdown('mytoken', '2025-01-15T18:00:00Z');
// or
await sdk.setNextLiveStreamCountdown('mytoken', new Date('2025-01-15T18:00:00Z'));
// Clear countdown
await sdk.setNextLiveStreamCountdown('mytoken', null);
set next live stream countdown token name at
startStream()
startStream(
tokenName):Promise<StartStreamResult>
Start a live stream for a token.
Creates a new stream session and returns streaming credentials. The stream key can be used with OBS or other RTMP-compatible software.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
Promise<StartStreamResult>
Promise resolving to stream credentials
Throws
Error if wallet is not configured
Throws
Error if streaming is disabled for this token
Since
5.1.0
Example
Start streaming for a token
const stream = await sdk.startStream('mytoken');
console.log(`RTMP URL: ${stream.rtmpUrl}`);
console.log(`Stream Key: ${stream.streamKey}`);
console.log(`Playback URL: ${stream.playbackUrl}`);
start stream token name result
stopStream()
stopStream(
tokenName):Promise<void>
Stop an active stream for a token.
Immediately ends the current broadcast and sets the stream to IDLE. Requires JWT authentication (stream creator only). The stream can be restarted by calling startStream() again.
Unlike disableStream() which is an admin operation that prevents streaming, stopStream() is for stream owners to end their current broadcast.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
Promise<void>
Throws
ValidationError if token name is invalid
Throws
Error if user is not authorized (not stream owner)
Throws
Error if stream is not currently active
Since
5.3.0
See
https://www.mux.com/docs/api-reference/video/live-streams/signal-live-stream-complete
Example
Stop an active stream
await sdk.stopStream('mytoken');
console.log('Stream stopped successfully');
stop stream token name
Token Creation
launchToken()
launchToken(
data):Promise<TokenLaunchResult>
Launch a new token with bonding curve trading
Creates a new launchpad token with an automated bonding curve for initial price discovery and liquidity. This method handles the complete token creation workflow including blockchain submission, WebSocket monitoring, and confirmation waiting. Returns comprehensive launch details after on-chain confirmation.
Process Flow:
- Validates token data (name uniqueness, symbol format, etc.)
- Submits launch transaction to GalaChain
- Monitors transaction via WebSocket for real-time updates
- Waits for blockchain confirmation
- Returns complete token metadata including vault address
Important: This is a write operation requiring wallet configuration.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | LaunchTokenData | Token launch configuration |
Returns
Promise<TokenLaunchResult>
Promise with complete token launch result including vault address, transaction ID, and metadata
Throws
If wallet not configured or token data invalid
Throws
If transaction monitoring fails
Throws
If blockchain transaction fails
Throws
If API request fails
Since
4.0.4-beta.0
Examples
Basic token launch
import { Wallet } from 'ethers';
import { LaunchpadSDK } from '@gala-chain/launchpad-sdk';
const wallet = new Wallet(process.env.PRIVATE_KEY);
const sdk = new LaunchpadSDK({ wallet });
const result = await sdk.launchToken({
tokenName: 'mytoken',
tokenSymbol: 'MTK',
tokenDescription: 'My amazing token for the community',
tokenImage: 'https://example.com/token.png'
});
console.log('Token launched successfully!');
console.log('Token:', result.tokenName);
console.log('Symbol:', result.tokenSymbol);
console.log('Vault:', result.vaultAddress);
console.log('Transaction:', result.transactionId);
console.log('Creator:', result.creatorAddress);
Launch with pre-buy and custom supply
const result = await sdk.launchToken({
tokenName: 'premium',
tokenSymbol: 'PREM',
tokenDescription: 'Premium features token',
tokenImage: 'https://example.com/premium.png',
preBuyQuantity: '1000', // Buy 1000 tokens immediately
maxSupply: '5000000' // Custom max supply of 5 million
});
console.log(`Pre-bought ${result.preBuyQuantity} tokens`);
Launch with custom bonding curve fees
const result = await sdk.launchToken({
tokenName: 'custom',
tokenSymbol: 'CSTM',
tokenDescription: 'Custom fee structure',
bondingCurveFees: {
minFeePortion: '0.15', // 15% minimum fee
maxFeePortion: '0.45' // 45% maximum fee
}
});
Error handling
try {
const result = await sdk.launchToken({
tokenName: 'newtoken',
tokenSymbol: 'NEW',
tokenDescription: 'New project token'
});
console.log('Success!', result.transactionId);
} catch (error) {
if (error.code === 'WALLET_REQUIRED') {
console.error('Please configure wallet before launching token');
} else if (error.code === 'TOKEN_NAME_TAKEN') {
console.error('Token name already exists, choose another');
} else if (error.code === 'TRANSACTION_FAILED') {
console.error('Blockchain transaction failed:', error.message);
} else {
console.error('Launch failed:', error);
}
}
launch token result data
Token Data
fetchTokenClassesWithSupply()
fetchTokenClassesWithSupply(
tokenClasses):Promise<GalaChainTokenClass[]>
Fetch supply information for token classes from GalaChain
Queries GalaChain for authoritative token supply data including:
- Total supply and maximum supply
- Total burned amount
- Mint-related supply metrics
- Token metadata (symbol, decimals, name)
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenClasses | GalaChainTokenClassKey[] | Array of token class keys to query |
Returns
Promise<GalaChainTokenClass[]>
Promise<GalaChainTokenClass[]> Array of token classes with supply information
Throws
if tokenClasses array is empty
Throws
if network request fails
Example
// Query single token
const supplies = await sdk.fetchTokenClassesWithSupply([
{ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' }
]);
console.log(`GALA total supply: ${supplies[0].totalSupply}`);
// Query multiple tokens
const multiSupplies = await sdk.fetchTokenClassesWithSupply([
{ collection: 'GALA', category: 'Unit', type: 'none', additionalKey: 'none' },
{ collection: 'GUSDC', category: 'Unit', type: 'none', additionalKey: 'eth:0x...' }
]);
// Print supply summary
for (const token of multiSupplies) {
console.log(`${token.symbol}: ${token.totalSupply} (max: ${token.maxSupply})`);
}
Since
3.32.0
fetch token classes with supply gala chain class key
Token Information
fetchTokenDistribution()
fetchTokenDistribution(
tokenName):Promise<TokenDistributionResult>
Fetch token ownership distribution with holder percentages
Retrieves complete token holder distribution data including all wallet addresses, their token balances, and ownership percentages. This endpoint returns ALL holders in a single non-paginated response, making it perfect for distribution analysis, whale tracking, and supply health metrics.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to fetch distribution for (e.g., 'anime', 'mytoken') |
Returns
Promise<TokenDistributionResult>
Promise with distribution data including holders array, total supply, and total holder count
Throws
If tokenName is invalid or empty
Throws
If API request fails
Since
4.0.4-beta.0
Examples
Basic distribution query
const distribution = await sdk.fetchTokenDistribution('anime');
console.log(`Total holders: ${distribution.totalHolders}`);
console.log(`Total supply: ${distribution.totalSupply}`);
distribution.holders.forEach(holder => {
console.log(`${holder.address}: ${holder.percentage}%`);
});
Whale analysis
const dist = await sdk.fetchTokenDistribution('mytoken');
const whales = dist.holders.filter(h => h.percentage > 5);
console.log(`Found ${whales.length} whales with >5% ownership`);
fetch token distribution name result
fetchUserHolderContext()
fetchUserHolderContext(
tokenName,userAddress):Promise<UserHolderContext>
Fetch a user's holder context for a specific token
Retrieves holder tier, quantity, percentage, and creator status for a user on a specific token. Used for user cards in comments/chat to show token-specific holder information.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to check holdings for (e.g., 'anime', 'mytoken') |
userAddress | string | User wallet address to lookup |
Returns
Promise<UserHolderContext>
Promise with user holder context including tier, quantity, percentage, isCreator
Throws
If tokenName or userAddress is invalid or empty
Throws
If API request fails
Since
3.7.0
Example
Get holder context for user card
const context = await sdk.fetchUserHolderContext('anime', '0x1234...');
if (context.holderTier) {
console.log(`User is a ${context.holderTier.tierName} holding ${context.percentage}%`);
}
if (context.isCreator) {
console.log('User created this token');
}
fetch user holder context token name address
getHolderCount()
getHolderCount(
tokenName):Promise<{count:number;totalBalance:string; }>
Get the total holder count and combined balance for a token
Convenience wrapper around fetchTokenDistribution().
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (e.g. 'anime') |
Returns
Promise<{ count: number; totalBalance: string; }>
Object with count (number of holders) and totalBalance (total supply across all holders)
Throws
If tokenName is invalid
Since
9.2.0
Example
const { count, totalBalance } = await sdk.getHolderCount('anime');
console.log(`${count} holders, total supply: ${totalBalance}`);
get holder count token name total balance fetch distribution
getHolderRank()
getHolderRank(
tokenName,userAddress):Promise<{balance:string;holderCount:number;rank:number; } |null>
Get a user's holder rank and balance for a token
Returns the user's position in the holder distribution (rank 1 = largest holder), their balance, and the total holder count. Returns null if the user holds no tokens.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (e.g. 'anime') |
userAddress | string | User's wallet address (eth|... format) |
Returns
Promise<{ balance: string; holderCount: number; rank: number; } | null>
Rank info or null if user is not a holder
Throws
If tokenName or userAddress is invalid
Since
9.2.0
Example
const rank = await sdk.getHolderRank('anime', 'eth|1234...');
if (rank) {
console.log(`Rank #${rank.rank} of ${rank.holderCount} holders, balance: ${rank.balance}`);
}
get holder rank token name user address count
getHoldersByBalance()
getHoldersByBalance(
tokenName,options?):Promise<(TokenHolder&object)[]>
Get holders within a specific balance range
Convenience wrapper around fetchTokenDistribution() that filters holders
by balance and returns them enriched with their rank.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (e.g. 'anime') |
options? | { limit?: number; maxBalance?: number; minBalance?: number; } | Filter options |
options.limit? | number | Maximum results to return (default: 100, max: 1000) |
options.maxBalance? | number | Maximum balance (no ceiling if omitted) |
options.minBalance? | number | Minimum balance (no floor if omitted) |
Returns
Promise<(TokenHolder & object)[]>
Filtered holders with rank
Throws
If tokenName is invalid
Since
9.2.0
Example
const whales = await sdk.getHoldersByBalance('anime', { minBalance: 10000 });
console.log(`${whales.length} whales hold ≥10,000 tokens`);
get holders by balance token name holder fetch distribution max min
getTopHolders()
getTopHolders(
tokenName,limit?):Promise<(TokenHolder&object)[]>
Get the top N token holders by balance
Convenience wrapper around fetchTokenDistribution() that returns the top
holders sorted by balance descending, each enriched with their rank.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (e.g. 'anime') |
limit? | number | Number of top holders to return (default: 10, max: 100) |
Returns
Promise<(TokenHolder & object)[]>
Array of top holders with address, balance, percentage, and rank
Throws
If tokenName is invalid
Since
9.2.0
Example
const topHolders = await sdk.getTopHolders('anime', 5);
topHolders.forEach(h => console.log(`#${h.rank} ${h.address}: ${h.balance} (${h.percentage}%)`));
get top holders token name holder fetch distribution
Token Lookup
fetchToken()
fetchToken(
tokenName):Promise<PoolData>
Fetch full token pool data by token name Returns complete PoolData including streaming fields
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | The token name to fetch (e.g., 'anime') |
Returns
Promise<PoolData>
The full PoolData object with all fields including streaming data
Throws
Error if token not found or request fails
Since
6.0.0
Example
const pool = await sdk.fetchToken('anime');
console.log(pool.tokenName, pool.playbackId, pool.muxStreamStatus);
fetch token name pool data
fetchTokenStats()
fetchTokenStats(
tokenName):Promise<FetchTokenStatsResult>
Fetch engagement statistics for a token (v7.1.0+)
Returns metrics for chat activity, comments, and overall engagement on a token. Useful for token detail pages and engagement analytics.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to fetch stats for |
Returns
Promise<FetchTokenStatsResult>
Engagement statistics result
Throws
ValidationError if tokenName is invalid
Since
7.1.0
Example
const stats = await sdk.fetchTokenStats('anime');
console.log(`Chat messages: ${stats.data.chatMessageCount}`);
console.log(`Comments: ${stats.data.commentCount}`);
fetch token stats name result
Token Resolution
resolveVaultAddress()
resolveVaultAddress(
tokenName):Promise<string|null>
Resolve token name to its GalaChain vault address
Performs a lookup to find the blockchain vault address associated with a token name. Vault addresses are used internally for direct GalaChain API calls. This method is useful for caching, optimization, or low-level blockchain operations.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to resolve (e.g., 'anime', 'mytoken') |
Returns
Promise<string | null>
Promise resolving to vault address string, or null if token not found
Throws
If API request fails
Since
4.0.4-beta.0
Example
Resolve vault for direct API calls
const vaultAddress = await sdk.resolveVaultAddress('anime');
if (vaultAddress) {
console.log(`Vault address: ${vaultAddress}`);
// Use for direct GalaChain API calls or caching
} else {
console.log('Token not found');
}
resolve vault address token name
Token Validation
checkPoolExists()
checkPoolExists(
tokenName?,symbol?):Promise<boolean>
Checks if a pool exists (v6.x.0+)
Convenience method that checks pool existence by token name or symbol. At least one parameter is required.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName? | string | Optional token name to check |
symbol? | string | Optional token symbol to check |
Returns
Promise<boolean>
Promise
Throws
If neither parameter is provided
Since
6.x.0
Example
Check pool existence
const exists = await sdk.checkPoolExists('mytoken');
console.log('Pool exists:', exists);
// Or check by symbol
const existsBySymbol = await sdk.checkPoolExists(undefined, 'MT');
console.log('Pool with symbol MT exists:', existsBySymbol);
check pool exists token name
isTokenNameAvailable()
isTokenNameAvailable(
tokenName):Promise<boolean>
Check if a token name is available for use
Validates whether a token name is available to be registered on the platform. Token names must be unique across the entire launchpad. Use this before attempting to launch a token to prevent registration failures.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to check availability for (letters and digits, up to 25 characters) |
Returns
Promise<boolean>
Promise resolving to true if name is available, false if already taken
Throws
If tokenName format is invalid
Throws
If API request fails
Since
4.0.4-beta.0
Example
Check name availability before launch
const isAvailable = await sdk.isTokenNameAvailable('mytoken');
if (isAvailable) {
console.log('Name is available!');
await sdk.launchToken({ tokenName: 'mytoken', ... });
} else {
console.log('Name already taken, choose another');
}
is token name available
isTokenSymbolAvailable()
isTokenSymbolAvailable(
symbol):Promise<boolean>
Check if a token symbol is available for use
Validates whether a token symbol is available to be registered on the platform. Token symbols must be unique across the entire launchpad. Use this before attempting to launch a token to prevent registration failures.
Parameters
| Parameter | Type | Description |
|---|---|---|
symbol | string | Token symbol to check availability for (typically 3-6 uppercase characters) |
Returns
Promise<boolean>
Promise resolving to true if symbol is available, false if already taken
Throws
If symbol format is invalid
Throws
If API request fails
Since
4.0.4-beta.0
Example
Check symbol availability before launch
const isAvailable = await sdk.isTokenSymbolAvailable('MTK');
if (isAvailable) {
console.log('Symbol is available!');
await sdk.launchToken({ tokenSymbol: 'MTK', ... });
} else {
console.log('Symbol already taken, choose another');
}
is token symbol available
validateToken()
validateToken(
options):Promise<ValidateTokenResponse>
Validate if token name and/or symbol are available Useful for token creation forms to check availability before submission
Parameters
| Parameter | Type | Description |
|---|---|---|
options | { symbol?: string; tokenName?: string; } | Object containing optional tokenName and/or symbol to validate |
options.symbol? | string | - |
options.tokenName? | string | - |
Returns
Promise<ValidateTokenResponse>
Validation result with availability flags and errors
Since
6.0.0
Example
const result = await sdk.validateToken({ tokenName: 'mytoken', symbol: 'MYTKN' });
if (result.nameAvailable && result.symbolAvailable) {
console.log('Names are available!');
} else {
console.log('Errors:', result.errors);
}
validate token response name
TokenBan
token ban
banToken()
banToken(
options):Promise<BanTokenResult>
Ban a token from the platform (overseer only).
When a token is banned:
- Hidden from ALL pool listings (including creator's profile)
- Comments blocked on banned tokens
- Live streaming blocked on banned tokens
- Chat messages blocked on banned tokens
- Trading NOT blocked (GalaChain handles trading independently)
Requires either Admin API key or JWT with overseer status.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | BanTokenOptions | Ban options including tokenName and optional reason |
Returns
Promise<BanTokenResult>
Created ban data with token name
Throws
ValidationError if parameters are invalid
Throws
ConfigurationError if neither admin API key nor JWT is configured
Throws
Error if token is already banned (409 Conflict)
Since
6.x.0
Examples
Ban a token with reason
const result = await sdk.banToken({
tokenName: 'scamtoken',
reason: 'Fraudulent project - reported by multiple users'
});
console.log('Banned token:', result.tokenName);
console.log('Ban ID:', result.ban.id);
console.log('Banned by:', result.ban.bannedBy);
Ban without reason
await sdk.banToken({ tokenName: 'problematictoken' });
ban token result options
getTokenBan()
getTokenBan(
options):Promise<TokenBanStatusResult>
Get ban details for a specific token (overseer only).
Returns ban data if banned, or indicates not banned. Use this to get full ban details including reason and who banned it.
Requires either Admin API key or JWT with overseer status.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetTokenBanOptions | Options including tokenName |
Returns
Promise<TokenBanStatusResult>
Ban status with full details if banned
Throws
ValidationError if token name is invalid
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
6.x.0
Example
const status = await sdk.getTokenBan({ tokenName: 'sometoken' });
if (status.banned) {
console.log('Token is banned');
console.log('Reason:', status.ban?.reason);
console.log('Banned by:', status.ban?.bannedBy);
console.log('Banned at:', status.ban?.createdAt);
} else {
console.log('Token is not banned');
}
get token ban status result options
isTokenBanned()
isTokenBanned(
options):Promise<TokenBanStatusResult>
Check if a token is banned (overseer only).
Convenience alias for getTokenBan() - provided for semantic clarity. Use when you just need to check if a token is banned.
Requires either Admin API key or JWT with overseer status.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetTokenBanOptions | Options including tokenName |
Returns
Promise<TokenBanStatusResult>
Ban status with full details if banned
Throws
ValidationError if token name is invalid
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
6.x.0
Example
const status = await sdk.isTokenBanned({ tokenName: 'sometoken' });
if (status.banned) {
console.log('Token is banned:', status.ban?.reason);
}
is token banned ban status result get options
listTokenBans()
listTokenBans(
options?):Promise<TokenBanListResult>
List all banned tokens (overseer only).
Returns paginated list of banned tokens with full details.
Requires either Admin API key or JWT with overseer status.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | ListTokenBansOptions | Optional pagination and search parameters |
Returns
Promise<TokenBanListResult>
Paginated list of banned tokens
Throws
ValidationError if pagination parameters are invalid
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
6.x.0
Examples
List all banned tokens
const result = await sdk.listTokenBans();
console.log(`Total banned: ${result.pageInfo.totalCount}`);
for (const ban of result.items) {
console.log(`${ban.tokenName}: ${ban.reason || 'No reason'}`);
}
Search for specific tokens
const result = await sdk.listTokenBans({
search: 'scam',
pageSize: 10
});
Paginate through all bans (cursor-based)
let cursor: string | undefined;
let hasMore = true;
while (hasMore) {
const result = await sdk.listTokenBans({ cursor, pageSize: 20 });
console.log('Bans:', result.items.map(b => b.tokenName));
hasMore = result.pageInfo.hasNextPage;
cursor = result.pageInfo.endCursor ?? undefined;
}
list token bans ban result options
unbanToken()
unbanToken(
options):Promise<UnbanTokenResult>
Remove a ban from a token (overseer only).
When a token is unbanned:
- Restored to all pool listings
- Visible on creator's profile again
- Comments re-enabled
- Live streaming re-enabled
- Chat re-enabled
Requires either Admin API key or JWT with overseer status.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | UnbanTokenOptions | Unban options including tokenName |
Returns
Promise<UnbanTokenResult>
Removal confirmation with token name
Throws
ValidationError if token name is invalid
Throws
ConfigurationError if neither admin API key nor JWT is configured
Throws
Error if token is not banned (404 Not Found)
Since
6.x.0
Example
const result = await sdk.unbanToken({ tokenName: 'scamtoken' });
console.log('Removed ban:', result.removed); // true
console.log('Token:', result.tokenName);
unban token result options
Trades
getHolderHistory()
getHolderHistory(
tokenName,userAddress,limit?):Promise<TradesQueryResult>
Get recent trade history for a specific holder
Returns trades that affected a user's holdings for a token, delegating to
getTrades() with userAddress and tokenName filters.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (e.g. 'anime') |
userAddress | string | Holder's wallet address |
limit? | number | Number of recent trades to return (default: 20, max: 100) |
Returns
Promise<TradesQueryResult>
Paginated trade history result
Throws
If tokenName or userAddress is invalid
Since
9.2.0
Example
const history = await sdk.getHolderHistory('anime', 'eth|1234...', 10);
history.trades.forEach(t => console.log(`${t.txnType}: ${t.inputAmount} → ${t.outputAmount}`));
get holder history token name user address trades query result
getRecentTrades()
getRecentTrades(
tokenName?,limit?):Promise<TradesQueryResult>
Get the most recently executed trades with optional filtering
Convenience wrapper around getTrades() for quick access to recent market
activity. Returns trades sorted by newest first.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName? | string | Filter by token name (optional) |
limit? | number | Number of recent trades to return (default: 50, max: 500) |
Returns
Promise<TradesQueryResult>
Paginated list of recent trades
Throws
If API request fails
Since
9.2.0
Examples
Get recent trades across all tokens
const { trades } = await sdk.getRecentTrades();
trades.forEach(t => console.log(`${t.tokenName} ${t.txnType}: ${t.inputAmount} → ${t.outputAmount}`));
Get recent trades for a specific token
const { trades } = await sdk.getRecentTrades('anime', 10);
console.log(`Last 10 anime trades`);
get recent trades token name query result
getTrades()
getTrades(
options):Promise<TradesQueryResult>
Get trades with flexible filtering.
Public endpoint - no authentication required. Filter by tokenName, userAddress, or both. At least one filter is required.
This is the unified trades endpoint that provides flexible querying for trade history across tokens and users.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetTradesOptions | Query options with tokenName and/or userAddress |
Returns
Promise<TradesQueryResult>
Paginated list of trades with metadata
Throws
ValidationError if neither tokenName nor userAddress provided
Throws
ValidationError if options contain invalid values
Since
6.2.0
Examples
Get all trades for a token
const { trades, pageInfo } = await sdk.getTrades({ tokenName: 'anime' });
console.log(`Found ${trades.length} trades, more: ${pageInfo.hasNextPage}`);
trades.forEach(trade => {
console.log(`${trade.txnType}: ${trade.inputAmount} -> ${trade.outputAmount}`);
});
Get all trades by a user
const { trades, pageInfo } = await sdk.getTrades({
userAddress: 'eth|1234567890abcdef...'
});
console.log(`${trades.length} trades across all tokens, more: ${pageInfo.hasNextPage}`);
Get a user's trades on a specific token with pagination
const page = await sdk.getTrades({
tokenName: 'anime',
userAddress: 'eth|1234567890abcdef...',
pageSize: 20
});
console.log(`${page.trades.length} trades, next cursor: ${page.pageInfo.endCursor}`);
get trades query result options
Trading Actions
buy()
buy(
options):Promise<TradeResult>
Buy tokens with blockchain confirmation and WebSocket monitoring
Executes a buy order on the bonding curve and waits for GalaChain confirmation via WebSocket, returning complete trade details including actual amounts traded, fees paid, and transaction metadata.
trade result
Token Format
Use simple tokenName (e.g., "anime"), NOT full TokenClassKey format.
This method is for bonding curve tokens only (pre-graduation). For DEX trading
of graduated tokens, use @gala-chain/gswap-sdk (new GSwap({ signer }).swaps.swap()) with full TokenClassKey format.
// ✅ CORRECT - Simple token name
await sdk.buy({ tokenName: 'anime', amount: '100', type: 'native', ... });
// ❌ WRONG - Do NOT use TokenClassKey format
await sdk.buy({ tokenName: 'Token|Unit|ANIME|client:gala-launchpad', ... }); // Error!
Slippage Protection:
- Uses
expectedAmountto protect against price changes during execution slippageToleranceFactorallows variance (e.g., 0.01 = 1% tolerance)- Transaction fails if actual amount deviates beyond tolerance
Transaction Types:
- type: 'native' - Spend exact GALA amount, receive variable tokens
- type: 'exact' - Buy exact token amount, spend variable GALA
WebSocket Confirmation:
- Pre-connects WebSocket before submission to avoid race conditions
- Blocks until transaction confirmed on GalaChain
- Returns rich trade result with all transaction details
Parameters
| Parameter | Type | Description |
|---|---|---|
options | BuyTokenOptions | Buy options with required tokenName, amount, and slippage protection |
Returns
Promise<TradeResult>
Promise
Throws
If wallet not configured or parameters invalid
Throws
If transaction fails or no transaction ID returned
Throws
If confirmation fails or times out
Throws
If price moves beyond tolerance
Since
1.0.0
Examples
Buy tokens with GALA (type: 'native')
// Step 1: Calculate expected output
const quote = await sdk.calculateBuyAmount({
tokenName: 'anime',
amount: '100', // 100 GALA
type: 'native'
});
// Step 2: Execute buy with slippage protection
const result = await sdk.buy({
tokenName: 'anime',
amount: '100', // Spend 100 GALA
type: 'native',
expectedAmount: quote.amount, // Expected tokens from quote
slippageToleranceFactor: 0.01 // 1% slippage tolerance
});
console.log('Spent GALA:', result.inputAmount);
console.log('Received tokens:', result.outputAmount);
console.log('Transaction fee:', result.transactionFee);
console.log('Total fees:', result.totalFees);
console.log('Block hash:', result.blockHash);
console.log('Transaction ID:', result.transactionId);
Buy exact token amount (type: 'exact')
// Step 1: Calculate GALA cost
const quote = await sdk.calculateBuyAmount({
tokenName: 'anime',
amount: '1000', // 1000 tokens desired
type: 'exact'
});
// Step 2: Execute buy
const result = await sdk.buy({
tokenName: 'anime',
amount: '1000', // Buy exactly 1000 tokens
type: 'exact',
expectedAmount: quote.amount, // Expected GALA cost from quote
slippageToleranceFactor: 0.02 // 2% slippage tolerance
});
console.log('Bought tokens:', result.outputAmount); // Should be ~1000
console.log('Spent GALA:', result.inputAmount);
Error handling with slippage
try {
const result = await sdk.buy({
tokenName: 'anime',
amount: '100',
type: 'native',
expectedAmount: '950',
slippageToleranceFactor: 0.01
});
console.log('Trade successful:', result.transactionId);
} catch (error) {
if (error instanceof SlippageError) {
console.error('Price moved too much:', error.message);
// Retry with fresh quote
} else {
console.error('Trade failed:', error);
}
}
token name expected amount slippage tolerance factor buy options trade result
Trading Data
fetchTrades()
fetchTrades(
options):Promise<TradesResult>
Fetch trade history with optional filters and pagination
Retrieves paginated historical trades for a specific token from the Launchpad backend. Supports filtering by trade type (buy/sell), wallet address, and time range for detailed trade analysis and portfolio tracking.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | FetchTradesOptions | Trade fetching options with required tokenName |
Returns
Promise<TradesResult>
Promise
Throws
If tokenName is not provided
Throws
If API request fails
Since
1.0.0
Examples
Basic trade history
const trades = await sdk.fetchTrades({
tokenName: 'anime',
pageSize: 50
});
console.log(`Found ${trades.total} trades`);
trades.trades.forEach(trade => {
console.log(`${trade.type}: ${trade.amount} @ ${trade.price}`);
});
Filter by trade type
const buys = await sdk.fetchTrades({
tokenName: 'anime',
type: 'buy',
pageSize: 20
});
console.log(`Recent buy trades: ${buys.trades.length}`);
Filter by wallet and date range
const myTrades = await sdk.fetchTrades({
tokenName: 'anime',
address: sdk.getAddress(),
startDate: new Date('2025-01-01'),
endDate: new Date('2025-01-31')
});
console.log(`My January trades: ${myTrades.total}`);
fetch trades result options
fetchVolumeData()
fetchVolumeData(
options):Promise<GraphDataResult>
Fetch historical trading volume data for charting
Retrieves time-series trading volume data for a specific token, perfect for building volume charts, analyzing trading activity patterns, and monitoring market engagement. Data is aggregated by time period with buy/sell breakdowns.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | FetchVolumeDataOptions | Volume data options |
Returns
Promise<GraphDataResult>
{ dataPoints }: { timestamp, value, ... } points, as the backend's chart returns them
Throws
If tokenName is invalid, or from, to or resolution is missing
(MISSING_GRAPH_OPTIONS) or out of range: all three are required although the type marks
them optional
Throws
If API request fails
Since
4.0.4-beta.0
Example
Volume over the last 30 days
const now = Math.floor(Date.now() / 1000);
const { dataPoints } = await sdk.fetchVolumeData({
tokenName: 'anime',
from: now - 30 * 24 * 60 * 60,
to: now,
resolution: 5,
});
dataPoints.forEach((point) => console.log(`${point.timestamp}: ${point.value}`));
fetch volume data graph result options points missing
User
getManagedTokens()
getManagedTokens(
options?):Promise<ManagedTokensResult>
Get all tokens the authenticated user can manage.
Returns a comprehensive view of the user's management capabilities:
- ownedTokens: Tokens the user created (full OWNER access)
- moderatedTokens: Tokens with moderator access via claimed invites
- isOverseer: Whether user has platform-wide overseer access
- overseerSince: When user became overseer (if applicable)
This is used by the /moderators dashboard page to show all tokens a user can access in Studio.
Requires JWT authentication - call sdk.login() before using this method.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | GetManagedTokensOptions | Optional pagination options (pageSize) |
Returns
Promise<ManagedTokensResult>
Promise resolving to managed tokens result
Throws
ConfigurationError if JWT auth is not configured
Throws
ValidationError if pagination parameters are invalid
Since
5.11.0
Example
Get all managed tokens
const managed = await sdk.getManagedTokens();
console.log(`Owned tokens: ${managed.ownedTokensCount}`);
console.log(`Moderated tokens: ${managed.moderatedTokensCount}`);
console.log(`Is overseer: ${managed.isOverseer}`);
// List owned tokens with Studio links
managed.ownedTokens.forEach(token => {
console.log(`${token.tokenName} - ${token.isLive ? 'LIVE' : 'offline'}`);
});
// List moderated tokens with role info
managed.moderatedTokens.forEach(token => {
console.log(`${token.tokenName} - ${token.role} (${token.inviteScope})`);
});
get managed tokens result options
User Management
fetchReferralCode()
fetchReferralCode():
Promise<ReferralCode>
The authenticated user's referral code (GET /v1/connect/users/referrals/code, JWT session;
the backend asks Gala Connect for the wallet of the token). Not LaunchpadSDK.fetchReferralUrl,
which is the DEX API's link for the SDK wallet.
Returns
Promise<ReferralCode>
{ code, username? }
Throws
ConfigurationError if no JWT session is configured
Since
9.0.0
Example
const { code } = await sdk.fetchReferralCode();
console.log(`https://pump.gala.com/?ref=${code}`);
fetch referral code
getUserGalaBalance()
getUserGalaBalance(
address):Promise<UserGalaBalance>
A user's GALA balance and its USD value, as the launchpad backend reads them from the chain
(GET /v1/users/:address/gala-balance). Public; the backend never caches it. For a chain read
through the gateway instead, use LaunchpadSDK.fetchGalaBalance.
Parameters
| Parameter | Type | Description |
|---|---|---|
address | string | The user's address (eth|..., 0x... or client|...) |
Returns
Promise<UserGalaBalance>
{ name: 'GALA', quantity, price, holdingPrice }
Throws
ValidationError if no address is given
Throws
NetworkError if the backend cannot read the balance or the GALA price
Since
9.0.0
Example
const gala = await sdk.getUserGalaBalance('eth|1234567890abcdef1234567890abcdef12345678');
console.log(`${gala.quantity} GALA = $${gala.holdingPrice}`);
get user gala balance holding price
Utility
getUrlByTokenName()
getUrlByTokenName(
tokenName):string
Get the frontend URL for a specific token
Constructs the launchpad frontend URL for viewing/trading a specific token. The base URL is determined by the environment configuration or can be overridden in the SDK config.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name to generate URL for |
Returns
string
Complete frontend URL for the token
Since
3.1.0
Examples
Get token URL
const sdk = new LaunchpadSDK({ wallet, env: 'prod' });
const url = sdk.getUrlByTokenName('dragnrkti');
console.log(url);
// Output: `${getEnvironmentConfig('prod').launchpadFrontendUrl}/buy-sell/dragnrkti`
With custom frontend URL
const sdk = new LaunchpadSDK({
wallet,
env: 'stage',
launchpadFrontendUrl: 'https://custom-frontend.example.com'
});
const url = sdk.getUrlByTokenName('mytoken');
console.log(url);
// Output: https://custom-frontend.example.com/buy-sell/mytoken
Generate URLs for multiple tokens
const tokens = ['dragnrkti', 'rocketri', 'unicornri'];
const urls = tokens.map(token => ({
token,
url: sdk.getUrlByTokenName(token)
}));
console.log(urls);
get url by token name
getVersion()
getVersion():
string
Get the SDK version
Returns
string
SDK version string (e.g., "3.12.1")
Since
3.12.0
get version
Wallet Management
getWallet()
getWallet():
Wallet|undefined
Gets the currently configured wallet
Returns the wallet if configured, or undefined if in read-only mode.
Returns
Wallet | undefined
The configured wallet, or undefined if not set
Since
3.23.0
Examples
Check wallet and get address
const wallet = sdk.getWallet();
if (wallet) {
console.log('Authenticated as:', wallet.address);
} else {
console.log('Running in read-only mode');
}
Conditionally perform operations
const wallet = sdk.getWallet();
if (wallet) {
// Perform authenticated operations
await sdk.buyTokens('anime', '10', 'native', 0.05);
} else {
// Perform read-only operations only
const pools = await sdk.fetchPools();
const price = await sdk.fetchTokenPrice('anime');
}
get wallet
hasWallet()
hasWallet():
boolean
Checks if a wallet is configured
Useful for conditionally enabling trading operations in UI or determining which operations are available.
Returns
boolean
true if wallet is configured, false otherwise
Since
3.23.0
Examples
Enable/disable trading UI
if (sdk.hasWallet()) {
// Show trading interface
renderTradingPanel();
} else {
// Show connect wallet prompt
renderConnectWalletPrompt();
}
Graceful fallback
async function buyOrAlert(tokenName: string) {
if (!sdk.hasWallet()) {
alert('Please connect wallet to trade');
return;
}
return await sdk.buyTokens(tokenName, '10', 'native', 0.05);
}
has wallet
setWallet()
setWallet(
wallet):void
Sets or updates the wallet for the SDK
Allows dynamic wallet configuration after SDK initialization. Useful for switching between different wallets or upgrading from read-only to signing mode.
Parameters
| Parameter | Type | Description |
|---|---|---|
wallet | Wallet | The new wallet to configure |
Returns
void
Throws
ValidationError if wallet is invalid
Since
3.23.0
Examples
Set wallet after initialization
const sdk = createLaunchpadSDK({}); // Start in read-only mode
// Later, when user authenticates...
const userWallet = new ethers.Wallet(process.env.PRIVATE_KEY);
sdk.setWallet(userWallet);
// Now trading operations are available
const result = await sdk.buyTokens('anime', '10', 'native', 0.05);
Switch wallets
const wallet1 = new ethers.Wallet(key1);
sdk.setWallet(wallet1);
await sdk.buyTokens('token', '100', 'native', 0.05);
// Switch to different wallet
const wallet2 = new ethers.Wallet(key2);
sdk.setWallet(wallet2);
await sdk.buyTokens('token', '50', 'native', 0.05);
set wallet
validateWallet()
validateWallet():
Wallet
Type guard that validates a wallet is configured
Throws a ValidationError if the SDK is not configured with a wallet. Use this method to ensure wallet-dependent operations can proceed safely.
Returns
Wallet
The configured wallet
Throws
ValidationError if no wallet is configured
Since
3.23.0
Examples
Validate wallet before trading
const sdk = createLaunchpadSDK({}); // No wallet
try {
sdk.validateWallet(); // Throws ValidationError
} catch (error) {
console.log('Wallet required for trading operations');
}
Use in async function
async function buyTokens(amount: string) {
const wallet = sdk.validateWallet(); // Throws if not configured
const result = await sdk.buyTokens('token', amount, 'native', 0.05);
return result;
}
validate wallet
Watchers
onLaunchpadTokenCreation()
onLaunchpadTokenCreation(
callback,options?): () =>void
Watch for new launchpad token creation events in real-time
Polls for newly created launchpad tokens at regular intervals and invokes the callback for each new token detected. Automatically deduplicates tokens to avoid duplicate callbacks.
Memory Management: This watcher maintains a bounded history of the 1000 most recently seen tokens using LRU (Least Recently Used) cleanup. This prevents unbounded memory growth even when watching for extended periods.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (token) => void | Promise<void> | Called when a new token is created |
options? | { creatorAddress?: string; intervalMs?: number; } | Configuration options for token watching |
options.creatorAddress? | string | Only notify about tokens created by this address (optional) |
options.intervalMs? | number | Poll interval in milliseconds (default: 30000 / 30 seconds) |
Returns
Cleanup function to stop watching
() => void
Since
3.29.0
Examples
Watch all new tokens
const unsubscribe = sdk.onLaunchpadTokenCreation((token) => {
console.log(`New token: ${token.name} (${token.symbol})`);
console.log(`Creator: ${token.creatorAddress}`);
});
// Later: stop watching
unsubscribe();
Watch tokens by specific creator
const unsubscribe = sdk.onLaunchpadTokenCreation(
(token) => console.log(`${token.name} created!`),
{ creatorAddress: 'eth|1234...' }
);
on launchpad token creation creator address interval ms
WebSocket
web socket
realtime
Get Signature
get realtime():
StreamWebSocketService
The realtime socket: one registry of subscribers for every event the backend emits (token rooms,
comment rooms, the global feed, the overseers' firehose, a connection's own user and overseer
rooms). Every subscribe* method on it is synchronous, returns that subscriber's own unsubscribe,
serves any number of subscribers per event, and joins a room on its first subscriber and leaves it on
its last. It also has connect, authenticate, deauthenticate, onConnectionStateChange,
onReconnect and the chat / reaction / typing senders.
Created on first use.
Throws
ConfigurationError if streamWebSocketUrl is not configured
Since
9.0.0
Returns
stream web socket service on connection state change reconnect url
authenticateStreamWebSocket()
authenticateStreamWebSocket(
token?):Promise<boolean>
Authenticate the stream WebSocket connection.
Required before sending chat messages via WebSocket, and for the user and overseer events.
Opens the connection if it is not open. With an app session the token is session.accessToken(),
otherwise the SDK's own session token (refreshed when near expiry); pass token to use a specific
one, e.g. right after the app refreshed its JWT. After a reconnect the socket re-authenticates
itself with the token current at that moment.
Parameters
| Parameter | Type | Description |
|---|---|---|
token? | string | JWT to authenticate with (default: the session's current token) |
Returns
Promise<boolean>
Promise resolving true once the server confirms; false when the server rejects the
token, does not answer within 10 seconds, the connection drops, there is no token, or a newer
authenticateStreamWebSocket / deauthenticateStreamWebSocket call replaced this one
Since
5.1.0
Example
Authenticate for chat
await sdk.connectStreamWebSocket();
await sdk.authenticateStreamWebSocket();
// Now can send chat messages via WebSocket
authenticate stream web socket access token deauthenticate
connectStreamWebSocket()
connectStreamWebSocket(
callbacks?):Promise<void>
Connect to the stream WebSocket server.
Establishes a WebSocket connection for real-time stream events. Idempotent and safe to call concurrently (one socket). Subscribing opens it by itself, so calling this is only needed to wait for the connection.
Parameters
| Parameter | Type | Description |
|---|---|---|
callbacks? | StreamEventCallbacks | Event callback handlers: each becomes its own subscriber of its event on every token (they join no room, and replace nothing registered before); disconnectStreamWebSocket() removes them |
Returns
Promise<void>
Promise resolving when connected
Throws
Error if streamWebSocketUrl is not configured
Since
5.1.0
Example
Connect with event handlers
await sdk.connectStreamWebSocket({
onStreamStatus: (event) => {
console.log(`Stream ${event.tokenName}: ${event.status}`);
},
onViewerCount: (event) => {
console.log(`Viewers: ${event.viewerCount}`);
},
onChatMessage: (event) => {
console.log(`Chat: ${event.content}`);
},
});
connect stream web socket event callbacks disconnect
connectWebSocket()
connectWebSocket():
void
Connect to WebSocket for real-time events
Establishes a WebSocket connection for receiving real-time transaction status updates. This method returns immediately - connection happens asynchronously.
Returns
void
Since
3.29.0
Examples
Connect WebSocket
const sdk = createLaunchpadSDK({ wallet });
sdk.connectWebSocket();
Pre-connect before transactions
const sdk = createLaunchpadSDK({ wallet });
sdk.connectWebSocket(); // Connect first
const result = await sdk.buy({ tokenName: 'anime', amount: '10' });
// WebSocket ready to monitor transaction immediately
connect web socket
deauthenticateStreamWebSocket()
deauthenticateStreamWebSocket():
void
Forget the stream socket's authenticated identity (call it when the wallet disconnects).
Cancels a pending authentication and stops re-authenticating on reconnect. The server has no message that drops a connection's identity, so an authenticated socket is closed and opened again: your subscriptions stay registered and are joined again on the new connection.
Returns
void
Since
9.0.0
deauthenticate stream web socket
disconnectStreamWebSocket()
disconnectStreamWebSocket():
void
Disconnect from the stream WebSocket server.
Closes the WebSocket connection and releases everything it holds: every subscriber, listener and timer. Unsubscribe functions handed out earlier stay harmless; subscribing again opens a new socket.
Returns
void
Since
5.1.0
disconnect stream web socket
disconnectWebSocket()
disconnectWebSocket():
void
Disconnect from WebSocket
Closes the WebSocket connection and cleans up all listeners. Safe to call even if not connected.
Returns
void
Since
3.29.0
Example
Disconnect WebSocket
sdk.disconnectWebSocket();
disconnect web socket
emitDownloadReady()
emitDownloadReady(
tokenName,payload):Promise<void>
Emit download ready event (admin/overseer only)
Notifies token subscribers that a recording download is ready for consumption.
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | DownloadReadyPayload |
Returns
Promise<void>
Since
9.1.0
emit download ready token name payload
emitRecordingsCountUpdated()
emitRecordingsCountUpdated(
tokenName,payload):Promise<void>
Emit recordings count updated event (admin/overseer only)
Notifies token subscribers that the number of available recordings has changed.
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | RecordingsCountUpdatedPayload |
Returns
Promise<void>
Since
9.1.0
emit recordings count updated token name payload
emitRecordingStatus()
emitRecordingStatus(
tokenName,payload):Promise<void>
Emit recording status change event (admin/overseer only)
Notifies token subscribers that a Mux recording has changed status (CREATED, READY, or DELETED).
Parameters
| Parameter | Type |
|---|---|
tokenName | string |
payload | RecordingStatusPayload |
Returns
Promise<void>
Since
9.1.0
emit recording status token name payload
emitTradeExecuted()
emitTradeExecuted(
tokenName,payload):Promise<void>
Emit a trade execution event to token subscribers (admin/overseer only)
Notifies all users subscribed to a token that a trade has executed.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token being traded |
payload | TradeExecutedPayload | Trade details (tradeType, inputAmount, outputAmount) |
Returns
Promise<void>
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
5.15.0
emit trade executed token name payload
emitWebSocketEvent()
emitWebSocketEvent(
request):Promise<void>
Emit a generic WebSocket event (admin/overseer only, advanced/custom use).
Low-level escape hatch for event types the boutique emitXxx() methods (emitTradeExecuted, emitChatMessage, etc.) don't cover. Routes to a token room, a user room, or globally depending on which of tokenName/userAddress/broadcast is supplied.
Parameters
| Parameter | Type | Description |
|---|---|---|
request | EmitWebSocketEventRequest | action, optional tokenName/userAddress/broadcast, and payload |
Returns
Promise<void>
Throws
ConfigurationError if neither admin API key nor JWT is configured
Since
7.1.0
emit web socket event request
isStreamWebSocketConnected()
isStreamWebSocketConnected():
boolean
Check if stream WebSocket is connected.
Returns
boolean
true if WebSocket is connected
Since
5.1.0
is stream web socket connected
isWebSocketConnected()
isWebSocketConnected():
boolean
Check if WebSocket is connected
Returns
boolean
true if WebSocket is currently connected, false otherwise
Since
3.29.0
Example
Check connection status
if (sdk.isWebSocketConnected()) {
console.log('Real-time features enabled');
} else {
console.log('Real-time features disabled');
}
is web socket connected
onAuthenticated()
onAuthenticated(
callback):Unsubscribe
Subscribe to WebSocket authentication events
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"authenticated"> | Handler for authenticated events |
Returns
Unsubscribe function
Since
5.12.0
on authenticated realtime listener
onBanEnforcement()
onBanEnforcement(
callback):Unsubscribe
Subscribe to ban enforcement events (kick, mute, ban)
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"BAN_ENFORCEMENT"> | Handler for ban enforcement events |
Returns
Unsubscribe function
Since
5.12.0
on ban enforcement realtime listener
onChatStatusChanged()
onChatStatusChanged(
callback):Unsubscribe
Subscribe to chat status changes (enable/disable)
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"CHAT_STATUS_CHANGED"> | Handler for chat status events |
Returns
Unsubscribe function
Since
5.12.0
on chat status changed realtime listener
onConnection()
onConnection(
callback):Unsubscribe
Subscribe to WebSocket connection events
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"connection"> | Handler for connection events |
Returns
Unsubscribe function
Since
5.12.0
on connection realtime listener
onContentFlagged()
onContentFlagged(
callback):Unsubscribe
Subscribe to content flagged events (overseer)
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"CONTENT_FLAGGED"> | Handler for content flagged events |
Returns
Unsubscribe function
Since
5.12.0
on content flagged realtime listener
onContentReactionAdded()
onContentReactionAdded(
callback):Unsubscribe
Subscribe to content reaction additions
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"CONTENT_REACTION_ADDED"> | Handler for content reaction added events |
Returns
Unsubscribe function
Since
5.12.0
on content reaction added realtime listener
onContentReactionRemoved()
onContentReactionRemoved(
callback):Unsubscribe
Subscribe to content reaction removals
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"CONTENT_REACTION_REMOVED"> | Handler for content reaction removed events |
Returns
Unsubscribe function
Since
5.12.0
on content reaction removed realtime listener
onDownloadReady()
onDownloadReady(
callback):Unsubscribe
Subscribe to download ready events
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"DOWNLOAD_READY"> | Handler for download ready events |
Returns
Unsubscribe function
Since
5.12.0
on download ready realtime listener
onEngagementStatsUpdated()
onEngagementStatsUpdated(
callback):Unsubscribe
Subscribe to engagement stats update events
Fires after the chat flush job processes messages for a stream, containing updated chat message counts and comment counts for the token. Broadcast to the token room every ~15 seconds when chat activity occurs.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"ENGAGEMENT_STATS_UPDATED"> | Handler for engagement stats updated events |
Returns
Unsubscribe function
Since
8.5.0
Example
const unsubscribe = sdk.onEngagementStatsUpdated((event) => {
console.log(`${event.tokenName}: ${event.chat.messageCount} chat messages`);
console.log(`Comments: ${event.comments.count} from ${event.comments.uniqueCommenters} users`);
});
on engagement stats updated realtime listener
onFlagResolved()
onFlagResolved(
callback):Unsubscribe
Subscribe to flag resolved events
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"FLAG_RESOLVED"> | Handler for flag resolved events |
Returns
Unsubscribe function
Since
5.12.0
on flag resolved realtime listener
onRecordingsCountUpdated()
onRecordingsCountUpdated(
callback):Unsubscribe
Subscribe to recordings count updates
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"RECORDINGS_COUNT_UPDATED"> | Handler for recordings count updated events |
Returns
Unsubscribe function
Since
9.0.0
on recordings count updated realtime listener
onRecordingStatusChanged()
onRecordingStatusChanged(
callback):Unsubscribe
Subscribe to recording status changes
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"RECORDING_STATUS"> | Handler for recording status events |
Returns
Unsubscribe function
Since
5.12.0
on recording status changed realtime listener
onRoomLeft()
onRoomLeft(
callback):Unsubscribe
Subscribe to comment room unsubscription events
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"room_left"> | Handler for room left events |
Returns
Unsubscribe function
Since
5.12.0
on room left realtime listener
onRoomSubscribed()
onRoomSubscribed(
callback):Unsubscribe
Subscribe to comment room subscription events
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"room_subscribed"> | Handler for room subscribed events |
Returns
Unsubscribe function
Since
5.12.0
on room subscribed realtime listener
onSimulcastStatusChanged()
onSimulcastStatusChanged(
callback):Unsubscribe
Subscribe to simulcast target status changes
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"SIMULCAST_STATUS"> | Handler for simulcast status events |
Returns
Unsubscribe function
Since
5.12.0
on simulcast status changed realtime listener
onStreamChatDeleted()
onStreamChatDeleted(
callback):Unsubscribe
Subscribe to stream chat message deletions
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"STREAM_CHAT_DELETED"> | Handler for message deleted events |
Returns
Unsubscribe function
Since
5.12.0
on stream chat deleted realtime listener
onStreamChatMessage()
onStreamChatMessage(
callback):Unsubscribe
Subscribe to new stream chat messages
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"STREAM_CHAT_MESSAGE"> | Handler for chat message events |
Returns
Unsubscribe function
Since
5.12.0
on stream chat message realtime listener
onStreamChatPinned()
onStreamChatPinned(
callback):Unsubscribe
Subscribe to stream chat message pins
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"STREAM_CHAT_PINNED"> | Handler for message pinned events |
Returns
Unsubscribe function
Since
5.12.0
on stream chat pinned realtime listener
onStreamChatUnpinned()
onStreamChatUnpinned(
callback):Unsubscribe
Subscribe to stream chat message unpins
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"STREAM_CHAT_UNPINNED"> | Handler for message unpinned events |
Returns
Unsubscribe function
Since
5.12.0
on stream chat unpinned realtime listener
onStreamChatUpdated()
onStreamChatUpdated(
callback):Unsubscribe
Subscribe to stream chat message updates
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"STREAM_CHAT_UPDATED"> | Handler for message updated events |
Returns
Unsubscribe function
Since
5.12.0
on stream chat updated realtime listener
onStreamControlStatusChanged()
onStreamControlStatusChanged(
callback):Unsubscribe
Subscribe to stream control status changes
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"STREAM_CONTROL_STATUS_CHANGED"> | Handler for control status changed events |
Returns
Unsubscribe function
Since
5.12.0
on stream control status changed realtime listener
onStreamCountdownUpdated()
onStreamCountdownUpdated(
callback):Unsubscribe
Subscribe to stream countdown updates
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"STREAM_COUNTDOWN_UPDATED"> | Handler for countdown updated events |
Returns
Unsubscribe function
Since
5.12.0
on stream countdown updated realtime listener
onStreamLanguageUpdated()
onStreamLanguageUpdated(
callback):Unsubscribe
Subscribe to stream language updates
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"STREAM_LANGUAGE_UPDATED"> | Handler for language updated events |
Returns
Unsubscribe function
Since
5.12.0
on stream language updated realtime listener
onStreamReaction()
onStreamReaction(
callback):Unsubscribe
Subscribe to stream reactions (emoji)
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"STREAM_REACTION"> | Handler for stream reaction events |
Returns
Unsubscribe function
Since
5.12.0
on stream reaction realtime listener
onStreamStatusChanged()
onStreamStatusChanged(
callback):Unsubscribe
Subscribe to stream status changes (online/offline)
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"STREAM_STATUS"> | Handler for stream status events |
Returns
Unsubscribe function
Since
5.12.0
Example
const unsubscribe = sdk.onStreamStatusChanged((event) => {
console.log(`${event.tokenName}: ${event.status}`);
});
on stream status changed realtime listener
onTokenSubscribed()
onTokenSubscribed(
callback):Unsubscribe
Subscribe to token stream room subscription events
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"token_subscribed"> | Handler for token subscribed events |
Returns
Unsubscribe function
Since
5.12.0
on token subscribed realtime listener
onTokenUnsubscribed()
onTokenUnsubscribed(
callback):Unsubscribe
Subscribe to token stream room unsubscription events
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"token_unsubscribed"> | Handler for token unsubscribed events |
Returns
Unsubscribe function
Since
5.12.0
on token unsubscribed realtime listener
onUserBanned()
onUserBanned(
callback):Unsubscribe
Subscribe to user ban events
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"USER_BANNED"> | Handler for user banned events |
Returns
Unsubscribe function
Since
5.12.0
on user banned realtime listener
onUserTyping()
onUserTyping(
callback):Unsubscribe
Subscribe to user typing indicators
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"USER_TYPING"> | Handler for user typing events |
Returns
Unsubscribe function
Since
5.12.0
on user typing realtime listener
onUserUnbanned()
onUserUnbanned(
callback):Unsubscribe
Subscribe to user unban events
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"USER_UNBANNED"> | Handler for user unbanned events |
Returns
Unsubscribe function
Since
5.12.0
on user unbanned realtime listener
onViewerCountChanged()
onViewerCountChanged(
callback):Unsubscribe
Subscribe to viewer count changes
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | RealtimeListener<"VIEWER_COUNT"> | Handler for viewer count events |
Returns
Unsubscribe function
Since
5.12.0
on viewer count changed realtime listener
sendStreamChatViaWebSocket()
sendStreamChatViaWebSocket(
tokenName,content):void
Send a chat message via WebSocket.
Sends a chat message through the WebSocket connection for lower latency than the REST API. Requires prior authentication.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
content | string | Message content |
Returns
void
Promise resolving when sent
Throws
Error if not connected or authenticated
Since
5.1.0
Example
Send chat via WebSocket
await sdk.connectStreamWebSocket();
await sdk.authenticateStreamWebSocket();
await sdk.subscribeToStream('mytoken');
await sdk.sendStreamChatViaWebSocket('mytoken', 'Hello!');
send stream chat via web socket token name
sendStreamReaction()
sendStreamReaction(
tokenName,emoji,streamTime?):void
Send an ephemeral emoji reaction to a live stream.
Reactions are broadcast to all viewers via WebSocket but NOT persisted to database. Rate limiting is enforced server-side (burst of 10, then 0.5/sec refill).
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
emoji | string | Emoji to send (single emoji or short sequence, max 15 chars) |
streamTime? | number | Current stream timecode in seconds (for viewer sync, defaults to 0) |
Returns
void
Promise resolving when sent
Throws
Error if not connected or authenticated
Since
5.2.0
Example
Send a reaction during a live stream
await sdk.connectStreamWebSocket({
onReaction: (e) => console.log(`${e.emoji} from ${e.userAddress}`),
});
await sdk.authenticateStreamWebSocket();
await sdk.subscribeToStream('mytoken');
// Send a heart reaction at current stream position
const currentTime = player.getCurrentTime(); // from MuxPlayer
sdk.sendStreamReaction('mytoken', '❤️', currentTime);
send stream reaction token name time
sendTypingStart()
sendTypingStart(
tokenName):void
Send a typing indicator start event to a stream chat.
Indicates that the authenticated user has started typing. The indicator auto-clears after 5 seconds of inactivity on the server. Use sendTypingStop() to explicitly stop the indicator.
Requires:
- WebSocket connected via connectStreamWebSocket()
- Authenticated via authenticateStreamWebSocket()
- Subscribed to the stream via subscribeToStream()
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name for the stream chat room |
Returns
void
Throws
ValidationError if WebSocket not connected or not authenticated
Since
5.11.0
Example
Send typing indicator
await sdk.connectStreamWebSocket({
onTypingIndicator: (e) => console.log(`${e.typingUsers.length} users typing`),
});
await sdk.authenticateStreamWebSocket();
await sdk.subscribeToStream('mytoken');
// User starts typing
sdk.sendTypingStart('mytoken');
send typing start token name
sendTypingStop()
sendTypingStop(
tokenName):void
Send a typing indicator stop event to a stream chat.
Indicates that the authenticated user has stopped typing. Call this when the user sends a message, clears the input, or blurs the input.
Requires:
- WebSocket connected via connectStreamWebSocket()
- Authenticated via authenticateStreamWebSocket()
- Subscribed to the stream via subscribeToStream()
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name for the stream chat room |
Returns
void
Throws
ValidationError if WebSocket not connected or not authenticated
Since
5.11.0
Example
Stop typing indicator after sending message
await sdk.sendStreamChatViaWebSocket('mytoken', message);
sdk.sendTypingStop('mytoken');
send typing stop token name
subscribeToEvent()
subscribeToEvent<
T>(channel,callback): () =>void
Subscribe to WebSocket events on a specific channel
Allows custom subscription to WebSocket events. Returns a cleanup function that removes the listener when called.
Type Parameters
| Type Parameter | Description |
|---|---|
T | Type of event data |
Parameters
| Parameter | Type | Description |
|---|---|---|
channel | string | Event channel name |
callback | (data) => void | Function called when event is received |
Returns
Cleanup function to unsubscribe from the event
() => void
Since
3.29.0
Examples
Subscribe to custom channel
const unsubscribe = sdk.subscribeToEvent<PoolCreatedEvent>(
'pool:created',
(event) => {
console.log(`New pool: ${event.token0}/${event.token1}`);
}
);
// Later: Stop listening
unsubscribe();
Multiple subscriptions
const cleanup1 = sdk.subscribeToEvent('event1', handler1);
const cleanup2 = sdk.subscribeToEvent('event2', handler2);
// Cleanup all
cleanup1();
cleanup2();
subscribe to event
subscribeToStream()
subscribeToStream(
tokenName,callbacks?):Promise<StreamSubscribedEvent>
Subscribe to real-time events for a stream.
Joins the stream room and registers each callback in callbacks as a subscriber of that token.
Calling it again for a token ADDS callbacks (it replaces nothing). The room is joined once however
many callers share it; use the sdk.realtime.subscribe* methods for subscriptions that are released
one by one.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
callbacks? | StreamEventCallbacks | Event callbacks for this token |
Returns
Promise<StreamSubscribedEvent>
Promise resolving when the server confirms the room
Throws
Error if the connection fails or the server does not confirm within 10 seconds
Since
5.1.0
Example
Subscribe to a stream
await sdk.connectStreamWebSocket({
onStreamStatus: (e) => console.log(`Status: ${e.status}`),
onViewerCount: (e) => console.log(`Viewers: ${e.viewerCount}`),
});
await sdk.subscribeToStream('mytoken');
// Events will now fire for 'mytoken'
subscribe to stream token name subscribed event callbacks
unsubscribeFromStream()
unsubscribeFromStream(
tokenName):void
Remove what subscribeToStream registered for a token.
The token's room is left when no subscriber of any kind remains for it; other subscribers (from
sdk.realtime.subscribe*) are untouched.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenName | string | Token name (lowercase) |
Returns
void
Since
5.1.0
unsubscribe from stream token name subscribe to
watchBanEnforcement()
watchBanEnforcement(
callback,filters?): () =>void
Watch all user ban/unban/enforcement events, normalized into a single stream.
Composes onUserBanned/onUserUnbanned/onBanEnforcement (each a separate real-time
channel) into one callback tagged with actionType, and applies the given filters
client-side before invoking it - none of the three underlying events are filterable
server-side.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (event) => void | Called for each event that passes the filters |
filters? | { actionType?: "BANNED" | "UNBANNED" | "ENFORCEMENT"; reason?: string; tokenName?: string; userAddress?: string; } | Optional filters, all client-side |
filters.actionType? | "BANNED" | "UNBANNED" | "ENFORCEMENT" | Only invoke for 'BANNED' | 'UNBANNED' | 'ENFORCEMENT' |
filters.reason? | string | Only invoke when the event's reason contains this substring |
filters.tokenName? | string | Only invoke for this token (lowercase) |
filters.userAddress? | string | Only invoke for this user address |
Returns
Cleanup function that unsubscribes from all three underlying channels
() => void
Since
7.1.0
watch ban enforcement action type token name user address
watchCommentCreated()
watchCommentCreated(
callback,filters?): () =>void
Watch comment-created events for one token.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (event) => void | Called for each new comment on the token that passes the filters |
filters? | { authorAddress?: string; minLength?: number; tokenName?: string; } | Must include tokenName; authorAddress/minLength are client-side |
filters.authorAddress? | string | Only invoke for comments from this author |
filters.minLength? | number | Only invoke for comments at least this many characters long |
filters.tokenName? | string | The token to watch (required) |
Returns
Cleanup function
() => void
Throws
Error if filters.tokenName is missing
Since
7.1.0
watch comment created author address min length token name
watchHolderCountUpdated()
watchHolderCountUpdated(
callback,filters?): () =>void
Watch holder-count-updated events for one token.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (event) => void | Called whenever the token's holder count changes by at least minThreshold |
filters? | { minThreshold?: number; tokenName?: string; } | Must include tokenName; minThreshold is client-side |
filters.minThreshold? | number | Only invoke if the holder-count change is at least this large |
filters.tokenName? | string | The token to watch (required) |
Returns
Cleanup function
() => void
Throws
Error if filters.tokenName is missing
Since
7.1.0
watch holder count updated min threshold token name
watchModeratorAdded()
watchModeratorAdded(
callback,filters?): () =>void
Watch moderator-added events for one token.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (event) => void | Called whenever a moderator is added to the token |
filters? | { tokenName?: string; } | Must include tokenName |
filters.tokenName? | string | The token to watch (required) |
Returns
Cleanup function
() => void
Throws
Error if filters.tokenName is missing
Since
7.1.0
watch moderator added token name
watchModeratorChanged()
watchModeratorChanged(
callback,filters?): () =>void
Watch moderator added/removed/role-updated events for one token, normalized into a single actionType-tagged stream.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (event) => void | Called for each moderator change that passes the filters |
filters? | { eventType?: "ADDED" | "REMOVED" | "ROLE_UPDATED"; moderatorAddress?: string; tokenName?: string; } | Must include tokenName; eventType and moderatorAddress are client-side |
filters.eventType? | "ADDED" | "REMOVED" | "ROLE_UPDATED" | Only invoke for 'ADDED' | 'REMOVED' | 'ROLE_UPDATED' |
filters.moderatorAddress? | string | Only invoke for this moderator's address |
filters.tokenName? | string | The token to watch (required) |
Returns
Cleanup function that unsubscribes from all three underlying channels
() => void
Throws
Error if filters.tokenName is missing
Since
7.1.0
watch moderator changed event type role updated address token name
watchPoolMetadataUpdated()
watchPoolMetadataUpdated(
callback,filters?): () =>void
Watch pool-metadata-updated events for one token.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (event) => void | Called whenever the token's pool metadata changes |
filters? | { tokenName?: string; } | Must include tokenName |
filters.tokenName? | string | The token to watch (required) |
Returns
Cleanup function
() => void
Throws
Error if filters.tokenName is missing
Since
7.1.0
watch pool metadata updated token name
watchPoolUpdated()
watchPoolUpdated(
callback,filters?): () =>void
Watch pool metadata/social-links/badge-assigned events for one token, normalized into a single updateType-tagged stream.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (event) => void | Called for each pool update that passes the filters |
filters? | { tokenName?: string; updateType?: "METADATA" | "SOCIAL_LINKS" | "BADGE_ASSIGNED"; } | Must include tokenName; updateType is client-side |
filters.tokenName? | string | The token to watch (required) |
filters.updateType? | "METADATA" | "SOCIAL_LINKS" | "BADGE_ASSIGNED" | Only invoke for 'METADATA' | 'SOCIAL_LINKS' | 'BADGE_ASSIGNED' |
Returns
Cleanup function that unsubscribes from all three underlying channels
() => void
Throws
Error if filters.tokenName is missing
Since
7.1.0
watch pool updated token name update type social links badge assigned
watchTokenBanChanged()
watchTokenBanChanged(
callback,filters?): () =>void
Watch token banned/unbanned events for one token, normalized into a single banStatus-tagged stream (a TOKEN being restricted from trading/creation - distinct from watchBanEnforcement, which bans a USER from chat/platform activity).
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (event) => void | Called for each ban-status change that passes the filters |
filters? | { banStatus?: "BANNED" | "UNBANNED"; tokenName?: string; } | Must include tokenName; banStatus is client-side |
filters.banStatus? | "BANNED" | "UNBANNED" | Only invoke for 'BANNED' | 'UNBANNED' |
filters.tokenName? | string | The token to watch (required) |
Returns
Cleanup function that unsubscribes from both underlying channels
() => void
Throws
Error if filters.tokenName is missing
Since
7.1.0
watch token ban changed status name
watchTokenBanned()
watchTokenBanned(
callback,filters?): () =>void
Watch token-banned events for one token (a token being restricted from trading - distinct from watchBanEnforcement/onUserBanned, which ban a USER from chat/platform activity).
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (event) => void | Called if/when the token is banned |
filters? | { tokenName?: string; } | Must include tokenName |
filters.tokenName? | string | The token to watch (required) |
Returns
Cleanup function
() => void
Throws
Error if filters.tokenName is missing
Since
7.1.0
watch token banned name
watchTradeExecuted()
watchTradeExecuted(
callback,filters?): () =>void
Watch trade-executed events for one token.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (event) => void | Called for each executed trade on the token that passes the filters |
filters? | { minAmount?: number; tokenName?: string; tradeType?: "BUY" | "SELL"; userAddress?: string; } | Must include tokenName; tradeType/minAmount/userAddress are client-side |
filters.minAmount? | number | Only invoke when inputAmount is at least this large |
filters.tokenName? | string | The token to watch (required) |
filters.tradeType? | "BUY" | "SELL" | Only invoke for 'BUY' or 'SELL' trades |
filters.userAddress? | string | Only invoke for trades from this user address |
Returns
Cleanup function
() => void
Throws
Error if filters.tokenName is missing
Since
7.1.0
watch trade executed min amount token name type user address
WeeklyChallenge
weekly challenge
getTokenWeeklyHistory()
getTokenWeeklyHistory(
options):Promise<GetTokenWeeklyHistoryResult>
Get weekly snapshot history for a specific token.
Returns the last 4 weeks of snapshot data for tracking performance over time.
Public endpoint - no authentication required.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | GetTokenWeeklyHistoryOptions | Options with vaultAddress |
Returns
Promise<GetTokenWeeklyHistoryResult>
Array of weekly snapshots with market cap and price data
Throws
ValidationError if vaultAddress is missing or invalid
Since
9.0.0
Example
Get token weekly history
const { snapshots } = await sdk.getTokenWeeklyHistory({
vaultAddress: 'eth|abc123...'
});
for (const snap of snapshots) {
const date = new Date(snap.snapshotDate).toLocaleDateString();
console.log(`${date}: ${snap.marketCapGala} GALA`);
}
// Calculate week-over-week change
if (snapshots.length >= 2) {
const current = parseFloat(snapshots[0].marketCapGala);
const previous = parseFloat(snapshots[1].marketCapGala);
const change = ((current - previous) / previous * 100).toFixed(2);
console.log(`Week-over-week change: ${change}%`);
}
get token weekly history result options
getWeeklyChallengeLeaderboard()
getWeeklyChallengeLeaderboard(
options?):Promise<GetWeeklyChallengeResult>
Get the weekly challenge leaderboard.
Returns tokens ranked by market cap increase for the current challenge week. The challenge week runs Saturday to Friday, with Saturday being the baseline.
Public endpoint - no authentication required.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | GetWeeklyChallengeOptions | Options including limit (1-50, default 10) |
Returns
Promise<GetWeeklyChallengeResult>
Leaderboard with ranked tokens, week dates, and snapshot info
Throws
ValidationError if limit is out of range
Since
9.0.0
Example
Get top 10 tokens in weekly challenge
const { leaderboard } = await sdk.getWeeklyChallengeLeaderboard({ limit: 10 });
console.log(`Week: ${leaderboard.weekStart} to ${leaderboard.weekEnd}`);
console.log(`Total tokens: ${leaderboard.count}`);
for (const token of leaderboard.tokens) {
console.log(`#${token.rank} ${token.symbol}: +${token.marketCapIncreaseGala} GALA`);
}
get weekly challenge leaderboard result options
Wrap/Unwrap
estimateUnwrapFee()
estimateUnwrapFee(
tokenId,amount):Promise<WrapUnwrapFeeEstimate>
Estimate fees for an unwrap operation
Calculates expected fees for unwrapping a token back to its native channel.
Unwrap operations use automatic fee authorization.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenId | TokenId | Token class key (pipe-delimited string or TokenClassKey; a bare symbol is refused) |
amount | string | Amount to unwrap (decimal string) |
Returns
Promise<WrapUnwrapFeeEstimate>
Promise resolving to fee estimate
Throws
GalaSDKError TOKEN_NOT_WRAPPABLE, INVALID_WRAP_DIRECTION, INVALID_BRIDGE_AMOUNT
Since
4.0.18
Example
Estimate unwrap fee
const estimate = await sdk.estimateUnwrapFee('$GMUSIC|Unit|none|none', '50');
console.log(`Fee: ${estimate.fee} ${estimate.feeToken}`);
console.log(`Auth type: ${estimate.authorizationType}`);
estimate unwrap fee token id wrap not wrappable invalid direction bridge amount
estimateWrapFee()
estimateWrapFee(
tokenId,amount):Promise<WrapUnwrapFeeEstimate>
Estimate fees for a wrap operation
Calculates expected fees for wrapping a token to the asset channel.
Wrap operations use cross_channel_authorization fee type.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenId | TokenId | Token class key (pipe-delimited string or TokenClassKey; a bare symbol is refused) |
amount | string | Amount to wrap (decimal string) |
Returns
Promise<WrapUnwrapFeeEstimate>
Promise resolving to fee estimate
Throws
GalaSDKError TOKEN_NOT_WRAPPABLE, INVALID_WRAP_DIRECTION, INVALID_BRIDGE_AMOUNT
Since
4.0.18
Example
Estimate wrap fee
const estimate = await sdk.estimateWrapFee('$MUSIC|Unit|none|none', '100');
console.log(`Fee: ${estimate.fee} ${estimate.feeToken}`);
console.log(`Auth type: ${estimate.authorizationType}`);
estimate wrap fee token id unwrap cross channel authorization not wrappable invalid direction bridge amount
unwrapToken()
unwrapToken(
options):Promise<WrapUnwrapResult>
Unwrap a token back to its native channel
Converts tokens from the asset channel back to their native channel. Reverses a previous wrap operation. Example: GMUSIC (asset channel) → MUSIC (music channel)
Note: This is an internal GalaChain cross-channel operation, NOT an external bridge (Ethereum/Solana).
Parameters
| Parameter | Type | Description |
|---|---|---|
options | UnwrapTokenOptions | Unwrap options including tokenId and amount |
Returns
Promise<WrapUnwrapResult>
Promise resolving to the completed unwrap
Throws
GalaSDKError (@gala-chain/gala-core-sdk): as wrapToken
(INVALID_WRAP_DIRECTION for a token not on the asset channel)
Since
4.0.18
Example
Unwrap GMUSIC to MUSIC
const result = await sdk.unwrapToken({
tokenId: '$GMUSIC|Unit|none|none',
amount: '50'
});
console.log(`Unwrapped ${result.amount} ${result.fromToken} → ${result.toToken}`);
unwrap token wrap result options invalid direction
wrapToken()
wrapToken(
options):Promise<WrapUnwrapResult>
Wrap a token to its asset-channel counterpart
Converts tokens from their native channel to the asset channel. This is required for some tokens to be traded on the DEX. Example: MUSIC (music channel) → GMUSIC (asset channel)
Note: This is an internal GalaChain cross-channel operation, NOT an external bridge (Ethereum/Solana).
Parameters
| Parameter | Type | Description |
|---|---|---|
options | WrapTokenOptions | Wrap options including tokenId and amount |
Returns
Promise<WrapUnwrapResult>
Promise resolving to the completed wrap
Throws
GalaSDKError (@gala-chain/gala-core-sdk): TOKEN_NOT_WRAPPABLE,
INVALID_WRAP_DIRECTION (already on the asset channel), INVALID_BRIDGE_OPTION (no wallet),
BRIDGE_REQUEST_REJECTED (GalaChain refused it: nothing locked), BRIDGE_OUT_OUTCOME_UNKNOWN
(accepted, then failed: never wrap again)
Since
4.0.18
Examples
Wrap MUSIC to GMUSIC
// token ids are class keys (a bare symbol such as 'MUSIC' is refused)
const result = await sdk.wrapToken({
tokenId: '$MUSIC|Unit|none|none',
amount: '100'
});
console.log(`Wrapped ${result.amount} ${result.fromToken} → ${result.toToken}`);
console.log(`Transaction: ${result.transactionId}`);
With a recipient
const result = await sdk.wrapToken({
tokenId: '$MUSIC|Unit|none|none',
amount: '50',
recipient: 'eth|1234...',
});
wrap token unwrap result options not wrappable invalid direction bridge option request rejected out outcome unknown
Wrappable Tokens
fetchAllWrappableTokens()
fetchAllWrappableTokens():
Promise<FetchWrappableTokensResult>
Fetch ALL wrappable tokens with auto-pagination
Automatically handles pagination to retrieve all wrappable tokens. Returns cached data if available; fetches from API otherwise.
For balance data, use fetchAllWrappableTokenBalances instead.
Returns
Promise<FetchWrappableTokensResult>
Promise resolving to all wrappable tokens
Throws
NetworkError if DEX API is unavailable
Since
4.0.18
Example
Fetch all wrappable tokens
const result = await sdk.fetchAllWrappableTokens();
console.log(`Total: ${result.tokenCount} tokens`);
result.tokens.forEach(t => {
console.log(`${t.symbol} ↔ ${t.wrapCounterpart}`);
});
fetch all wrappable tokens result
fetchWrappableTokens()
fetchWrappableTokens(
options?):Promise<FetchWrappableTokensResult>
Fetch wrappable tokens with pagination
Fetches tokens that can be wrapped/unwrapped (e.g., MUSIC ↔ GMUSIC). Results are cached permanently for the SDK lifetime.
For balance data, use fetchWrappableTokenBalances instead.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | FetchWrappableTokensOptions | Fetch options including pagination |
Returns
Promise<FetchWrappableTokensResult>
Promise resolving to fetch result with tokens array
Throws
NetworkError if DEX API is unavailable
Since
4.0.18
Example
Paginated fetch
const result = await sdk.fetchWrappableTokens({
pageSize: 100
});
console.log(`Found ${result.tokenCount} wrappable tokens`);
fetch wrappable tokens result options
getWrapCounterpart()
getWrapCounterpart(
tokenId):Promise<WrappableToken|undefined>
Get the wrap counterpart for a token
Returns the token that the given token can be wrapped/unwrapped to. For example, MUSIC → GMUSIC or GMUSIC → MUSIC.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenId | TokenId | Token identifier (pipe-delimited string or TokenClassKey) |
Returns
Promise<WrappableToken | undefined>
Promise resolving to counterpart token or undefined
Throws
NetworkError if DEX API is unavailable
Throws
ValidationError if tokenId format is invalid
Since
4.0.18
Example
Get GMUSIC from MUSIC
const counterpart = await sdk.getWrapCounterpart('$MUSIC|Unit|none|none');
console.log(counterpart?.symbol); // "GMUSIC"
get wrap counterpart token id wrappable
getWrappableToken()
getWrappableToken(
tokenId):Promise<WrappableToken|undefined>
Get a wrappable token by tokenId
Uses cache for efficient lookup. If cache not populated, fetches first.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenId | TokenId | Token identifier (pipe-delimited string or TokenClassKey) |
Returns
Promise<WrappableToken | undefined>
Promise resolving to wrappable token or undefined
Throws
NetworkError if DEX API is unavailable
Throws
ValidationError if tokenId format is invalid
Since
4.0.18
Examples
Get MUSIC token
const token = await sdk.getWrappableToken('$MUSIC|Unit|none|none');
if (token) {
console.log(`${token.symbol} wraps to ${token.wrapCounterpart}`);
}
Using TokenClassKey object
const token = await sdk.getWrappableToken({
collection: '$MUSIC',
category: 'Unit',
type: 'none',
additionalKey: 'none'
});
get wrappable token id
isTokenWrappable()
isTokenWrappable(
tokenId):Promise<IsTokenWrappableResult>
Check if a token is wrappable
Returns wrappability status and counterpart token ID if available. Uses cached data for efficient lookups; fetches from API if not cached.
Parameters
| Parameter | Type | Description |
|---|---|---|
tokenId | TokenId | Token identifier (pipe-delimited string or TokenClassKey) |
Returns
Promise<IsTokenWrappableResult>
Promise resolving to wrappability check result
Throws
NetworkError if DEX API is unavailable
Throws
ValidationError if tokenId format is invalid
Since
4.0.18
Examples
Check if MUSIC is wrappable
const result = await sdk.isTokenWrappable('$MUSIC|Unit|none|none');
if (result.isWrappable) {
console.log(`MUSIC can wrap to: ${result.wrapCounterpart}`);
}
Using TokenClassKey object
const result = await sdk.isTokenWrappable({
collection: '$MUSIC',
category: 'Unit',
type: 'none',
additionalKey: 'none'
});
is token wrappable id result