kmp-stellar-sdk

Comprehensive SDK for building Stellar Network apps: keypair management, transaction building/signing, Horizon REST client, Soroban RPC, smart-contract deployment/invocation, multi-signature and auth workflows.

JVMKotlin/NativeJS
GitHub stars8
AuthorsSoneso
Open issues0
LicenseApache License 2.0
Creation date6 months ago

Last activity24 days ago
Latest release1.3.0 (about 1 month ago)

Stellar SDK for Kotlin Multiplatform

Version Kotlin Multiplatform Maven Central codecov Ask DeepWiki

A comprehensive Kotlin Multiplatform SDK for building applications on the Stellar Network. Write your Stellar integration once in Kotlin and deploy it across JVM (Android, Server), iOS, macOS, and Web (Browser/Node.js) platforms.

Platform Support

Platform Status Crypto Library Notes
JVM (Android, Server) Supported BouncyCastle Production-ready
iOS Supported libsodium (native) iOS 14.0+
macOS Supported libsodium (native) macOS 11.0+
JavaScript (Browser) Supported libsodium.js (WebAssembly) Modern browsers
JavaScript (Node.js) Supported libsodium.js (WebAssembly) Node.js 14+

Quick Links

What Is This?

The Stellar SDK for Kotlin Multiplatform enables you to:

  • Build and sign Stellar transactions
  • Connect to Horizon (Stellar's REST API server)
  • Interact with Soroban smart contracts via RPC
  • Run the same business logic on mobile, web, desktop, and server platforms

This SDK uses audited cryptographic libraries on all platforms.

What Can I Build?

With this SDK, you can create:

  • Wallets & Payment Apps - Send/receive XLM and assets, manage accounts across platforms
  • DEX Interfaces - Build trading interfaces, liquidity pools, and order book managers
  • Soroban DApps - Deploy and interact with smart contracts from any platform
  • Token Issuance Platforms - Create and distribute custom assets with trustline management
  • Cross-Border Payment Systems - Leverage path payments for currency conversion
  • Account Services - Multi-signature support, account recovery, and sponsorship flows
  • Mobile-First Apps - iOS and Android apps sharing business logic with desktop, web and server

See the demo app for examples.

Features

The SDK provides comprehensive Stellar functionality:

  • Cryptography - Ed25519 keypairs, signing, verification with production-ready libraries (BouncyCastle, libsodium)
  • Transaction Building - TransactionBuilder with fluent API, all 27 Stellar operations, memos, time bounds, multi-signature support
  • Assets & Accounts - Native (XLM) and issued assets, trustlines, muxed accounts, SAC contract ID derivation
  • Horizon API Client - Full REST API coverage with request builders, SSE streaming, automatic retries, SEP-29 validation
  • Soroban Smart Contracts - High-level ContractClient with beginner-friendly Map-based API and power-user mode
  • Soroban RPC Client - Transaction simulation, event queries, ledger data, contract deployment and invocation
  • Contract Deployment - One-step deploy() or two-step install/deployFromWasmId for WASM reuse
  • Authorization - Automatic and custom auth handling with signature verification
  • SEP Support - SEP-1 (stellar.toml), SEP-2 (Federation), SEP-5 (Key Derivation), SEP-6 (Deposit and Withdrawal API), SEP-8 (Regulated Assets), SEP-9/12 (KYC), SEP-10 (Web Authentication), SEP-24 (Hosted Deposit/Withdrawal), SEP-30 (Account Recovery), SEP-38 (Anchor RFQ), SEP-45 (Web Authentication for Contracts), SEP-53 (Sign and Verify Messages)

Installation

Add the SDK as a Maven dependency (recommended for most projects):

// In your module's build.gradle.kts
dependencies {
    implementation("com.soneso.stellar:stellar-sdk:1.3.0")
}

See Platform-Specific Requirements below and docs/platforms/ for detailed setup instructions

Platform-Specific Requirements

Most platforms require no additional setup. The SDK includes all necessary cryptographic libraries (BouncyCastle for JVM/Android, libsodium.js for JavaScript/Web).

Exception - Native iOS/macOS SwiftUI/UIKit Apps: For native Swift apps where Swift code directly uses SDK types, add libsodium:

  • iOS: Add via Swift Package Manager: https://github.com/jedisct1/swift-sodium
  • macOS Native: Install via Homebrew: brew install libsodium

See docs/platforms/ for detailed platform-specific instructions.

Quick Start

Generate a Random KeyPair

All cryptographic operations use Kotlin's suspend functions for proper async support across platforms.

import com.soneso.stellar.sdk.KeyPair
import kotlinx.coroutines.runBlocking

suspend fun example() {
    // Generate a random keypair
    val keypair = KeyPair.random()

    println("Account ID: ${keypair.getAccountId()}")
    println("Secret Seed: ${keypair.getSecretSeed()?.concatToString()}")
}

Create KeyPair from Secret Seed

suspend fun fromSeed() {
    val seed = "SDJHRQF4GCMIIKAAAQ6IHY42X73FQFLHUULAPSKKD4DFDM7UXWWCRHBE"
    val keypair = KeyPair.fromSecretSeed(seed)

    println("Account ID: ${keypair.getAccountId()}")
    // Output: GCZHXL5HXQX5ABDM26LHYRCQZ5OJFHLOPLZX47WEBP3V2PF5AVFK2A5D
}

Fetch Data from Horizon

import com.soneso.stellar.sdk.horizon.HorizonServer

suspend fun fetchAccountData() {
    val server = HorizonServer("https://horizon-testnet.stellar.org")
    val accountId = "GCZHXL5HXQX5ABDM26LHYRCQZ5OJFHLOPLZX47WEBP3V2PF5AVFK2A5D"

    val account = server.accounts().account(accountId)
    println("Sequence: ${account.sequenceNumber}")
    println("Balances: ${account.balances}")
}

Build and Sign a Transaction

import com.soneso.stellar.sdk.*
import com.soneso.stellar.sdk.horizon.HorizonServer

suspend fun sendPayment() {
    val server = HorizonServer("https://horizon-testnet.stellar.org")
    val sourceKeypair = KeyPair.fromSecretSeed("SXXX...")
    val sourceAccount = server.accounts().account(sourceKeypair.getAccountId())

    val destination = "GDUKMGUGDZQK6YHYA5Z6AY2G4XDSZPSZ3SW5UN3ARVMO6QSRDWP5YLEX"

    val transaction = TransactionBuilder(sourceAccount, Network.TESTNET)
        .setBaseFee(100) // stroops per operation
        .addOperation(
            PaymentOperation(destination, AssetTypeNative, "10.0")
        )
        .addMemo(MemoText("Test payment"))
        .build()

    transaction.sign(sourceKeypair)

    val response = server.submitTransaction(transaction.toEnvelopeXdrBase64())
    println("Transaction successful: ${response.hash}")
}

Fetch Data from Soroban RPC

import com.soneso.stellar.sdk.rpc.SorobanServer
import com.soneso.stellar.sdk.rpc.GetTransactionStatus

suspend fun fetchTransactionData() {
    val server = SorobanServer("https://soroban-testnet.stellar.org")
    val txHash = "3389e9f0f1a65f19736cacf544c2e825313e8447f569233bb8db39aa607c8889"

    val response = server.getTransaction(txHash)
    when (response.status) {
        GetTransactionStatus.SUCCESS -> {
            println("Transaction succeeded in ledger ${response.ledger}")
            println("Result: ${response.resultXdr}")
        }
        GetTransactionStatus.FAILED -> {
            println("Transaction failed: ${response.resultXdr}")
        }
        GetTransactionStatus.NOT_FOUND -> {
            println("Transaction not yet in ledger")
        }
    }

    server.close()
}

Interact with Soroban Smart Contracts

The SDK provides a high-level ContractClient API with automatic type conversion:

Simple invocation with auto-execution:

import com.soneso.stellar.sdk.contract.ContractClient
import com.soneso.stellar.sdk.scval.Scv

suspend fun callContract() {
    // Load contract spec from network
    val client = ContractClient.forContract(
        contractId = "CDLZ...",
        rpcUrl = "https://soroban-testnet.stellar.org:443",
        network = Network.TESTNET
    )

    // Query with Map-based arguments (auto-executes)
    val balance = client.invoke<Long>(
        functionName = "balance",
        arguments = mapOf("account" to accountAddress),
        source = sourceAccount,
        signer = null,  // No signer for read calls
        parseResultXdrFn = { Scv.fromInt128(it).toLong() }
    )
    println("Balance: $balance")

    // Write operation - auto signs and submits
    client.invoke<Unit>(
        functionName = "transfer",
        arguments = mapOf(
            "from" to fromAddress,
            "to" to toAddress,
            "amount" to 1000
        ),
        source = sourceAccount,
        signer = keypair,  // Required for writes
        parseResultXdrFn = null
    )

    client.close()
}

Multi-signature workflows with buildInvoke for manual control:

suspend fun multiSigContractCall() {
    val client = ContractClient.forContract(contractId, rpcUrl, Network.TESTNET)
    val assembled = client.buildInvoke<String>(...)

    // Detect and sign for additional signers
    val whoNeedsToSign = assembled.needsNonInvokerSigningBy()
    whoNeedsToSign.forEach { assembled.signAuthEntries(getKeypairFor(it)) }

    val result = assembled.signAndSubmit(sourceKeypair)
}

For deployment examples, authorization patterns, and advanced usage, see the Getting Started Guide and Demo App.

Demo Application

The demo app showcases SDK usage across all platforms with 11 comprehensive features:

  1. Key Generation - Generate and manage Ed25519 keypairs
  2. Fund Testnet Account - Get free test XLM from Friendbot
  3. Fetch Account Details - Retrieve account information from Horizon
  4. Trust Asset - Establish trustlines for issued assets
  5. Send Payment - Transfer XLM and issued assets
  6. Fetch Transaction Details - View transaction operations and events from Horizon or Soroban RPC
  7. Fetch Smart Contract Details - Parse and inspect Soroban contracts
  8. Deploy Smart Contract - Deploy Soroban WASM contracts to testnet
  9. Invoke Hello World Contract - Simple contract invocation with automatic result parsing
  10. Invoke Auth Contract - Dynamic authorization handling for same-invoker and different-invoker scenarios
  11. Invoke Token Contract - SEP-41 token contract interaction with multi-signature workflows

See demo/README.md for screenshots and platform-specific build instructions.

Agent Skill

This repository includes an Agent Skill that teaches AI coding agents how to use this SDK. See skills/ for installation instructions.

Documentation

SDK Documentation

  • Docs folder - containing getting started guide, many sdk usage examples, advanced topics, api documentation and more.

External Resources

Cryptography

This SDK uses production-ready, audited cryptographic libraries on all platforms:

  • JVM: BouncyCastle for Ed25519 operations
  • iOS/macOS: libsodium (native C interop)
  • JavaScript: libsodium-wrappers-sumo (WebAssembly)

All implementations provide constant-time operations, proper memory safety, and comprehensive input validation. No experimental or custom cryptography.

Testing

See Testing Guide for information on running tests.

Requirements

  • Kotlin: 2.2.20
  • Gradle: 9.0+
  • JVM: Java 17+
  • Android: API 24+ (Android 7.0)
  • iOS: iOS 14.0+
  • macOS: macOS 11.0+
  • JavaScript: Node.js 14+, modern browsers with WebAssembly support

Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines on reporting issues, proposing features, and submitting pull requests.

License

Licensed under the Apache License, Version 2.0. See LICENSE for the full license text.

Acknowledgments

JVMKotlin/NativeJS
GitHub stars8
AuthorsSoneso
Open issues0
LicenseApache License 2.0
Creation date6 months ago

Last activity24 days ago
Latest release1.3.0 (about 1 month ago)

Stellar SDK for Kotlin Multiplatform

Version Kotlin Multiplatform Maven Central codecov Ask DeepWiki

A comprehensive Kotlin Multiplatform SDK for building applications on the Stellar Network. Write your Stellar integration once in Kotlin and deploy it across JVM (Android, Server), iOS, macOS, and Web (Browser/Node.js) platforms.

Platform Support

Platform Status Crypto Library Notes
JVM (Android, Server) Supported BouncyCastle Production-ready
iOS Supported libsodium (native) iOS 14.0+
macOS Supported libsodium (native) macOS 11.0+
JavaScript (Browser) Supported libsodium.js (WebAssembly) Modern browsers
JavaScript (Node.js) Supported libsodium.js (WebAssembly) Node.js 14+

Quick Links

What Is This?

The Stellar SDK for Kotlin Multiplatform enables you to:

  • Build and sign Stellar transactions
  • Connect to Horizon (Stellar's REST API server)
  • Interact with Soroban smart contracts via RPC
  • Run the same business logic on mobile, web, desktop, and server platforms

This SDK uses audited cryptographic libraries on all platforms.

What Can I Build?

With this SDK, you can create:

  • Wallets & Payment Apps - Send/receive XLM and assets, manage accounts across platforms
  • DEX Interfaces - Build trading interfaces, liquidity pools, and order book managers
  • Soroban DApps - Deploy and interact with smart contracts from any platform
  • Token Issuance Platforms - Create and distribute custom assets with trustline management
  • Cross-Border Payment Systems - Leverage path payments for currency conversion
  • Account Services - Multi-signature support, account recovery, and sponsorship flows
  • Mobile-First Apps - iOS and Android apps sharing business logic with desktop, web and server

See the demo app for examples.

Features

The SDK provides comprehensive Stellar functionality:

  • Cryptography - Ed25519 keypairs, signing, verification with production-ready libraries (BouncyCastle, libsodium)
  • Transaction Building - TransactionBuilder with fluent API, all 27 Stellar operations, memos, time bounds, multi-signature support
  • Assets & Accounts - Native (XLM) and issued assets, trustlines, muxed accounts, SAC contract ID derivation
  • Horizon API Client - Full REST API coverage with request builders, SSE streaming, automatic retries, SEP-29 validation
  • Soroban Smart Contracts - High-level ContractClient with beginner-friendly Map-based API and power-user mode
  • Soroban RPC Client - Transaction simulation, event queries, ledger data, contract deployment and invocation
  • Contract Deployment - One-step deploy() or two-step install/deployFromWasmId for WASM reuse
  • Authorization - Automatic and custom auth handling with signature verification
  • SEP Support - SEP-1 (stellar.toml), SEP-2 (Federation), SEP-5 (Key Derivation), SEP-6 (Deposit and Withdrawal API), SEP-8 (Regulated Assets), SEP-9/12 (KYC), SEP-10 (Web Authentication), SEP-24 (Hosted Deposit/Withdrawal), SEP-30 (Account Recovery), SEP-38 (Anchor RFQ), SEP-45 (Web Authentication for Contracts), SEP-53 (Sign and Verify Messages)

Installation

Add the SDK as a Maven dependency (recommended for most projects):

// In your module's build.gradle.kts
dependencies {
    implementation("com.soneso.stellar:stellar-sdk:1.3.0")
}

See Platform-Specific Requirements below and docs/platforms/ for detailed setup instructions

Platform-Specific Requirements

Most platforms require no additional setup. The SDK includes all necessary cryptographic libraries (BouncyCastle for JVM/Android, libsodium.js for JavaScript/Web).

Exception - Native iOS/macOS SwiftUI/UIKit Apps: For native Swift apps where Swift code directly uses SDK types, add libsodium:

  • iOS: Add via Swift Package Manager: https://github.com/jedisct1/swift-sodium
  • macOS Native: Install via Homebrew: brew install libsodium

See docs/platforms/ for detailed platform-specific instructions.

Quick Start

Generate a Random KeyPair

All cryptographic operations use Kotlin's suspend functions for proper async support across platforms.

import com.soneso.stellar.sdk.KeyPair
import kotlinx.coroutines.runBlocking

suspend fun example() {
    // Generate a random keypair
    val keypair = KeyPair.random()

    println("Account ID: ${keypair.getAccountId()}")
    println("Secret Seed: ${keypair.getSecretSeed()?.concatToString()}")
}

Create KeyPair from Secret Seed

suspend fun fromSeed() {
    val seed = "SDJHRQF4GCMIIKAAAQ6IHY42X73FQFLHUULAPSKKD4DFDM7UXWWCRHBE"
    val keypair = KeyPair.fromSecretSeed(seed)

    println("Account ID: ${keypair.getAccountId()}")
    // Output: GCZHXL5HXQX5ABDM26LHYRCQZ5OJFHLOPLZX47WEBP3V2PF5AVFK2A5D
}

Fetch Data from Horizon

import com.soneso.stellar.sdk.horizon.HorizonServer

suspend fun fetchAccountData() {
    val server = HorizonServer("https://horizon-testnet.stellar.org")
    val accountId = "GCZHXL5HXQX5ABDM26LHYRCQZ5OJFHLOPLZX47WEBP3V2PF5AVFK2A5D"

    val account = server.accounts().account(accountId)
    println("Sequence: ${account.sequenceNumber}")
    println("Balances: ${account.balances}")
}

Build and Sign a Transaction

import com.soneso.stellar.sdk.*
import com.soneso.stellar.sdk.horizon.HorizonServer

suspend fun sendPayment() {
    val server = HorizonServer("https://horizon-testnet.stellar.org")
    val sourceKeypair = KeyPair.fromSecretSeed("SXXX...")
    val sourceAccount = server.accounts().account(sourceKeypair.getAccountId())

    val destination = "GDUKMGUGDZQK6YHYA5Z6AY2G4XDSZPSZ3SW5UN3ARVMO6QSRDWP5YLEX"

    val transaction = TransactionBuilder(sourceAccount, Network.TESTNET)
        .setBaseFee(100) // stroops per operation
        .addOperation(
            PaymentOperation(destination, AssetTypeNative, "10.0")
        )
        .addMemo(MemoText("Test payment"))
        .build()

    transaction.sign(sourceKeypair)

    val response = server.submitTransaction(transaction.toEnvelopeXdrBase64())
    println("Transaction successful: ${response.hash}")
}

Fetch Data from Soroban RPC

import com.soneso.stellar.sdk.rpc.SorobanServer
import com.soneso.stellar.sdk.rpc.GetTransactionStatus

suspend fun fetchTransactionData() {
    val server = SorobanServer("https://soroban-testnet.stellar.org")
    val txHash = "3389e9f0f1a65f19736cacf544c2e825313e8447f569233bb8db39aa607c8889"

    val response = server.getTransaction(txHash)
    when (response.status) {
        GetTransactionStatus.SUCCESS -> {
            println("Transaction succeeded in ledger ${response.ledger}")
            println("Result: ${response.resultXdr}")
        }
        GetTransactionStatus.FAILED -> {
            println("Transaction failed: ${response.resultXdr}")
        }
        GetTransactionStatus.NOT_FOUND -> {
            println("Transaction not yet in ledger")
        }
    }

    server.close()
}

Interact with Soroban Smart Contracts

The SDK provides a high-level ContractClient API with automatic type conversion:

Simple invocation with auto-execution:

import com.soneso.stellar.sdk.contract.ContractClient
import com.soneso.stellar.sdk.scval.Scv

suspend fun callContract() {
    // Load contract spec from network
    val client = ContractClient.forContract(
        contractId = "CDLZ...",
        rpcUrl = "https://soroban-testnet.stellar.org:443",
        network = Network.TESTNET
    )

    // Query with Map-based arguments (auto-executes)
    val balance = client.invoke<Long>(
        functionName = "balance",
        arguments = mapOf("account" to accountAddress),
        source = sourceAccount,
        signer = null,  // No signer for read calls
        parseResultXdrFn = { Scv.fromInt128(it).toLong() }
    )
    println("Balance: $balance")

    // Write operation - auto signs and submits
    client.invoke<Unit>(
        functionName = "transfer",
        arguments = mapOf(
            "from" to fromAddress,
            "to" to toAddress,
            "amount" to 1000
        ),
        source = sourceAccount,
        signer = keypair,  // Required for writes
        parseResultXdrFn = null
    )

    client.close()
}

Multi-signature workflows with buildInvoke for manual control:

suspend fun multiSigContractCall() {
    val client = ContractClient.forContract(contractId, rpcUrl, Network.TESTNET)
    val assembled = client.buildInvoke<String>(...)

    // Detect and sign for additional signers
    val whoNeedsToSign = assembled.needsNonInvokerSigningBy()
    whoNeedsToSign.forEach { assembled.signAuthEntries(getKeypairFor(it)) }

    val result = assembled.signAndSubmit(sourceKeypair)
}

For deployment examples, authorization patterns, and advanced usage, see the Getting Started Guide and Demo App.

Demo Application

The demo app showcases SDK usage across all platforms with 11 comprehensive features:

  1. Key Generation - Generate and manage Ed25519 keypairs
  2. Fund Testnet Account - Get free test XLM from Friendbot
  3. Fetch Account Details - Retrieve account information from Horizon
  4. Trust Asset - Establish trustlines for issued assets
  5. Send Payment - Transfer XLM and issued assets
  6. Fetch Transaction Details - View transaction operations and events from Horizon or Soroban RPC
  7. Fetch Smart Contract Details - Parse and inspect Soroban contracts
  8. Deploy Smart Contract - Deploy Soroban WASM contracts to testnet
  9. Invoke Hello World Contract - Simple contract invocation with automatic result parsing
  10. Invoke Auth Contract - Dynamic authorization handling for same-invoker and different-invoker scenarios
  11. Invoke Token Contract - SEP-41 token contract interaction with multi-signature workflows

See demo/README.md for screenshots and platform-specific build instructions.

Agent Skill

This repository includes an Agent Skill that teaches AI coding agents how to use this SDK. See skills/ for installation instructions.

Documentation

SDK Documentation

  • Docs folder - containing getting started guide, many sdk usage examples, advanced topics, api documentation and more.

External Resources

Cryptography

This SDK uses production-ready, audited cryptographic libraries on all platforms:

  • JVM: BouncyCastle for Ed25519 operations
  • iOS/macOS: libsodium (native C interop)
  • JavaScript: libsodium-wrappers-sumo (WebAssembly)

All implementations provide constant-time operations, proper memory safety, and comprehensive input validation. No experimental or custom cryptography.

Testing

See Testing Guide for information on running tests.

Requirements

  • Kotlin: 2.2.20
  • Gradle: 9.0+
  • JVM: Java 17+
  • Android: API 24+ (Android 7.0)
  • iOS: iOS 14.0+
  • macOS: macOS 11.0+
  • JavaScript: Node.js 14+, modern browsers with WebAssembly support

Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines on reporting issues, proposing features, and submitting pull requests.

License

Licensed under the Apache License, Version 2.0. See LICENSE for the full license text.

Acknowledgments