package
0.0.0-20250213232608-c453f8b35c75
Repository: https://github.com/stellar/go.git
Documentation: pkg.go.dev

# README

txnbuild

txnbuild is a Stellar SDK, implemented in Go. It provides a reference implementation of the complete set of operations that compose transactions for the Stellar distributed ledger.

This project is maintained by the Stellar Development Foundation.

    import (
        "log"
        
        "github.com/stellar/go/clients/horizonclient"
        "github.com/stellar/go/keypair"
        "github.com/stellar/go/network"
        "github.com/stellar/go/txnbuild"
    )
    
    // Make a keypair for a known account from a secret seed
    kp, _ := keypair.Parse("SBPQUZ6G4FZNWFHKUWC5BEYWF6R52E3SEP7R3GWYSM2XTKGF5LNTWW4R")
    
    // Get the current state of the account from the network
    client := horizonclient.DefaultTestNetClient
    ar := horizonclient.AccountRequest{AccountID: kp.Address()}
    sourceAccount, err := client.AccountDetail(ar)
    if err != nil {
        log.Fatalln(err)
    }
    
    // Build an operation to create and fund a new account
    op := txnbuild.CreateAccount{
        Destination: "GCCOBXW2XQNUSL467IEILE6MMCNRR66SSVL4YQADUNYYNUVREF3FIV2Z",
        Amount:      "10",
    }
    
    // Construct the transaction that holds the operations to execute on the network
    tx, err := txnbuild.NewTransaction(
        txnbuild.TransactionParams{
            SourceAccount:        &sourceAccount,
            IncrementSequenceNum: true,
            Operations:           []txnbuild.Operation{&op},
            BaseFee:              txnbuild.MinBaseFee,
            Timebounds:           txnbuild.NewTimeout(300),
        },
    )
    if err != nil {
        log.Fatalln(err)
    )
    
    // Sign the transaction
    tx, err = tx.Sign(network.TestNetworkPassphrase, kp.(*keypair.Full))
    if err != nil {
        log.Fatalln(err)
    )
    
    // Get the base 64 encoded transaction envelope
    txe, err := tx.Base64()
    if err != nil {
        log.Fatalln(err)
    }
    
    // Send the transaction to the network
    resp, err := client.SubmitTransactionXDR(txe)
    if err != nil {
        log.Fatalln(err)
    }

Getting Started

This library is aimed at developers building Go applications on top of the Stellar network. Transactions constructed by this library may be submitted to any Horizon instance for processing onto the ledger, using any Stellar SDK client. The recommended client for Go programmers is horizonclient. Together, these two libraries provide a complete Stellar SDK.

An easy-to-follow demonstration that exercises this SDK on the TestNet with actual accounts is also included! See the Demo section below.

Prerequisites

  • Go (this repository is officially supported on the last two releases of Go)
  • Modules to manage dependencies

Installing

  • go get github.com/stellar/go/txnbuild

Running the tests

Run the unit tests from the package directory: go test

Demo

To see the SDK in action, build and run the demo:

  • Enter the demo directory: cd $GOPATH/src/github.com/stellar/go/txnbuild/cmd/demo
  • Build the demo: go build
  • Run the demo: ./demo init

Contributing

Please read Code of Conduct to understand this project's communication rules.

To submit improvements and fixes to this library, please see CONTRIBUTING.

License

This project is licensed under the Apache License - see the LICENSE file for details.

# Packages

Package examplehorizonclient provides a dummy client for use with the GoDoc examples.

# Functions

AndPredicate returns a xdr.ClaimPredicate.
BeforeAbsoluteTimePredicate returns a Before Absolute Time xdr.ClaimPredicate This predicate will be fulfilled if the closing time of the ledger that includes the CreateClaimableBalance operation is less than this (absolute) Unix timestamp.
BeforeRelativeTimePredicate returns a Before Relative Time xdr.ClaimPredicate This predicate will be fulfilled if the closing time of the ledger that includes the CreateClaimableBalance operation plus this relative time delta (in seconds) is less than the current time.
BuildChallengeTx is a factory method that creates a valid SEP 10 challenge, for use in web authentication.
CreateOfferOp returns a ManageSellOffer operation to create a new offer, by setting the OfferID to "0".
DeleteOfferOp returns a ManageSellOffer operation to delete an offer, by setting the Amount to "0".
MustAssetFromXDR constructs an Asset from its xdr representation.
NewClaimant returns a new Claimant, if predicate is nil then a Claimant with unconditional predicate is returned.
NewFeeBumpTransaction returns a new FeeBumpTransaction instance.
NewGenericTransactionWithFeeBumpTransaction creates a GenericTransaction containing a FeeBumpTransaction.
NewGenericTransactionWithTransaction creates a GenericTransaction containing a Transaction.
NewHomeDomain is syntactic sugar that makes instantiating SetOptions more convenient.
NewInfiniteTimeout is a factory method that sets the MaxTime to a value representing an indefinite upper time bound.
NewInflationDestination is syntactic sugar that makes instantiating SetOptions more convenient.
NewLiquidityPoolDeposit creates a new LiquidityPoolDeposit operation, checking the ordering assets so we generate the correct pool id.
NewLiquidityPoolWithdraw creates a new LiquidityPoolWithdraw operation, checking the ordering assets so we generate the correct pool id.
NewSimpleAccount is a factory method that creates a SimpleAccount from "accountID" and "sequence".
NewThreshold is syntactic sugar that makes instantiating SetOptions more convenient.
NewTimebounds is a factory method that constructs a TimeBounds object from a min and max time.
NewTimeout is a factory method that sets the MaxTime to be the duration in seconds in the future specified by 'timeout'.
NewTransaction returns a new Transaction instance.
NewValidationError creates a ValidationError struct with the provided field and message values.
NotPredicate returns a new predicate inverting the passed in predicate.
OrPredicate returns a xdr.ClaimPredicate.
ParseAssetString parses an asset string in canonical form (SEP-11) into an Asset structure.
ReadChallengeTx reads a SEP 10 challenge transaction and returns the decoded transaction and client account ID contained within.
RemoveTrustlineOp returns a ChangeTrust operation to remove the trustline of the described asset, by setting the limit to "0".
SetOpSourceAccount sets the source account ID on an Operation, allowing M-strkeys (as defined in SEP23).
TransactionFromXDR parses the supplied transaction envelope in base64 XDR and returns a GenericTransaction instance.
UpdateOfferOp returns a ManageSellOffer operation to update an offer.
VerifyChallengeTxSigners verifies that for a SEP 10 challenge transaction all signatures on the transaction are accounted for.
VerifyChallengeTxThreshold verifies that for a SEP 10 challenge transaction all signatures on the transaction are accounted for and that the signatures meet a threshold on an account.

# Constants

AssetTypeNative, AssetTypeCreditAlphanum4, AssetTypeCreditAlphanum12 enumerate the different types of asset on the Stellar network.
AssetTypeNative, AssetTypeCreditAlphanum4, AssetTypeCreditAlphanum12 enumerate the different types of asset on the Stellar network.
AssetTypeNative, AssetTypeCreditAlphanum4, AssetTypeCreditAlphanum12 enumerate the different types of asset on the Stellar network.
AssetTypeNative, AssetTypeCreditAlphanum4, AssetTypeCreditAlphanum12 enumerate the different types of asset on the Stellar network.
AuthClawbackEnabled is a flag that if set allows clawing back assets.
AuthImmutable is a flag that if set prevents any authorization flags from being set, and prevents the account from ever being merged (deleted).
AuthRequired is a flag that requires the issuing account to give other accounts permission before they can hold the issuing account's credit.
AuthRevocable is a flag that allows the issuing account to revoke its credit held by other accounts.
MemoTextMaxLength is the maximum number of bytes allowed for a text memo.
MinBaseFee is the minimum transaction fee for the Stellar network of 100 stroops (0.00001 XLM).
TimeoutInfinite allows an indefinite upper bound to be set for Transaction.MaxTime.
TrustLineAuthorized is a flag that indicates whether the trustline is authorized.
TrustLineAuthorizedToMaintainLiabilities is a flag that if set, will allow a trustline to maintain liabilities without permitting any other operations.
TrustLineClawbackEnabled is a flag that if set allows clawing back assets.

# Variables

MaxTrustlineLimit represents the maximum value that can be set as a trustline limit.

# Structs

AccountMerge represents the Stellar merge account operation.
Deprecated: use SetTrustLineFlags instead.
AssetAmount is a "tuple", pairing an asset with an amount.
BeginSponsoringFutureReserves represents the Stellar begin sponsoring future reserves operation.
BumpSequence represents the Stellar bump sequence operation.
ChangeTrust represents the Stellar change trust operation.
ChangeTrustAssetWrapper wraps a native/credit Asset so it generates xdr to be used in a change trust operation.
Claimant represents a claimable balance claimant.
ClaimClaimableBalance represents the Stellar claim claimable balance operation.
Clawback represents the Stellar clawback operation.
ClawbackClaimableBalance represents the Stellar clawback claimable balance operation.
CreateAccount represents the Stellar create account operation.
CreateClaimableBalance represents the Stellar create claimable balance operation.
CreatePassiveSellOffer represents the Stellar create passive offer operation.
CreditAsset represents non-XLM assets on the Stellar network.
EndSponsoringFutureReserves represents the Stellar begin sponsoring future reserves operation.
FeeBumpTransaction represents a CAP 15 fee bump transaction.
FeeBumpTransactionParams is a container for parameters which are used to construct new FeeBumpTransaction instances.
GenericTransaction represents a parsed transaction envelope returned by TransactionFromXDR.
Inflation represents the Stellar inflation operation.
LedgerBounds represent a transaction precondition that controls the ledger range for which a transaction is valid.
LiquidityPoolDeposit represents the Stellar liquidity pool deposit operation.
LiquidityPoolParameters represents the Stellar liquidity pool parameters.
LiquidityPoolShareChangeTrustAsset represents non-XLM assets on the Stellar network.
LiquidityPoolShareTrustLineAsset represents shares in a liquidity pool on the Stellar network.
LiquidityPoolWithdraw represents the Stellar liquidity pool withdraw operation.
ManageBuyOffer represents the Stellar manage buy offer operation.
ManageData represents the Stellar manage data operation.
ManageSellOffer represents the Stellar manage offer operation.
NativeAsset represents the native XLM asset.
PathPaymentStrictReceive represents the Stellar path_payment_strict_receive operation.
PathPaymentStrictSend represents the Stellar path_payment_strict_send operation.
Payment represents the Stellar payment operation.
Preconditions is a container for all transaction preconditions.
RevokeSponsorship is a union type representing a RevokeSponsorship Operation.
SetOptions represents the Stellar set options operation.
SetTrustLineFlags represents the Stellar set trust line flags operation.
Signer represents the Signer in a SetOptions operation.
SimpleAccount is a minimal implementation of an Account.
TimeBounds represents the time window during which a Stellar transaction is considered valid.
Transaction represents a Stellar transaction.
TransactionParams is a container for parameters which are used to construct new Transaction instances.
TrustLineAssetWrapper wraps a native/credit Asset so it generates xdr to be used in a trust line operation.
ValidationError is a custom error struct that holds validation errors of txnbuild's operation structs.

# Interfaces

Account represents the aspects of a Stellar account necessary to construct transactions.
Asset represents a Stellar asset.
Breaks out some stuff common to all assets.
ChangeTrustAsset represents a Stellar change trust asset.
Memo represents the superset of all memo types.
Operation represents the operation types of the Stellar network.
SorobanOperation represents a smart contract operation on the Stellar network.
TrustLineAsset represents a Stellar trust line asset.

# Type aliases

AccountFlag represents the bitmask flags used to set and clear account authorization options.
Assets represents a list of Stellar assets.
AssetType represents the type of a Stellar asset.
LiquidityPoolId represents the Stellar liquidity pool id.
MemoHash is a hash representing a reference to another transaction.
MemoID is an identifier representing the transaction originator.
MemoReturn is a hash representing the hash of the transaction the sender is refunding.
MemoText is used to send human messages of up to 28 bytes of ASCII/UTF-8.
PathPayment represents the Stellar path_payment operation.
SignerSummary is a map of signers to their weights.
Threshold is the datatype for MasterWeight, Signer.Weight, and Thresholds.
TrustLineFlag represents the bitmask flags used to set and clear account authorization options.