Documentation ¶
Overview ¶
Package microstellar is an easy-to-use Go client for the Stellar network.
go get github.com/0xfe/microstellar
Author: Mohit Muthanna Cheppudira <mohit@muthanna.com>
Usage notes ¶
In Stellar lingo, a private key is called a seed, and a public key is called an address. Seed strings start with "S", and address strings start with "G". (Not techincally accurate, but you get the picture.)
Seed: S6H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA Address: GAUYTZ24ATLEBIV63MXMPOPQO2T6NHI6TQYEXRTFYXWYZ3JOCVO6UYUM
In most the methods below, the first parameter is usually "sourceSeed", which should be the seed of the account that signs the transaction.
You can add a *Options struct to the end of many methods, which set extra parameters on the submitted transaction. If you add new signers via Options, then sourceSeed will not be used to sign the transaction -- and it's okay to use a public address instead of a seed for sourceSeed. See examples for how to use Options.
Amounts in Microstellar are typically represented as strings, to protect users from accidentaly performing floating point operations on them. The convenience methods `ParseAmount` and `ToAmountString` to convert the strings to `int64` values that represent a `10e7` multiple of the numeric value. E.g.,
ParseAmount("2.5") == int64(25000000) ToAmountString(1000000) == "1.000000"
You can use ErrorString(...) to extract the Horizon error from a returned error.
Example ¶
// Create a new MicroStellar client connected to a mock network. The client is not // thread-safe, however you can create as many instances as you need. ms := New("fake") // Generate a new random keypair. pair, _ := ms.CreateKeyPair() // In stellar, you can create all kinds of asset types -- dollars, houses, kittens. These // customized assets are called credit assets. // // However, the native asset is always lumens (XLM). Lumens are used to pay for transactions // on the stellar network, and are used to fund the operations of Stellar. // // When you first create a key pair, you need to fund it with atleast 0.5 lumens. This // is called the "base reserve", and makes the account valid. You can only transact to // and from accounts that maintain the base reserve. ms.FundAccount("S6H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA", pair.Address, "1") // On the test network, you can ask FriendBot to fund your account. You don't need to buy // lumens. (If you do want to buy lumens for the test network, call me!) FundWithFriendBot(pair.Address) // Now load the account from the ledger and check its balance. account, _ := ms.LoadAccount(pair.Address) log.Printf("Native Balance: %v XLM", account.GetNativeBalance()) // Note that we used GetNativeBalance() above, which implies lumens as the asset. You // could also do the following. log.Printf("Native Balance: %v XLM", account.GetBalance(NativeAsset)) // Pay your buddy 3 lumens. ms.PayNative("S6H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA", "GAUYTZ24ATLEBIV63MXMPOPQO2T6NHI6TQYEXRTFYXWYZ3JOCVO6UYUM", "3") // Alternatively, be explicit about lumens. ms.Pay("S6H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA", "GAUYTZ24ATLEBIV63MXMPOPQO2T6NHI6TQYEXRTFYXWYZ3JOCVO6UYUM", "3", NativeAsset) // Create a credit asset called USD issued by anchor GAT5GKDILNY2G6NOBEIX7XMGSPPZD5MCHZ47MGTW4UL6CX55TKIUNN53 USD := NewAsset("USD", "GAT5GKDILNY2G6NOBEIX7XMGSPPZD5MCHZ47MGTW4UL6CX55TKIUNN53", Credit4Type) // Pay your buddy 3 USD and add a memo ms.Pay("S6H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA", "GAUYTZ24ATLEBIV63MXMPOPQO2T6NHI6TQYEXRTFYXWYZ3JOCVO6UYUM", "3", USD, Opts().WithMemoText("for beer")) // Create a trust line to the USD credit asset with a limit of 1000. ms.CreateTrustLine("S4H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA", USD, "10000") // Check your balances. account, _ = ms.LoadAccount("GAUYTZ24ATLEBIV63MXMPOPQO2T6NHI6TQYEXRTFYXWYZ3JOCVO6UYUM") log.Printf("USD Balance: %v USD", account.GetBalance(USD)) log.Printf("Native Balance: %v XLM", account.GetNativeBalance()) // Find your home domain. log.Printf("Home domain: %s", account.HomeDomain) // Who are the signers on the account? for i, s := range account.Signers { log.Printf("Signer %d (weight: %v): %v", i, s.PublicKey, s.Weight) } log.Printf("ok")
Output:
Example (Multisig) ¶
// Create a new MicroStellar client connected to a mock network. ms := New("fake") // Add two signers to the source account with weight 1 each ms.AddSigner( "S8H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA", // source account "G6H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA", // signer address 1) // weight ms.AddSigner( "S8H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA", // source account "G9H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGB", // signer address 1) // weight // Set the low, medium, and high thresholds of the account. (Here we require a minimum // total signing weight of 2 for all operations.) ms.SetThresholds("S8H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA", 2, 2, 2) // Kill the master weight of account, so only the new signers can sign transactions ms.SetMasterWeight("S8H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA", 0, Opts().WithSigner("S2H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA")) // Make a payment (and sign with new signers). Note that the first parameter (source) here // can be an address instead of a seed (since the seed can't sign anymore.) ms.PayNative( "G6H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA", // from "GAUYTZ24ATLEBIV63MXMPOPQO2T6NHI6TQYEXRTFYXWYZ3JOCVO6UYUM", // to "3", // amount Opts(). WithSigner("S1H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA"). WithSigner("S2H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA")) log.Printf("ok")
Output:
Index ¶
- Constants
- Variables
- func DecodeTx(base64tx string) (*xdr.TransactionEnvelope, error)
- func DecodeTxToJSON(base64tx string, pretty bool) (string, error)
- func ErrorString(err error, showStackTrace ...bool) string
- func FundWithFriendBot(address string) (string, error)
- func ParseAmount(v string) (int64, error)
- func ToAmountString(v int64) string
- func ValidAddress(address string) error
- func ValidAddressOrSeed(addressOrSeed string) bool
- func ValidSeed(seed string) error
- type Account
- type AccountFlags
- type Address
- type Asset
- type AssetType
- type Balance
- type BidAsk
- type Error
- type Event
- type Flags
- type KeyPair
- type Ledger
- type LedgerWatcher
- type MemoType
- type MicroStellar
- func (ms *MicroStellar) AddSigner(sourceSeed string, signerAddress string, signerWeight uint32, ...) error
- func (ms *MicroStellar) AllowTrust(sourceSeed string, address string, assetCode string, authorized bool, ...) error
- func (ms *MicroStellar) ClearData(sourceSeed string, key string, options ...*Options) error
- func (ms *MicroStellar) ClearFlags(sourceSeed string, flags AccountFlags, options ...*Options) error
- func (ms *MicroStellar) CreateKeyPair() (*KeyPair, error)
- func (ms *MicroStellar) CreateOffer(sourceSeed string, sellAsset *Asset, buyAsset *Asset, price string, ...) error
- func (ms *MicroStellar) CreateTrustLine(sourceSeed string, asset *Asset, limit string, options ...*Options) error
- func (ms *MicroStellar) DeleteOffer(sourceSeed string, offerID string, sellAsset *Asset, buyAsset *Asset, ...) error
- func (ms *MicroStellar) Err() error
- func (ms *MicroStellar) FindPaths(sourceAddress string, destAddress string, destAsset *Asset, destAmount string, ...) ([]Path, error)
- func (ms *MicroStellar) FundAccount(sourceSeed string, addressOrSeed string, amount string, options ...*Options) error
- func (ms *MicroStellar) LoadAccount(address string) (*Account, error)
- func (ms *MicroStellar) LoadOffers(address string, options ...*Options) ([]Offer, error)
- func (ms *MicroStellar) LoadOrderBook(sellAsset *Asset, buyAsset *Asset, options ...*Options) (*OrderBook, error)
- func (ms *MicroStellar) ManageOffer(sourceSeed string, params *OfferParams, options ...*Options) error
- func (ms *MicroStellar) Pay(sourceAddressOrSeed string, targetAddress string, amount string, asset *Asset, ...) error
- func (ms *MicroStellar) PayNative(sourceSeed string, targetAddress string, amount string, options ...*Options) error
- func (ms *MicroStellar) Payload() (string, error)
- func (ms *MicroStellar) RemoveSigner(sourceSeed string, signerAddress string, options ...*Options) error
- func (ms *MicroStellar) RemoveTrustLine(sourceSeed string, asset *Asset, options ...*Options) error
- func (ms *MicroStellar) Resolve(address string) (string, error)
- func (ms *MicroStellar) Response() *TxResponse
- func (ms *MicroStellar) SetData(sourceSeed string, key string, val []byte, options ...*Options) error
- func (ms *MicroStellar) SetFlags(sourceSeed string, flags AccountFlags, options ...*Options) error
- func (ms *MicroStellar) SetHomeDomain(sourceSeed string, domain string, options ...*Options) error
- func (ms *MicroStellar) SetMasterWeight(sourceSeed string, weight uint32, options ...*Options) error
- func (ms *MicroStellar) SetThresholds(sourceSeed string, low, medium, high uint32, options ...*Options) error
- func (ms *MicroStellar) SignTransaction(b64Tx string, seeds ...string) (string, error)
- func (ms *MicroStellar) Start(sourceSeed string, options ...*Options) *MicroStellar
- func (ms *MicroStellar) Submit() error
- func (ms *MicroStellar) SubmitTransaction(b64Tx string) (*TxResponse, error)
- func (ms *MicroStellar) UpdateOffer(sourceSeed string, offerID string, sellAsset *Asset, buyAsset *Asset, ...) error
- func (ms *MicroStellar) WatchLedgers(options ...*Options) (*LedgerWatcher, error)
- func (ms *MicroStellar) WatchPayments(address string, options ...*Options) (*PaymentWatcher, error)
- func (ms *MicroStellar) WatchTransactions(address string, options ...*Options) (*TransactionWatcher, error)
- type Offer
- type OfferParams
- type OfferType
- type Options
- func (o *Options) FindPathFrom(sourceAddress string) *Options
- func (o *Options) MakePassive() *Options
- func (o *Options) MultiOp(sourceAccount string) *Options
- func (o *Options) On(event Event, handler *TxHandler) *Options
- func (o *Options) SkipSignatures() *Options
- func (o *Options) Through(asset ...*Asset) *Options
- func (o *Options) WithAsset(asset *Asset, maxAmount string) *Options
- func (o *Options) WithContext(context context.Context) *Options
- func (o *Options) WithCursor(cursor string) *Options
- func (o *Options) WithLimit(limit uint) *Options
- func (o *Options) WithMemoHash(hash [32]byte) *Options
- func (o *Options) WithMemoID(id uint64) *Options
- func (o *Options) WithMemoReturn(hash [32]byte) *Options
- func (o *Options) WithMemoText(text string) *Options
- func (o *Options) WithSigner(signerSeed string) *Options
- func (o *Options) WithSortOrder(order SortOrder) *Options
- func (o *Options) WithTimeBounds(min time.Time, max time.Time) *Options
- type OrderBook
- type Params
- type Path
- type Payment
- type PaymentWatcher
- type Seed
- type Signer
- type SortOrder
- type Thresholds
- type Transaction
- type TransactionWatcher
- type Tx
- func (tx *Tx) Build(sourceAccount build.TransactionMutator, muts ...build.TransactionMutator) error
- func (tx *Tx) Err() error
- func (tx *Tx) GetClient() *horizon.Client
- func (tx *Tx) IsSigned() bool
- func (tx *Tx) Payload() (string, error)
- func (tx *Tx) Reset()
- func (tx *Tx) Response() *TxResponse
- func (tx *Tx) SetOptions(options *Options)
- func (tx *Tx) Sign(keys ...string) error
- func (tx *Tx) Start(account string) *Tx
- func (tx *Tx) Submit() error
- func (tx *Tx) WithOptions(options *Options) *Tx
- type TxHandler
- type TxOptions
- type TxResponse
- type Watcher
Examples ¶
- Package
- Package (Multisig)
- MicroStellar.AddSigner
- MicroStellar.AllowTrust
- MicroStellar.CreateKeyPair
- MicroStellar.CreateOffer
- MicroStellar.CreateTrustLine
- MicroStellar.DeleteOffer
- MicroStellar.FundAccount
- MicroStellar.LoadAccount (Balance)
- MicroStellar.LoadOffers
- MicroStellar.LoadOrderBook
- MicroStellar.ManageOffer
- MicroStellar.Pay
- MicroStellar.Pay (Memohash)
- MicroStellar.Pay (Memotext)
- MicroStellar.Pay (Multisig)
- MicroStellar.Pay (Path)
- MicroStellar.Pay (Timebounds)
- MicroStellar.PayNative
- MicroStellar.RemoveSigner
- MicroStellar.RemoveTrustLine
- MicroStellar.SetData
- MicroStellar.SetFlags
- MicroStellar.SetHomeDomain
- MicroStellar.SetMasterWeight
- MicroStellar.SetThresholds
- MicroStellar.Start
- MicroStellar.UpdateOffer
- MicroStellar.WatchLedgers
- MicroStellar.WatchPayments
- MicroStellar.WatchTransactions
- TxOptions (Memotext)
- TxOptions (Multisig)
Constants ¶
const ( // FlagsNone disables all flags (can only be used alone.) FlagsNone = AccountFlags(0) // FlagAuthRequired requires the issuing account to give the receiving // account permission to hold the asset. FlagAuthRequired = AccountFlags(1) // FlagAuthRevocable allows the issuer to revoke the credit held by another // account. FlagAuthRevocable = AccountFlags(2) // FlagAuthImmutable means that the other auth parameters can never be set // and the issuer's account can never be deleted. FlagAuthImmutable = AccountFlags(4) )
const ( OfferCreate = OfferType(0) OfferCreatePassive = OfferType(1) OfferUpdate = OfferType(2) OfferDelete = OfferType(3) )
The available offer types.
const ( SortAscending = SortOrder(0) SortDescending = SortOrder(1) )
For use with WithSortOrder
const ( MemoNone = MemoType(0) // No memo MemoID = MemoType(1) // ID memo MemoText = MemoType(2) // Text memo (max 28 chars) MemoHash = MemoType(3) // Hash memo MemoReturn = MemoType(4) // Return hash memo )
Supported memo types.
const (
EvBeforeSubmit = Event(0)
)
Supported events.
Variables ¶
var NativeAsset = &Asset{"XLM", "", NativeType}
NativeAsset is a convenience const representing a native asset.
Functions ¶
func DecodeTx ¶
func DecodeTx(base64tx string) (*xdr.TransactionEnvelope, error)
DecodeTx extracts a TransactionEnvelope out of the base64-encoded string.
func DecodeTxToJSON ¶
DecodeTxToJSON converts the base-64 TX to a JSON string.
func ErrorString ¶
ErrorString parses the horizon error out of err.
func FundWithFriendBot ¶
FundWithFriendBot funds address on the test network with some initial funds.
func ParseAmount ¶
ParseAmount converts a currency amount string to an int64
func ToAmountString ¶
ToAmountString converts an int64 amount to a string
func ValidAddress ¶
ValidAddress returns error if address is an invalid stellar address
func ValidAddressOrSeed ¶
ValidAddressOrSeed returns true if the string is a valid address or seed
Types ¶
type Account ¶
type Account struct { Address string `json:"address"` Balances []Balance `json:"balances"` Signers []Signer `json:"signers"` Flags Flags `json:"flags"` NativeBalance Balance `json:"native_balance"` HomeDomain string `json:"home_domain"` Thresholds Thresholds `json:"thresholds"` Data map[string]string `json:"data"` Sequence string `json:"seq"` }
Account represents an account on the stellar network.
func (*Account) GetBalance ¶
GetBalance returns the balance for asset in account. If no balance is found for the asset, returns "".
func (*Account) GetMasterWeight ¶
GetMasterWeight returns the weight of the primary key in the account.
func (*Account) GetNativeBalance ¶
GetNativeBalance returns the balance of the native currency (typically lumens) in the account.
type Asset ¶
type Asset struct { Code string `json:"code"` Issuer string `json:"issuer"` Type AssetType `json:"type"` }
Asset represents a specific asset class on the stellar network. For native assets "Code" and "Issuer" are ignored.
func NewAsset ¶
NewAsset creates a new asset with the given code, issuer, and assetType. assetType can be one of: NativeType, Credit4Type, or Credit12Type.
USD := microstellar.NewAsset("USD", "issuer_address", microstellar.Credit4Type)
func (Asset) ToStellarAsset ¶
ToStellarAsset returns a stellar-go Asset from this one.
type AssetType ¶
type AssetType string
AssetType represents an asset type on the stellar network.
const Credit12Type AssetType = "credit_alphanum12"
Credit12Type represents credit assets with 12-digit codes.
const Credit4Type AssetType = "credit_alphanum4"
Credit4Type represents credit assets with 4-digit codes.
const NativeType AssetType = "native"
NativeType represents native assets (like lumens.)
type Balance ¶
type Balance struct { Asset *Asset `json:"asset"` Amount string `json:"amount"` Limit string `json:"limit"` }
Balance is the balance amount of the asset in the account.
type Flags ¶
type Flags struct { AuthRequired bool `json:"auth_required"` AuthRevocable bool `json:"auth_revocable"` AuthImmutable bool `json:"auth_immutable"` }
Flags contains the auth flags in the account
type KeyPair ¶
KeyPair represents a key pair for a signer on a stellar account. An account can have multiple signers.
type Ledger ¶
Ledger represents an entry in the ledger. You can subscribe a continuous stream of ledger updates on the Stellar network via the WatchLedgers call.
type LedgerWatcher ¶
type LedgerWatcher struct { Watcher // Ch gets a *Ledger everytime there's a new entry. Ch chan *Ledger }
LedgerWatcher is returned by WatchLedgers, which watches the stellar network for ledger updates.
type MicroStellar ¶
type MicroStellar struct {
// contains filtered or unexported fields
}
MicroStellar is the user handle to the Stellar network. Use the New function to create a new instance.
func New ¶
func New(networkName string, params ...Params) *MicroStellar
New returns a new MicroStellar client connected that operates on the network specified by networkName. The supported networks are:
public: the public horizon network test: the public horizon testnet fake: a fake network used for tests custom: a custom network specified by the parameters
If you're using "custom", provide the URL and Passphrase to your horizon network server in the parameters.
New("custom", Params{ "url": "https://my-horizon-server.com", "passphrase": "foobar"})
The microstellar client is not thread-safe, however you can create as many clients as you need.
func NewFromSpec ¶
func NewFromSpec(spec string) *MicroStellar
NewFromSpec is a helper that creates a new MicroStellar client based on spec, which is a semicolon-separated string.
spec == "test": connect to test network spec == "public": connect to live network spec == "custom;https://foobar.com;myverylongpassphrase": connect to custom network
func (*MicroStellar) AddSigner ¶
func (ms *MicroStellar) AddSigner(sourceSeed string, signerAddress string, signerWeight uint32, options ...*Options) error
AddSigner adds signerAddress as a signer to sourceSeed's account with weight signerWeight.
Example ¶
This example adds a signer to an account.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Add signer to account err := ms.AddSigner("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", "GCCRUJJGPYWKQWM5NLAXUCSBCJKO37VVJ74LIZ5AQUKT6KPVCPNAGC4A", 10) if err != nil { log.Fatalf("AddSigner: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) AllowTrust ¶
func (ms *MicroStellar) AllowTrust(sourceSeed string, address string, assetCode string, authorized bool, options ...*Options) error
AllowTrust authorizes an trustline that was just created by an account to an asset. This can be used by issuers that have the AUTH_REQUIRED flag. The flag can be cleared if the issuer has the AUTH_REVOCABLE flag. The assetCode field must be an asset issued by sourceSeed.
Example ¶
This example authorizes an account to create a trustline to an asset.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer. USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Issuer sets AUTH_REQUIRED flag on account. err := ms.SetFlags("SDPLQEABOETMI7PPKJZYBHHW2BSA3424CI3V5ZRNN3NP2H7KYQOKY5ST", FlagAuthRequired) if err != nil { log.Fatalf("SetFlags: %v", ErrorString(err)) } // Customer creates a trustline to the custom asset with no limit. err = ms.CreateTrustLine("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", USD, "") if err != nil { log.Fatalf("CreateTrustLine: %v", err) } // Issuer then authorizes the trustline that was just created. err = ms.AllowTrust("SDPLQEABOETMI7PPKJZYBHHW2BSA3424CI3V5ZRNN3NP2H7KYQOKY5ST", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", "USD", true) if err != nil { log.Fatalf("AllowTrust: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) ClearData ¶
func (ms *MicroStellar) ClearData(sourceSeed string, key string, options ...*Options) error
ClearData removes attached data from an account.
func (*MicroStellar) ClearFlags ¶
func (ms *MicroStellar) ClearFlags(sourceSeed string, flags AccountFlags, options ...*Options) error
ClearFlags clears the specified flags for the account.
func (*MicroStellar) CreateKeyPair ¶
func (ms *MicroStellar) CreateKeyPair() (*KeyPair, error)
CreateKeyPair generates a new random key pair.
Example ¶
This example creates a key pair and displays the private and public keys. In stellar-terminology, the private key is typically called a "seed", and the publick key. an "address."
ms := New("test") // Generate a new random keypair. pair, err := ms.CreateKeyPair() if err != nil { log.Fatalf("CreateKeyPair: %v", err) } // Display address and key log.Printf("Private seed: %s, Public address: %s", pair.Seed, pair.Address) fmt.Printf("ok")
Output: ok
func (*MicroStellar) CreateOffer ¶
func (ms *MicroStellar) CreateOffer(sourceSeed string, sellAsset *Asset, buyAsset *Asset, price string, sellAmount string, options ...*Options) error
CreateOffer creates an offer to trade sellAmount of sellAsset held by sourceSeed for buyAsset at price (which buy_unit-over-sell_unit.) The offer is made on Stellar's decentralized exchange (DEX.)
You can use add Opts().MakePassive() to make this a passive offer.
Example ¶
This example creates a passive offer on stellar's DEX.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Sell 200 USD on the DEX for lumens (at 2 lumens per USD). This is a passive // offer. (This is equivalent to an offer to buy 400 lumens for 200 USD.) err := ms.CreateOffer("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", USD, NativeAsset, "2", "200", Opts().MakePassive()) if err != nil { log.Fatalf("CreateOffer: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) CreateTrustLine ¶
func (ms *MicroStellar) CreateTrustLine(sourceSeed string, asset *Asset, limit string, options ...*Options) error
CreateTrustLine creates a trustline from sourceSeed to asset, with the specified trust limit. An empty limit string indicates no limit.
Example ¶
This example creates a trust line to a credit asset.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Create a trustline to the custom asset with no limit err := ms.CreateTrustLine("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", USD, "") if err != nil { log.Fatalf("CreateTrustLine: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) DeleteOffer ¶
func (ms *MicroStellar) DeleteOffer(sourceSeed string, offerID string, sellAsset *Asset, buyAsset *Asset, price string, options ...*Options) error
DeleteOffer deletes the specified parameters (assets, price, ID) on the DEX.
Example ¶
This example deletes an existing offer on the DEX.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Delete Offer ID 23456 on the DEX. err := ms.DeleteOffer("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", "23456", USD, NativeAsset, "0.4") if err != nil { log.Fatalf("DeleteOffer: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) Err ¶
func (ms *MicroStellar) Err() error
Err returns the last error on the transaction.
func (*MicroStellar) FindPaths ¶
func (ms *MicroStellar) FindPaths(sourceAddress string, destAddress string, destAsset *Asset, destAmount string, options ...*Options) ([]Path, error)
FindPaths finds payment paths between source and dest assets. Use Options.WithAsset to filter the results by source asset and max spend.
func (*MicroStellar) FundAccount ¶
func (ms *MicroStellar) FundAccount(sourceSeed string, addressOrSeed string, amount string, options ...*Options) error
FundAccount creates a new account out of addressOrSeed by funding it with lumens from sourceSeed. The minimum funding amount today is 0.5 XLM.
Example ¶
This example creates a key pair and funds the account with lumens. FundAccount is used for the initial funding of the account -- it is what turns a public address into an account.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Generate a new random keypair. pair, err := ms.CreateKeyPair() if err != nil { log.Fatalf("CreateKeyPair: %v", err) } // Fund the account with 1 lumen from an existing account. err = ms.FundAccount("SD3M3RG4G54JSFIG4RJYPPKTB4G77IPSXKZPTMN5CKAFWNRQP6V24ZDQ", pair.Address, "1") if err != nil { log.Fatalf("FundAccount: %v", ErrorString(err)) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) LoadAccount ¶
func (ms *MicroStellar) LoadAccount(address string) (*Account, error)
LoadAccount loads the account information for the given address.
Example (Balance) ¶
This example loads and displays the native and a non-native balance on an account.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Load account from ledger. account, err := ms.LoadAccount("GCCRUJJGPYWKQWM5NLAXUCSBCJKO37VVJ74LIZ5AQUKT6KPVCPNAGC4A") if err != nil { log.Fatalf("LoadAccount: %v", err) } // See balances log.Printf("Native Balance: %v", account.GetNativeBalance()) log.Printf("USD Balance: %v", account.GetBalance(USD)) fmt.Printf("ok")
Output: ok
func (*MicroStellar) LoadOffers ¶
func (ms *MicroStellar) LoadOffers(address string, options ...*Options) ([]Offer, error)
LoadOffers returns all existing trade offers made by address.
Example ¶
This example lists the offers currently out by an address.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Get at most 10 offers made by address in descending order offers, err := ms.LoadOffers("GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Opts().WithLimit(10).WithSortOrder(SortDescending)) if err != nil { log.Fatalf("LoadOffers: %v", err) } for _, o := range offers { log.Printf("Offer ID: %v, Selling: %v, Price: %v, Amount: %v", o.ID, o.Selling.Code, o.Price, o.Amount) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) LoadOrderBook ¶
func (ms *MicroStellar) LoadOrderBook(sellAsset *Asset, buyAsset *Asset, options ...*Options) (*OrderBook, error)
LoadOrderBook returns the current orderbook for all trades between sellAsset and buyAsset. Use Opts().WithLimit(limit) to limit the number of entries returned.
Example ¶
This example lists all asks on the DEX between USD <-> XLM
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Get at most 10 orders made between USD and XLM orderbook, err := ms.LoadOrderBook(USD, NativeAsset, Opts().WithLimit(10).WithSortOrder(SortDescending)) if err != nil { log.Fatalf("LoadOrderBook: %v", err) } // List all the returned asks. for _, ask := range orderbook.Asks { log.Printf("ask: %s %s for %s %s/%s", ask.Amount, orderbook.Base.Code, ask.Price, orderbook.Counter.Code, orderbook.Base.Code) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) ManageOffer ¶
func (ms *MicroStellar) ManageOffer(sourceSeed string, params *OfferParams, options ...*Options) error
ManageOffer lets you trade on the DEX. See the Create/Update/DeleteOffer methods below to see how this is used.
Example ¶
This example creates a new offer using the ManageOffer method.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Create an offer to buy 200 lumens at 2 lumens/dollar. err := ms.ManageOffer("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", &OfferParams{ OfferType: OfferCreate, SellAsset: USD, BuyAsset: NativeAsset, Price: "2", SellAmount: "100", }) if err != nil { log.Fatalf("ManageOffer: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) Pay ¶
func (ms *MicroStellar) Pay(sourceAddressOrSeed string, targetAddress string, amount string, asset *Asset, options ...*Options) error
Pay lets you make payments with credit assets.
USD := microstellar.NewAsset("USD", "ISSUERSEED", microstellar.Credit4Type) ms.Pay("source_seed", "target_address", "3", USD, microstellar.Opts().WithMemoText("for shelter"))
Pay also lets you make path payments. E.g., Mary pays Bob 2000 INR with XLM (lumens), using the path XLM -> USD -> EUR -> INR, spending no more than 20 XLM (lumens.)
XLM := microstellar.NativeAsset USD := microstellar.NewAsset("USD", "ISSUERSEED", microstellar.Credit4Type) EUR := microstellar.NewAsset("EUR", "ISSUERSEED", microstellar.Credit4Type) INR := microstellar.NewAsset("INR", "ISSUERSEED", microstellar.Credit4Type) ms.Pay("marys_seed", "bobs_address", "2000", INR, microstellar.Opts().WithAsset(XLM, "20").Through(USD, EUR).WithMemoText("take your rupees!"))
If you don't know what path to take ahead of time, use Options.FindPathFrom(sourceAddress) to find a path for you.
ms.Pay("marys_seed", "bobs_address", "2000", INR, microstellar.Opts().WithAsset(XLM, "20").Through(USD, EUR).FindPathFrom("marys_address"))
Example ¶
This example makes a payment of a credit asset from one account to another.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Pay 1 USD to targetAddress err := ms.Pay("SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD) if err != nil { log.Fatalf("Pay: %v", ErrorString(err)) } fmt.Printf("ok")
Output: ok
Example (Memohash) ¶
Payments with memohash and memoreturn
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GALC5V4UUUICHENN3ZZLQY6UWAC67CMKVXYT4MT7YGQRD6RMXXCAMHP6", Credit4Type) // Pay 1 USD to targetAddress and set the memohash field var hash [32]byte copy(hash[:], "boo"[:]) err := ms.Pay("SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD, Opts().WithMemoHash(hash)) if err != nil { log.Fatalf("Pay (memohash): %v", ErrorString(err)) } // Pay 1 USD to targetAddress and set the memoreturn field err = ms.Pay("SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD, Opts().WithMemoReturn(hash)) if err != nil { log.Fatalf("Pay (memoreturn): %v", ErrorString(err)) } fmt.Printf("ok")
Output: ok
Example (Memotext) ¶
Payments with memotext and memoid
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GALC5V4UUUICHENN3ZZLQY6UWAC67CMKVXYT4MT7YGQRD6RMXXCAMHP6", Credit4Type) // Pay 1 USD to targetAddress and set the memotext field err := ms.Pay("SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD, Opts().WithMemoText("boo")) if err != nil { log.Fatalf("Pay (memotext): %v", ErrorString(err)) } // Pay 1 USD to targetAddress and set the memotext field err = ms.Pay("SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD, Opts().WithMemoID(42)) if err != nil { log.Fatalf("Pay (memoid): %v", ErrorString(err)) } fmt.Printf("ok")
Output: ok
Example (Multisig) ¶
Makes a multisignature payment
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Pay 1 USD to targetAddress and set the memotext field err := ms.Pay("SDKORMIXFL2QW2UC3HWJ4GKL4PYFUMDOPEJMGWVQBW4GWJ5W2ZBOGRSZ", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD, Opts().WithMemoText("multisig"). WithSigner("SAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ"). WithSigner("SBIUIQNMSXTGR4TGZETSQCGBTIF32G2L5D4AML4LFTMTHKM44UABFDMS")) if err != nil { log.Fatalf("Pay (memotext): %v", ErrorString(err)) } // Pay 1 USD to targetAddress and set the memotext field err = ms.Pay("SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD, Opts().WithMemoID(73223)) if err != nil { log.Fatalf("Pay (memoid): %v", ErrorString(err)) } fmt.Printf("ok")
Output: ok
Example (Path) ¶
This example makes a path payment from XLM to INR via USD and EUR.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") XLM := NativeAsset // Custom USD, EUR, and INR assets issued by Bank of America USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) EUR := NewAsset("EUR", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) INR := NewAsset("INR", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Pay 5000 INR with XLM, going through USD and EUR. Spend no more than 40 lumens on this // transaction. err := ms.Pay( "SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC", // from "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", // to "5000", INR, // they receive 5000 INR Opts(). WithAsset(XLM, "40"). // we spend no more than 40 XLM Through(USD, EUR)) // go through USD and EUR if err != nil { log.Fatalf("Pay: %v", ErrorString(err)) } fmt.Printf("ok")
Output: ok
Example (Timebounds) ¶
Payments with time bounds
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GALC5V4UUUICHENN3ZZLQY6UWAC67CMKVXYT4MT7YGQRD6RMXXCAMHP6", Credit4Type) // Start a new timebound transaction, valid between 1 and 24 hours from now ms.Start("GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", Opts().WithTimeBounds(time.Now().Add(1*time.Hour), time.Now().Add(24*time.Hour))) // Pay 1 USD to targetAddress, only valid between 1 and 24 hours from now. ms.Pay("GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD) // Get the transaction to submit later. payload, err := ms.Payload() if err != nil { log.Fatalf("Could not generate payload: %v", err) } /* // A few hours later, sign and submit transaction... signedPayload, err := ms.SignTransaction(payload, "SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC") if err != nil { log.Fatalf("Could not sign transaction: %v", err) } _, err = ms.SubmitTransaction(signedPayload) if err != nil { log.Fatalf("Pay (timebounds): %v", ErrorString(err)) } */ _ = payload fmt.Printf("ok")
Output: ok
func (*MicroStellar) PayNative ¶
func (ms *MicroStellar) PayNative(sourceSeed string, targetAddress string, amount string, options ...*Options) error
PayNative makes a native asset payment of amount from source to target.
Example ¶
This example makes a native asset (lumens) payment from one account to another.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Pay 1 XLM to targetAddress err := ms.PayNative("SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC", "GDS2DXCCTW5VO5A2KCEBHAP3W4XOCJSI2QVHNN63TXVGBUIIW4DI3BCW", "1") if err != nil { log.Fatalf("PayNative: %v", ErrorString(err)) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) Payload ¶
func (ms *MicroStellar) Payload() (string, error)
Payload returns the payload for the current transaction without submitting it to the network. This only works for transactions started with Start(). This method closes the transaction like Submit().
func (*MicroStellar) RemoveSigner ¶
func (ms *MicroStellar) RemoveSigner(sourceSeed string, signerAddress string, options ...*Options) error
RemoveSigner removes signerAddress as a signer from sourceSeed's account.
Example ¶
This example removes a signer from an account.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Remove signer from account err := ms.RemoveSigner("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", "GCCRUJJGPYWKQWM5NLAXUCSBCJKO37VVJ74LIZ5AQUKT6KPVCPNAGC4A") if err != nil { log.Fatalf("RemoveSigner: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) RemoveTrustLine ¶
func (ms *MicroStellar) RemoveTrustLine(sourceSeed string, asset *Asset, options ...*Options) error
RemoveTrustLine removes an trustline from sourceSeed to an asset.
Example ¶
This example removes a trust line to a credit asset.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Remove the trustline (if exists) err := ms.RemoveTrustLine("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", USD) if err != nil { log.Fatalf("RemoveTrustLine: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) Resolve ¶
func (ms *MicroStellar) Resolve(address string) (string, error)
Resolve looks up a federated address
func (*MicroStellar) Response ¶
func (ms *MicroStellar) Response() *TxResponse
Response returns the response from the last submission.
func (*MicroStellar) SetData ¶
func (ms *MicroStellar) SetData(sourceSeed string, key string, val []byte, options ...*Options) error
SetData lets you attach (or update) arbitrary data to an account. The lengths of the key and value must each be less than 64 bytes.
Example ¶
This example sets some data values on an account
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Set some string data err := ms.SetData("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", "foo", []byte("this is a string")) if err != nil { log.Fatalf("SetData: %v", err) } // Set some byte data err = ms.SetData("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", "bytes", []byte{0xFF, 0xFF}) if err != nil { log.Fatalf("SetData: %v", err) } // Read the data values that were just set account, err := ms.LoadAccount("GAKMTB3D6AOE5HZ3QK726TZG6A22NGN7B46B2UALVYCLLHLOBMUBXZBJ") if err != nil { log.Fatalf("LoadAccount: %v", err) } if v, ok := account.GetData("foo"); ok { fmt.Printf("foo = %s", string(v)) } if v, ok := account.GetData("bytes"); ok { fmt.Printf("bytes = %v", v) } // Clear data err = ms.ClearData("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", "bytes") if err != nil { log.Fatalf("ClearData: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) SetFlags ¶
func (ms *MicroStellar) SetFlags(sourceSeed string, flags AccountFlags, options ...*Options) error
SetFlags sets flags on the account.
Example ¶
This example sets flags on an issuer's account
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Set the AUTH_REQUIRED and AUTH_REVOCABLE flags on the account. err := ms.SetFlags("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", FlagAuthRequired|FlagAuthRevocable) if err != nil { log.Fatalf("SetFlags: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) SetHomeDomain ¶
func (ms *MicroStellar) SetHomeDomain(sourceSeed string, domain string, options ...*Options) error
SetHomeDomain changes the home domain of sourceSeed.
Example ¶
This example sets the home domain for an account
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Set the home domain to qubit.sh err := ms.SetHomeDomain("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", "qubit.sh") if err != nil { log.Fatalf("SetHomeDomain: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) SetMasterWeight ¶
func (ms *MicroStellar) SetMasterWeight(sourceSeed string, weight uint32, options ...*Options) error
SetMasterWeight changes the master weight of sourceSeed.
Example ¶
This example sets the weight of the accounts primary signer (the master weight) to zero. This effectively kills the account.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Set master weight to zero. err := ms.SetMasterWeight("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", 0) if err != nil { log.Fatalf("SetMasterWeight: %v", err) } // Load the account and check its master weight account, err := ms.LoadAccount("GCCRUJJGPYWKQWM5NLAXUCSBCJKO37VVJ74LIZ5AQUKT6KPVCPNAGC4A") if err != nil { log.Fatalf("LoadAccount: %v", err) } log.Printf("Master weight: %v", account.GetMasterWeight()) fmt.Printf("ok")
Output: ok
func (*MicroStellar) SetThresholds ¶
func (ms *MicroStellar) SetThresholds(sourceSeed string, low, medium, high uint32, options ...*Options) error
SetThresholds sets the signing thresholds for the account.
Example ¶
This example sets the signing thresholds for an account
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Set the low, medium, and high thresholds for an account err := ms.SetThresholds("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", 2, 2, 2) if err != nil { log.Fatalf("SetThresholds: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) SignTransaction ¶
func (ms *MicroStellar) SignTransaction(b64Tx string, seeds ...string) (string, error)
SignTransaction signs a base64-encoded transaction envelope with the specified seeds for the current network.
func (*MicroStellar) Start ¶
func (ms *MicroStellar) Start(sourceSeed string, options ...*Options) *MicroStellar
Start begins a new multi-op transaction. This lets you lump a set of operations into a single transaction, and submit them together in one atomic step.
You can pass in the signers and envelope fields (such as memotext, memoid, etc.) for the transaction as options. The signers must have signing authority on all the operations in the transaction.
The fee for the transaction is billed to sourceSeed, which is typically a seed, but can be an address if differnt signers are used.
Call microstellar.Submit() on the instance to close the transaction and send it to the network.
ms = microstellar.New("test") ms.Start("sourceSeed", microstellar.Opts().WithMemoText("big op").WithSigner("signerSeed")) ms.Pay("marys_address", "bobs_address", "2000", INR) ms.Pay("marys_address", "bills_address", "2000", USD) ms.SetMasterWeight("bobs_address", 0) ms.SetHomeDomain("bobs_address", "qubit.sh") ms.Submit()
Example ¶
This example demonstrates multi-op transactions.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") feeSource := "GAKMTB3D6AOE5HZ3QK726TZG6A22NGN7B46B2UALVYCLLHLOBMUBXZBJ" signer := "SDPLQEABOETMI7PPKJZYBHHW2BSA3424CI3V5ZRNN3NP2H7KYQOKY5ST" // Start a new multi-op transaction and bill the fee to feeSource. Also provide the // seed of the signer with authority to sign all operations. ms.Start(feeSource, Opts().WithMemoText("multi-op").WithSigner(signer)) // Set the home domain to qubit.sh err := ms.SetHomeDomain("GAD3LPHSTZHNZOJOPRS7OZ2P74VXFCP5J4QNYIGGHZ246XINHGKPJIQR", "qubit.sh") if err != nil { log.Fatalf("SetHomeDomain: %v", err) } // Set the AUTH_REQUIRED and AUTH_REVOCABLE flags on the account. err = ms.SetFlags("GAD3LPHSTZHNZOJOPRS7OZ2P74VXFCP5J4QNYIGGHZ246XINHGKPJIQR", FlagAuthRequired|FlagAuthRevocable) if err != nil { log.Fatalf("SetFlags: %v", err) } // Sign and submit the transaction to the network err = ms.Submit() if err != nil { log.Fatalf("Submit: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) Submit ¶
func (ms *MicroStellar) Submit() error
Submit signs and submits a multi-op transaction to the network. See microstellar.Start() for details.
func (*MicroStellar) SubmitTransaction ¶
func (ms *MicroStellar) SubmitTransaction(b64Tx string) (*TxResponse, error)
SubmitTransaction submits a base64-encoded transaction envelope to the Stellar network
func (*MicroStellar) UpdateOffer ¶
func (ms *MicroStellar) UpdateOffer(sourceSeed string, offerID string, sellAsset *Asset, buyAsset *Asset, price string, sellAmount string, options ...*Options) error
UpdateOffer updates the existing offer with ID offerID on the DEX.
Example ¶
This example updates an existing offer on the DEX.
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Update Offer ID 23456 to sell 200 USD on the DEX for lumens (at 1 lumen / USD.) err := ms.UpdateOffer("SCSMBQYTXKZYY7CLVT6NPPYWVDQYDOQ6BB3QND4OIXC7762JYJYZ3RMK", "23456", USD, NativeAsset, "1", "200") if err != nil { log.Fatalf("UpdateOffer: %v", err) } fmt.Printf("ok")
Output: ok
func (*MicroStellar) WatchLedgers ¶
func (ms *MicroStellar) WatchLedgers(options ...*Options) (*LedgerWatcher, error)
WatchLedgers watches the the stellar network for entries and streams them to LedgerWatcher.Ch. Use Options.WithContext to set a context.Context, and Options.WithCursor to set a cursor.
Example ¶
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Get notified on new ledger entries in Stellar. watcher, err := ms.WatchLedgers(Opts().WithCursor("now")) if err != nil { log.Fatalf("Can't watch ledger: %+v", err) } // Count the number of entries seen. entries := 0 go func() { for l := range watcher.Ch { entries++ log.Printf("WatchLedgers %d: %v -- %v\n", entries, l.ID, l.TotalCoins) } log.Printf("## WatchLedgers ## Done -- Error: %v\n", *watcher.Err) }() // Stream the ledger for about a second then stop the watcher. time.Sleep(1 * time.Second) watcher.Done() // Sleep a bit to wait for the done message from the goroutine. time.Sleep(500 * time.Millisecond) fmt.Printf("%d entries seen", entries)
Output: 5 entries seen
func (*MicroStellar) WatchPayments ¶
func (ms *MicroStellar) WatchPayments(address string, options ...*Options) (*PaymentWatcher, error)
WatchPayments watches the ledger for payments to and from address and streams them on a channel . Use Options.WithContext to set a context.Context, and Options.WithCursor to set a cursor.
Example ¶
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Watch for payments to address. (The fake network sends payments every 200ms.) watcher, err := ms.WatchPayments("GCCRUJJGPYWKQWM5NLAXUCSBCJKO37VVJ74LIZ5AQUKT6KPVCPNAGC4A", Opts().WithContext(context.Background())) if err != nil { log.Fatalf("Can't watch ledger: %+v", err) } // Count the number of payments received. paymentsReceived := 0 go func() { for p := range watcher.Ch { paymentsReceived++ log.Printf("WatchPayments %d: %v -- %v %v from %v to %v\n", paymentsReceived, p.Type, p.Amount, p.AssetCode, p.From, p.To) } log.Printf("## WatchPayments ## Done -- Error: %v\n", *watcher.Err) }() // Stream the ledger for about a second then stop the watcher. time.Sleep(1 * time.Second) watcher.Done() // Sleep a bit to wait for the done message from the goroutine. time.Sleep(500 * time.Millisecond) fmt.Printf("%d payments received", paymentsReceived)
Output: 5 payments received
func (*MicroStellar) WatchTransactions ¶
func (ms *MicroStellar) WatchTransactions(address string, options ...*Options) (*TransactionWatcher, error)
WatchTransactions watches the ledger for transactions to and from address and streams them on a channel . Use Options.WithContext to set a context.Context, and Options.WithCursor to set a cursor.
Example ¶
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Watch for transactions to address. (The fake network sends transactions every 200ms.) watcher, err := ms.WatchTransactions("GCCRUJJGPYWKQWM5NLAXUCSBCJKO37VVJ74LIZ5AQUKT6KPVCPNAGC4A", Opts().WithContext(context.Background())) if err != nil { log.Fatalf("Can't watch ledger: %+v", err) } // Count the number of transactions received. received := 0 go func() { for t := range watcher.Ch { received++ log.Printf("WatchTransactions %d: %v %v %v\n", received, t.ID, t.Account, t.Ledger) } log.Printf("## WatchTransactions ## Done -- Error: %v\n", *watcher.Err) }() // Stream the ledger for about a second then stop the watcher. time.Sleep(1 * time.Second) watcher.Done() // Sleep a bit to wait for the done message from the goroutine. time.Sleep(500 * time.Millisecond) fmt.Printf("%d transactions received", received)
Output: 5 transactions received
type OfferParams ¶
type OfferParams struct { // Create, update, or delete. OfferType OfferType // The asset that's being sold on the DEX. SellAsset *Asset // The asset that you want to buy on the DEX. BuyAsset *Asset // How much you're willing to pay (in BuyAsset units) per unit of SellAsset. Price string // How many units of SellAsset are you selling? SellAmount string // Existing offer ID (for Update and Delete) OfferID string }
OfferParams specify the parameters
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
Options are additional parameters for a transaction. Use Opts() or NewOptions() to create a new instance.
func (*Options) FindPathFrom ¶
FindPathFrom enables automatic path finding for path payments. Use sourceAddress to specify the address (not seed) for the source account.
func (*Options) MakePassive ¶
MakePassive turns this into a passive offer. Used with LoadOffers.
func (*Options) MultiOp ¶
MultiOp specifies that this is a multi-op transactions, and sets the fund source account to sourceAccount.
func (*Options) On ¶
On attaches a handler to an event. E.g.,
Opts().On(microstellar.EvBeforeSubmit, func(tx) { log.Print(tx); return nil })
func (*Options) SkipSignatures ¶
SkipSignatures prevents Tx from signing transactions. This is typically done if the transaction is not meant to be submitted.
func (*Options) Through ¶
Through adds "asset" as a routing point in the payment path.
E.g.,
ms.Pay(sourceSeed, address, "20", INR, Opts().WithAsset(NativeAsset, "20").Through(USD, EUR)
func (*Options) WithAsset ¶
WithAsset is used to setup a path payment. This makes the Pay method use "asset" as the sending asset, and sends no more than maxAmount units of the asset. Used with Pay and FindPaths.
E.g.,
ms.Pay(sourceSeed, address, "20", INR, Opts().WithAsset(NativeAsset, "20").Through(USD, EUR)
func (*Options) WithContext ¶
WithContext sets the context.Context for the connection. Used with Watch* methods.
func (*Options) WithCursor ¶
WithCursor sets the cursor for watchers and queries. Used with Watch* methods and LoadOffers.
func (*Options) WithMemoHash ¶
WithMemoHash sets the memoType and memoHash fields on a Transaction. Used with all transactions.
func (*Options) WithMemoID ¶
WithMemoID sets the memoType and memoID fields on a Transaction. Used with all transactions.
func (*Options) WithMemoReturn ¶
WithMemoReturn sets the memoType and memoReturn fields on a Transaction. Used with all transactions.
func (*Options) WithMemoText ¶
WithMemoText sets the memoType and memoText fields on a Transaction. Used with all transactions.
func (*Options) WithSigner ¶
WithSigner adds a signer to Payment. Used with all transactions.
func (*Options) WithSortOrder ¶
WithSortOrder sets the sort order of the results. Used with LoadOffers.
type OrderBook ¶
type OrderBook struct { Asks []BidAsk `json:"asks"` Bids []BidAsk `json:"bids"` Base *Asset `json:"base"` Counter *Asset `json:"counter"` }
OrderBook is returned by LoadOrderBook.
type Params ¶
type Params map[string]interface{}
Params lets you add optional parameters to the common microstellar methods.
type Path ¶
type Path struct { DestAsset *Asset DestAmount string SourceAsset *Asset SourceAmount string Hops []*Asset }
Path is a microstellar payment path
type Payment ¶
Payment represents a finalized payment in the ledger. You can subscribe to payments on the stellar network via the WatchPayments call.
type PaymentWatcher ¶
type PaymentWatcher struct { Watcher // Ch gets a *Payment everytime there's a new entry in the ledger. Ch chan *Payment }
PaymentWatcher is returned by WatchPayments, which watches the ledger for payments to and from an address.
type Signer ¶
type Signer struct { PublicKey string `json:"public_key"` Weight int32 `json:"weight"` Key string `json:"key"` Type string `json:"type"` }
Signer represents a key that can sign for an account.
type Thresholds ¶
type Thresholds struct { High byte `json:"high"` Medium byte `json:"medium"` Low byte `json:"low"` }
Thresholds represent the signing thresholds on the account
type Transaction ¶
type Transaction horizon.Transaction
Transaction represents a finalized transaction in the ledger. You can subscribe to transactions on the stellar network via the WatchTransactions call.
type TransactionWatcher ¶
type TransactionWatcher struct { Watcher // Ch gets a *Transaction everytime there's a new entry in the ledger. Ch chan *Transaction }
TransactionWatcher is returned by WatchTransactions, which watches the ledger for transactions to and from an address.
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx represents a unique stellar transaction. This is used by the MicroStellar library to abstract away the Horizon API and transport. To reuse Tx instances, you must call Tx.Reset() between operations.
This struct is not thread-safe by design -- you must use separate instances in different goroutines.
Unless you're hacking around in the guts, you should not need to use Tx.
func NewTx ¶
NewTx returns a new Tx that operates on the network specified by networkName. The supported networks are:
public: the public horizon network test: the public horizon testnet fake: a fake network used for tests custom: a custom network specified by the parameters
If you're using "custom", provide the URL and Passphrase to your horizon network server in the parameters.
NewTx("custom", Params{ "url": "https://my-horizon-server.com", "passphrase": "foobar"})
func (*Tx) Build ¶
func (tx *Tx) Build(sourceAccount build.TransactionMutator, muts ...build.TransactionMutator) error
Build creates a new operation out of the provided mutators.
func (*Tx) Payload ¶
Payload returns the built (and possibly signed) payload for this transaction as a base64 string.
func (*Tx) Reset ¶
func (tx *Tx) Reset()
Reset clears all internal sate, so you can run a new operation.
func (*Tx) Response ¶
func (tx *Tx) Response() *TxResponse
Response returns the horison response for the submitted operation.
func (*Tx) WithOptions ¶
WithOptions sets the Tx options and returns the Tx
type TxHandler ¶
TxHandler is a custom function that can be called when certain events occur. If false is returned or if the method returns an error, the caller stops processing the event immediately.
type TxOptions ¶
type TxOptions Options
TxOptions is a deprecated alias for TxOptoins
Example (Memotext) ¶
Payments with memotext and memoid
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GALC5V4UUUICHENN3ZZLQY6UWAC67CMKVXYT4MT7YGQRD6RMXXCAMHP6", Credit4Type) // Pay 1 USD to targetAddress and set the memotext field err := ms.Pay("SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD, Opts().WithMemoText("boo")) if err != nil { log.Fatalf("Pay (memotext): %v", ErrorString(err)) } // Pay 1 USD to targetAddress and set the memotext field err = ms.Pay("SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD, Opts().WithMemoID(42)) if err != nil { log.Fatalf("Pay (memoid): %v", ErrorString(err)) } fmt.Printf("ok")
Output: ok
Example (Multisig) ¶
Makes a multisignature payment
// Create a new MicroStellar client connected to a fake network. To // use a real network replace "fake" below with "test" or "public". ms := New("fake") // Custom USD asset issued by specified issuer USD := NewAsset("USD", "GAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ", Credit4Type) // Pay 1 USD to targetAddress and set the memotext field err := ms.Pay("SDKORMIXFL2QW2UC3HWJ4GKL4PYFUMDOPEJMGWVQBW4GWJ5W2ZBOGRSZ", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD, Opts().WithMemoText("multisig"). WithSigner("SAIUIQNMSXTTR4TGZETSQCGBTIF32G2L5P4AML4LFTMTHKM44UHIN6XQ"). WithSigner("SBIUIQNMSXTGR4TGZETSQCGBTIF32G2L5D4AML4LFTMTHKM44UABFDMS")) if err != nil { log.Fatalf("Pay (memotext): %v", ErrorString(err)) } // Pay 1 USD to targetAddress and set the memotext field err = ms.Pay("SAED4QHN3USETFHECASIM2LRI3H4QTVKZK44D2RC27IICZPZQEGXGXFC", "GAGTJGMT55IDNTFTF2F553VQBWRBLGTWLU4YOOIFYBR2F6H6S4AEC45E", "1", USD, Opts().WithMemoID(73223)) if err != nil { log.Fatalf("Pay (memoid): %v", ErrorString(err)) } fmt.Printf("ok")
Output: ok
type TxResponse ¶
type TxResponse horizon.TransactionSuccess
TxResponse is returned by the horizon server for a successful transaction.