# Examples

#### Example 1: Complete Rune Purchase Flow <a href="#example-1-complete-rune-purchase-flow" id="example-1-complete-rune-purchase-flow"></a>

Below is a complete example flow for buying runes using the simplified SDK V2, including waiting for user input for signed PSBTs:

```javascript
import { SatsTerminal } from 'satsterminal-sdk';
import readlineSync from 'readline-sync';

// Configuration
const CONFIG = {
  apiKey: 'your_api_key_here',
};

// Trade Parameters
const TRADE_PARAMS = {
  fromToken: 'BTC',
  toToken: 'LOBO•THE•WOLF•PUP',
  address: 'bc1p...',
  publicKey: '...',
  paymentAddress: '3Pc...',
  paymentPublicKey: '...',
  amount: '0.0001',
  protocol: 'runes'
};

// Initialize the SDK
const satsTerminal = new SatsTerminal(CONFIG);

// Function to get user input for signed PSBTs (V2 can have multiple)
const getSignedPSBTs = (psbts) => {
  console.log(`\nPlease sign ${psbts.length} PSBT(s):`);
  const signedPsbts = [];
  
  for (let i = 0; i < psbts.length; i++) {
    console.log(`\nPSBT ${i + 1} hex: ${psbts[i].hex}`);
    const signed = readlineSync.question(`Enter signed PSBT ${i + 1} hex: `);
    signedPsbts.push(signed);
  }
  
  return signedPsbts;
};

// Main execution
(async () => {
  try {
    // 1. Get a quote for the swap
    console.log('\n1. Fetching swap quote...');
    const quote = await satsTerminal.swapQuote({
      amount: TRADE_PARAMS.amount,
      fromToken: TRADE_PARAMS.fromToken,
      toToken: TRADE_PARAMS.toToken,
      address: TRADE_PARAMS.address,
      protocol: TRADE_PARAMS.protocol,
      params: {}
    });
  
    console.log('Best marketplace:', quote.bestMarketplace);
    console.log('Swap ID:', quote.swapId);
    console.log('From token amount:', quote.fromTokenAmount);
    console.log('To token amount:', quote.toTokenAmount);
    console.log('Available marketplaces:', Object.keys(quote.marketplaces));

    // 2. Create PSBT(s) for the swap
    console.log('\n2. Creating PSBT(s)...');
    const psbtResponse = await satsTerminal.swapPSBT({
      marketplace: quote.bestMarketplace,
      swapId: quote.swapId,
      address: TRADE_PARAMS.address,
      publicKey: TRADE_PARAMS.publicKey,
      paymentAddress: TRADE_PARAMS.paymentAddress,
      paymentPublicKey: TRADE_PARAMS.paymentPublicKey,
      protocol: TRADE_PARAMS.protocol,
      feeRate: 5,
      slippage: 9,
      themeID: null
    });
  
    console.log(`Created ${psbtResponse.psbts.length} PSBT(s)`);
    console.log('Updated swap ID:', psbtResponse.swapId);
  
    // Wait for user to sign all PSBTs
    const signedPsbts = getSignedPSBTs(psbtResponse.psbts);

    // 3. Submit the signed PSBTs
    console.log('\n3. Submitting signed PSBTs...');
    const result = await satsTerminal.swapSubmit({
      marketplace: quote.bestMarketplace,
      swapId: psbtResponse.swapId,
      address: TRADE_PARAMS.address,
      publicKey: TRADE_PARAMS.publicKey,
      paymentAddress: TRADE_PARAMS.paymentAddress,
      paymentPublicKey: TRADE_PARAMS.paymentPublicKey,
      protocol: TRADE_PARAMS.protocol,
      signedPsbts: signedPsbts
    });
  
    console.log('✅ Swap completed successfully!');
    console.log('Transaction ID:', result.txid);
    console.log('Marketplace used:', result.marketplace);

  } catch (error) {
    console.error('Error:', error.message);
  }
})();
```

#### Example 2: Selling Runes for BTC <a href="#example-2-selling-runes-for-btc" id="example-2-selling-runes-for-btc"></a>

```javascript
// Import the SDK
import { SatsTerminal } from 'satsterminal-sdk';
import readlineSync from 'readline-sync';


// Configuration
const CONFIG = {
  // Your API key for SatsTerminal
  apiKey: 'your_api_key_here',
};

// Trade Parameters
const TRADE_PARAMS = {
  // Clear direction: selling runes for BTC
  fromToken: 'DOG•GO•TO•THE•MOON',  // What we're selling
  toToken: 'BTC',                   // What we want to receive
  address: 'bc1puxa2cwvfw47vaadt4lfxwgl4zln9epqtfsq3y7cl7vr5wvfayz6s22mmwp',
  publicKey: 'dd4c950d7a5f86e92235687cffeee1bfb61b5c8a9e15b80751077c3d4315821c',
  paymentAddress: '3PcP9J6C9ZNQpTRHrtqFBhP3LoBjSmMkZq',
  paymentPublicKey: '02af6d71243386e3a24a23ebf47ea91dcf0d114b8ec29163ed9716e9b14a8fe3d8',
  sellAmount: "10000",              // Amount of runes to sell
  protocol: 'runes'
};

// Initialize the SDK
const satsTerminal = new SatsTerminal(CONFIG);

// Function to get user input for signed PSBTs
const getSignedPSBTs = (psbts) => {
  console.log(`\nFound ${psbts.length} PSBT(s) to sign:`);
  const signedPsbts = [];
  
  for (let i = 0; i < psbts.length; i++) {
    console.log(`\nPSBT ${i + 1}:`);
    console.log(`Base64: ${psbts[i].base64.substring(0, 50)}...`);
    console.log(`Hex: ${psbts[i].hex.substring(0, 50)}...`);
    console.log(`Inputs: [${psbts[i].inputs.join(', ')}]`);
    
    const signed = readlineSync.question(`Enter signed PSBT ${i + 1} hex: `);
    signedPsbts.push(signed);
  }
  
  return signedPsbts;
};

// Main execution block (sell runes for BTC)
(async () => {
  try {
    // 1. Get a quote for selling runes
    console.log('\n1. Fetching sell quote...');
    console.log('Trade parameters:', TRADE_PARAMS);
    
    const quote = await satsTerminal.swapQuote({
      amount: TRADE_PARAMS.sellAmount,
      fromToken: TRADE_PARAMS.fromToken,  // Selling runes
      toToken: TRADE_PARAMS.toToken,      // For BTC
      address: TRADE_PARAMS.address,
      protocol: TRADE_PARAMS.protocol,
      params: {}
    });
    
    console.log('✅ Quote received:');
    console.log('Best marketplace:', quote.bestMarketplace);
    console.log('Swap ID:', quote.swapId);
    console.log('Selling:', quote.fromTokenAmount, TRADE_PARAMS.fromToken);
    console.log('Receiving:', quote.toTokenAmount, 'BTC');
    
    // Show all available marketplaces
    console.log('\nAvailable marketplaces:');
    Object.entries(quote.marketplaces).forEach(([name, data]) => {
      console.log(`- ${name}: ${data.fromTokenAmount} → ${data.toTokenAmount} BTC`);
    });

    // 2. Create PSBT(s) for the swap
    console.log('\n2. Creating PSBT(s)...');
    const psbtResponse = await satsTerminal.swapPSBT({
      marketplace: quote.bestMarketplace,
      swapId: quote.swapId,
      address: TRADE_PARAMS.address,
      publicKey: TRADE_PARAMS.publicKey,
      paymentAddress: TRADE_PARAMS.paymentAddress,
      paymentPublicKey: TRADE_PARAMS.paymentPublicKey,
      protocol: TRADE_PARAMS.protocol,
      feeRate: 5,
      slippage: 9,
      themeID: null
    });
    
    console.log(`✅ Created ${psbtResponse.psbts.length} PSBT(s)`);
    console.log('Updated swap ID:', psbtResponse.swapId);
    
    // Wait for user to sign all PSBTs
    const signedPsbts = getSignedPSBTs(psbtResponse.psbts);
    
    // 3. Submit the signed PSBTs
    console.log('\n3. Submitting signed PSBTs...');
    const confirmation = await satsTerminal.swapSubmit({
      marketplace: quote.bestMarketplace,
      swapId: psbtResponse.swapId,
      address: TRADE_PARAMS.address,
      publicKey: TRADE_PARAMS.publicKey,
      paymentAddress: TRADE_PARAMS.paymentAddress,
      paymentPublicKey: TRADE_PARAMS.paymentPublicKey,
      protocol: TRADE_PARAMS.protocol,
      signedPsbts: signedPsbts
    });
    
    console.log('✅ Sell order completed successfully!');
    console.log('Transaction ID:', confirmation.txid);
    console.log('Marketplace:', confirmation.marketplace);
    

  } catch (error) {
    console.error('Error:', error.message);
  }
})();
```

#### Example 3: Alkanes Swap <a href="#example-3-alkanes-swap" id="example-3-alkanes-swap"></a>

```javascript
import { SatsTerminal } from 'satsterminal-sdk';
import readlineSync from 'readline-sync';

/**
 * This example demonstrates swapping BTC for alkanes tokens using V2 API
 */

// Configuration
const CONFIG = {
  apiKey: 'your_api_key_here',
};

// Trade Parameters for Alkanes
const TRADE_PARAMS = {
  fromToken: 'BTC',
  toToken: 'GOLD DUST',              // Alkanes token
  address: 'bc1p4mffk7l9a040dgqrl8spunwkguxn68ldwx848urafar9sj85nnrq9rcvyj',
  publicKey: '03962e74f53d3620f82aab9ecfadbaa2d2b34ab1d794b346f53deb4c1a9d287bfc',
  paymentAddress: 'bc1qjtyqu4uqrpnvsfg9tq0wzzsdge3e559wzk4epc',
  paymentPublicKey: '02325fb34ee9ff76df92b34d13059fa8d14008a9426fb1de52f038bfdca5075588',
  amount: '0.00008',
  protocol: 'alkanes'               // Different protocol
};

const satsTerminal = new SatsTerminal(CONFIG);

const getSignedPSBTs = (psbts) => {
  console.log(`\nPlease sign ${psbts.length} PSBT(s) for alkanes swap:`);
  const signedPsbts = [];
  
  psbts.forEach((psbt, index) => {
    console.log(`\nPSBT ${index + 1} details:`);
    console.log(`- Inputs: [${psbt.inputs.join(', ')}]`);
    console.log(`- Hex length: ${psbt.hex.length} characters`);
    
    const signed = readlineSync.question(`Enter signed PSBT ${index + 1} hex: `);
    signedPsbts.push(signed);
  });
  
  return signedPsbts;
};

(async () => {
  try {
    console.log('🔄 Starting alkanes token swap...');
    
    // 1. Get quote for alkanes swap
    console.log('\n1. Getting alkanes swap quote...');
    const quote = await satsTerminal.swapQuote({
      amount: TRADE_PARAMS.amount,
      fromToken: TRADE_PARAMS.fromToken,
      toToken: TRADE_PARAMS.toToken,
      address: TRADE_PARAMS.address,
      protocol: TRADE_PARAMS.protocol,
      params: {}
    });
    
    console.log('✅ Alkanes quote received:');
    console.log(`Swapping ${quote.fromTokenAmount} BTC → ${quote.toTokenAmount} ${TRADE_PARAMS.toToken}`);
    console.log('Best marketplace:', quote.bestMarketplace);
    
    // Show metrics for different marketplaces
    if (quote.metrics) {
      console.log('\nMarketplace performance:');
      Object.entries(quote.metrics).forEach(([marketplace, metrics]) => {
        console.log(`- ${marketplace}: ${metrics.percentFulfilled}% fulfilled, avg price: ${metrics.averageUnitPrice}`);
      });
    }

    // 2. Create PSBTs
    console.log('\n2. Creating alkanes swap PSBTs...');
    const psbtResponse = await satsTerminal.swapPSBT({
      marketplace: quote.bestMarketplace,
      swapId: quote.swapId,
      address: TRADE_PARAMS.address,
      publicKey: TRADE_PARAMS.publicKey,
      paymentAddress: TRADE_PARAMS.paymentAddress,
      paymentPublicKey: TRADE_PARAMS.paymentPublicKey,
      protocol: TRADE_PARAMS.protocol,
      feeRate: 3,
      slippage: 5,
      themeID: null
    });
    
    console.log(`✅ Generated ${psbtResponse.psbts.length} PSBT(s) for alkanes swap`);
    
    // Sign PSBTs
    const signedPsbts = getSignedPSBTs(psbtResponse.psbts);
    
    // 3. Submit alkanes swap
    console.log('\n3. Executing alkanes swap...');
    const result = await satsTerminal.swapSubmit({
      marketplace: quote.bestMarketplace,
      swapId: psbtResponse.swapId,
      address: TRADE_PARAMS.address,
      publicKey: TRADE_PARAMS.publicKey,
      paymentAddress: TRADE_PARAMS.paymentAddress,
      paymentPublicKey: TRADE_PARAMS.paymentPublicKey,
      protocol: TRADE_PARAMS.protocol,
      signedPsbts: signedPsbts
    });
    
    console.log('🎉 Alkanes swap completed!');
    console.log('Transaction ID:', result.txid);
    console.log(`Successfully swapped BTC for ${TRADE_PARAMS.toToken}`);

  } catch (error) {
    console.error('Error:', error.message);
  }
})();
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.satsterminal.com/trade/swap-sdk/examples.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
