Stellar SDK for PHP
Overview
The soneso/stellar-php-sdk is a PHP 8.1+ library for the Stellar blockchain network. It provides 100% Horizon API coverage (50/50 endpoints), 100% Soroban RPC coverage (12/12 methods), 31/31 streaming endpoints, and 23 SEP implementations. All HTTP operations are synchronous using Guzzle 7. The root namespace is Soneso\StellarSDK.
Installation
bash
composer require soneso/stellar-php-sdk
All code examples below assume <?php declare(strict_types=1); and relevant use imports.
If you can't find a constructor or method signature in this file or the topic references, grep references/api_reference.md — it has all public class/method signatures.
1. Stellar Basics
Fundamental Stellar concepts and SDK patterns.
Keys and KeyPairs
php
use Soneso\StellarSDK\Crypto\KeyPair;
// Generate new keypair
$keyPair = KeyPair::random();
$accountId = $keyPair->getAccountId(); // G... public address
$secretSeed = $keyPair->getSecretSeed(); // S... secret seed
// IMPORTANT: Store secretSeed securely. Never log or expose it.
// From existing seed (never hardcode — use getenv() in production)
$keyPair = KeyPair::fromSeed(getenv('STELLAR_SECRET_SEED'));
$publicOnly = KeyPair::fromAccountId($accountId); // public-key-only, cannot sign
Accounts
php
use Soneso\StellarSDK\Crypto\KeyPair;
use Soneso\StellarSDK\StellarSDK;
use Soneso\StellarSDK\Util\FriendBot;
$keyPair = KeyPair::random();
$accountId = $keyPair->getAccountId();
// Fund on testnet using FriendBot (10,000 test XLM)
FriendBot::fundTestAccount($accountId);
// Query account
$sdk = StellarSDK::getTestNetInstance();
$account = $sdk->requestAccount($accountId);
echo 'Sequence: ' . $account->getSequenceNumber() . PHP_EOL;
echo 'Subentry Count: ' . $account->getSubentryCount() . PHP_EOL;
foreach ($account->getBalances() as $balance) {
if ($balance->getAssetType() === 'native') {
echo 'XLM: ' . $balance->getBalance() . PHP_EOL;
} else {
echo $balance->getAssetCode() . ': ' . $balance->getBalance() . PHP_EOL;
}
}
// Check existence without exception (returns bool)
$exists = $sdk->accountExists('GDEF...');
Assets
php
use Soneso\StellarSDK\Asset;
$xlm = Asset::native(); // Returns AssetTypeNative instance
// 1-4 char code -> AssetTypeCreditAlphanum4; 5-12 char -> AssetTypeCreditAlphanum12
$usdc = Asset::createNonNativeAsset('USDC', 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN');
// From canonical form
$asset = Asset::createFromCanonicalForm('USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN');
Networks
php
use Soneso\StellarSDK\Network;
use Soneso\StellarSDK\StellarSDK;
// Testnet: Network::testnet() + StellarSDK::getTestNetInstance()
// Public: Network::public() + StellarSDK::getPublicNetInstance()
$network = Network::testnet();
$sdk = StellarSDK::getTestNetInstance();
// Custom Horizon (HTTPS required — HTTP URLs throw InvalidArgumentException)
$network = new Network('My Custom Network ; Passphrase');
$sdk = new StellarSDK('https://my-horizon.example.com');
2. Horizon API - Fetching Data
Query patterns for retrieving blockchain data. All calls are synchronous.
Query Accounts
php
$sdk = StellarSDK::getTestNetInstance();
// Query accounts with filters (builder pattern)
$response = $sdk->accounts()
->forSigner('GABC...')
->limit(10)
->order('desc')
->execute();
foreach ($response->getAccounts() as $acct) {
echo $acct->getAccountId() . PHP_EOL;
}
For single account queries, see $sdk->requestAccount() in Accounts above.
Query Transactions
php
$sdk = StellarSDK::getTestNetInstance();
// Same builder pattern as accounts — forAccount(), limit(), order(), cursor()
$response = $sdk->transactions()
->forAccount('GABC...')
->limit(5)
->order('desc')
->execute();
foreach ($response->getTransactions() as $tx) {
echo $tx->getHash() . ' ledger=' . $tx->getLedger() . PHP_EOL;
}
// Pagination: cursor from last result
$arr = $response->getTransactions()->toArray();
$nextPage = $sdk->transactions()->forAccount('GABC...')
->cursor(end($arr)->getPagingToken())->limit(5)->order('desc')->execute();
// Single transaction by hash
$tx = $sdk->requestTransaction('abc123def...');
For all Horizon endpoints, advanced queries, and pagination patterns: Horizon API Reference
3. Horizon API - Streaming
Real-time update patterns using Server-Sent Events. Streaming runs in a blocking while(true) loop.
Stream Payments
php
use Soneso\StellarSDK\Responses\Operations\OperationResponse;
use Soneso\StellarSDK\Responses\Operations\PaymentOperationResponse;
// Stream payments for an account (blocking infinite loop)
$sdk->payments()
->forAccount($accountId)
->cursor('now')
->stream(function (OperationResponse $payment) {
if ($payment instanceof PaymentOperationResponse) {
echo $payment->getFrom() . ' -> ' . $payment->getTo() . ': ' . $payment->getAmount() . PHP_EOL;
}
});
// WRONG: return false to stop streaming -- return values are IGNORED
// CORRECT: throw an exception to break out, or use exit() in a forked child process
The same pattern applies to all streamable resources (transactions(), ledgers(), operations(), etc.). Auto-reconnects on server errors with a 10-second delay. Streams block indefinitely — use pcntl_fork() to run a stream alongside other operations (see streaming guide).
For reconnection patterns and all 31 streaming endpoints: Horizon Streaming Guide
4. Transactions & Operations
Complete transaction lifecycle: Build -> Sign -> Submit.
Transaction Lifecycle
php
use Soneso\StellarSDK\Crypto\KeyPair;
use Soneso\StellarSDK\TransactionBuilder;
use Soneso\StellarSDK\PaymentOperationBuilder;
use Soneso\StellarSDK\Asset;
use Soneso\StellarSDK\Memo;
$sdk = StellarSDK::getTestNetInstance();
$network = Network::testnet();
// 1. Load source account keypair
$sourceKeyPair = KeyPair::fromSeed(getenv('STELLAR_SECRET_SEED'));
$sourceId = $sourceKeyPair->getAccountId();
// 2. Fetch source account (provides sequence number)
$sourceAccount = $sdk->requestAccount($sourceId);
// 3. Build the transaction
$paymentOp = (new PaymentOperationBuilder(
'GDEST...', // destination account ID
Asset::native(),
'100.50' // amount in XLM
))->build();
// A transaction can contain up to 100 operations.
$transaction = (new TransactionBuilder($sourceAccount))
->addOperation($paymentOp)
->addMemo(Memo::text('Payment for services'))
->setMaxOperationFee(200) // stroops per operation
->build();
// 4. Sign the transaction
$transaction->sign($sourceKeyPair, $network);
// 5. Submit to Horizon
$response = $sdk->submitTransaction($transaction);
if ($response->isSuccessful()) {
echo 'Success! Hash: ' . $response->getHash() . PHP_EOL;
} else {
$codes = $response->getExtras()->getResultCodes();
echo 'Failed: ' . $codes->getTransactionResultCode() . PHP_EOL;
echo 'Op codes: ' . json_encode($codes->getOperationsResultCodes()) . PHP_EOL;
}
// For HorizonRequestException handling, see Error Handling section
Each operation has its own builder (PaymentOperationBuilder, ChangeTrustOperationBuilder, ManageSellOfferOperationBuilder, ...) that takes the operation's parameters and returns the operation from build(). For all 26 operations with parameters and examples: Operations Reference
5. Soroban RPC API
RPC endpoint patterns for Soroban smart contract queries.
php
use Soneso\StellarSDK\Soroban\SorobanServer;
$server = new SorobanServer('https://soroban-testnet.stellar.org');
// $server->setLogger($psr3Logger); // optional: PSR-3 debug logging
$health = $server->getHealth(); // ->status
For all 12 RPC methods including event queries and transaction simulation: RPC Reference
6. Smart Contracts
Contract deployment and invocation patterns using the high-level SorobanClient.
Deploy Contract
php
use Soneso\StellarSDK\Crypto\KeyPair;
use Soneso\StellarSDK\Network;
use Soneso\StellarSDK\Soroban\Contract\SorobanClient;
use Soneso\StellarSDK\Soroban\Contract\InstallRequest;
use Soneso\StellarSDK\Soroban\Contract\DeployRequest;
use Soneso\StellarSDK\Xdr\XdrSCVal;
$keyPair = KeyPair::fromSeed(getenv('STELLAR_SECRET_SEED'));
$rpcUrl = 'https://soroban-testnet.stellar.org';
$network = Network::testnet();
// Step 1: Install WASM bytecode (returns wasm hash)
$wasmBytes = file_get_contents('/path/to/contract.wasm');
$wasmHash = SorobanClient::install(new InstallRequest(
sourceAccountKeyPair: $keyPair,
wasmBytes: $wasmBytes,
network: $network,
rpcUrl: $rpcUrl,
));
// Step 2: Deploy contract instance
$client = SorobanClient::deploy(new DeployRequest(
sourceAccountKeyPair: $keyPair,
wasmHash: $wasmHash,
network: $network,
rpcUrl: $rpcUrl,
constructorArgs: [XdrSCVal::forSymbol('init')], // optional constructor args
));
echo 'Contract ID: ' . $client->getContractId() . PHP_EOL;
Invoke Contract Function
php
use Soneso\StellarSDK\Soroban\Contract\ClientOptions;
use Soneso\StellarSDK\Soroban\Contract\MethodOptions;
// Create client for an existing contract
$client = SorobanClient::forClientOptions(new ClientOptions(
sourceAccountKeyPair: $keyPair,
contractId: 'CABC...',
network: $network,
rpcUrl: $rpcUrl,
));
// Read call (simulation only, no transaction submitted)
$result = $client->invokeMethod('get_count');
echo 'Count: ' . $result->u32 . PHP_EOL;
// Write call (simulates, signs, submits automatically)
$result = $client->invokeMethod('increment', [XdrSCVal::forU32(5)]);
// With custom options (fee, timeout)
$result = $client->invokeMethod('expensive_operation', [XdrSCVal::forSymbol('data')],
methodOptions: new MethodOptions(fee: 10000, timeoutInSeconds: 60));
Protocol 27 (CAP-71) adds ADDRESS_V2 and ADDRESS_WITH_DELEGATES credential arms; ADDRESS_V2 is the default — simulation requests it (set useUpgradedAuth: false for legacy ADDRESS) and SorobanCredentials::forAddress()/forAddressCredentials() build it (legacy via forAddressLegacy()/forAddressCredentialsLegacy()). Build delegate trees with SorobanAuthorizationEntry::withDelegates(...).
MuxedAddress parameters accept muxed contract addresses (CAP-0084), which are invalid as Soroban authorization addresses.
Protocol 28 (CAP-85) lets a contract instance name an owner contract and a tag instead of carrying its own wasm hash; SorobanClient::deployFromExternalRef() deploys from such a reference and SorobanServer::loadWasmIdForExternalRef() resolves one to its wasm.
For external-reference deploy and resolution, contract authorization, multi-auth workflows, delegated auth, and remote signing: Smart Contracts Guide
7. XDR Encoding & Decoding
XDR (External Data Representation) is Stellar's binary serialization format.
Transaction XDR Roundtrip
php
use Soneso\StellarSDK\AbstractTransaction;
// Encode: Transaction -> base64 XDR
$xdrBase64 = $transaction->toEnvelopeXdrBase64();
// Decode: base64 XDR -> Transaction
$decoded = AbstractTransaction::fromEnvelopeBase64XdrString($xdrBase64);
echo 'Source: ' . $decoded->getSourceAccount()->getAccountId() . PHP_EOL;
Working with Soroban XDR Values (XdrSCVal)
php
use Soneso\StellarSDK\Xdr\XdrSCVal;
use Soneso\StellarSDK\Xdr\XdrSCAddress;
use Soneso\StellarSDK\Xdr\XdrSCMapEntry;
use Soneso\StellarSDK\Xdr\XdrUInt128Parts;