Tutorial:- Stellar Smart Contracts (Conditional Payments)

Introduction

Stellar supports simple smart contracts through multi-signature and conditional payments. This tutorial will guide you through creating a conditional payment 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 (refer to the first 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 conditionalPayment.js and add the following code:

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

// Source account keys
const sourceKeys = StellarSdk.Keypair.fromSecret('SOURCE_SECRET_KEY');

// Conditional account keys
const conditionalKeys = StellarSdk.Keypair.random();

// Destination account public key
const destinationPublicKey = 'DESTINATION_PUBLIC_KEY';

// Transaction details
const amount = '10'; // Amount of XLM to send
const preimage = 'your_preimage';
const hash = StellarSdk.StrKey.encodePreAuthTx(StellarSdk.hash(Buffer.from(preimage)));

Replace SOURCE_SECRET_KEY with the secret key of your source account and DESTINATION_PUBLIC_KEY with the public key of your destination account. Replace your_preimage with a string that will be used to create a hash for the pre-auth transaction.

Step 3: Create the Conditional Account

Add the following code to create the conditional account with the pre-auth transaction signer:

async function createConditionalAccount() {
  try {
    const account = await server.loadAccount(sourceKeys.publicKey());
   
    const transaction = new StellarSdk.TransactionBuilder(account, {
      fee: StellarSdk.BASE_FEE,
      networkPassphrase: StellarSdk.Networks.TESTNET,
    })
    .addOperation(StellarSdk.Operation.createAccount({
      destination: conditionalKeys.publicKey(),
      startingBalance: '2', // Minimum balance for a new account
    }))
    .addOperation(StellarSdk.Operation.setOptions({
      signer: {
        ed25519PublicKey: hash,
        weight: 1,
      },
    }))
    .setTimeout(30)
    .build();
   
    transaction.sign(sourceKeys);
   
    const transactionResult = await server.submitTransaction(transaction);
    console.log('Conditional account created successfully!', transactionResult);
  }
  catch (error) {
    console.error('Error!', error);
  }
}

createConditionalAccount();

This script creates a new account with a pre-auth transaction signer, requiring the preimage to authorize transactions.

Step 4: Build and Submit the Conditional Payment

Add the following code to create and submit the conditional payment:

async function conditionalPayment() {
  try {
    const account = await server.loadAccount(conditionalKeys.publicKey());
   
    const transaction = new StellarSdk.TransactionBuilder(account, {
      fee: StellarSdk.BASE_FEE,
      networkPassphrase: StellarSdk.Networks.TESTNET,
    })
    .addOperation(StellarSdk.Operation.payment({
      destination: destinationPublicKey,
      asset: StellarSdk.Asset.native(),
      amount: amount,
    }))
    .setTimeout(30)
    .build();
   
    transaction.sign(conditionalKeys);
   
    const transactionResult = await server.submitTransaction(transaction);
    console.log('Conditional payment successful!', transactionResult);
  }
  catch (error) {
    console.error('Error!', error);
  }
}
 
conditionalPayment();

This script builds and submits a payment that will be conditionally approved using the preimage.

Step 5: Run the Script

Run the script using Node.js:

node createConditionalAccount.js

Run the script to perform the conditional payment:

node conditionalPayment.js

If successful, you'll see messages indicating the creation of the conditional account and the conditional payment, along with the transaction details.

Conclusion

You've successfully created a conditional payment on the Stellar network using the Stellar SDK for JavaScript. You can use this technique to create more complex smart contracts and multi-signature transactions. For more details on conditional payments, check out the Stellar Pre-authorized Transactions documentation.