soneso/stellar-php-sdk

Stellar PHP SDK for the Stellar Network

1.6.0beta2 2024-11-04 13:53 UTC

README

v1.6.0beta2

The Soneso open source Stellar SDK for PHP provides APIs to build and sign transactions, connect and query Horizon.

Installation

composer require soneso/stellar-php-sdk

Quick Start

1. Create a Stellar key pair

Random generation

// create a completely new and unique pair of keys.
$keyPair = KeyPair::random();

print($keyPair->getAccountId());
// GCFXHS4GXL6BVUCXBWXGTITROWLVYXQKQLF4YH5O5JT3YZXCYPAFBJZB

print($keyPair->getSecretSeed());
// SAV76USXIJOBMEQXPANUOQM6F5LIOTLPDIDVRJBFFE2MDJXG24TAPUU7

2. Create an account

After the key pair generation, you have already got the address, but it is not activated until someone transfers at least 1 lumen into it.

2.1 Testnet

If you want to play in the Stellar test network, the SDK can ask Friendbot to create an account for you as shown below:

$funded = FriendBot::fundTestAccount($keyPair->getAccountId());
print ($funded ? "account funded" : "account not funded");

2.2 Public net

On the other hand, if you would like to create an account in the public net, you should buy some Stellar Lumens (XLM) from an exchange. When you withdraw the Lumens into your new account, the exchange will automatically create the account for you. However, if you want to create an account from another account of your own, you may run the following code:

/// Init sdk for public net
$sdk = StellarSDK::getPublicNetInstance();
 
/// Create a key pair for your existing account.
$keyA = KeyPair::fromSeed("SAPS66IJDXUSFDSDKIHR4LN6YPXIGCM5FBZ7GE66FDKFJRYJGFW7ZHYF");

/// Load the data of your account from the stellar network.
$accA = $sdk->requestAccount($keyA->getAccountId());

/// Create a keypair for a new account.
$keyB = KeyPair::random();

/// Create the operation builder.
$createAccBuilder = new CreateAccountOperationBuilder($keyB->getAccountId(), "3"); // send 3 XLM (lumen)

// Create the transaction.
$transaction = (new TransactionBuilder($accA))
    ->addOperation($createAccBuilder->build())
    ->build();

/// Sign the transaction with the key pair of your existing account.
$transaction->sign($keyA, Network::public());

/// Submit the transaction to the stellar network.
$response = $sdk->submitTransaction($transaction);

if ($response->isSuccessful()) {
    printf (PHP_EOL."account %s created", $keyB->getAccountId());
}

3. Check account

3.1 Basic info

After creating the account, we may check the basic information of the account.

$accountId = "GCQHNQR2VM5OPXSTWZSF7ISDLE5XZRF73LNU6EOZXFQG2IJFU4WB7VFY";

// Request the account data.
$account = $sdk->requestAccount($accountId);

// You can check the `balance`, `sequence`, `flags`, `signers`, `data` etc.
foreach ($account->getBalances() as $balance) {
    switch ($balance->getAssetType()) {
        case Asset::TYPE_NATIVE:
            printf (PHP_EOL."Balance: %s XLM", $balance->getBalance() );
            break;
        default:
            printf(PHP_EOL."Balance: %s %s Issuer: %s",
                $balance->getBalance(), $balance->getAssetCode(),
                $balance->getAssetIssuer());
    }
}

print(PHP_EOL."Sequence number: ".$account->getSequenceNumber());

foreach ($account->getSigners() as $signer) {
    print(PHP_EOL."Signer public key: ".$signer->getKey());
}

3.2 Check payments

You can check the payments connected to an account:

$accountId = $account->getAccountId();

$operationsPage = $sdk->payments()->forAccount($accountId)->order("desc")->execute();

foreach ($operationsPage->getOperations() as $payment) {
    if ($payment->isTransactionSuccessful()) {
        print(PHP_EOL."Transaction hash: ".$payment->getTransactionHash());
    }
}

You can use:limit, order, and cursor to customize the query. Get the most recent payments for accounts, ledgers and transactions.

Horizon has SSE support for push data. You can use it like this:

$accountId = "GCDBA6GFGEHAMVAMRL6R2733EXUENJ35EMYNA2LE7WWJPVANORVC4UNA";

$sdk->payments()->forAccount($accountId)->cursor("now")->stream(function(OperationResponse $response) {
    if ($response instanceof PaymentOperationResponse) {
        switch ($response->getAsset()->getType()) {
            case Asset::TYPE_NATIVE:
                printf("Payment of %s XLM from %s received.", $response->getAmount(), $response->getSourceAccount());
                break;
            default:
                printf("Payment of %s %s from %s received.", $response->getAmount(),  $response->getAsset()->getCode(), $response->getSourceAccount());
        }
        if (floatval($response->getAmount()) > 0.5) {
            exit;
        }
    }
});

see also stream payments example

3.3 Check others

Just like payments, you can check assets, transactions, effects, offers, operations, ledgers etc.

$sdk->assets()
$sdk->transactions()
$sdk->effects()
$sdk->offers()
$sdk->operations()
$sdk->orderBook()
$sdk->trades()
// add so on ...

4. Building and submitting transactions

Example "send native payment":

$senderKeyPair = KeyPair::fromSeed("SA52PD5FN425CUONRMMX2CY5HB6I473A5OYNIVU67INROUZ6W4SPHXZB");
$destination = "GCRFFUKMUWWBRIA6ABRDFL5NKO6CKDB2IOX7MOS2TRLXNXQD255Z2MYG";

// Load sender account data from the stellar network.
$sender = $sdk->requestAccount($senderKeyPair->getAccountId());

// Build the transaction to send 100 XLM native payment from sender to destination
$paymentOperation = (new PaymentOperationBuilder($destination,Asset::native(), "100"))->build();
$transaction = (new TransactionBuilder($sender))->addOperation($paymentOperation)->build();

// Sign the transaction with the sender's key pair.
$transaction->sign($senderKeyPair, Network::testnet());

// Submit the transaction to the stellar network.
$response = $sdk->submitTransaction($transaction);
if ($response->isSuccessful()) {
    print(PHP_EOL."Payment sent");
}

Documentation and Examples

Examples

More examples can be found in the tests.

SEPs implemented

Soroban support

This SDK provides support for Soroban.