Why Verify Trustlines?
In Stellar, trustlines are used to establish a relationship between an account and a Stellar Asset. They are created with the change trust operation, and indicate that the account is willing to hold and transact with that asset. If a trustline is not established for an asset, the account cannot receive payments in that asset, leading to transaction failures. Furthermore, asset issuers may enforce specific requirements through trustlines, such as maximum balances an account can hold or granular authorization to receive/send the asset or to maintain liabilities. See the Asset Design Considerations for more details on how control flags and trustlines can be used to customize these behaviors. Verifying trustlines before sending transactions helps ensure that the receiving account meets the requirements and can successfully receive the asset. This allows for the application to handle cases where trustlines are not established or invalid, providing clear feedback and a smooth user experience while preventing failed transactions.Checking a Trustline through the Stellar RPC
Unlike Horizon, Stellar RPC does not return an account’s trustlines alongside the account itself — a trustline is its own ledger entry, so you look it up directly. The JavaScript SDK gives you two ways to do that:getAssetBalanceis the quick path. One call tells you whether the trustline exists at all, whether it is authorized, and how much of the asset the account currently holds.getLedgerEntriesgives you the raw trustline entry, which you need when you also care about the trustline’s limit — the maximum balance the account is willing to hold.
getAssetBalance helper, so their examples read the trustline entry with get_ledger_entries, GetLedgerEntries, and getLedgerEntries.
Existence and authorization
The following snippet checks that the destination account exists, that it trusts the asset, and that the trustline is authorized to receive it:import { Asset } from "@stellar/stellar-sdk";
import { Server } from "@stellar/stellar-sdk/rpc";
// Initialize Stellar RPC server for testnet
const rpc = new Server("https://soroban-testnet.stellar.org");
// The account you're about to pay. Replace this with your real destination.
// On Testnet you can create one with `rpc.requestAirdrop()` and give it a
// trustline with a `changeTrust` operation.
const receiver = "G...";
// First, check to make sure that the destination account exists.
try {
await rpc.getAccount(receiver);
} catch (error) {
console.error("Error checking destination account:", error);
throw error;
}
// Now we define which asset we want to check the trustline for.
// In this case, we are checking for USDC issued on testnet.
const USDC = new Asset(
"USDC",
"GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5",
);
// `getAssetBalance` looks up the trustline ledger entry for us and returns it
// already decoded. If the account has no trustline for the asset at all, the
// call throws, so we handle that case here. Note that the SDK reports any
// failure of this lookup — including a network or RPC error — with the same
// "not found" error, so treat this branch as "could not confirm a trustline"
// rather than proof that none exists.
let balanceEntry;
try {
({ balanceEntry } = await rpc.getAssetBalance(receiver, USDC));
} catch (error) {
console.error(
`Could not confirm a trustline for asset ${USDC.code} issued by ${USDC.issuer} for account ${receiver}.`,
);
throw error;
}
// The trustline exists, but the issuer may not have authorized it yet. An
// unauthorized trustline cannot receive payments, so sending would fail.
if (!balanceEntry.authorized) {
console.error(
`Trustline for asset ${USDC.code} issued by ${USDC.issuer} is not authorized for account ${receiver}.`,
);
throw new Error("Trustline not authorized");
}
// `amount` is the account's current balance of the asset, as a string of
// stroops (1 unit = 10,000,000 stroops). Keep it as a string or a BigInt
// rather than a Number — see the note on precision below.
console.log(
`Trustline for asset ${USDC.code} issued by ${USDC.issuer} is valid for account ${receiver} (${balanceEntry.amount} stroops).`,
);
// Proceed with sending the payment...
from stellar_sdk import Asset, Keypair, SorobanServer
from stellar_sdk.exceptions import AccountNotFoundException
from stellar_sdk.xdr import (
LedgerEntryData,
LedgerEntryType,
LedgerKey,
LedgerKeyTrustLine,
TrustLineFlags,
)
# Initialize Stellar RPC server for testnet
rpc = SorobanServer("https://soroban-testnet.stellar.org")
# The account you're about to pay. Replace this with your real destination.
receiver = "G..."
# First, check to make sure that the destination account exists.
try:
rpc.load_account(receiver)
except AccountNotFoundException:
print(f"Destination account {receiver} does not exist.")
raise
# Now we define which asset we want to check the trustline for.
# In this case, we are checking for USDC issued on testnet.
USDC = Asset("USDC", "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5")
# The Python SDK has no `getAssetBalance` helper, so we look up the trustline
# ledger entry directly. If the account has no trustline for the asset,
# `entries` comes back empty. A network or RPC error raises instead.
key = LedgerKey(
LedgerEntryType.TRUSTLINE,
trust_line=LedgerKeyTrustLine(
account_id=Keypair.from_public_key(receiver).xdr_account_id(),
asset=USDC.to_trust_line_asset_xdr_object(),
),
)
response = rpc.get_ledger_entries([key])
if not response.entries:
print(
f"Trustline for asset {USDC.code} issued by {USDC.issuer} "
f"not found for account {receiver}."
)
raise RuntimeError("Trustline not found")
trust_line = LedgerEntryData.from_xdr(response.entries[0].xdr).trust_line
# The trustline exists, but the issuer may not have authorized it yet. An
# unauthorized trustline cannot receive payments, so sending would fail.
if not trust_line.flags.uint32 & TrustLineFlags.AUTHORIZED_FLAG:
print(
f"Trustline for asset {USDC.code} issued by {USDC.issuer} "
f"is not authorized for account {receiver}."
)
raise RuntimeError("Trustline not authorized")
# `balance` is the account's current balance of the asset, as an int of
# stroops (1 unit = 10,000,000 stroops).
print(
f"Trustline for asset {USDC.code} issued by {USDC.issuer} is valid "
f"for account {receiver} ({trust_line.balance.int64} stroops)."
)
# Proceed with sending the payment...
package main
import (
"context"
"log"
"github.com/stellar/go-stellar-sdk/txnbuild"
"github.com/stellar/go-stellar-sdk/xdr"
client "github.com/stellar/go-stellar-sdk/clients/rpcclient"
protocol "github.com/stellar/go-stellar-sdk/protocols/rpc"
)
func main() {
ctx := context.Background()
// Initialize Stellar RPC client for testnet
rpc := client.NewClient("https://soroban-testnet.stellar.org", nil)
defer rpc.Close()
// The account you're about to pay. Replace this with your real destination.
receiver := "G..."
// First, check to make sure that the destination account exists.
if _, err := rpc.LoadAccount(ctx, receiver); err != nil {
log.Fatalf("Destination account %s does not exist: %v", receiver, err)
}
// Now we define which asset we want to check the trustline for.
// In this case, we are checking for USDC issued on testnet.
USDC := txnbuild.CreditAsset{Code: "USDC", Issuer: "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5"}
// The Go SDK has no `getAssetBalance` helper, so we look up the trustline
// ledger entry directly. If the account has no trustline for the asset,
// `Entries` comes back empty. A network or RPC error returns an error instead.
trustLineAsset, err := USDC.MustToTrustLineAsset().ToXDR()
if err != nil {
log.Fatal(err)
}
key, err := xdr.MarshalBase64(xdr.LedgerKey{
Type: xdr.LedgerEntryTypeTrustline,
TrustLine: &xdr.LedgerKeyTrustLine{
AccountId: xdr.MustAddress(receiver),
Asset: trustLineAsset,
},
})
if err != nil {
log.Fatal(err)
}
response, err := rpc.GetLedgerEntries(ctx, protocol.GetLedgerEntriesRequest{Keys: []string{key}})
if err != nil {
log.Fatal(err)
}
if len(response.Entries) == 0 {
log.Fatalf("Trustline for asset %s issued by %s not found for account %s.", USDC.Code, USDC.Issuer, receiver)
}
var entry xdr.LedgerEntryData
if err := xdr.SafeUnmarshalBase64(response.Entries[0].DataXDR, &entry); err != nil {
log.Fatal(err)
}
trustLine := entry.MustTrustLine()
// The trustline exists, but the issuer may not have authorized it yet. An
// unauthorized trustline cannot receive payments, so sending would fail.
if xdr.TrustLineFlags(trustLine.Flags)&xdr.TrustLineFlagsAuthorizedFlag == 0 {
log.Fatalf("Trustline for asset %s issued by %s is not authorized for account %s.", USDC.Code, USDC.Issuer, receiver)
}
// `Balance` is the account's current balance of the asset, as an int64 of
// stroops (1 unit = 10,000,000 stroops).
log.Printf("Trustline for asset %s issued by %s is valid for account %s (%d stroops).",
USDC.Code, USDC.Issuer, receiver, trustLine.Balance)
// Proceed with sending the payment...
}
import java.util.List;
import org.stellar.sdk.Asset;
import org.stellar.sdk.AssetTypeCreditAlphaNum;
import org.stellar.sdk.KeyPair;
import org.stellar.sdk.SorobanServer;
import org.stellar.sdk.TrustLineAsset;
import org.stellar.sdk.exception.AccountNotFoundException;
import org.stellar.sdk.responses.sorobanrpc.GetLedgerEntriesResponse;
import org.stellar.sdk.xdr.LedgerEntryType;
import org.stellar.sdk.xdr.LedgerKey;
import org.stellar.sdk.xdr.TrustLineEntry;
import org.stellar.sdk.xdr.TrustLineFlags;
public final class VerifyTrustline {
public static void main(String[] args) {
// Initialize Stellar RPC server for testnet
SorobanServer rpc = new SorobanServer("https://soroban-testnet.stellar.org");
// The account you're about to pay. Replace this with your real destination.
String receiver = "G...";
// First, check to make sure that the destination account exists.
try {
rpc.getAccount(receiver);
} catch (AccountNotFoundException error) {
System.err.println("Destination account " + receiver + " does not exist.");
throw error;
}
// Now we define which asset we want to check the trustline for.
// In this case, we are checking for USDC issued on testnet.
AssetTypeCreditAlphaNum USDC = (AssetTypeCreditAlphaNum)
Asset.createNonNativeAsset("USDC", "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5");
// The Java SDK has no `getAssetBalance` helper, so we look up the trustline
// ledger entry directly. If the account has no trustline for the asset,
// `entries` comes back empty. A network or RPC error throws instead.
LedgerKey key = LedgerKey.builder()
.discriminant(LedgerEntryType.TRUSTLINE)
.trustLine(LedgerKey.LedgerKeyTrustLine.builder()
.accountID(KeyPair.fromAccountId(receiver).getXdrAccountId())
.asset(new TrustLineAsset(USDC).toXdr())
.build())
.build();
GetLedgerEntriesResponse response = rpc.getLedgerEntries(List.of(key));
if (response.getEntries() == null || response.getEntries().isEmpty()) {
System.err.printf("Trustline for asset %s issued by %s not found for account %s.%n",
USDC.getCode(), USDC.getIssuer(), receiver);
throw new IllegalStateException("Trustline not found");
}
TrustLineEntry trustLine = response.getEntries().get(0).parseXdr().getTrustLine();
// The trustline exists, but the issuer may not have authorized it yet. An
// unauthorized trustline cannot receive payments, so sending would fail.
long flags = trustLine.getFlags().getUint32().getNumber();
if ((flags & TrustLineFlags.AUTHORIZED_FLAG.getValue()) == 0) {
System.err.printf("Trustline for asset %s issued by %s is not authorized for account %s.%n",
USDC.getCode(), USDC.getIssuer(), receiver);
throw new IllegalStateException("Trustline not authorized");
}
// `balance` is the account's current balance of the asset, as a long of
// stroops (1 unit = 10,000,000 stroops).
System.out.printf("Trustline for asset %s issued by %s is valid for account %s (%d stroops).%n",
USDC.getCode(), USDC.getIssuer(), receiver, trustLine.getBalance().getInt64());
// Proceed with sending the payment...
}
}
getAssetBalance also accepts a contract address, so the same call verifies a Soroban contract’s balance of the asset through its Stellar Asset Contract.getAssetBalance raises the same Trustline for CODE:ISSUER not found for ACCOUNT error whether the trustline is genuinely absent or the lookup simply failed — a timeout or an unreachable RPC endpoint surfaces as “not found” too. If your application needs to tell those cases apart, use getLedgerEntries instead: it returns an empty entries array for a missing trustline and only rejects on a transport error.Checking the trustline limit
A trustline also carries alimit: the maximum balance of the asset the account is willing to hold. A payment that would push the balance past that limit fails, even when the trustline exists and is authorized.
getAssetBalance does not surface the limit, so we fetch the raw trustline ledger entry with getLedgerEntries.
Amounts are stored on the ledger as int64 stroops, and the largest representable amount — 922,337,203,685.4775807 — exceeds what a JavaScript Number can hold exactly. Trustline limits routinely sit at that maximum, so this example keeps the arithmetic in BigInt stroops; converting to Number first can silently misjudge whether a payment fits. See Amount precision for the full picture.
import { Asset, Keypair, xdr } from "@stellar/stellar-sdk";
import { Server } from "@stellar/stellar-sdk/rpc";
const rpc = new Server("https://soroban-testnet.stellar.org");
// The account you're about to pay, and the asset and amount you want to send.
const receiver = "G...";
const USDC = new Asset(
"USDC",
"GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5",
);
// Amounts live on the ledger as int64 stroops, whose maximum (9223372036854775807,
// or 922,337,203,685.4775807 units) is far beyond what a JavaScript `Number` can
// hold exactly. Convert the amount you want to send into stroops as a BigInt and
// do the comparison there, so a large trustline can't be misjudged.
function toStroops(amount) {
const [whole, fraction = ""] = amount.split(".");
return BigInt(whole + fraction.padEnd(7, "0").slice(0, 7));
}
const sendingAmount = toStroops("1");
// A ledger key uniquely identifies an entry on the ledger. For a trustline, it
// is the combination of the account that holds it and the asset it is for.
const key = xdr.LedgerKey.trustline(
new xdr.LedgerKeyTrustLine({
accountId: Keypair.fromPublicKey(receiver).xdrAccountId(),
asset: USDC.toTrustLineXDRObject(),
}),
);
// Query the ledger for that entry. If the account has no trustline for the
// asset, `entries` comes back empty rather than throwing.
const { entries } = await rpc.getLedgerEntries(key);
if (entries.length === 0) {
console.error(
`Trustline for asset ${USDC.code} issued by ${USDC.issuer} not found for account ${receiver}.`,
);
throw new Error("Trustline not found");
}
// `val` is the decoded ledger entry data. Its `trustLine` arm holds the
// trustline fields as plain properties.
const trustlineData = entries[0].val.trustLine;
// Trustline flags are a bitfield, so check the individual bit rather than
// comparing the whole value: 0x1 is AUTHORIZED_FLAG, 0x2 is
// AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG and 0x4 is
// TRUSTLINE_CLAWBACK_ENABLED_FLAG. An authorized, clawback-enabled trustline
// has flags of 5, so `flags === 1` would wrongly reject it.
if (!(trustlineData.flags & 1)) {
console.error(
`Trustline for asset ${USDC.code} issued by ${USDC.issuer} is not authorized for account ${receiver}.`,
);
throw new Error("Trustline not authorized");
}
// The limit and balance are already BigInt stroops, so no Number conversion.
const limit = trustlineData.limit;
const balance = trustlineData.balance;
// Finally, we check if the trustline has enough limit to receive the payment.
// We compare the trustline's limit minus its current balance with the amount we
// want to send. Attempting to send an amount that exceeds the available limit
// will result in a failed transaction, therefore, if the limit is insufficient,
// we log an error and throw an exception.
if (limit - balance < sendingAmount) {
console.error(
`Insufficient limit for asset ${USDC.code} issued by ${USDC.issuer} in account ${receiver}.`,
);
throw new Error("Insufficient limit for asset");
}
console.log(
`Trustline for asset ${USDC.code} issued by ${USDC.issuer} is valid for account ${receiver}.`,
);
// Proceed with sending the payment...
from decimal import Decimal
from stellar_sdk import Asset, Keypair, SorobanServer
from stellar_sdk.xdr import (
LedgerEntryData,
LedgerEntryType,
LedgerKey,
LedgerKeyTrustLine,
TrustLineFlags,
)
rpc = SorobanServer("https://soroban-testnet.stellar.org")
# The account you're about to pay, and the asset and amount you want to send.
receiver = "G..."
USDC = Asset("USDC", "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5")
# Amounts live on the ledger as int64 stroops. Python ints are exact at any
# size, so convert the amount you want to send into stroops and compare there.
# Use Decimal, not float, for the conversion.
def to_stroops(amount: str) -> int:
return int(Decimal(amount) * 10_000_000)
sending_amount = to_stroops("1")
# A ledger key uniquely identifies an entry on the ledger. For a trustline, it
# is the combination of the account that holds it and the asset it is for.
key = LedgerKey(
LedgerEntryType.TRUSTLINE,
trust_line=LedgerKeyTrustLine(
account_id=Keypair.from_public_key(receiver).xdr_account_id(),
asset=USDC.to_trust_line_asset_xdr_object(),
),
)
# Query the ledger for that entry. If the account has no trustline for the
# asset, `entries` comes back empty rather than raising.
response = rpc.get_ledger_entries([key])
if not response.entries:
print(
f"Trustline for asset {USDC.code} issued by {USDC.issuer} "
f"not found for account {receiver}."
)
raise RuntimeError("Trustline not found")
# Decode the ledger entry data. Its `trust_line` arm holds the trustline fields.
trustline_data = LedgerEntryData.from_xdr(response.entries[0].xdr).trust_line
# Trustline flags are a bitfield, so check the individual bit rather than
# comparing the whole value. An authorized, clawback-enabled trustline has
# flags of 5, so `flags == 1` would wrongly reject it.
if not trustline_data.flags.uint32 & TrustLineFlags.AUTHORIZED_FLAG:
print(
f"Trustline for asset {USDC.code} issued by {USDC.issuer} "
f"is not authorized for account {receiver}."
)
raise RuntimeError("Trustline not authorized")
# The limit and balance are int64 stroops.
limit = trustline_data.limit.int64
balance = trustline_data.balance.int64
# Finally, we check if the trustline has enough limit to receive the payment.
# If the limit minus the current balance is less than the amount we want to
# send, the payment would fail, so we raise an exception.
if limit - balance < sending_amount:
print(
f"Insufficient limit for asset {USDC.code} issued by {USDC.issuer} "
f"in account {receiver}."
)
raise RuntimeError("Insufficient limit for asset")
print(
f"Trustline for asset {USDC.code} issued by {USDC.issuer} "
f"is valid for account {receiver}."
)
# Proceed with sending the payment...
package main
import (
"context"
"log"
"github.com/stellar/go-stellar-sdk/amount"
"github.com/stellar/go-stellar-sdk/txnbuild"
"github.com/stellar/go-stellar-sdk/xdr"
client "github.com/stellar/go-stellar-sdk/clients/rpcclient"
protocol "github.com/stellar/go-stellar-sdk/protocols/rpc"
)
func main() {
ctx := context.Background()
rpc := client.NewClient("https://soroban-testnet.stellar.org", nil)
defer rpc.Close()
// The account you're about to pay, and the asset and amount you want to send.
receiver := "G..."
USDC := txnbuild.CreditAsset{Code: "USDC", Issuer: "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5"}
// Amounts live on the ledger as int64 stroops. Convert the amount you want
// to send into stroops with amount.ParseInt64, which parses the decimal
// string exactly, and compare there.
sendingAmount, err := amount.ParseInt64("1")
if err != nil {
log.Fatal(err)
}
// A ledger key uniquely identifies an entry on the ledger. For a trustline, it
// is the combination of the account that holds it and the asset it is for.
trustLineAsset, err := USDC.MustToTrustLineAsset().ToXDR()
if err != nil {
log.Fatal(err)
}
key, err := xdr.MarshalBase64(xdr.LedgerKey{
Type: xdr.LedgerEntryTypeTrustline,
TrustLine: &xdr.LedgerKeyTrustLine{
AccountId: xdr.MustAddress(receiver),
Asset: trustLineAsset,
},
})
if err != nil {
log.Fatal(err)
}
// Query the ledger for that entry. If the account has no trustline for the
// asset, `Entries` comes back empty rather than returning an error.
response, err := rpc.GetLedgerEntries(ctx, protocol.GetLedgerEntriesRequest{Keys: []string{key}})
if err != nil {
log.Fatal(err)
}
if len(response.Entries) == 0 {
log.Fatalf("Trustline for asset %s issued by %s not found for account %s.", USDC.Code, USDC.Issuer, receiver)
}
// Decode the ledger entry data. Its `TrustLine` arm holds the trustline fields.
var entry xdr.LedgerEntryData
if err := xdr.SafeUnmarshalBase64(response.Entries[0].DataXDR, &entry); err != nil {
log.Fatal(err)
}
trustlineData := entry.MustTrustLine()
// Trustline flags are a bitfield, so check the individual bit rather than
// comparing the whole value. An authorized, clawback-enabled trustline has
// flags of 5, so `Flags == 1` would wrongly reject it.
if xdr.TrustLineFlags(trustlineData.Flags)&xdr.TrustLineFlagsAuthorizedFlag == 0 {
log.Fatalf("Trustline for asset %s issued by %s is not authorized for account %s.", USDC.Code, USDC.Issuer, receiver)
}
// The limit and balance are int64 stroops.
limit := int64(trustlineData.Limit)
balance := int64(trustlineData.Balance)
// Finally, we check if the trustline has enough limit to receive the payment.
// If the limit minus the current balance is less than the amount we want to
// send, the payment would fail, so we stop with an error.
if limit-balance < sendingAmount {
log.Fatalf("Insufficient limit for asset %s issued by %s in account %s.", USDC.Code, USDC.Issuer, receiver)
}
log.Printf("Trustline for asset %s issued by %s is valid for account %s.", USDC.Code, USDC.Issuer, receiver)
// Proceed with sending the payment...
}
import java.math.BigDecimal;
import java.util.List;
import org.stellar.sdk.Asset;
import org.stellar.sdk.AssetTypeCreditAlphaNum;
import org.stellar.sdk.KeyPair;
import org.stellar.sdk.SorobanServer;
import org.stellar.sdk.TrustLineAsset;
import org.stellar.sdk.operations.Operation;
import org.stellar.sdk.responses.sorobanrpc.GetLedgerEntriesResponse;
import org.stellar.sdk.xdr.LedgerEntryType;
import org.stellar.sdk.xdr.LedgerKey;
import org.stellar.sdk.xdr.TrustLineEntry;
import org.stellar.sdk.xdr.TrustLineFlags;
public final class CheckTrustlineLimit {
public static void main(String[] args) {
SorobanServer rpc = new SorobanServer("https://soroban-testnet.stellar.org");
// The account you're about to pay, and the asset and amount you want to send.
String receiver = "G...";
AssetTypeCreditAlphaNum USDC = (AssetTypeCreditAlphaNum)
Asset.createNonNativeAsset("USDC", "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5");
// Amounts live on the ledger as int64 stroops. Convert the amount you want
// to send into stroops with Operation.toXdrAmount, which parses the decimal
// exactly (and throws if it has more than 7 decimal places), and compare there.
long sendingAmount = Operation.toXdrAmount(new BigDecimal("1"));
// A ledger key uniquely identifies an entry on the ledger. For a trustline, it
// is the combination of the account that holds it and the asset it is for.
LedgerKey key = LedgerKey.builder()
.discriminant(LedgerEntryType.TRUSTLINE)
.trustLine(LedgerKey.LedgerKeyTrustLine.builder()
.accountID(KeyPair.fromAccountId(receiver).getXdrAccountId())
.asset(new TrustLineAsset(USDC).toXdr())
.build())
.build();
// Query the ledger for that entry. If the account has no trustline for the
// asset, `entries` comes back empty rather than throwing.
GetLedgerEntriesResponse response = rpc.getLedgerEntries(List.of(key));
if (response.getEntries() == null || response.getEntries().isEmpty()) {
System.err.printf("Trustline for asset %s issued by %s not found for account %s.%n",
USDC.getCode(), USDC.getIssuer(), receiver);
throw new IllegalStateException("Trustline not found");
}
// Decode the ledger entry data. Its `trustLine` arm holds the trustline fields.
TrustLineEntry trustlineData = response.getEntries().get(0).parseXdr().getTrustLine();
// Trustline flags are a bitfield, so check the individual bit rather than
// comparing the whole value. An authorized, clawback-enabled trustline has
// flags of 5, so `flags == 1` would wrongly reject it.
long flags = trustlineData.getFlags().getUint32().getNumber();
if ((flags & TrustLineFlags.AUTHORIZED_FLAG.getValue()) == 0) {
System.err.printf("Trustline for asset %s issued by %s is not authorized for account %s.%n",
USDC.getCode(), USDC.getIssuer(), receiver);
throw new IllegalStateException("Trustline not authorized");
}
// The limit and balance are int64 stroops.
long limit = trustlineData.getLimit().getInt64();
long balance = trustlineData.getBalance().getInt64();
// Finally, we check if the trustline has enough limit to receive the payment.
// If the limit minus the current balance is less than the amount we want to
// send, the payment would fail, so we stop with an error.
if (limit - balance < sendingAmount) {
System.err.printf("Insufficient limit for asset %s issued by %s in account %s.%n",
USDC.getCode(), USDC.getIssuer(), receiver);
throw new IllegalStateException("Insufficient trustline limit");
}
System.out.printf("Trustline for asset %s issued by %s is valid for account %s.%n",
USDC.getCode(), USDC.getIssuer(), receiver);
// Proceed with sending the payment...
}
}
Checking a Trustline through the Stellar Asset Contract (SAC)
All Stellar assets, including the native asset (XLM), can be managed with smart contract transactions through Stellar Asset Contracts (SAC). SACs provide a smart contract interface for handling assets, allowing for more complex interactions and programmability. This means that it includes certain functions to help developers manage assets, such as verifying trustlines and sending payments, in a more flexible way than classic operations. For this example, we’ll be using SAC as a smart contract interface for the testnet USDC asset. A contract invocation transaction will be made to call the functionauthorized, which returns a boolean indicating whether the account’s trustline is authorized.
This function can be accessed directly in a smart contract invocation as the example below demonstrates, or it can also be invoked by another contract, allowing for more complex interactions and programmability to be built in smart contracts.
Note that authorized only reports the trustline’s authorization state. If the account has no trustline for the asset at all, the invocation does not return false — the simulation fails with Error(Contract, #13) (trustline entry is missing for account), so the two cases are handled in different branches below. If you also need to check the trustline’s limit, use the getLedgerEntries approach shown above.
To use the JavaScript example below you should first generate the contract bindings so the client can be used accordingly. This can be achieved with the bindings generator in the JavaScript SDK,
@stellar/stellar-sdk.E.g.: Generating the typescript bindings for the SAC of a given asset. The generated package takes its name from --contract-name, so --contract-name=sac is what makes import ... from "sac" below resolve once you install the package from ./sac:npx @stellar/stellar-sdk generate --network=testnet --contract-id=CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA --contract-name=sac --output-dir=./sac
import { Asset, Networks } from "@stellar/stellar-sdk";
import { Client } from "sac";
import { Server } from "@stellar/stellar-sdk/rpc";
// Initialize Stellar RPC server for testnet
const rpc = new Server("https://soroban-testnet.stellar.org");
// The account you're about to pay. Replace this with your real destination.
const receiver = "G...";
// First, check to make sure that the destination account exists.
try {
await rpc.getAccount(receiver);
} catch (error) {
console.error("Error checking destination account:", error);
throw error;
}
// Now we define which asset we want to check the trustline for.
// In this case, we are checking for USDC issued on testnet.
const USDC = new Asset(
"USDC",
"GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5",
);
// Now we initialize the Stellar Asset Contract (SAC) client.
// The client needs the RPC endpoint, network passphrase, contract ID for the asset,
// and your account's public key. Since we are only going to simulate the transaction,
// we do not need to provide a signing function.
const usdcClient = new Client({
rpcUrl: "https://soroban-testnet.stellar.org",
networkPassphrase: Networks.TESTNET,
contractId: USDC.contractId(Networks.TESTNET),
publicKey: receiver,
});
// Now, using the client, we assemble a soroban transaction to invoke the
// `authorized` function of the USDC asset contract. The client will automatically
// bundle the operation and simulate the transaction before providing us
// with an assembled transaction object. This object contains the result of the simulation,
// which we can check to see if the trustline is authorized or not.
let assembledTx;
try {
assembledTx = await usdcClient.authorized({
id: receiver,
});
// The result parameter contains the return value of the contract function.
// If the trustline is authorized, it will return true; otherwise, it will return false.
const result = assembledTx.result;
// A `false` result means the trustline exists but the issuer has not
// authorized it, so any attempt to send USDC to this account will fail.
if (result === false) {
console.error(
`Trustline for asset ${USDC.code} issued by ${USDC.issuer} not authorized for account ${receiver}.`,
);
throw new Error("Trustline not authorized");
}
// If the trustline is authorized, we log a success message.
// This means that the account is allowed to receive payments in USDC.
console.log(
`Trustline for asset ${USDC.code} issued by ${USDC.issuer} is authorized for account ${receiver}.`,
);
} catch (error) {
// A missing trustline surfaces here rather than as a `false` result: the
// simulation fails with `Error(Contract, #13)`.
console.error("Error assembling and simulating the transaction:", error);
throw error;
}
// If the trustline is authorized, we can proceed with sending the payment...
from stellar_sdk import Asset, Network, SorobanServer, TransactionBuilder, scval
from stellar_sdk.exceptions import AccountNotFoundException
# Initialize Stellar RPC server for testnet
rpc = SorobanServer("https://soroban-testnet.stellar.org")
# The account you're about to pay. Replace this with your real destination.
receiver = "G..."
# First, check to make sure that the destination account exists.
try:
account = rpc.load_account(receiver)
except AccountNotFoundException:
print(f"Destination account {receiver} does not exist.")
raise
# Now we define which asset we want to check the trustline for.
# In this case, we are checking for USDC issued on testnet.
USDC = Asset("USDC", "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5")
# The Python SDK simulates the call directly, so it needs no generated
# bindings. We build a transaction that invokes the `authorized` function of
# the USDC asset contract. We only simulate it, so we never sign or send it.
tx = (
TransactionBuilder(account, Network.TESTNET_NETWORK_PASSPHRASE)
.append_invoke_contract_function_op(
contract_id=USDC.contract_id(Network.TESTNET_NETWORK_PASSPHRASE),
function_name="authorized",
parameters=[scval.to_address(receiver)],
)
.set_timeout(30)
.build()
)
sim = rpc.simulate_transaction(tx)
# A missing trustline surfaces here rather than as a `False` result: the
# simulation fails with `Error(Contract, #13)`.
if sim.error:
print("Error simulating the transaction:", sim.error)
raise RuntimeError(sim.error)
# The simulation result holds the return value of the contract function.
# If the trustline is authorized, it is True; otherwise, it is False.
result = scval.from_bool(sim.results[0].xdr)
# A `False` result means the trustline exists but the issuer has not
# authorized it, so any attempt to send USDC to this account will fail.
if not result:
print(
f"Trustline for asset {USDC.code} issued by {USDC.issuer} "
f"not authorized for account {receiver}."
)
raise RuntimeError("Trustline not authorized")
# If the trustline is authorized, we log a success message.
# This means that the account is allowed to receive payments in USDC.
print(
f"Trustline for asset {USDC.code} issued by {USDC.issuer} "
f"is authorized for account {receiver}."
)
# If the trustline is authorized, we can proceed with sending the payment...
package main
import (
"context"
"log"
"github.com/stellar/go-stellar-sdk/network"
"github.com/stellar/go-stellar-sdk/txnbuild"
"github.com/stellar/go-stellar-sdk/xdr"
client "github.com/stellar/go-stellar-sdk/clients/rpcclient"
protocol "github.com/stellar/go-stellar-sdk/protocols/rpc"
)
func main() {
ctx := context.Background()
// Initialize Stellar RPC client for testnet
rpc := client.NewClient("https://soroban-testnet.stellar.org", nil)
defer rpc.Close()
// The account you're about to pay. Replace this with your real destination.
receiver := "G..."
// First, check to make sure that the destination account exists.
account, err := rpc.LoadAccount(ctx, receiver)
if err != nil {
log.Fatalf("Destination account %s does not exist: %v", receiver, err)
}
// Now we define which asset we want to check the trustline for.
// In this case, we are checking for USDC issued on testnet.
USDC := txnbuild.CreditAsset{Code: "USDC", Issuer: "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5"}
usdcXDR, err := USDC.ToXDR()
if err != nil {
log.Fatal(err)
}
contractID, err := usdcXDR.ContractID(network.TestNetworkPassphrase)
if err != nil {
log.Fatal(err)
}
sacID := xdr.ContractId(contractID)
// The Go SDK simulates the call directly, so it needs no generated
// bindings. We build a transaction that invokes the `authorized` function of
// the USDC asset contract. We only simulate it, so we never sign or send it.
id := xdr.ScAddress{Type: xdr.ScAddressTypeScAddressTypeAccount, AccountId: xdr.MustAddressPtr(receiver)}
tx, err := txnbuild.NewTransaction(txnbuild.TransactionParams{
SourceAccount: account,
IncrementSequenceNum: true,
BaseFee: txnbuild.MinBaseFee,
Preconditions: txnbuild.Preconditions{TimeBounds: txnbuild.NewTimeout(30)},
Operations: []txnbuild.Operation{
&txnbuild.InvokeHostFunction{
HostFunction: xdr.HostFunction{
Type: xdr.HostFunctionTypeHostFunctionTypeInvokeContract,
InvokeContract: &xdr.InvokeContractArgs{
ContractAddress: xdr.ScAddress{Type: xdr.ScAddressTypeScAddressTypeContract, ContractId: &sacID},
FunctionName: "authorized",
Args: []xdr.ScVal{{Type: xdr.ScValTypeScvAddress, Address: &id}},
},
},
},
},
})
if err != nil {
log.Fatal(err)
}
envelope, err := tx.Base64()
if err != nil {
log.Fatal(err)
}
sim, err := rpc.SimulateTransaction(ctx, protocol.SimulateTransactionRequest{Transaction: envelope})
if err != nil {
log.Fatal(err)
}
// A missing trustline surfaces here rather than as a `false` result: the
// simulation fails with `Error(Contract, #13)`.
if sim.Error != "" {
log.Fatal("Error simulating the transaction: ", sim.Error)
}
// The simulation result holds the return value of the contract function.
// If the trustline is authorized, it is true; otherwise, it is false.
if len(sim.Results) == 0 || sim.Results[0].ReturnValueXDR == nil {
log.Fatal("The simulation returned no result")
}
var result xdr.ScVal
if err := xdr.SafeUnmarshalBase64(*sim.Results[0].ReturnValueXDR, &result); err != nil {
log.Fatal(err)
}
authorized, ok := result.GetB()
if !ok {
log.Fatalf("Unexpected return value type: %s", result.Type)
}
// A `false` result means the trustline exists but the issuer has not
// authorized it, so any attempt to send USDC to this account will fail.
if !authorized {
log.Fatalf("Trustline for asset %s issued by %s not authorized for account %s.", USDC.Code, USDC.Issuer, receiver)
}
// If the trustline is authorized, we log a success message.
// This means that the account is allowed to receive payments in USDC.
log.Printf("Trustline for asset %s issued by %s is authorized for account %s.", USDC.Code, USDC.Issuer, receiver)
// If the trustline is authorized, we can proceed with sending the payment...
}
import java.util.List;
import org.stellar.sdk.Asset;
import org.stellar.sdk.AssetTypeCreditAlphaNum;
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.exception.AccountNotFoundException;
import org.stellar.sdk.operations.InvokeHostFunctionOperation;
import org.stellar.sdk.responses.sorobanrpc.SimulateTransactionResponse;
import org.stellar.sdk.scval.Scv;
public final class CheckTrustlineSac {
public static void main(String[] args) {
// Initialize Stellar RPC server for testnet
SorobanServer rpc = new SorobanServer("https://soroban-testnet.stellar.org");
// The account you're about to pay. Replace this with your real destination.
String receiver = "G...";
// First, check to make sure that the destination account exists.
TransactionBuilderAccount account;
try {
account = rpc.getAccount(receiver);
} catch (AccountNotFoundException error) {
System.err.println("Destination account " + receiver + " does not exist.");
throw error;
}
// Now we define which asset we want to check the trustline for.
// In this case, we are checking for USDC issued on testnet.
AssetTypeCreditAlphaNum USDC = (AssetTypeCreditAlphaNum)
Asset.createNonNativeAsset("USDC", "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5");
// The Java SDK simulates the call directly, so it needs no generated
// bindings. We build a transaction that invokes the `authorized` function of
// the USDC asset contract. We only simulate it, so we never sign or send it.
Transaction tx = new TransactionBuilder(account, Network.TESTNET)
.setBaseFee(Transaction.MIN_BASE_FEE)
.setTimeout(30)
.addOperation(
InvokeHostFunctionOperation.invokeContractFunctionOperationBuilder(
USDC.getContractId(Network.TESTNET),
"authorized",
List.of(Scv.toAddress(receiver)))
.build())
.build();
SimulateTransactionResponse sim = rpc.simulateTransaction(tx);
// A missing trustline surfaces here rather than as a `false` result: the
// simulation fails with `Error(Contract, #13)`.
if (sim.getError() != null) {
System.err.println("Error simulating the transaction: " + sim.getError());
throw new IllegalStateException(sim.getError());
}
// The simulation result holds the return value of the contract function.
// If the trustline is authorized, it is true; otherwise, it is false.
if (sim.getResults() == null || sim.getResults().isEmpty()) {
throw new IllegalStateException("The simulation returned no result");
}
boolean authorized = Scv.fromBoolean(sim.getResults().get(0).parseXdr());
// A `false` result means the trustline exists but the issuer has not
// authorized it, so any attempt to send USDC to this account will fail.
if (!authorized) {
System.err.printf("Trustline for asset %s issued by %s not authorized for account %s.%n",
USDC.getCode(), USDC.getIssuer(), receiver);
throw new IllegalStateException("Trustline not authorized");
}
// If the trustline is authorized, we log a success message.
// This means that the account is allowed to receive payments in USDC.
System.out.printf("Trustline for asset %s issued by %s is authorized for account %s.%n",
USDC.getCode(), USDC.getIssuer(), receiver);
// If the trustline is authorized, we can proceed with sending the payment...
}
}