Tutorial:- Creating and Managing Offers

Introduction

Stellar allows you to create offers to buy or sell assets. This tutorial will guide you through creating and managing offers using the Stellar SDK for JavaScript.

Prerequisites

Ensure you have:

  • Node.js installed.
  • A text editor or IDE (like VSCode).
  • Basic knowledge of JavaScript.
  • A funded Stellar account with custom assets (refer to the first tutorial and asset creation tutorial).
Step 1: Set Up the Project

First, create a new project directory and install the Stellar SDK:

mkdir stellar-custom-asset
cd stellar-custom-asset
npm init -y
npm install stellar-sdk
Step 2: Load the Stellar SDK and Configure Accounts

Create a file named createOffer.js and add the following code:

const StellarSdk = require('stellar-sdk');
const server = new StellarSdk.Server('https://horizon-testnet.stellar.org');

// Seller's keys
const sellerKeys = StellarSdk.Keypair.fromSecret('SELLER_SECRET_KEY');

// Asset details
const sellingAsset = new StellarSdk.Asset('MYTOKEN', sellerKeys.publicKey());
const buyingAsset = StellarSdk.Asset.native(); // Buying XLM
const amount = '100'; // Amount of MYTOKEN to sell
const price = '0.5'; // Price of 1 MYTOKEN in XLM

Replace SELLER_SECRET_KEY with the secret key of your seller account and adjust the asset details as needed.

Step 3: Build and Submit the Offer

Add the following code to create and submit an offer:

async function createOffer() {
  try {
    const account = await server.loadAccount(sellerKeys.publicKey());
   
    const transaction = new StellarSdk.TransactionBuilder(account, {
      fee: StellarSdk.BASE_FEE,
      networkPassphrase: StellarSdk.Networks.TESTNET,
    })
   
    .addOperation(StellarSdk.Operation.manageSellOffer({
      selling: sellingAsset,
      buying: buyingAsset,
      amount: amount,
      price: price,
    }))
    .setTimeout(30)
    .build();
   
    transaction.sign(sellerKeys);
   
    const transactionResult = await server.submitTransaction(transaction);
    console.log('Offer created successfully!', transactionResult);
  }
  catch (error) {
    console.error('Error!', error);
  }
}

createOffer();

This script builds and submits an offer to sell MYTOKEN for XLM at a specified price.

Step 4: Run the Script

Run the script using Node.js:

node createOffer.js

If successful, you'll see a message indicating the offer was created successfully along with the transaction details.

Conclusion

You've successfully created an offer on the Stellar network using the Stellar SDK for JavaScript. You can modify the script to manage existing offers, adjust prices, or create offers for different assets. For more details on offers, check out the Stellar Offers documentation.