### Quick Start Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-45.md A concise example demonstrating the complete flow of authenticating a contract account and obtaining a JWT token using the SDK. ```APIDOC ## Quick Start ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; // Your contract account (C... address) — must implement __check_auth const contractId = 'CCIBUCGPOHWMMMFPFTDWBSVHQRT4DIBJ7AD6BZJYDITBK2LCVBYW7HUQ'; // Signer registered in your contract's __check_auth — must have private key final signer = KeyPair.fromSecretSeed(contractSignerSeed); // Load config from anchor's stellar.toml and authenticate in one call final webAuth = await WebAuthForContracts.fromDomain('anchor.example.com', Network.TESTNET); final jwtToken = await webAuth.jwtToken(contractId, [signer]); print('Authenticated! Token: ${jwtToken.substring(0, 50)}...'); ``` ``` -------------------------------- ### Quick Start: Install, Deploy, and Invoke Soroban Contract Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/soroban.md This snippet demonstrates the complete lifecycle of a Soroban smart contract: installing WASM, deploying the contract, and invoking a method. Ensure you have 'hello.wasm' in your project directory and replace 'SXXX...' with your secret seed. ```dart import 'dart:io'; import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; KeyPair keyPair = KeyPair.fromSecretSeed('SXXX...'); String rpcUrl = 'https://soroban-testnet.stellar.org:443'; // 1. Install WASM String wasmHash = await SorobanClient.install( installRequest: InstallRequest( wasmBytes: File('hello.wasm').readAsBytesSync(), rpcUrl: rpcUrl, network: Network.TESTNET, sourceAccountKeyPair: keyPair, ), ); // 2. Deploy SorobanClient client = await SorobanClient.deploy( deployRequest: DeployRequest( rpcUrl: rpcUrl, network: Network.TESTNET, sourceAccountKeyPair: keyPair, wasmHash: wasmHash, ), ); // 3. Invoke XdrSCVal result = await client.invokeMethod( name: 'hello', args: [XdrSCVal.forSymbol('World')], ); print('${result.vec![0].sym}, ${result.vec![1].sym}'); // Hello, World ``` -------------------------------- ### Complete Transaction Flow Example Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/documentation-strategy.md Demonstrates the correct way to build, sign, and submit a transaction, including necessary setup and imports. Avoids undefined variables. ```dart StellarSDK sdk = StellarSDK.TESTNET; KeyPair sourceKeyPair = KeyPair.fromSecretSeed("S..."); AccountResponse account = await sdk.accounts.account(sourceKeyPair.accountId); Transaction transaction = TransactionBuilder(account) .addOperation(operation) .build(); transaction.sign(sourceKeyPair, Network.TESTNET); SubmitTransactionResponse response = await sdk.submitTransaction(transaction); ``` -------------------------------- ### Quick Example: Generate Mnemonic and Derive First Account Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/sep/sep-05.md Generates a new 24-word mnemonic and derives the first Stellar account keypair from it. This is a common starting point for wallet integration. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; // Generate a new 24-word mnemonic String mnemonic = await Wallet.generate24WordsMnemonic(); print(mnemonic); // Create wallet and derive the first account Wallet wallet = await Wallet.from(mnemonic); KeyPair keyPair = await wallet.getKeyPair(index: 0); print("Account: ${keyPair.accountId}"); ``` -------------------------------- ### Install SDK via Claude Code Marketplace Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/README.md Commands to add and install the stellar_flutter_sdk from the Claude Code marketplace. ```bash /plugin marketplace add Soneso/stellar_flutter_sdk ``` ```bash /plugin install stellar-flutter-sdk@soneso-stellar-flutter-sdk ``` -------------------------------- ### Complete Stellar Payment Example Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/quick-start.md A comprehensive example demonstrating the creation of two accounts, funding them, and sending a payment from one to the other on the Stellar testnet. It also shows how to check the recipient's balance. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; void main() async { // 1. Generate two keypairs KeyPair alice = KeyPair.random(); KeyPair bob = KeyPair.random(); print("Alice: ${alice.accountId}"); print("Bob: ${bob.accountId}"); // 2. Fund both accounts on testnet await FriendBot.fundTestAccount(alice.accountId); await FriendBot.fundTestAccount(bob.accountId); print("Accounts funded!"); // 3. Connect to testnet StellarSDK sdk = StellarSDK.TESTNET; // 4. Load Alice's account AccountResponse aliceAccount = await sdk.accounts.account(alice.accountId); // 5. Build payment: Alice sends 100 XLM to Bob PaymentOperation paymentOp = PaymentOperationBuilder( bob.accountId, Asset.NATIVE, "100", ).build(); Transaction transaction = TransactionBuilder(aliceAccount) .addOperation(paymentOp) .build(); // 6. Sign with Alice's key transaction.sign(alice, Network.TESTNET); // 7. Submit to network SubmitTransactionResponse response = await sdk.submitTransaction(transaction); if (response.success) { print("Payment successful! Transaction: ${response.hash}"); } else { print("Payment failed."); } // 8. Check Bob's new balance AccountResponse bobAccount = await sdk.accounts.account(bob.accountId); for (Balance balance in bobAccount.balances) { if (balance.assetType == Asset.TYPE_NATIVE) { print("Bob's balance: ${balance.balance} XLM"); } } } ``` -------------------------------- ### SEP30AuthMethod Constructor and Examples Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-30.md Demonstrates the constructor for SEP30AuthMethod and provides examples for common authentication types like email, phone number, and Stellar address. Access public fields directly. ```dart SEP30AuthMethod(String type, String value) SEP30AuthMethod("email", "person@example.com") SEP30AuthMethod("phone_number", "+10000000001") // E.164 format: +[country][number], no spaces SEP30AuthMethod("stellar_address", "GBUCA...H") // G... Stellar address method.type; // String method.value; // String ``` -------------------------------- ### Install WASM Code Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/soroban_contracts.md Demonstrates how to install WebAssembly (WASM) code to the Soroban network. This is the first step before deploying a contract instance. ```APIDOC ## Install WASM Code ### Description Installs WASM code to the Soroban network. This function takes the WASM bytecode, the source account, network details, and RPC URL as input and returns the WASM hash. ### Method `SorobanClient.install` ### Parameters #### Request Body - **installRequest** (InstallRequest) - Required - An object containing the WASM bytes, source account key pair, network, and RPC URL. - **wasmBytes** (List) - Required - The byte array of the WASM contract. - **sourceAccountKeyPair** (KeyPair) - Required - The key pair of the account that will pay for the installation. - **network** (Network) - Required - The Stellar network to use (e.g., Network.TESTNET). - **rpcUrl** (String) - Required - The URL of the Soroban RPC endpoint. ### Response #### Success Response (String) - **wasmId** (String) - The hash of the installed WASM code. ### Request Example ```dart String wasmId = await SorobanClient.install( installRequest: InstallRequest( wasmBytes: wasmBytes, sourceAccountKeyPair: keyPair, network: Network.TESTNET, rpcUrl: 'https://soroban-testnet.stellar.org:443', ), ); print('WASM hash: $wasmId'); ``` ``` -------------------------------- ### Send XLM Payment Example Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/getting-started.md This example demonstrates how to send 100 XLM on the testnet. It covers loading account data, building, signing, and submitting a payment transaction. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; StellarSDK sdk = StellarSDK.TESTNET; KeyPair senderKeyPair = KeyPair.fromSecretSeed("SA52PD5FN425CUONRMMX2CY5HB6I473A5OYNIVU67INROUZ6W4SPHXZB"); String destination = "GCRFFUKMUWWBRIA6ABRDFL5NKO6CKDB2IOX7MOS2TRLXNXQD255Z2MYG"; AccountResponse senderAccount = await sdk.accounts.account(senderKeyPair.accountId); PaymentOperation paymentOp = PaymentOperationBuilder(destination, Asset.NATIVE, "100").build(); Transaction transaction = TransactionBuilder(senderAccount) .addOperation(paymentOp) .addMemo(Memo.text("Coffee payment")) .build(); transaction.sign(senderKeyPair, Network.TESTNET); SubmitTransactionResponse response = await sdk.submitTransaction(transaction); if (response.success) { print("Payment sent! Hash: ${response.hash}"); } ``` -------------------------------- ### Deploy Contract Instance Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/soroban_contracts.md Shows how to deploy a contract instance from previously installed WASM code. ```APIDOC ## Deploy Contract Instance ### Description Deploys a contract instance using the provided WASM hash. This function requires the source account, network details, RPC URL, and the WASM hash. ### Method `SorobanClient.deploy` ### Parameters #### Request Body - **deployRequest** (DeployRequest) - Required - An object containing deployment details. - **sourceAccountKeyPair** (KeyPair) - Required - The key pair of the account that will pay for the deployment. - **network** (Network) - Required - The Stellar network to use. - **rpcUrl** (String) - Required - The URL of the Soroban RPC endpoint. - **wasmHash** (String) - Required - The hash of the WASM code to deploy. - **constructorArgs** (List) - Optional - Arguments for the contract constructor. ### Response #### Success Response (SorobanClient) - **client** (SorobanClient) - A SorobanClient instance configured for the deployed contract. ### Request Example ```dart SorobanClient client = await SorobanClient.deploy( deployRequest: DeployRequest( sourceAccountKeyPair: keyPair, network: Network.TESTNET, rpcUrl: 'https://soroban-testnet.stellar.org:443', wasmHash: wasmId, ), ); print('Contract ID: ${client.getContractId()}'); ``` ``` -------------------------------- ### Basic Deposit Request Example Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-06.md Demonstrates how to create a basic DepositRequest and initiate a deposit using the TransferServerService. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; TransferServerService service = await TransferServerService.fromDomain('anchor.example.com'); DepositRequest request = DepositRequest( assetCode: 'USD', account: userAccountId, // Stellar G... or M... account jwt: jwtToken, ); try { DepositResponse response = await service.deposit(request); // how: deprecated terse instructions (prefer instructions map) if (response.how != null) { print('How: ${response.how}'); } // instructions: structured deposit instructions keyed by SEP-9 field names if (response.instructions != null) { response.instructions!.forEach((key, instruction) { print('$key: ${instruction.value} (${instruction.description})'); }); } // id: anchor's transaction ID for status polling if (response.id != null) { print('Transaction ID: ${response.id}'); } print('ETA: ${response.eta}s'); print('Fee fixed: ${response.feeFixed}'); print('Fee percent: ${response.feePercent}'); print('Min: ${response.minAmount} Max: ${response.maxAmount}'); if (response.extraInfo?.message != null) { print('Note: ${response.extraInfo!.message}'); } } on CustomerInformationNeededException catch (e) { // HTTP 403, type=non_interactive_customer_info_needed // Submit listed fields via SEP-12, then retry print('KYC required: ${e.response.fields}'); } on CustomerInformationStatusException catch (e) { // HTTP 403, type=customer_info_status print('KYC status: ${e.response.status}'); print('More info: ${e.response.moreInfoUrl}'); print('ETA: ${e.response.eta}s'); } on AuthenticationRequiredException catch (e) { // HTTP 403, type=authentication_required print('Auth required — get a JWT via SEP-10 first'); } ``` -------------------------------- ### InstallRequest Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/api_reference.md Request object for installing a WASM contract. Includes WASM bytes, account, network, and RPC URL. ```APIDOC ## InstallRequest ### Description Represents the parameters required to install a WASM contract on the Stellar network. ### Fields - **wasmBytes** (Uint8List) - The byte array of the WASM contract. - **sourceAccountKeyPair** (KeyPair) - The key pair of the source account. - **network** (Network) - The Stellar network to install on. - **rpcUrl** (String) - The URL of the Soroban RPC endpoint. - **enableSorobanServerLogging** (bool) - Whether to enable logging on the Soroban server. ### Methods - **InstallRequest()** - Constructor. ``` -------------------------------- ### Quick KYC Workflow Example Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/sep/sep-12.md Illustrates a typical KYC process: initializing the KYC service, checking the required information from the anchor, and then submitting the customer's data. ```APIDOC ## Quick example This example shows the typical KYC workflow: create the service, check what information is needed, then submit customer data. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; // Create service from anchor's domain (discovers URL from stellar.toml) final kycService = await KYCService.fromDomain('testanchor.stellar.org'); // Check what info the anchor needs (requires JWT token from SEP-10 or SEP-45) final request = GetCustomerInfoRequest(); request.jwt = jwtToken; final response = await kycService.getCustomerInfo(request); print('Status: ${response.status}'); // Submit customer information final personFields = NaturalPersonKYCFields(); personFields.firstName = 'Jane'; personFields.lastName = 'Doe'; personFields.emailAddress = 'jane@example.com'; final kycFields = StandardKYCFields(); kycFields.naturalPersonKYCFields = personFields; final putRequest = PutCustomerInfoRequest(); putRequest.jwt = jwtToken; putRequest.kycFields = kycFields; final putResponse = await kycService.putCustomerInfo(putRequest); final customerId = putResponse.id; // Save for future requests ``` ``` -------------------------------- ### Fund Test Account with FriendBot Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/getting-started.md Use FriendBot to automatically fund a new testnet account with 10,000 test XLM. This is the simplest way to get started on the test network. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; KeyPair keyPair = KeyPair.random(); bool funded = await FriendBot.fundTestAccount(keyPair.accountId); ``` -------------------------------- ### Getting Account Details Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/sep/sep-30.md Retrieves registration status, current signers, and authenticated identities for a given Stellar account. Useful for monitoring key rotation and verifying recovery setups. ```APIDOC ## Getting Account Details ### Description Check registration status, view current signers, and see which identity is currently authenticated. Use this to monitor for key rotation and verify your recovery setup. ### Method ```dart // Assuming service is an instance of SEP30RecoveryService // and accountId and jwtToken are defined SEP30AccountResponse response = await service.accountDetails(accountId, jwtToken); ``` ### Response Example (Success) ```json { "address": "stellar_account_address", "identities": [ { "role": "identity_role", "authenticated": true } ], "signers": [ { "key": "signer_public_key" } ] } ``` ``` -------------------------------- ### Typical KYC Workflow Example Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/sep/sep-12.md Demonstrates the common KYC process: initializing the service, checking required information, and submitting customer data. Requires a JWT token for authentication. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; // Create service from anchor's domain (discovers URL from stellar.toml) final kycService = await KYCService.fromDomain('testanchor.stellar.org'); // Check what info the anchor needs (requires JWT token from SEP-10 or SEP-45) final request = GetCustomerInfoRequest(); request.jwt = jwtToken; final response = await kycService.getCustomerInfo(request); print('Status: ${response.status}'); // Submit customer information final personFields = NaturalPersonKYCFields(); personFields.firstName = 'Jane'; personFields.lastName = 'Doe'; personFields.emailAddress = 'jane@example.com'; final kycFields = StandardKYCFields(); kycFields.naturalPersonKYCFields = personFields; final putRequest = PutCustomerInfoRequest(); putRequest.jwt = jwtToken; putRequest.kycFields = kycFields; final putResponse = await kycService.putCustomerInfo(putRequest); final customerId = putResponse.id; // Save for future requests ``` -------------------------------- ### Quick Start: Full SEP-10 Flow Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-10.md Demonstrates the complete SEP-10 flow using `WebAuth.fromDomain` to fetch configuration and `jwtToken` to authenticate in a single, concise operation. ```APIDOC ## Quick Start: Full SEP-10 Flow This snippet shows how to perform the entire SEP-10 authentication process with minimal code, ideal for quick integration. ### Usage ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; // Load config from anchor's stellar.toml and run the full SEP-10 flow in one call final webAuth = await WebAuth.fromDomain('testanchor.stellar.org', Network.TESTNET); final userKeyPair = KeyPair.fromSecretSeed(userSecretSeed); final jwtToken = await webAuth.jwtToken(userKeyPair.accountId, [userKeyPair]); // Use jwtToken as Bearer token for SEP-12, SEP-24, SEP-31, etc. print('Authenticated! Token: $jwtToken'); ``` ### Parameters - `domain` (string): The home domain of the anchor or service. - `network` (Network): The Stellar network to use (e.g., `Network.TESTNET`, `Network.PUBLIC`). - `userKeyPair` (KeyPair): The key pair of the user's Stellar account. ### Returns - `Future`: A JWT token string upon successful authentication. ``` -------------------------------- ### Deploy with Constructor Arguments Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/soroban_contracts.md Explains how to deploy a contract instance with specific constructor arguments, emphasizing type matching and the use of `funcArgsToXdrSCValues`. ```APIDOC ## Deploy with Constructor Arguments ### Description Deploys a contract instance with constructor arguments. It's crucial to match the exact types expected by the contract. The `funcArgsToXdrSCValues` method is recommended for automatic type conversion when the contract specification is available. ### Method `SorobanClient.deploy` ### Parameters #### Request Body - **deployRequest** (DeployRequest) - Required - An object containing deployment details. - **sourceAccountKeyPair** (KeyPair) - Required - The key pair of the account that will pay for the deployment. - **network** (Network) - Required - The Stellar network to use. - **rpcUrl** (String) - Required - The URL of the Soroban RPC endpoint. - **wasmHash** (String) - Required - The hash of the WASM code to deploy. - **constructorArgs** (List) - Required - A list of `XdrSCVal` representing the constructor arguments. Use `XdrSCVal.forString()`, `XdrSCVal.forU32()`, etc., or `spec.funcArgsToXdrSCValues` for automatic conversion. ### Request Example (Manual Type Mapping) ```dart // WRONG: using forSymbol because "token names are symbols" -- crashes with UnreachableCodeReached // XdrSCVal.forSymbol('MyToken') // WRONG if spec says String (type 16) // CORRECT: spec says String -> use forString; spec says Symbol -> use forSymbol SorobanClient client = await SorobanClient.deploy( deployRequest: DeployRequest( sourceAccountKeyPair: keyPair, network: Network.TESTNET, rpcUrl: 'https://soroban-testnet.stellar.org:443', wasmHash: wasmId, constructorArgs: [ XdrSCVal.forString('MyToken'), // name: String in spec XdrSCVal.forU32(8), // decimals: u32 in spec ], ), ); ``` ### Request Example (Using `funcArgsToXdrSCValues`) ```dart // Load spec from installed WASM SorobanServer server = SorobanServer('https://soroban-testnet.stellar.org:443'); SorobanContractInfo? info = await server.loadContractInfoForWasmId(wasmId); ContractSpec spec = ContractSpec(info!.specEntries); // Auto-convert named args based on __constructor spec types List constructorArgs = spec.funcArgsToXdrSCValues('__constructor', { 'admin': keyPair.accountId, // String -> Address (automatic) 'decimal': 7, // int -> U32 (automatic) 'name': 'MyToken', // String -> String (automatic) 'symbol': 'MTK', // String -> Symbol (automatic) }); SorobanClient client = await SorobanClient.deploy( deployRequest: DeployRequest( sourceAccountKeyPair: keyPair, network: Network.TESTNET, rpcUrl: 'https://soroban-testnet.stellar.org:443', wasmHash: wasmId, constructorArgs: constructorArgs, ), ); ``` ``` -------------------------------- ### Get Account Details with SEP-30 Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-30.md Retrieve the current registration state of an account, including its identities, authentication status, and signer keys. This information is useful for understanding the account's recovery setup. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; final service = SEP30RecoveryService("https://recovery.example.com"); SEP30AccountResponse response = await service.accountDetails(accountId, jwtToken); print("Address: ${response.address}"); for (final identity in response.identities) { // authenticated is bool? — null when the server does not return the field // (typically during registration responses or when the current JWT didn't authenticate as this identity) final authStatus = identity.authenticated == true ? " (authenticated)" : ""; print(" Role: ${identity.role ?? 'unspecified'}$authStatus"); } for (final signer in response.signers) { print(" Signer: ${signer.key}"); } // Use the signer key for recovery (pass to signTransaction) final signingAddress = response.signers[0].key; ``` -------------------------------- ### Getting Account Details Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-30.md Retrieve the current registration state of an account, including its identities, authentication status, and signer keys. This information is crucial for understanding the account's recovery setup and current configuration. ```APIDOC ## Getting Account Details Retrieve the current registration state: identities, authentication status, and signer keys. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; final service = SEP30RecoveryService("https://recovery.example.com"); SEP30AccountResponse response = await service.accountDetails(accountId, jwtToken); print("Address: ${response.address}"); for (final identity in response.identities) { // authenticated is bool? — null when the server does not return the field // (typically during registration responses or when the current JWT didn't authenticate as this identity) final authStatus = identity.authenticated == true ? " (authenticated)" : ""; print(" Role: ${identity.role ?? 'unspecified'}$authStatus"); } for (final signer in response.signers) { print(" Signer: ${signer.key}"); } // Use the signer key for recovery (pass to signTransaction) final signingAddress = response.signers[0].key; ``` Method signature: ``` Future accountDetails(String address, String jwt) ``` ``` -------------------------------- ### SEP38QuoteService Initialization Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/sep/sep-38.md Demonstrates how to create an instance of the SEP38QuoteService, either by discovering the service URL from the anchor's stellar.toml file or by providing a direct URL. It also shows how to use a custom HTTP client and headers for advanced configurations. ```APIDOC ## Creating the service The `SEP38QuoteService` class has methods for all SEP-38 endpoints. You can create an instance by domain discovery or with a direct URL. **From stellar.toml (recommended):** The service address is automatically resolved from the anchor's `ANCHOR_QUOTE_SERVER` field in stellar.toml: ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; SEP38QuoteService quoteService = await SEP38QuoteService.fromDomain('anchor.example.com'); ``` **With a direct URL:** If you already know the quote server URL, you can instantiate the service directly: ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; SEP38QuoteService quoteService = SEP38QuoteService('https://anchor.example.com/sep38'); ``` **With a custom HTTP client:** For advanced use cases, you can provide your own HTTP client: ```dart import 'package:http/http.dart' as http; import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; SEP38QuoteService quoteService = SEP38QuoteService( 'https://anchor.example.com/sep38', httpClient: http.Client(), httpRequestHeaders: {'X-App-Version': '1.0'}, ); ``` ``` -------------------------------- ### Read Contract Return Values Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/soroban_contracts.md Extract typed results from contract invocations. Numeric XDR wrappers must be unwrapped to get the Dart value. For example, use result?.u32?.uint32 for u32 types. ```dart XdrSCVal? result = txResponse.getResultValue(); // Direct types (no unwrapping) String? strVal = result?.str; // String return String? symVal = result?.sym; // Symbol return bool? boolVal = result?.b; // Bool return // Numeric wrappers -- MUST unwrap to get Dart value int? u32Val = result?.u32?.uint32; // u32 -> int int? i32Val = result?.i32?.int32; // i32 -> int BigInt? u64Val = result?.u64?.uint64; // u64 -> BigInt BigInt? i64Val = result?.i64?.int64; // i64 -> BigInt // i128 extraction (common for token balances) if (result?.i128 != null) { XdrInt128Parts parts = result!.i128!; BigInt hi = parts.hi.int64; // XdrInt64 -> BigInt BigInt lo = parts.lo.uint64; // XdrUint64 -> BigInt BigInt value = (hi << 64) + lo; } // Address extraction if (result?.address != null) { String strKey = result!.address!.toStrKey(); // G... or C... format } // Map iteration if (result?.map != null) { for (XdrSCMapEntry entry in result!.map!) { XdrSCVal key = entry.key; XdrSCVal val = entry.val; } } // Vec iteration if (result?.vec != null) { for (XdrSCVal item in result!.vec!) { // each item is XdrSCVal } } ``` -------------------------------- ### Install SDK via Zip (Codex CLI) Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/README.md Use this command to unzip the SDK into the correct directory for Codex CLI. ```bash unzip stellar-flutter-sdk.zip -d .codex/skills/ ``` -------------------------------- ### WebAuthForContracts.fromDomain() Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-45.md Instantiates `WebAuthForContracts` by fetching configuration from the anchor's `stellar.toml` file. This is the recommended approach for initializing the service. ```APIDOC ## WebAuthForContracts.fromDomain() ### Description `WebAuthForContracts.fromDomain()` is a static async factory. It fetches the anchor's `stellar.toml`, reads `WEB_AUTH_FOR_CONTRACTS_ENDPOINT`, `WEB_AUTH_CONTRACT_ID`, and `SIGNING_KEY`, and returns a configured instance. ### Method `static Future fromDomain( String domain, Network network, { http.Client? httpClient, Map? httpRequestHeaders, } )` ### Example ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; try { final webAuth = await WebAuthForContracts.fromDomain( 'anchor.example.com', Network.TESTNET, ); } on NoWebAuthForContractsEndpointFoundException catch (e) { print('No WEB_AUTH_FOR_CONTRACTS_ENDPOINT for ${e.domain}'); } on NoWebAuthContractIdFoundException catch (e) { print('No WEB_AUTH_CONTRACT_ID for ${e.domain}'); } catch (e) { print('Failed to load WebAuth config: $e'); } ``` ``` -------------------------------- ### Typical Integration Pattern: SEP-01, SEP-10, SEP-24 Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-01.md Demonstrates a common integration flow starting with SEP-01 discovery to get anchor information, followed by SEP-10 authentication to obtain a JWT, and finally initiating a SEP-24 deposit request. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; Future connectToAnchor(String domain, KeyPair userKeyPair) async { // Step 1: SEP-01 — discover what the anchor supports StellarToml stellarToml; try { stellarToml = await StellarToml.fromDomain(domain); } catch (e) { throw Exception('Cannot reach anchor stellar.toml: $e'); } final info = stellarToml.generalInformation; // Verify the anchor supports what we need if (info.webAuthEndpoint == null || info.signingKey == null) { throw Exception('Anchor does not support SEP-10'); } if (info.transferServerSep24 == null) { throw Exception('Anchor does not support SEP-24'); } // Step 2: SEP-10 — authenticate and obtain JWT // (WebAuth uses SEP-01 discovery internally, but you can also pass endpoints directly) WebAuth webAuth = await WebAuth.fromDomain(domain, Network.PUBLIC); String jwt = await webAuth.jwtToken(userKeyPair.accountId, [userKeyPair]); // Step 3: SEP-24 — start interactive deposit/withdrawal TransferServerSEP24Service sep24 = await TransferServerSEP24Service.fromDomain(domain); SEP24DepositRequest request = SEP24DepositRequest(); request.assetCode = 'USDC'; request.jwt = jwt; SEP24InteractiveResponse response = await sep24.deposit(request); // Open response.url in a webview print('Open in webview: ${response.url}'); } ``` -------------------------------- ### Service Initialization - From Domain Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-24.md Initializes the TransferServerSEP24Service by fetching the anchor's stellar.toml and reading the TRANSFER_SERVER_SEP0024 field. This is the recommended method. ```APIDOC ## Service Initialization - From Domain ### Description Initializes the `TransferServerSEP24Service` by fetching the anchor's `stellar.toml` and reading the `TRANSFER_SERVER_SEP0024` field. Throws if the field is absent. ### Method Signature ```dart static Future fromDomain( String domain, { http.Client? httpClient, Map? httpRequestHeaders, } ) ``` ### Example Usage ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; // Fetches stellar.toml from https://testanchor.stellar.org/.well-known/stellar.toml // and reads TRANSFER_SERVER_SEP0024 TransferServerSEP24Service service = await TransferServerSEP24Service.fromDomain('testanchor.stellar.org'); ``` ``` -------------------------------- ### Get Account Details with SEP-30 Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/sep/sep-30.md Retrieve detailed information about a Stellar account registered with the SEP-30 service. This includes checking authentication status, viewing current signers, and identifying the authenticated identity. Useful for monitoring key rotation and verifying recovery setups. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; final service = SEP30RecoveryService("https://recovery.example.com"); SEP30AccountResponse response = await service.accountDetails(accountId, jwtToken); print("Account: ${response.address}"); print("\nIdentities:"); for (final identity in response.identities) { final authStatus = identity.authenticated == true ? " (authenticated)" : ""; print(" Role: ${identity.role ?? 'unspecified'}$authStatus"); } print("\nSigners (ordered most recent first):"); for (final signer in response.signers) { print(" Key: ${signer.key}"); } // Best practice: periodically check for new signers and update your account // to use the most recent one (key rotation) final latestSigner = response.signers[0].key; print("\nLatest signer for key rotation: $latestSigner"); ``` -------------------------------- ### RevokeSponsorshipOperation Examples Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/operations.md Provides examples for revoking sponsorship of various ledger entries and signers using the `RevokeSponsorshipOperationBuilder`. ```dart var builder = RevokeSponsorshipOperationBuilder(); // Revoke account sponsorship builder.revokeAccountSponsorship(accountId); // Revoke trustline sponsorship builder.revokeTrustlineSponsorship(accountId, asset); // Revoke data entry sponsorship builder.revokeDataSponsorship(accountId, dataName); // Revoke offer sponsorship builder.revokeOfferSponsorship(accountId, offerId); // offerId is int // Revoke claimable balance sponsorship builder.revokeClaimableBalanceSponsorship(balanceId); // Revoke Ed25519 signer sponsorship builder.revokeEd25519Signer(signerAccountId, ed25519AccountId); // Revoke pre-auth tx signer sponsorship builder.revokePreAuthTxSigner(signerAccountId, preAuthTxHash); // Revoke SHA256 hash signer sponsorship builder.revokeSha256HashSigner(signerAccountId, sha256Hash); var revokeOp = builder.setSourceAccount(sponsorAccountId).build(); ``` -------------------------------- ### Initialize SorobanServer Instance Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/rpc.md Standard SDK import and initialization of a `SorobanServer` instance for interacting with the Soroban RPC. Logging can be enabled by setting `enableLogging` to true. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; final server = SorobanServer('https://soroban-testnet.stellar.org:443'); // Public: SorobanServer('https://mainnet.sorobanrpc.com') // Enable logging: server.enableLogging = true; ``` -------------------------------- ### Get Quote Endpoint Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/compatibility/sep/SEP-0038_COMPATIBILITY_MATRIX.md Details the GET /quote/:id endpoint for retrieving a previously generated firm quote. ```APIDOC ## Get Quote Endpoint Fetches a previously provided firm quote. ### Method GET ### Endpoint /quote/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the quote to retrieve. ### Response #### Success Response (200) - **quote** (object) - The details of the requested quote. #### Response Example ```json { "quote": { "id": "abc123xyz", "buy_asset": "iso:USD", "buy_amount": "100.00", "sell_asset": "iso:XLM", "sell_amount": "1000.00", "fee": { "asset": "iso:XLM", "total": "1.00", "details": [ { "type": "send", "amount": "0.50" }, { "type": "receive", "amount": "0.50" } ] }, "expires_at": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### Service initialization (manual) Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-12.md Manually constructs the KYCService with a known KYC endpoint URL. Allows for custom HTTP clients and headers. ```APIDOC ## Service initialization (manual) ### Description Use when you already know the KYC endpoint URL. Allows for manual construction of the `KYCService` with optional custom HTTP client and headers. ### Usage ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; final kycService = KYCService('https://api.anchor.com/kyc'); // With optional custom client and headers final kycService = KYCService( 'https://api.anchor.com/kyc', httpClient: myClient, httpRequestHeaders: {'X-Custom': 'value'}, ); ``` ### Constructor Signature ``` KYCService(String serviceAddress, {http.Client? httpClient, Map? httpRequestHeaders}) ``` ``` -------------------------------- ### KYC Service Creation Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/sep/sep-12.md Demonstrates how to initialize the KYCService, either by automatically discovering the anchor's KYC server URL from its stellar.toml file (recommended) or by providing the URL directly. ```APIDOC ## Creating the KYC service ### From Domain (Recommended) The recommended approach discovers the KYC service URL automatically from the anchor's `stellar.toml` file. This uses the `KYC_SERVER` or `TRANSFER_SERVER` endpoint. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; import 'package:http/http.dart' as http; // Loads service URL from stellar.toml automatically final kycService = await KYCService.fromDomain('testanchor.stellar.org'); // With custom HTTP client (for timeouts, proxies, etc.) final httpClient = http.Client(); final kycService2 = await KYCService.fromDomain( 'testanchor. '*.stellar.org', httpClient: httpClient, httpRequestHeaders: {'User-Agent': 'MyWallet/1.0'}, ); ``` ### From Direct URL Use this when you already know the KYC service endpoint URL. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; final kycService = KYCService('https://api.anchor.com/kyc'); ``` ``` -------------------------------- ### Install SDK via Zip (Claude Code) Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/README.md Use this command to unzip the SDK into the correct directory for Claude Code. ```bash unzip stellar-flutter-sdk.zip -d .claude/skills/ ``` -------------------------------- ### Stellar Flutter SDK Error Handling Example Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-08.md Example of how to handle various exceptions when using the Stellar Flutter SDK for regulated asset services. ```APIDOC ## Error Handling Example ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; try { final service = await RegulatedAssetsService.fromDomain('regulated-asset-issuer.com'); final response = await service.postTransaction(txXdr, approvalServer); // handle response types... } on IncompleteInitData catch (e) { // stellar.toml missing NETWORK_PASSPHRASE (or custom network with no HORIZON_URL) print('stellar.toml incomplete: $e'); } on IssuerAccountNotFound catch (e) { // authorizationRequired() could not load issuer account from Horizon print('Issuer account not found: $e'); } on UnknownPostTransactionResponse catch (e) { // Approval server returned HTTP code other than 200, or 400 without error field print('Approval server error (HTTP ${e.code}): ${e.body}'); } on UnknownPostTransactionResponseStatus catch (e) { // Server returned a status value not in: success, revised, pending, action_required, rejected print('Unknown approval server status: $e'); } on UnknownPostActionResponse catch (e) { // Action endpoint returned non-200 HTTP response print('Action endpoint error (HTTP ${e.code}): ${e.body}'); } on UnknownPostActionResponseResult catch (e) { // Action endpoint returned unknown result (not "no_further_action_required" or "follow_next_url") print('Unknown action result: $e'); } catch (e) { // stellar.toml fetch failed, network error, or other unexpected error print('Error: $e'); } ``` ``` -------------------------------- ### Install WASM Code Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/soroban_contracts.md Installs WASM bytecode onto the Soroban network. Requires WASM bytes, a source account key pair, network details, and the RPC URL. ```dart String wasmId = await SorobanClient.install( installRequest: InstallRequest( wasmBytes: wasmBytes, sourceAccountKeyPair: keyPair, network: Network.TESTNET, rpcUrl: 'https://soroban-testnet.stellar.org:443', ), ); print('WASM hash: $wasmId'); ``` -------------------------------- ### SorobanClient: Creating a Client Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/soroban.md Set up a SorobanClient instance for interacting with a specific contract. ```APIDOC ## SorobanClient High-level API for contract interaction. ### Creating a Client Set up a SorobanClient instance for interacting with a specific contract. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; SorobanClient client = await SorobanClient.forClientOptions( options: ClientOptions( sourceAccountKeyPair: KeyPair.fromSecretSeed('SXXX...'), contractId: 'CCXYZ...', network: Network.TESTNET, rpcUrl: 'https://soroban-testnet.stellar.org:443', ), ); List methodNames = client.getMethodNames(); ContractSpec spec = client.getContractSpec(); ``` ``` -------------------------------- ### Get Price Quote with Delivery Methods Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-38.md Use this to get a price quote for an asset exchange, specifying delivery methods for off-chain assets. Ensure the anchor domain is correctly specified. ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; SEP38QuoteService service = await SEP38QuoteService.fromDomain('anchor.example.com'); SEP38PriceResponse response = await service.price( context: 'sep6', sellAsset: 'iso4217:BRL', buyAsset: 'stellar:USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN', sellAmount: '500', sellDeliveryMethod: 'PIX', countryCode: 'BRA', jwtToken: jwtToken, ); ``` -------------------------------- ### Soroban: Deploy Contract and Invoke Method Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/sdk-usage.md Quick example to deploy a Soroban contract from WASM bytes and then invoke a method on it. Requires a Stellar account and RPC URL. ```dart import 'dart:typed_data'; import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; KeyPair keyPair = KeyPair.fromSecretSeed('SXXX...'); String rpcUrl = 'https://soroban-testnet.stellar.org:443'; // Install WASM and deploy contract Uint8List wasmBytes = ...; // load your contract WASM bytes String wasmHash = await SorobanClient.install( installRequest: InstallRequest( wasmBytes: wasmBytes, rpcUrl: rpcUrl, network: Network.TESTNET, sourceAccountKeyPair: keyPair, ), ); SorobanClient client = await SorobanClient.deploy( deployRequest: DeployRequest( rpcUrl: rpcUrl, network: Network.TESTNET, sourceAccountKeyPair: keyPair, wasmHash: wasmHash, ), ); // Invoke contract method XdrSCVal result = await client.invokeMethod( name: 'hello', args: [XdrSCVal.forSymbol('World')], ); print('${result.vec![0].sym}, ${result.vec![1].sym}'); // Hello, World ``` -------------------------------- ### Correct Handling of PostTransactionActionRequired Action Method Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/skills/stellar-flutter-sdk/references/sep-08.md The `actionMethod` for `PostTransactionActionRequired` defaults to 'GET' and is never null. Check for 'POST' to use programmatic posting; otherwise, assume 'GET' for browser interaction. ```dart if (response.actionMethod == 'POST') { final actionResponse = await service.postAction(response.actionUrl, fields); } else { // actionMethod is "GET" (or server omitted it, which also defaults to "GET") print('Open in browser: ${response.actionUrl}'); } ``` -------------------------------- ### Pagination Example Source: https://github.com/soneso/stellar_flutter_sdk/blob/master/documentation/sdk-usage.md Demonstrates how to navigate through large result sets using cursors. Each record has a paging token that can be used to fetch subsequent pages of data. ```APIDOC ## Pagination ### Description Navigate through large result sets using cursors. Each record has a paging token you can use to fetch the next page. ### Method ```dart import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; StellarSDK sdk = StellarSDK.TESTNET; // First page Page page = await sdk.transactions .forAccount("GABC...") .limit(20) .order(RequestBuilderOrder.DESC) .execute(); // Process results for (TransactionResponse tx in page.records) { print(tx.hash); } // Get next page using cursor from last record if (page.records.isNotEmpty) { Page nextPage = await sdk.transactions .forAccount("GABC...") .limit(20) .order(RequestBuilderOrder.DESC) .cursor(page.records.last.pagingToken) .execute(); } ``` ```