Split a payment into two parts by creating a claimable balance.
Claimable balances were introduced in CAP-23 and are used to split a payment into two parts.
Part 1: sending account creates a payment, or ClaimableBalanceEntry, using the Create Claimable Balance operation
Part 2: destination account(s), or claimant(s), accepts the ClaimableBalanceEntry using the Claim Claimable Balance operation
Claimable balances allow an account to send a payment to another account that is not necessarily prepared to receive the payment. They can be used when you send a non-native asset to an account that has not yet established a trustline, which can be useful for anchors onboarding new users. A trustline must be established by the claimant to the asset before it can claim the claimable balance, otherwise, the claim will result in an op_no_trust error.It is important to note that if a claimable balance isn’t claimed, it sits on the ledger forever, taking up space and ultimately making the network less efficient. For this reason, it is a good idea to put one of your own accounts as a claimant for a claimable balance. Then you can accept your own claimable balance if needed, freeing up space on the network.Each ClaimableBalanceEntry is a ledger entry, and each claimant in that entry increases the source account’s minimum balance by one base reserve.Once a ClaimableBalanceEntry has been claimed, it is deleted.
Claim_Predicate_ Claimant — an object that holds both the destination account that can claim the ClaimableBalanceEntry and a ClaimPredicate that must evaluate to true for the claim to succeed.A ClaimPredicate is a recursive data structure that can be used to construct complex conditionals using different ClaimPredicateTypes. Below are some examples with the Claim_Predicate_ prefix removed for readability. Note that the SDKs expect the Unix timestamps to be expressed in seconds.
Can claim at any time - UNCONDITIONAL
Can claim if the close time of the ledger, including the claim is before X seconds + the ledger close time in which the ClaimableBalanceEntry was created - BEFORE_RELATIVE_TIME(X)
Can claim if the close time of the ledger including the claim is before X (Unix timestamp) - BEFORE_ABSOLUTE_TIME(X)
Can claim if the close time of the ledger, including the claim is at or after X seconds + the ledger close time in which the ClaimableBalanceEntry was created - NOT(BEFORE_RELATIVE_TIME(X))
Can claim if the close time of the ledger, including the claim is at or after X (Unix timestamp) - NOT(BEFORE_ABSOLUTE_TIME(X))
Can claim between X and Y Unix timestamps (given X < Y) - AND(NOT(BEFORE_ABSOLUTE_TIME(X)), BEFORE_ABSOLUTE_TIME(Y))
Can claim outside X and Y Unix timestamps (given X < Y) - OR(BEFORE_ABSOLUTE_TIME(X), NOT(BEFORE_ABSOLUTE_TIME(Y))
ClaimableBalanceID ClaimableBalanceID is a union with one possible type (CLAIMABLE_BALANCE_ID_TYPE_V0). It contains an SHA-256 hash of the OperationID for Claimable Balances.A successful Create Claimable Balance operation will return a Balance ID, which is required when claiming the ClaimableBalanceEntry with the Claim Claimable Balance operation.
Claim Claimable Balance
For basic parameters, see the Claim Claimable Balance entry in our List of Operations section.This operation will load the ClaimableBalanceEntry that corresponds to the Balance ID and then search for the source account of this operation in the list of claimants on the entry. If a match on the claimant is found, and the ClaimPredicate evaluates to true, then the ClaimableBalanceEntry can be claimed. The balance on the entry will be moved to the source account if there are no limit or trustline issues (for non-native assets), meaning the claimant must establish a trustline to the asset before claiming it.
Clawback Claimable Balance
This operation claws back a claimable balance, returning the asset to the issuer account, burning it. You must claw back the entire claimable balance, not just part of it. Once a claimable balance has been claimed, use the regular clawback operation to claw it back.Clawback claimable balances require the claimable balance ID.Learn more about clawbacks in our Clawback Guide.
Example
The below code demonstrates via the JavaScript, Python, Go, and Java SDKs how an account (Account A) creates a ClaimableBalanceEntry with two claimants: Account A (itself) and Account B (another recipient).Each of these accounts can only claim the balance under unique conditions. Account B has a full minute to claim the balance before Account A can reclaim the balance back for itself.Note: there is no recovery mechanism for a claimable balance in general — if none of the predicates can be fulfilled, the balance cannot be recovered. The reclaim example below acts as a safety net for this situation.
Click here to see helper functions
func fundAccount(rpcClient *client.Client, address string) error { ctx := context.Background() // Use GetNetwork method from client networkResp, err := rpcClient.GetNetwork(ctx) if err != nil { return err } if networkResp.FriendbotURL != "" { friendbotURL := networkResp.FriendbotURL + "?addr=" + url.QueryEscape(address) resp, err := http.Post(friendbotURL, "application/x-www-form-urlencoded", nil) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != 200 { return fmt.Errorf("friendbot failed with status: %d", resp.StatusCode) } return nil } return fmt.Errorf("friendbot not configured for network - %s", networkResp.Passphrase)}func panicIf(err error) { if err != nil { log.Fatal(err) }}
// Add this helper to the CreateClaimableBalance class below. It needs these imports:// java.net.URI, java.net.URLEncoder, java.net.http.HttpClient,// java.net.http.HttpRequest, java.net.http.HttpResponse and// java.nio.charset.StandardCharsets.private static void fundAccount(SorobanServer rpcClient, String address) throws Exception { // Use getNetwork method from client String friendbotUrl = rpcClient.getNetwork().getFriendbotUrl(); if (friendbotUrl == null || friendbotUrl.isEmpty()) { throw new IllegalStateException("friendbot not configured for network"); } HttpRequest request = HttpRequest.newBuilder( URI.create(friendbotUrl + "?addr=" + URLEncoder.encode(address, StandardCharsets.UTF_8))) .POST(HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { throw new IllegalStateException("friendbot failed with status: " + response.statusCode()); }}
import * as StellarSdk from "@stellar/stellar-sdk";/** * Creates a claimable balance on Stellar testnet * A claimable balance allows splitting a payment into two parts: * 1. Sender creates the claimable balance * 2. Recipient(s) can claim it later */async function createClaimableBalance() { // Connect to Stellar testnet RPC server const server = new StellarSdk.rpc.Server( "https://soroban-testnet.stellar.org", ); const A = StellarSdk.Keypair.random(); const B = StellarSdk.Keypair.random(); console.log( `Account A... public key: ${A.publicKey()}, secret: ${A.secret()}`, ); console.log( `Account B... public key: ${B.publicKey()}, secret: ${B.secret()}`, ); try { // Fund the source account using testnet's built-in airdrop await server.requestAirdrop(A.publicKey()); // Load the funded account to get current sequence number const aAccount = await server.getAccount(A.publicKey()); console.log(`Account sequence: ${aAccount.sequenceNumber()}`); // Create a claimable balance with our two above-described conditions. let soon = Math.ceil(Date.now() / 1000 + 60); // .now() is in ms let bCanClaim = StellarSdk.Claimant.predicateBeforeRelativeTime("60"); let aCanReclaim = StellarSdk.Claimant.predicateNot( StellarSdk.Claimant.predicateBeforeAbsoluteTime(soon.toString()), ); // Create claimable balance operation const claimableBalanceOp = StellarSdk.Operation.createClaimableBalance({ claimants: [ new StellarSdk.Claimant(B.publicKey(), bCanClaim), new StellarSdk.Claimant(A.publicKey(), aCanReclaim), ], asset: StellarSdk.Asset.native(), amount: "420", }); // Bid what recent transactions paid, capped at what you're willing to spend. const { inclusionFee } = await server.getFeeStats(); const MAX_FEE = 100_000; // stroops per operation (0.01 XLM): pick your own cap const fee = String(Math.min(Number(inclusionFee.p90), MAX_FEE)); // Build the transaction console.log(`Building transaction...`); const transaction = new StellarSdk.TransactionBuilder(aAccount, { fee, networkPassphrase: StellarSdk.Networks.TESTNET, }) .addOperation(claimableBalanceOp) .setTimeout(180) .build(); /* Claimable BalanceIds are predictable and can be derived from the Sha256 hash of the operation that creates them. */ const predictableBalanceId = transaction.getClaimableBalanceId(0); // Sign the transaction with source account transaction.sign(A); // Submit transaction to the network console.log(`Submitting transaction...`); const response = await server.sendTransaction(transaction); // Poll for transaction completion (RPC is asynchronous) console.log(`Polling for result...`); const finalResponse = await server.pollTransaction(response.hash); if (finalResponse.status === "SUCCESS") { // Extract claimable balance ID from transaction result const txResult = finalResponse.resultXdr; const results = txResult.result.results; const operationResult = results[0].tr.createClaimableBalanceResult; const balanceId = operationResult.balanceId.toXdr("hex"); console.log(`Balance ID (from txResult): ${balanceId}`); console.log( `Predictable Balance ID (obtained before txSubmission): ${predictableBalanceId}`, ); if (balanceId === predictableBalanceId) { console.log(`Balance ID from txResult matches the predictable ID`); } else { console.log( ` Balance ID from txResult does NOT match the predictable ID`, ); } } else { console.log(`Transaction failed: ${finalResponse.status}`); } } catch (error) { console.error(`Error: ${error.message}`); }}// Run the functioncreateClaimableBalance();
import mathimport timeimport requestsfrom stellar_sdk import ( Asset, ClaimPredicate, Claimant, CreateClaimableBalance, Keypair, Network, SorobanServer, TransactionBuilder,)from stellar_sdk.soroban_rpc import GetTransactionStatusfrom stellar_sdk.xdr import TransactionResultdef create_claimable_balance(): """Creates a claimable balance on Stellar testnet. A claimable balance allows splitting a payment into two parts: 1. Sender creates the claimable balance 2. Recipient(s) can claim it later """ # Connect to Stellar testnet RPC server server = SorobanServer("https://soroban-testnet.stellar.org") A = Keypair.random() B = Keypair.random() print(f"Account A... public key: {A.public_key}, secret: {A.secret}") print(f"Account B... public key: {B.public_key}, secret: {B.secret}") try: # Fund the source account with testnet's Friendbot friendbot_url = server.get_network().friendbot_url requests.get( friendbot_url, params={"addr": A.public_key}, timeout=30 ).raise_for_status() # Load the funded account to get current sequence number a_account = server.load_account(A.public_key) print(f"Account sequence: {a_account.sequence}") # Create a claimable balance with our two above-described conditions. soon = math.ceil(time.time() + 60) b_can_claim = ClaimPredicate.predicate_before_relative_time(60) a_can_reclaim = ClaimPredicate.predicate_not( ClaimPredicate.predicate_before_absolute_time(soon) ) # Create claimable balance operation claimable_balance_op = CreateClaimableBalance( claimants=[ Claimant(destination=B.public_key, predicate=b_can_claim), Claimant(destination=A.public_key, predicate=a_can_reclaim), ], asset=Asset.native(), amount="420", ) # Bid what recent transactions paid, capped at what you're willing to spend. MAX_FEE = 100_000 # stroops per operation (0.01 XLM): pick your own cap fee = min(server.get_fee_stats().inclusion_fee.p90, MAX_FEE) # Build the transaction print("Building transaction...") transaction = ( TransactionBuilder( source_account=a_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=fee, ) .append_operation(claimable_balance_op) .set_timeout(180) .build() ) # Claimable BalanceIds are predictable and can be derived from the # Sha256 hash of the operation that creates them. predictable_balance_id = transaction.transaction.get_claimable_balance_id(0) # Sign the transaction with source account transaction.sign(A) # Submit transaction to the network print("Submitting transaction...") response = server.send_transaction(transaction) # Poll for transaction completion (RPC is asynchronous) print("Polling for result...") final_response = server.poll_transaction(response.hash) if final_response.status == GetTransactionStatus.SUCCESS: # Extract claimable balance ID from transaction result tx_result = TransactionResult.from_xdr(final_response.result_xdr) results = tx_result.result.results operation_result = results[0].tr.create_claimable_balance_result balance_id = operation_result.balance_id.to_xdr_bytes().hex() print(f"Balance ID (from txResult): {balance_id}") print( "Predictable Balance ID (obtained before txSubmission): " f"{predictable_balance_id}" ) if balance_id == predictable_balance_id: print("Balance ID from txResult matches the predictable ID") else: print(" Balance ID from txResult does NOT match the predictable ID") else: print(f"Transaction failed: {final_response.status.value}") except Exception as error: print(f"Error: {error}")# Run the functioncreate_claimable_balance()
package mainimport ( "context" "fmt" "log" "net/http" "net/url" "time" client "github.com/stellar/go-stellar-sdk/clients/rpcclient" protocol "github.com/stellar/go-stellar-sdk/protocols/rpc" "github.com/stellar/go-stellar-sdk/keypair" "github.com/stellar/go-stellar-sdk/network" "github.com/stellar/go-stellar-sdk/txnbuild" "github.com/stellar/go-stellar-sdk/xdr")func main() { // Create RPC client rpcClient := client.NewClient("https://soroban-testnet.stellar.org", nil) defer rpcClient.Close() // Generate random keypairs A := keypair.MustRandom() B := keypair.MustRandom() fmt.Printf("Account A: public key: %s, secret key: %s\n", A.Address(), A.Seed()) fmt.Printf("Account B: public key: %s\n", B.Address()) // Fund account using GetNetwork + friendbot fmt.Println("\nFunding account...") panicIf(fundAccount(rpcClient, A.Address())) fmt.Println("Account funded") // Wait for funding time.Sleep(3 * time.Second) // Use LoadAccount method from the client ctx := context.Background() sourceAccount, err := rpcClient.LoadAccount(ctx, A.Address()) panicIf(err) // Create a claimable balance with our two above-described conditions. soon := time.Now().Add(time.Second * 60) bCanClaim := txnbuild.BeforeRelativeTimePredicate(60) aCanReclaim := txnbuild.NotPredicate( txnbuild.BeforeAbsoluteTimePredicate(soon.Unix()), ) // Create claimable balance operation claimableBalanceOp := txnbuild.CreateClaimableBalance{ Destinations: []txnbuild.Claimant{ txnbuild.NewClaimant(B.Address(), &bCanClaim), txnbuild.NewClaimant(A.Address(), &aCanReclaim), }, Asset: txnbuild.NativeAsset{}, Amount: "1", } // Bid what recent transactions paid, capped at what you're willing to spend. feeStats, err := rpcClient.GetFeeStats(ctx) panicIf(err) const maxFee = 100_000 // stroops per operation (0.01 XLM): pick your own cap fee := min(int64(feeStats.InclusionFee.P90), maxFee) // Build transaction tx, err := txnbuild.NewTransaction( txnbuild.TransactionParams{ SourceAccount: sourceAccount, IncrementSequenceNum: true, BaseFee: fee, Preconditions: txnbuild.Preconditions{TimeBounds: txnbuild.NewInfiniteTimeout()}, Operations: []txnbuild.Operation{&claimableBalanceOp}, }, ) panicIf(err) // Sign transaction tx, err = tx.Sign(network.TestNetworkPassphrase, A) panicIf(err) // Get transaction XDR txXDR, err := tx.Base64() panicIf(err) // Submit using RPC client's SendTransaction method fmt.Println("Submitting transaction...") sendResp, err := rpcClient.SendTransaction(ctx, protocol.SendTransactionRequest{ Transaction: txXDR, }) panicIf(err) if sendResp.Status != "PENDING" { log.Fatalf("Transaction not pending: %s", sendResp.Status) } fmt.Printf("Transaction submitted: %s\n", sendResp.Hash) // Poll using RPC client's GetTransaction method fmt.Println("Polling for result...") for i := 0; i < 10; i++ { resp, err := rpcClient.GetTransaction(ctx, protocol.GetTransactionRequest{ Hash: sendResp.Hash, }) if err != nil { log.Printf("Error getting transaction: %v", err) time.Sleep(1 * time.Second) continue } if resp.Status != protocol.TransactionStatusNotFound { if resp.Status == protocol.TransactionStatusSuccess { // Extract balance ID balanceID, err := extractBalanceID(&resp) if err != nil { log.Printf("Error extracting balance ID: %v", err) } else { fmt.Println("\nSUCCESS: Claimable balance created") fmt.Printf("Balance ID: %s\n", balanceID) } } else { fmt.Printf("Transaction failed: %s\n", resp.Status) } return } time.Sleep(time.Duration(i+1) * time.Second) } fmt.Println("Transaction polling timeout")}func extractBalanceID(resp *protocol.GetTransactionResponse) (string, error) { if resp.ResultXDR == "" { return "", fmt.Errorf("no result XDR") } var txResult xdr.TransactionResult err := xdr.SafeUnmarshalBase64(resp.ResultXDR, &txResult) if err != nil { return "", err } if results, ok := txResult.OperationResults(); ok && len(results) > 0 { operationResult := results[0].MustTr().CreateClaimableBalanceResult return xdr.MarshalHex(operationResult.BalanceId) } return "", fmt.Errorf("no operation results")}
import java.math.BigDecimal;import java.time.Instant;import java.util.List;import org.stellar.sdk.AssetTypeNative;import org.stellar.sdk.Claimant;import org.stellar.sdk.KeyPair;import org.stellar.sdk.Network;import org.stellar.sdk.Predicate;import org.stellar.sdk.SorobanServer;import org.stellar.sdk.Transaction;import org.stellar.sdk.TransactionBuilder;import org.stellar.sdk.TransactionBuilderAccount;import org.stellar.sdk.TransactionPreconditions;import org.stellar.sdk.Util;import org.stellar.sdk.operations.CreateClaimableBalanceOperation;import org.stellar.sdk.responses.sorobanrpc.GetTransactionResponse;import org.stellar.sdk.responses.sorobanrpc.GetTransactionResponse.GetTransactionStatus;import org.stellar.sdk.responses.sorobanrpc.SendTransactionResponse;import org.stellar.sdk.xdr.ClaimableBalanceID;import org.stellar.sdk.xdr.OperationResult;public final class CreateClaimableBalance { public static void main(String[] args) throws Exception { // Create RPC client SorobanServer rpcClient = new SorobanServer("https://soroban-testnet.stellar.org"); // Generate random keypairs KeyPair A = KeyPair.random(); KeyPair B = KeyPair.random(); System.out.printf("Account A: public key: %s, secret key: %s%n", A.getAccountId(), new String(A.getSecretSeed())); System.out.printf("Account B: public key: %s%n", B.getAccountId()); // Fund account using getNetwork + friendbot System.out.println("\nFunding account..."); fundAccount(rpcClient, A.getAccountId()); System.out.println("Account funded"); // Wait for funding Thread.sleep(3000); // Use getAccount method from the client TransactionBuilderAccount sourceAccount = rpcClient.getAccount(A.getAccountId()); // Create a claimable balance with our two above-described conditions. long soon = Instant.now().plusSeconds(60).getEpochSecond(); Predicate bCanClaim = new Predicate.RelBefore(60); Predicate aCanReclaim = new Predicate.Not(new Predicate.AbsBefore(soon)); // Create claimable balance operation CreateClaimableBalanceOperation claimableBalanceOp = CreateClaimableBalanceOperation.builder() .claimants(List.of( new Claimant(B.getAccountId(), bCanClaim), new Claimant(A.getAccountId(), aCanReclaim))) .asset(new AssetTypeNative()) .amount(new BigDecimal("1")) .build(); // Bid what recent transactions paid, capped at what you're willing to spend. long maxFee = 100_000L; // stroops per operation (0.01 XLM): pick your own cap long fee = Math.min(rpcClient.getFeeStats().getInclusionFee().getP90(), maxFee); // Build transaction Transaction tx = new TransactionBuilder(sourceAccount, Network.TESTNET) .setBaseFee(fee) .setTimeout(TransactionPreconditions.TIMEOUT_INFINITE) .addOperation(claimableBalanceOp) .build(); // Sign transaction tx.sign(A); // Submit using RPC client's sendTransaction method System.out.println("Submitting transaction..."); SendTransactionResponse sendResp = rpcClient.sendTransaction(tx); if (sendResp.getStatus() != SendTransactionResponse.SendTransactionStatus.PENDING) { throw new IllegalStateException("Transaction not pending: " + sendResp.getStatus()); } System.out.printf("Transaction submitted: %s%n", sendResp.getHash()); // Poll using RPC client's getTransaction method System.out.println("Polling for result..."); for (int i = 0; i < 10; i++) { GetTransactionResponse resp = rpcClient.getTransaction(sendResp.getHash()); if (resp.getStatus() != GetTransactionStatus.NOT_FOUND) { if (resp.getStatus() == GetTransactionStatus.SUCCESS) { // Extract balance ID System.out.println("\nSUCCESS: Claimable balance created"); System.out.printf("Balance ID: %s%n", extractBalanceID(resp)); } else { System.out.printf("Transaction failed: %s%n", resp.getStatus()); } return; } Thread.sleep((i + 1) * 1000L); } System.out.println("Transaction polling timeout"); } private static String extractBalanceID(GetTransactionResponse resp) throws Exception { OperationResult[] results = resp.parseResultXdr().getResult().getResults(); if (results == null || results.length == 0) { throw new IllegalStateException("no operation results"); } ClaimableBalanceID balanceId = results[0].getTr().getCreateClaimableBalanceResult().getBalanceID(); return Util.bytesToHex(balanceId.toXdrByteArray()).toLowerCase(); }}
At this point, the ClaimableBalanceEntry exists in the ledger, but we’ll need its Balance ID to claim it. You can call the RPC’s getLedgerEntries endpoint to do this.
import * as StellarSdk from "@stellar/stellar-sdk";// Replace with your actual Claimable Balance ID// Format: 72 hex characters (includes ClaimableBalanceId type + hash)const BALANCE_ID = "00000000db1108ff108a807150d02b8672d9a8c0e808bff918cdbe5c7605e63a7f565df5";/** * Fetches and displays claimable balance details using Stellar RPC */async function fetchClaimableBalance(balanceId) { const server = new StellarSdk.rpc.Server( "https://soroban-testnet.stellar.org", ); try { console.log(`Looking up balance ID: ${balanceId}`); // Parse the claimable balance ID from hex XDR const claimableBalanceId = StellarSdk.xdr.ClaimableBalanceId.fromXDR( balanceId, "hex", ); // Create ledger key for the claimable balance entry const ledgerKey = StellarSdk.xdr.LedgerKey.claimableBalance( new StellarSdk.xdr.LedgerKeyClaimableBalance({ balanceId: claimableBalanceId, }), ); console.log(`Fetching from RPC server...`); // Use SDK's getLedgerEntries method with XDR object array const response = await server.getLedgerEntries(ledgerKey); if (response.entries && response.entries.length > 0) { const claimableBalance = response.entries[0].val.claimableBalance; const asset = StellarSdk.Asset.fromOperation(claimableBalance.asset); console.log(`Found claimable balance`); console.log(`Amount: ${claimableBalance.amount.toString()}`); console.log(`Asset: ${asset.toString()} `); // Show claimant details console.log(`\nClaimants:`); claimableBalance.claimants.forEach((claimant, index) => { const destination = claimant.v0.destination.ed25519.toBytes(); console.log( ` ${index + 1}. ${StellarSdk.StrKey.encodeEd25519PublicKey( destination, )}`, ); }); } else { console.log(`Claimable balance not found`); } } catch (error) { console.error(`Error: ${error.message}`); }}fetchClaimableBalance(BALANCE_ID);
from stellar_sdk import Asset, SorobanServer, StrKeyfrom stellar_sdk.xdr import ( ClaimableBalanceID, LedgerEntryData, LedgerEntryType, LedgerKey, LedgerKeyClaimableBalance,)# Replace with your actual Claimable Balance ID# Format: 72 hex characters (includes ClaimableBalanceId type + hash)BALANCE_ID = "00000000db1108ff108a807150d02b8672d9a8c0e808bff918cdbe5c7605e63a7f565df5"def fetch_claimable_balance(balance_id): """Fetches and displays claimable balance details using Stellar RPC.""" server = SorobanServer("https://soroban-testnet.stellar.org") try: print(f"Looking up balance ID: {balance_id}") # Parse the claimable balance ID from hex XDR claimable_balance_id = ClaimableBalanceID.from_xdr_bytes( bytes.fromhex(balance_id) ) # Create ledger key for the claimable balance entry ledger_key = LedgerKey( LedgerEntryType.CLAIMABLE_BALANCE, claimable_balance=LedgerKeyClaimableBalance( balance_id=claimable_balance_id ), ) print("Fetching from RPC server...") # Use SDK's get_ledger_entries method with XDR object list response = server.get_ledger_entries([ledger_key]) if response.entries: entry_data = LedgerEntryData.from_xdr(response.entries[0].xdr) claimable_balance = entry_data.claimable_balance asset = Asset.from_xdr_object(claimable_balance.asset) print("Found claimable balance") print(f"Amount: {claimable_balance.amount.int64}") if asset.is_native(): print("Asset: native ") else: print(f"Asset: {asset.code}:{asset.issuer} ") # Show claimant details print("\nClaimants:") for index, claimant in enumerate(claimable_balance.claimants): destination = claimant.v0.destination.account_id.ed25519.uint256 address = StrKey.encode_ed25519_public_key(destination) print(f" {index + 1}. {address}") else: print("Claimable balance not found") except Exception as error: print(f"Error: {error}")fetch_claimable_balance(BALANCE_ID)
package mainimport ( "context" "fmt" client "github.com/stellar/go-stellar-sdk/clients/rpcclient" protocol "github.com/stellar/go-stellar-sdk/protocols/rpc" "github.com/stellar/go-stellar-sdk/xdr")// Replace with your claimable balance IDconst BALANCE_ID = "00000000a4c91c4561f2d8b30dad9cf6475221b3003a3b4e12fc0cf78a13251c0e7ff665"func main() { // Create RPC client rpcClient := client.NewClient("https://soroban-testnet.stellar.org", nil) defer rpcClient.Close() fmt.Printf("Looking up balance ID: %s\n", BALANCE_ID) // Parse claimable balance ID from hex var claimableBalanceID xdr.ClaimableBalanceId err := xdr.SafeUnmarshalHex(BALANCE_ID, &claimableBalanceID) panicIf(err) // Create ledger key for claimable balance ledgerKey := xdr.LedgerKey{ Type: xdr.LedgerEntryTypeClaimableBalance, ClaimableBalance: &xdr.LedgerKeyClaimableBalance{ BalanceId: claimableBalanceID, }, } // Convert ledger key to base64 for RPC call ledgerKeyB64, err := xdr.MarshalBase64(ledgerKey) panicIf(err) fmt.Println("Fetching from RPC server...") // Use GetLedgerEntries method from client ctx := context.Background() resp, err := rpcClient.GetLedgerEntries(ctx, protocol.GetLedgerEntriesRequest{ Keys: []string{ledgerKeyB64}, }) panicIf(err) if len(resp.Entries) > 0 { entry := resp.Entries[0] fmt.Println("Found claimable balance") // Parse the ledger entry XDR var ledgerEntryData xdr.LedgerEntryData err = xdr.SafeUnmarshalBase64(entry.DataXDR, &ledgerEntryData) panicIf(err) claimableBalance := ledgerEntryData.ClaimableBalance // Display details fmt.Printf("Amount: %d\n", int64(claimableBalance.Amount)) fmt.Printf("Asset: %s\n", claimableBalance.Asset.String()) // Show claimants fmt.Println("\nClaimants:") for i, claimant := range claimableBalance.Claimants { address := claimant.V0.Destination.Address() fmt.Printf(" %d. %s\n", i+1, address) } } else { fmt.Println("Claimable balance not found") }}
import java.util.List;import org.stellar.sdk.Asset;import org.stellar.sdk.KeyPair;import org.stellar.sdk.SorobanServer;import org.stellar.sdk.Util;import org.stellar.sdk.responses.sorobanrpc.GetLedgerEntriesResponse;import org.stellar.sdk.xdr.ClaimableBalanceEntry;import org.stellar.sdk.xdr.ClaimableBalanceID;import org.stellar.sdk.xdr.Claimant;import org.stellar.sdk.xdr.LedgerEntryType;import org.stellar.sdk.xdr.LedgerKey;public final class FetchClaimableBalance { // Replace with your claimable balance ID private static final String BALANCE_ID = "00000000a4c91c4561f2d8b30dad9cf6475221b3003a3b4e12fc0cf78a13251c0e7ff665"; public static void main(String[] args) throws Exception { // Create RPC client SorobanServer rpcClient = new SorobanServer("https://soroban-testnet.stellar.org"); System.out.printf("Looking up balance ID: %s%n", BALANCE_ID); // Parse claimable balance ID from hex ClaimableBalanceID claimableBalanceID = ClaimableBalanceID.fromXdrByteArray(Util.hexToBytes(BALANCE_ID)); // Create ledger key for claimable balance LedgerKey ledgerKey = LedgerKey.builder() .discriminant(LedgerEntryType.CLAIMABLE_BALANCE) .claimableBalance(LedgerKey.LedgerKeyClaimableBalance.builder() .balanceID(claimableBalanceID) .build()) .build(); System.out.println("Fetching from RPC server..."); // Use getLedgerEntries method from client GetLedgerEntriesResponse resp = rpcClient.getLedgerEntries(List.of(ledgerKey)); if (resp.getEntries() != null && !resp.getEntries().isEmpty()) { System.out.println("Found claimable balance"); // Parse the ledger entry XDR ClaimableBalanceEntry claimableBalance = resp.getEntries().get(0).parseXdr().getClaimableBalance(); // Display details System.out.printf("Amount: %d%n", claimableBalance.getAmount().getInt64()); System.out.printf("Asset: %s%n", Asset.fromXdr(claimableBalance.getAsset())); // Show claimants System.out.println("\nClaimants:"); Claimant[] claimants = claimableBalance.getClaimants(); for (int i = 0; i < claimants.length; i++) { String address = KeyPair.fromXdrPublicKey( claimants[i].getV0().getDestination().getAccountID()).getAccountId(); System.out.printf(" %d. %s%n", i + 1, address); } } else { System.out.println("Claimable balance not found"); } }}
With the Claimable Balance ID acquired, either Account B or A can actually submit a claim, depending on which predicate is fulfilled. We’ll assume here that a minute has passed, so Account A just reclaims the balance entry.
import * as StellarSdk from "@stellar/stellar-sdk";// Replace with your claimable balance IDconst BALANCE_ID = "0000000067a94da6c5d487fa09fc93c558ca91f6338413d3152d2a17771353f7c4111e11";// Replace with the secret key of one of the claimantsconst CLAIMANT_SECRET = "SDJLAUDIHMDO6PAIVVVYH5IFIE5QMZOOBHO37NLF43335ULECK6EURVJ";/** * Claims a claimable balance */async function claimClaimableBalance(balanceId, claimantSecret) { const server = new StellarSdk.rpc.Server( "https://soroban-testnet.stellar.org", ); try { console.log(`Claiming balance ID: ${balanceId}`); // Create keypair from claimant's secret key const claimantKeypair = StellarSdk.Keypair.fromSecret(claimantSecret); // Load the claiming account const claimantAccount = await server.getAccount( claimantKeypair.publicKey(), ); // Convert balance ID to proper format for the operation const claimableBalanceId = StellarSdk.xdr.ClaimableBalanceId.fromXDR( balanceId, "hex", ); const balanceIdHex = claimableBalanceId.toXDR("hex"); // Create claim operation const claimOperation = StellarSdk.Operation.claimClaimableBalance({ balanceId: balanceIdHex, }); // Bid what recent transactions paid, capped at what you're willing to spend. const { inclusionFee } = await server.getFeeStats(); const MAX_FEE = 100_000; // stroops per operation (0.01 XLM): pick your own cap const fee = String(Math.min(Number(inclusionFee.p90), MAX_FEE)); // Build and sign transaction const transaction = new StellarSdk.TransactionBuilder(claimantAccount, { fee, networkPassphrase: StellarSdk.Networks.TESTNET, }) .addOperation(claimOperation) .setTimeout(180) .build(); transaction.sign(claimantKeypair); // Submit and poll for completion const response = await server.sendTransaction(transaction); const finalResponse = await server.pollTransaction(response.hash); if (finalResponse.status === "SUCCESS") { console.log(`Claimable balance claimed successfully`); console.log(`Transaction hash: ${response.hash}`); } else { console.log(`Transaction failed: ${finalResponse.status}`); } } catch (error) { console.error(`Error: ${error.message}`); }}claimClaimableBalance(BALANCE_ID, CLAIMANT_SECRET);
from stellar_sdk import ( ClaimClaimableBalance, Keypair, Network, SorobanServer, TransactionBuilder,)from stellar_sdk.soroban_rpc import GetTransactionStatus# Replace with your claimable balance IDBALANCE_ID = "0000000067a94da6c5d487fa09fc93c558ca91f6338413d3152d2a17771353f7c4111e11"# Replace with the secret key of one of the claimantsCLAIMANT_SECRET = "SDJLAUDIHMDO6PAIVVVYH5IFIE5QMZOOBHO37NLF43335ULECK6EURVJ"def claim_claimable_balance(balance_id, claimant_secret): """Claims a claimable balance.""" server = SorobanServer("https://soroban-testnet.stellar.org") try: print(f"Claiming balance ID: {balance_id}") # Create keypair from claimant's secret key claimant_keypair = Keypair.from_secret(claimant_secret) # Load the claiming account claimant_account = server.load_account(claimant_keypair.public_key) # Create claim operation (it takes the balance ID as a hex string) claim_operation = ClaimClaimableBalance(balance_id=balance_id) # Bid what recent transactions paid, capped at what you're willing to spend. MAX_FEE = 100_000 # stroops per operation (0.01 XLM): pick your own cap fee = min(server.get_fee_stats().inclusion_fee.p90, MAX_FEE) # Build and sign transaction transaction = ( TransactionBuilder( source_account=claimant_account, network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE, base_fee=fee, ) .append_operation(claim_operation) .set_timeout(180) .build() ) transaction.sign(claimant_keypair) # Submit and poll for completion response = server.send_transaction(transaction) final_response = server.poll_transaction(response.hash) if final_response.status == GetTransactionStatus.SUCCESS: print("Claimable balance claimed successfully") print(f"Transaction hash: {response.hash}") else: print(f"Transaction failed: {final_response.status.value}") except Exception as error: print(f"Error: {error}")claim_claimable_balance(BALANCE_ID, CLAIMANT_SECRET)
import org.stellar.sdk.KeyPair;import org.stellar.sdk.Network;import org.stellar.sdk.SorobanServer;import org.stellar.sdk.Transaction;import org.stellar.sdk.TransactionBuilder;import org.stellar.sdk.TransactionBuilderAccount;import org.stellar.sdk.TransactionPreconditions;import org.stellar.sdk.operations.ClaimClaimableBalanceOperation;import org.stellar.sdk.responses.sorobanrpc.GetTransactionResponse;import org.stellar.sdk.responses.sorobanrpc.GetTransactionResponse.GetTransactionStatus;import org.stellar.sdk.responses.sorobanrpc.SendTransactionResponse;public final class ClaimClaimableBalance { // Replace with your claimable balance ID and claimant secret private static final String BALANCE_ID = "00000000a4c91c4561f2d8b30dad9cf6475221b3003a3b4e12fc0cf78a13251c0e7ff665"; private static final String CLAIMANT_SECRET = "SBMODTOLLH2LGF4AJU5XOGHRQCGKEVJUZSAUAGJL7KGKC7XLJ3SG3F7N"; public static void main(String[] args) throws Exception { // Create RPC client SorobanServer rpcClient = new SorobanServer("https://soroban-testnet.stellar.org"); // Create keypair from claimant secret KeyPair keypairAccA = KeyPair.fromSecretSeed(CLAIMANT_SECRET); System.out.printf("Claiming account: %s%n", keypairAccA.getAccountId()); System.out.printf("Balance ID: %s%n", BALANCE_ID); // Load the claimant account using client's getAccount method TransactionBuilderAccount accountA = rpcClient.getAccount(keypairAccA.getAccountId()); // Create claim claimable balance operation (it takes the balance ID as a hex string) ClaimClaimableBalanceOperation claimOp = ClaimClaimableBalanceOperation.builder() .balanceId(BALANCE_ID) .build(); // Bid what recent transactions paid, capped at what you're willing to spend. long maxFee = 100_000L; // stroops per operation (0.01 XLM): pick your own cap long fee = Math.min(rpcClient.getFeeStats().getInclusionFee().getP90(), maxFee); // Build transaction System.out.println("Building claim transaction..."); Transaction tx = new TransactionBuilder(accountA, Network.TESTNET) .setBaseFee(fee) .setTimeout(TransactionPreconditions.TIMEOUT_INFINITE) .addOperation(claimOp) .build(); // Sign transaction tx.sign(keypairAccA); // Submit using RPC client's sendTransaction method System.out.println("Submitting claim transaction..."); SendTransactionResponse sendResp = rpcClient.sendTransaction(tx); if (sendResp.getStatus() != SendTransactionResponse.SendTransactionStatus.PENDING) { throw new IllegalStateException("Transaction not pending: " + sendResp.getStatus()); } System.out.printf("Transaction submitted: %s%n", sendResp.getHash()); // Poll for completion using RPC client's getTransaction method System.out.println("Polling for result..."); for (int i = 0; i < 10; i++) { GetTransactionResponse resp = rpcClient.getTransaction(sendResp.getHash()); if (resp.getStatus() != GetTransactionStatus.NOT_FOUND) { if (resp.getStatus() == GetTransactionStatus.SUCCESS) { System.out.println("\nSUCCESS: Claimable balance claimed"); System.out.printf("Transaction hash: %s%n", sendResp.getHash()); System.out.printf("Claimed by: %s%n", keypairAccA.getAccountId()); } else { System.out.printf("Transaction failed: %s%n", resp.getStatus()); if (resp.getResultXdr() != null) { System.out.printf("Result XDR: %s%n", resp.getResultXdr()); } } return; } Thread.sleep((i + 1) * 1000L); } System.out.println("Transaction polling timeout"); }}
And that’s it! Since we opted for the reclaim path, Account A should have the same balance as what it started with (minus fees), and Account B should be unchanged.