### Install satsterminal-sdk Source: https://www.npmjs.com/package/satsterminal-sdk/index Instructions for installing the satsterminal-sdk package using npm. ```bash npm i satsterminal-sdk ``` -------------------------------- ### Example: User Sign In Source: https://www.npmjs.com/package/satsterminal-sdk/index Illustrates how to use the signIn method to authenticate a user with their wallet details. This is crucial for user-specific operations. ```javascript const signIn = await satsTerminal.signIn({ ord_address: "bc1...", btc_address: "3Pc...", ord_public_key: "...", btc_public_key: "...", provider: "xverse" }); ``` -------------------------------- ### Example: Fetch Popular Collections Source: https://www.npmjs.com/package/satsterminal-sdk/index Demonstrates how to call the popularCollections method to get a list of trending rune collections. ```javascript const collections = await satsTerminal.popularCollections(); ``` -------------------------------- ### Install SatsTerminal SDK Source: https://www.npmjs.com/package/satsterminal-sdk/index Installs the latest version of the SatsTerminal SDK using npm. ```bash npm install satsterminal-sdk@latest ``` -------------------------------- ### Environment Variable Setup Source: https://www.npmjs.com/package/satsterminal-sdk/index Demonstrates how to set up the SatsTerminal API key using environment variables in a .env file and load it with dotenv. ```javascript require('dotenv').config(); ``` -------------------------------- ### Example: Search for Runes with Options Source: https://www.npmjs.com/package/satsterminal-sdk/index Provides an example of using the search method with an optional parameter to filter for sell orders. ```javascript const result = await satsTerminal.search({ rune_name: 'LOBO•THE•WOLF•PUP', sell: false }); ``` -------------------------------- ### Example: Get Points Balance Source: https://www.npmjs.com/package/satsterminal-sdk/index Shows how to retrieve a user's Amber points balance using the points method, requiring the user's Ordinals address. ```javascript const points = await satsTerminal.points({ ord_address: "bc1..." }); ``` -------------------------------- ### Example: Bind Wallet Source: https://www.npmjs.com/package/satsterminal-sdk/index Demonstrates the usage of the bind method to link a user's wallet. This is a prerequisite for performing transactions. ```javascript const bind = await satsTerminal.bind({ btcAddress: "3Pc...", nftAddress: "bc1...", sign: "user_signature_here" }); ``` -------------------------------- ### Buy Runes with RBF Protection Source: https://www.npmjs.com/package/satsterminal-sdk/index Demonstrates a full example flow for buying runes with RBF protection. It includes fetching quotes, creating PSBTs, obtaining user input for signed PSBTs (including RBF), and confirming the transaction. This example requires user interaction for signing. ```javascript import { SatsTerminal } from 'satsterminal-sdk'; import readlineSync from 'readline-sync'; // Configuration const CONFIG = { apiKey: 'your_api_key_here', baseURL: 'https://api.satsterminal.com/v1', timeout: 30000 // 30 seconds timeout }; // Trade Parameters const TRADE_PARAMS = { runeName: 'LOBO•THE•WOLF•PUP', address: 'bc1p...', publicKey: '...', paymentAddress: '3Pc...', paymentPublicKey: '...', btcAmount: 0.0001, rbfProtection: true, marketplaces: ["MagicEden"], fill: true }; // Initialize the SDK const satsTerminal = new SatsTerminal(CONFIG); // Function to get user input for signed PSBT const getSignedPSBT = () => { console.log('\nPlease sign the PSBT and enter the signed PSBT base64 string:'); return readlineSync.question('Signed PSBT: '); }; // Function to get user input for signed RBF PSBT const getSignedRbfPSBT = () => { console.log('\nPlease sign the RBF protection PSBT and enter the signed RBF PSBT base64 string:'); return readlineSync.question('Signed RBF PSBT: '); }; // Main execution (async () => { try { // 1. Get a quote for the trade console.log('\n1. Fetching quote...'); const quote = await satsTerminal.fetchQuote({ btcAmount: TRADE_PARAMS.btcAmount, runeName: TRADE_PARAMS.runeName, address: TRADE_PARAMS.address, marketplaces: TRADE_PARAMS.marketplaces, rbfProtection: TRADE_PARAMS.rbfProtection, fill: TRADE_PARAMS.fill }); console.log('Best marketplace:', quote.bestMarketplace); console.log('Quote:', quote.selectedOrders); // 2. Create a PSBT console.log('\n2. Creating PSBT...'); const psbtResponse = await satsTerminal.getPSBT({ orders: quote.selectedOrders, address: TRADE_PARAMS.address, publicKey: TRADE_PARAMS.publicKey, paymentAddress: TRADE_PARAMS.paymentAddress, paymentPublicKey: TRADE_PARAMS.paymentPublicKey, utxos: [], feeRate: 5, runeName: TRADE_PARAMS.runeName, themeID: null, sell: false, slippage: 9, rbfProtection: TRADE_PARAMS.rbfProtection }); console.log('PSBT created:', psbtResponse); // Wait for user to input the signed PSBT const signedPsbtBase64 = getSignedPSBT(); // Get signed RBF PSBT if RBF protection is enabled let signedRbfPsbtBase64 = null; if (TRADE_PARAMS.rbfProtection && psbtResponse.rbfProtected.base64) { console.log('\nRBF Protection PSBT:', psbtResponse.rbfProtected.base64); signedRbfPsbtBase64 = getSignedRbfPSBT(); } // 3. Confirm the PSBT after signing console.log('\n3. Confirming PSBT...'); const confirmation = await satsTerminal.confirmPSBT({ orders: quote.selectedOrders, address: TRADE_PARAMS.address, publicKey: TRADE_PARAMS.publicKey, paymentAddress: TRADE_PARAMS.paymentAddress, paymentPublicKey: TRADE_PARAMS.paymentPublicKey, signedRbfPsbtBase64: signedRbfPsbtBase64, swapId: psbtResponse.swapId, runeName: TRADE_PARAMS.runeName, rbfProtection: TRADE_PARAMS.rbfProtection, signedPsbtBase64: signedPsbtBase64 }); console.log('Confirmation:', confirmation); } catch (error) { console.error('Error:', error.message); // Provide more helpful information for network errors if (error.code === 'ECONNREFUSED') { console.error('Connection refused. Make sure the API server is running and accessible.'); } else if (error.code === 'ECONNRESET' || error.message.includes('socket hang up')) { console.error('Connection was reset or timed out. This could be due to:'); console.error('- Network connectivity issues'); console.error('- Server overload or maintenance'); console.error('- Invalid API key or authentication'); console.error('- Request timeout (the operation might take longer than expected)'); } if (process.env.NODE_ENV === 'development') { console.error('Full error:', error); } } })(); ``` -------------------------------- ### Search for Runes Source: https://www.npmjs.com/package/satsterminal-sdk/index An example of how to use the search method to find runes by name. It shows the asynchronous nature of the call and the expected result. ```javascript const searchResult = await satsTerminal.search({ rune_name: 'DOG•GO•TO•THE•MOON' }); ``` -------------------------------- ### Troubleshooting PSBT Errors Source: https://www.npmjs.com/package/satsterminal-sdk/index A guide to resolving errors encountered with Partially Signed Bitcoin Transactions (PSBTs). It covers ensuring all parameters are present, validating the PSBT, checking public keys and addresses, and verifying UTXO validity. ```APIDOC PSBT Errors: - Ensure all required parameters are provided - Ensure the PSBT is valid and signed - Verify the format of public keys and addresses - Check if UTXOs are valid and confirmed ``` -------------------------------- ### Initialize SatsTerminal SDK Source: https://www.npmjs.com/package/satsterminal-sdk/index Demonstrates how to import and initialize the SatsTerminal SDK with an API key. This is the first step to using the SDK's functionalities. ```javascript import { SatsTerminal } from 'satsterminal-sdk'; const satsTerminal = new SatsTerminal({ apiKey: 'your_api_key_here' }); ``` -------------------------------- ### SatsTerminal SDK API Reference Source: https://www.npmjs.com/package/satsterminal-sdk/index Provides an overview of the SatsTerminal SDK's API, including configuration and available methods. ```APIDOC SatsTerminal SDK API: Configuration: - SATSTERMINAL_API_KEY: Your API key obtained from the SatsTerminal Admin Dashboard. Can be set via environment variables or passed directly to the constructor. Methods: signIn(apiKey: string): Promise - Authenticates a user or application with the SatsTerminal API. - Parameters: - apiKey: The API key for authentication. - Returns: A promise that resolves with the user session information. bind(userSession: UserSession, walletAddress: string): Promise - Binds a wallet address to a user session. - Parameters: - userSession: The active user session object. - walletAddress: The wallet address to bind. - Returns: A promise that resolves with the binding result. points(userSession: UserSession, walletAddress: string): Promise - Retrieves points associated with a wallet address for a given user session. - Parameters: - userSession: The active user session object. - walletAddress: The wallet address to query points for. - Returns: A promise that resolves with the points information. search(query: SearchQuery): Promise - Searches for collections or items within the SatsTerminal ecosystem. - Parameters: - query: An object containing search parameters. - Returns: A promise that resolves with the search results. popularCollections(): Promise - Fetches a list of popular collections. - Returns: A promise that resolves with an array of popular collections. fetchQuote(params: FetchQuoteParams): - Fetches a quote for a transaction, potentially using the best-priced AMM. - Parameters: - params: An object containing fetch quote parameters, including an optional `fill` parameter. - fill: If true, automatically uses the best-priced AMM when no orders are found in specified marketplaces. - Returns: A promise that resolves with the quote details. getPSBT(params: GetPSBTParams): Promise - Retrieves a Partially Signed Bitcoin Transaction (PSBT) for a given operation. - Parameters: - params: An object containing parameters for generating the PSBT. - Includes support for RBF protection and PSBT inputs for non-RBF protected orders. - Returns: A promise that resolves with the PSBT details. confirmPSBT(psbt: string): Promise - Confirms a PSBT, likely broadcasting it to the network. - Parameters: - psbt: The PSBT string to confirm. - Returns: A promise that resolves with the confirmation result. ``` -------------------------------- ### SatsTerminal API Reference Source: https://www.npmjs.com/package/satsterminal-sdk/index Provides detailed API documentation for the SatsTerminal SDK, including method signatures, parameters, and return types. ```APIDOC SatsTerminal: __init__(config: SatsTerminalConfig) config: Configuration object for the SDK. apiKey: string - Your unique API key. search(params: SearchParams): Promise Searches for runes by name. Parameters: rune_name (string): The name of the rune to search for. sell (boolean, optional): Filter for sell orders. Returns: Promise - An object containing search results. signIn(params: SignInParams): Promise Registers and authenticates a user using their Bitcoin and Ordinals addresses. Parameters: ord_address (string): Ordinals address. btc_address (string): Bitcoin address. ord_public_key (string): Ordinals public key. btc_public_key (string): Bitcoin public key. provider (string): The wallet provider (e.g., 'xverse', 'unisat'). Returns: Promise - The response after signing in. bind(params: BindParams): Promise Binds a user's wallet to Unisat and DotSwap. This is a one-time operation. Parameters: btcAddress (string): Bitcoin address. nftAddress (string): Ordinals address. sign (string): User's signature of the bind message. Returns: Promise - The response after binding. points(params: PointsParams): Promise Retrieves the user's accumulated Amber points balance. Parameters: ord_address (string): Ordinals address. Returns: Promise - An object containing the points balance. popularCollections(): Promise Fetches popular rune collections. Returns: Promise - An object containing popular collections. ``` -------------------------------- ### SatsTerminal SDK Error Handling Source: https://www.npmjs.com/package/satsterminal-sdk/index Illustrates how to handle errors when using the SatsTerminal SDK. It shows how to wrap API calls in try-catch blocks and check for specific error messages or codes to provide user-friendly feedback. ```javascript try { const result = await satsTerminal.search({ rune_name: 'PEPE' }); } catch (error) { if (error.message.includes('API key')) { console.error('Invalid API key'); } else if (error.code === 'ECONNRESET' || error.message.includes('socket hang up')) { console.error('Network connection issue. Please try again.'); } else { console.error('An error occurred:', error); } } ``` -------------------------------- ### Troubleshooting RBF Protection Issues Source: https://www.npmjs.com/package/satsterminal-sdk/index Instructions for addressing issues related to Replace-By-Fee (RBF) protection. This involves ensuring both the main PSBT and RBF protection PSBT are signed correctly, the RBF flag is enabled, and the signed RBF PSBT is passed to the confirmPSBT method. ```APIDOC RBF Protection Issues: - Make sure both the main PSBT and RBF protection PSBT are properly signed - Verify that the RBF protection flag is set to true in all relevant method calls - Ensure the signed RBF PSBT is passed to the confirmPSBT method ``` -------------------------------- ### Troubleshooting Invalid API Key Source: https://www.npmjs.com/package/satsterminal-sdk/index Guidance for resolving issues related to an invalid API key. It emphasizes the need for a valid key and that only approved partners can use the SDK. ```APIDOC Invalid API Key: Ensure your API key is valid and properly configured. Only approved partners can use the SDK. ``` -------------------------------- ### Fetch Rune Purchase Quote Source: https://www.npmjs.com/package/satsterminal-sdk/index Fetches a price quote for a rune purchase. It requires the amount of BTC to spend, the rune name, and the recipient's Bitcoin address. Optional parameters include theme ID, sell order flag, specific marketplaces, RBF protection, and an option to automatically fill the order using the best AMM if no direct order is found. ```APIDOC satsTerminal.fetchQuote(params: QuoteParams): Promise Parameters: btcAmount (number/string): Amount of BTC to spend. runeName (string): Name of the rune. address (string): Bitcoin address. themeID? (string): Optional widget theme ID. sell? (boolean): Optional flag for sell orders (default: false). marketplaces? (string[]): Optional list of marketplaces to use (default: empty, uses all available). rbfProtection? (boolean): Optional RBF protection flag (default: false). fill? (boolean): Optional flag that, when true, will use the best AMM to fulfill the order if no order is found in the specified marketplaces (default: false). Example: const quote = await satsTerminal.fetchQuote({ btcAmount: 0.0001, runeName: "LOBO•THE•WOLF•PUP", address: "bc1...", marketplaces: ["MagicEden"], rbfProtection: true, fill: true }); Example Response: { bestMarketplace: 'MagicEden', selectedOrders: [ { amount: '2039350000000', formattedAmount: '20393.5', id: '5b35441a-297b-45b4-8277-a3048309837b', isPending: false, rune: 'LOBOTHEWOLFPUP', maker: 'bc1p97mujnqerk098gnd9actkpev6waeauvzk2yt3zznllshz5evz66q55vjw6', makerReceiveAddress: '393PuAEiJ7JTFmVvkJJSG42s7241gG1ncC', makerFeeBps: 0, price: 10000, side: 'sell', status: 'valid', formattedUnitPrice: '0.490352', utxoIds: [ 'f99df727b7268bd4662798a8893d965940a63a68b77bdcc92d924ccecee66035:0' ], filledAmount: '0', formattedFilledAmount: '0', rbfProtectionShield: true, rbfProtectedSacAddress: 'bc1pg5lj78n75nhmvv47xq8y0kf6wzzed6ewesuq9p4qu6hmsnketz9sgmfdeh', market: 'MagicEden' } ], totalFormattedAmount: '20393.5', totalPrice: '0.0001', metrics: { /* metrics data */ }, marketplaces: { /* marketplace data */ } } ``` -------------------------------- ### Troubleshooting Network Errors Source: https://www.npmjs.com/package/satsterminal-sdk/index Steps to diagnose and resolve network-related errors when using the SDK. This includes checking internet connectivity, API endpoint accessibility, firewall rules, and adjusting timeout configurations. ```APIDOC Network Errors: - Check your internet connection - Verify the API endpoint is accessible - Check if your firewall is blocking requests - Consider increasing the timeout value in the configuration ``` -------------------------------- ### SatsTerminal SDK Configuration Interface Source: https://www.npmjs.com/package/satsterminal-sdk/index Defines the TypeScript interface for configuring the SatsTerminal SDK, specifying the required apiKey. ```typescript interface SatsTerminalConfig { apiKey: string; } ``` -------------------------------- ### Fetch Quote Function Signature Source: https://www.npmjs.com/package/satsterminal-sdk/index The TypeScript signature for the fetchQuote function, detailing its parameters and return type. ```typescript async fetchQuote(params: QuoteParams): Promise ``` -------------------------------- ### Generate Partially Signed Bitcoin Transaction (PSBT) Source: https://www.npmjs.com/package/satsterminal-sdk/index Generates a Partially Signed Bitcoin Transaction (PSBT) required for Bitcoin transactions. It takes an array of orders, Bitcoin addresses, public keys, and optional parameters such as fee rate, slippage, and RBF protection. The function returns a PSBT response containing marketplace information, swap ID, valid orders, and RBF protection details. ```APIDOC OpenAPISpec: path: /getPSBT method: POST summary: Generate Partially Signed Bitcoin Transaction (PSBT) description: Generates a Partially Signed Bitcoin Transaction (PSBT) required for Bitcoin transactions. It takes an array of orders, Bitcoin addresses, public keys, and optional parameters such as fee rate, slippage, and RBF protection. The function returns a PSBT response containing marketplace information, swap ID, valid orders, and RBF protection details. parameters: requestBody: required: true content: application/json: schema: type: object properties: orders: type: array items: $ref: '#/components/schemas/RuneOrder' description: Array of orders to include (from fetchQuote) address: type: string description: Bitcoin address publicKey: type: string description: Bitcoin public key paymentAddress: type: string description: Payment address paymentPublicKey: type: string description: Payment public key runeName: type: string description: Rune name utxos: type: array items: $ref: '#/components/schemas/UTXO' description: Optional UTXOs to use feeRate: type: number description: Optional fee rate slippage: type: number description: Optional slippage percentage themeID: type: string description: Optional widget theme ID sell: type: boolean default: false description: Optional flag for sell orders rbfProtection: type: boolean default: false description: Optional RBF protection flag responses: 200: description: PSBT generation successful content: application/json: schema: $ref: '#/components/schemas/PSBTResponse' Components: schemas: RuneOrder: type: object properties: # ... properties of RuneOrder ... UTXO: type: object properties: # ... properties of UTXO ... PSBTResponse: type: object properties: marketplace: type: string swapId: type: string validOrders: type: array items: { type: string } inputs: type: array items: { type: number } rbfProtected: type: object properties: base64: type: string hex: type: string inputs: type: array items: { type: number } Example Usage: ```javascript const psbtResponse = await satsTerminal.getPSBT({ orders: quote.selectedOrders, address: "bc1...", publicKey: "...", paymentAddress: "3Pc...", paymentPublicKey: "...", feeRate: 5, runeName: "LOBO•THE•WOLF•PUP", slippage: 9, rbfProtection: true }); ``` ``` ```javascript async getPSBT(params: GetPSBTParams): Promise ``` -------------------------------- ### Confirm PSBT and Broadcast Transaction Source: https://www.npmjs.com/package/satsterminal-sdk/index Confirms a signed Partially Signed Bitcoin Transaction (PSBT) and broadcasts it. This method handles the finalization of a transaction, including optional RBF protection. It requires detailed parameters related to the transaction, addresses, public keys, and the signed PSBT itself. ```APIDOC confirmPSBT(params: ConfirmPSBTParams): Promise Parameters: * orders (RuneOrder[]): Array of orders (from fetchQuote). * address (string): Bitcoin address. * publicKey (string): Bitcoin public key. * paymentAddress (string): Payment address. * paymentPublicKey (string): Payment public key. * signedPsbtBase64 (string): Signed PSBT in base64 format. * swapId (string): Swap ID (from getPSBT). * themeID? (string): Optional widget theme ID. * sell? (boolean): Optional flag for sell orders (default: false). * runeName? (string): Optional rune name. * marketplaces? (string[]): Optional list of marketplaces to use. * rbfProtection? (boolean): Optional RBF protection flag (default: false). * signedRbfPsbtBase64? (string): Optional signed RBF protection PSBT in base64 format. Example: const confirmation = await satsTerminal.confirmPSBT({ orders: quote.selectedOrders, address: "bc1...", publicKey: "...", paymentAddress: "3Pc...", paymentPublicKey: "...", signedPsbtBase64: "cHNid...", signedRbfPsbtBase64: "cHNid...", // Only if rbfProtection is true swapId: psbtResponse.swapId, runeName: "LOBO•THE•WOLF•PUP", rbfProtection: true }); Example Response: { marketplace: 'magiceden', txid: '4fb3ae350ae4366687a1e069b1d4de528f3dc9dc097382de041e979a8187312b', rbfProtection: { fundsPreparationTxId: '4fb3ae350ae4366687a1e069b1d4de528f3dc9dc097382de041e979a8187312b', fulfillmentId: 'bd85a36b-7a54-458a-8585-e3af2b1a8fe1' }, isRbfTxid: true } ``` ```javascript async confirmPSBT(params: ConfirmPSBTParams): Promise ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.