UNPKG

@faktoryfun/core-sdk

Version:

The official SDK for interacting with Faktory tokens and DEX contracts

545 lines (415 loc) 17.7 kB
# Faktory SDK The official SDK for interacting with Faktory tokens and DEX contracts on Stacks. Getting started is straightforward with zero configuration required - no API keys needed and sensible defaults out of the box. ⚠️ Important: Token supply cannot exceed 1 billion tokens for better relatability. Note: If you receive a 500 status error during token creation, check if your supply exceeds 1 billion tokens. Please reduce the supply to 1 billion or less for better token relatability and market dynamics. ## Installation ```bash npm install @faktoryfun/core-sdk ``` ## Quick Start ```typescript import { FaktorySDK } from "@faktoryfun/core-sdk"; // Basic initialization (mainnet) const sdk = new FaktorySDK({ network: "mainnet", }); // For testnet const sdk = new FaktorySDK({ network: "testnet", }); // Or with custom configuration const sdk = new FaktorySDK({ network: "mainnet" | "testnet", apiHost: "your-api-host", // optional apiKey: "your-api-key", // optional hiroApiKey: "your-hiro-api-key", // optional }); ``` ## Features ### Buy Tokens The SDK supports both STX and BTC denominated tokens. It automatically detects the token's denomination and applies the appropriate conversion. ```typescript // Get buy parameters for STX-denominated tokens const buyParams = await sdk.getBuyParams({ dexContract: "SP000.token-dex", stx: 0.1, // amount in STX (converts to 100,000 microSTX) senderAddress: "SP000...", slippage: 15, // optional, default 15% }); // Get buy parameters for BTC-denominated tokens const buyBtcParams = await sdk.getBuyParams({ dexContract: "SP000.btc-token-dex", stx: 0.002, // amount in BTC (converts to 200,000 satoshis) senderAddress: "SP000...", slippage: 15, // optional, default 15% }); // User handles signing and broadcasting const tx = await makeContractCall(buyParams); const signedTx = await wallet.signTransaction(tx); const broadcastedTx = await broadcastTransaction(signedTx, network); ``` **Important:** The `stx` parameter represents the base unit amount: - For STX-denominated tokens: Input in STX (e.g., 0.1 STX = 100,000 microSTX) - For BTC-denominated tokens: Input in BTC (e.g., 0.002 BTC = 200,000 satoshis) The SDK automatically detects the token's denomination from the contract and applies the appropriate conversion: - STX: × 10^6 (microSTX) - BTC: × 10^8 (satoshis) ### Buy Token Amount Limits The SDK incorporates a built-in safety mechanism to prevent users from accidentally deploying excess funds during token purchases. When buying tokens, the SDK automatically: 1. Checks the contract's recommended remaining purchase amount (which already includes a 3% buffer for fees) 2. Caps your purchase at 15% above this recommended amount if exceeded 3. Proceeds with the transaction using the adjusted amount 4. Logs a notification about the adjustment **STX Example:** ```typescript // If a token needs only 100 STX more to graduate, but you try to buy with 1000 STX: const buyParams = await sdk.getBuyParams({ dexContract: "SP000.token-dex", inAmount: 1000, // Will be automatically capped at ~118.45 STX (100 * 1.03 * 1.15) senderAddress: "SP000...", slippage: 15, }); // The transaction will use the capped amount without error ``` **BTC Example:** ```typescript // If a token needs only 0.01 BTC more to graduate, but you try to buy with 0.1 BTC: const buyParams = await sdk.getBuyParams({ dexContract: "SP000.btc-token-dex", inAmount: 0.1, // Will be automatically capped at ~0.01185 BTC (0.01 * 1.03 * 1.15) senderAddress: "SP000...", slippage: 15, }); // The transaction will use the capped amount without error ``` **How it works:** - For internal DEX contracts: Uses the `stx-to-grad` value (which includes a 3% buffer) - For external DEX contracts: Uses the `recommend-stx-amount` value (which includes a 3% buffer) - For both types, the SDK adds an additional 15% leeway - Total maximum allowed is approximately original amount _ 1.03 _ 1.15 This protection helps prevent: - Overpaying during token purchases - Deploying excess capital for nearly-graduated tokens - Unnecessary transaction costs The combined buffer (approximately 18.45% total) provides flexibility while maintaining protection against significant overspending. **Note:** The capping is silent and allows the transaction to continue, making it more user-friendly than a hard error. ### Sell Tokens ```typescript // Get sell parameters - works for both STX and BTC denominated tokens const sellParams = await sdk.getSellParams({ dexContract: "SP000.token-dex", amount: 1000, // amount of tokens (automatically scaled by token decimals) senderAddress: "SP000...", slippage: 15, // optional, default 15% }); // User handles signing and broadcasting const tx = await makeContractCall(sellParams); const signedTx = await wallet.signTransaction(tx); const broadcastedTx = await broadcastTransaction(signedTx, network); ``` For sell operations, the SDK automatically detects if the token is BTC-denominated and creates the appropriate post conditions. ### Get Price Quotes ```typescript // Get buy quote const buyQuote = await sdk.getIn( "SP000.token-dex", "SP000...", // sender address 0.1 // amount in STX (not microSTX) ); // Get sell quote const sellQuote = await sdk.getOut( "SP000.token-dex", "SP000...", // sender address 1000 // token amount (will be scaled by token decimals) ); ``` ## Token Creation Faktory SDK provides a method for creating tokens through manual deployment: ### Manual Deployment (getTokenDeployParams) ```typescript // Get deployment parameters and handle deployment yourself const params = await sdk.getTokenDeployParams({ symbol: "TOKEN", name: "My Token", description: "A test token", supply: 69000000, targetStx: 1, creatorAddress: "SP2...", initialBuyAmount: 0.1, targetAmm: "SP2..." }); // Returns: { tokenCode: "...", // Token contract code dexCode: "...", // DEX contract code amounts: { dexTokens: "...", // Tokens sent to DEX deployerTokens: "...", // Tokens sent to deployer dexStx: number, // STX in DEX after first buy premiumStx: number // First buy amount in STX } } ``` With manual deployment: You receive complete contract code and parameters You handle contract deployments yourself You manage transaction signing and broadcasting First buy parameters are included for proper setup Required Fields All token creation requires these fields: symbol: Token ticker (e.g., "TOKEN") name: Token name description: Token description supply: Total token supply (capped at 1 billion tokens for better relatability). targetStx: Target STX liquidity to reach prior to graduation to AMM creatorAddress: Contract deployer's address initialBuyAmount: First buy amount in STX to protect against snipers (optional) targetAmm: Target AMM address for final liquidity Optional Fields You can also include: uri: Token metadata URI logoUrl: Token logo URL mediaUrl: Token media URL twitter: Twitter URL website: Website URL telegram: Telegram URL discord: Discord URL ### Browse Verified Tokens ```typescript const tokens = await sdk.getVerifiedTokens({ search: "search term", // optional sortOrder: "asc", // optional page: 1, // optional limit: 10, // optional daoOnly: true, // optional - filter for DAO tokens only - false returns non-DAO tokens }); // Convenience method to get DAO tokens const daoTokens = await sdk.getDaoTokens(); ``` ### Get a single Token Get details about a specific token by its DEX contract. ```typescript // Get a single token by DEX contract const token = await sdk.getToken( "SP2XCME6ED8RERGR9R7YDZW7CA6G3F113Y8JMVA46.tcorn-stxcity-dex" ); ``` Parameters: dex_contract: DEX contract identifier ### Get Token Trade History ```typescript // Fetch recent trades for a specific token const trades = await sdk.getTokenTrades( "SP2XCME6ED8RERGR9R7YDZW7CA6G3F113Y8JMVA46.nothing-faktory" ); // Response includes up to 100 most recent trades interface TokenTrade { txId: string; // Transaction ID tokenContract: string; // Token contract type: string; // "buy" or "sell" tokensAmount: number; // Amount of tokens ustxAmount: number; // Amount in microSTX pricePerToken: number; // Price per token in STX maker: string; // Maker address timestamp: number; // Unix timestamp } ``` Returns the 100 most recent trades for a specific token, ordered by timestamp. Each trade includes complete transaction details including amounts, prices, and participant addresses. ### Verify Token Transfer ```typescript const verification = await sdk.verifyTransfer("SP000.token"); ``` ## Error Handling The SDK throws descriptive errors that can be caught and handled: ```typescript try { const params = await sdk.getBuyParams({...}); } catch (error) { console.error("Failed to get buy parameters:", error); } ``` ## Configuration Options - `network`: "mainnet" or "testnet" [required] - `apiHost`: Faktory API endpoint [optional, defaults to Faktory API based on network] - `apiKey`: Your Faktory API key [optional, defaults to public key] - `hiroApiKey`: Optional Hiro API key for enhanced rate limits ## Types The SDK is fully typed with TypeScript. Key types include: - `TokenCreationInput`: Parameters for creating new tokens - `TransferVerification`: Response from transfer verification - `ReadResponse`: Response from read-only functions. The response structure varies between internal and external DEX contracts: ````typescript // For internal DEX responses (faktory-dex) interface InternalReadResponse { value: { value: { 'tokens-out'?: { value: string }; // From getIn 'new-stx'?: { value: string }; // From getIn 'stx-out'?: { value: string }; // From getOut } } } // For external DEX responses interface ExternalReadResponse { value: { value: { 'buyable-token'?: { value: string }; // From getIn 'stx-balance'?: { value: string }; // From getIn 'stx-buy'?: { value: string }; // From getIn 'stx-out'?: { value: string }; // From getOut } } } type ReadResponse = InternalReadResponse | ExternalReadResponse; ## Pre-Launch System Faktory's pre-launch system allows early participants to buy seats before token deployment. Seat holders receive vested tokens and participate in fee distribution from the DEX. ### Buy Pre-Launch Seats Purchase seats in a pre-launch offering using sBTC (Stacks-wrapped Bitcoin). ```typescript // Get buy seats parameters const buySeatsParams = await sdk.getBuySeatsParams({ prelaunchContract: "SP000.token-pre-faktory", seatCount: 3, // Number of seats to purchase (1-7 per user) senderAddress: "SP000...", contractType: "dao", // "dao", "meme", or "helico" - optional, auto-detected }); // User handles signing and broadcasting const tx = await makeContractCall(buySeatsParams); const signedTx = await wallet.signTransaction(tx); const broadcastedTx = await broadcastTransaction(signedTx, network); ``` **Seat Pricing:** - **DAO tokens**: 0.00020000 BTC per seat (20 seats total, 10 users minimum) - **Meme tokens**: 0.00069000 BTC per seat (20 seats total, 10 users minimum) - **Helico tokens**: 0.00006900 BTC per seat (200 seats total, 100 users minimum) ### Refund Pre-Launch Seats Refund your seats before the pre-launch completes and distribution begins. ```typescript // Get refund parameters const refundParams = await sdk.getRefundParams({ prelaunchContract: "SP000.token-pre-faktory", senderAddress: "SP000...", contractType: "dao", // optional, auto-detected }); // User handles signing and broadcasting const tx = await makeContractCall(refundParams); const signedTx = await wallet.signTransaction(tx); const broadcastedTx = await broadcastTransaction(signedTx, network); ``` ### Claim Vested Tokens Claim your vested tokens from a completed pre-launch. Tokens vest over time according to a predetermined schedule. ```typescript // Get claim parameters const claimParams = await sdk.getClaimParams({ prelaunchContract: "SP000.token-pre-faktory", tokenContract: "SP000.token-faktory", senderAddress: "SP000...", }); // User handles signing and broadcasting const tx = await makeContractCall(claimParams); const signedTx = await wallet.signTransaction(tx); const broadcastedTx = await broadcastTransaction(signedTx, network); ``` **Vesting Schedule:** - **10%** available immediately after pre-launch completion - **90%** vested over time through multiple unlock periods - Tokens can be claimed as they vest - Accelerated vesting if token graduates to bonding curve ### Trigger Fee Airdrop Trigger distribution of accumulated DEX fees to all seat holders. Anyone can call this function when conditions are met. ```typescript // Get trigger fee airdrop parameters const airdropParams = await sdk.getTriggerFeeAirdropParams({ prelaunchContract: "SP000.token-pre-faktory", senderAddress: "SP000...", }); // User handles signing and broadcasting const tx = await makeContractCall(airdropParams); const signedTx = await wallet.signTransaction(tx); const broadcastedTx = await broadcastTransaction(signedTx, network); ``` **Fee Distribution:** - Accumulated trading fees from the DEX are distributed proportionally to seat holders - Anyone can trigger the airdrop when cooldown period expires - Fees are distributed based on seat ownership percentage ### Check Market Status Check if the DEX market is open and trading is active (indicates pre-launch completion). ```typescript // Check if market is open (read-only) const marketStatus = await sdk.isMarketOpen( "SP000.token-pre-faktory", "SP000..." // sender address ); // Returns: { value: { type: "bool", value: true/false } } const isOpen = marketStatus.value.value; // boolean ``` ### Get Pre-Launch Status Get comprehensive pre-launch information including user data, remaining seats, and seat holders. ```typescript // Get complete pre-launch status const status = await sdk.getPrelaunchStatus( "SP000.token-pre-faktory", "SP000..." // sender address ); // Returns detailed information about: // - Contract status (users, seats taken, distribution period) // - User info (seats owned, amount claimed, claimable amount) // - Remaining seats // - Maximum seats allowed // - All seat holders ``` **Note:** This method may hit execution cost limits on contracts with many participants. Use `isMarketOpen()` for simple status checks. ## Pre-Launch Process Flow 1. **Pre-Launch Phase**: Users buy seats with sBTC 2. **Completion**: When minimum users and total seats are reached 3. **Distribution Setup**: Tokens allocated to pre-launch contract for vesting 4. **DEX Activation**: Market opens and remaining tokens/sBTC sent to DEX 5. **Vesting**: Seat holders claim tokens according to vesting schedule 6. **Fee Sharing**: Ongoing DEX fees distributed to seat holders ## Pre-Launch Important Notes - **sBTC Required**: All pre-launch transactions use sBTC (Stacks-wrapped Bitcoin) - **Seat Limits**: Maximum 7 seats per user across all pre-launch types - **Auto-Detection**: SDK automatically detects contract type and pricing - **Network Support**: Works on both mainnet and testnet - **Validation**: Built-in validation for seat limits and completion requirements ## Security Note This SDK never handles private keys or signing. All transaction signing should be handled by the user's wallet implementation. ## Example Implementation For a complete example of how to use this SDK with wallet integration and transaction signing, check out our test implementation repository: [faktory-sdk-examples](https://github.com/FaktoryFun/test-sdk-examples) This repository includes working examples of: - Token buying with wallet integration - Token selling with transaction signing - Token creation - Transfer verification - Transaction parameter building - Working with mnemonics and private keys - Error handling and logging These examples demonstrate how to integrate the SDK with your own wallet implementation and handle transaction signing and broadcasting. ## Testing The SDK supports both mainnet and testnet environments. For testing purposes, we recommend: 1. Using testnet for initial development and testing 2. Using smaller amounts on testnet to validate your integration 3. Testing all features (create, buy, sell) on testnet before moving to mainnet Example testnet configuration: ```typescript const testnetSdk = new FaktorySDK({ network: "testnet", }); // Test token creation on testnet const testToken = await testnetSdk.createToken({ symbol: "TEST", name: "Test Token", description: "Testing on testnet", supply: 69000000, targetStx: 1, creatorAddress: "ST...", // Your testnet address initialBuyAmount: 0.1, targetAmm: "ST...", // Testnet AMM address }); ```` ## Disclaimer THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The user acknowledges that trading cryptocurrencies involves substantial risk and any trading decisions are made at their own risk. Past performance is not indicative of future results. This SDK is provided as a tool for interacting with smart contracts and should not be considered as financial advice. ``` ```