microstellar

package module
v0.0.0-...-ba83830 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2019 License: MIT Imports: 21 Imported by: 0

README


MicroStellar is an easy-to-use Go client for the Stellar blockchain network. The API is simple and clean, without sacrificing flexibility.

MicroStellar is intended to be robust, well tested, and well documented -- we designed it for our Microbanking platform at @qubit-sh. It's also fun to use!

To get started, follow the instructions below, or read the API docs for more.

Also see:

  • Lumen, a commandline interface for Stellar, based on MicroStellar.
  • Hacking Stellar, an open-source e-book on working with Stellar.

QuickStart

Installation

go get github.com/0xfe/microstellar

Usage

Create and fund addresses
// Create a new MicroStellar client connected to the testnet. Use "public" to
// connect to public horizon servers, or "custom" to connect to your own instance.
ms := microstellar.New("test")

// Generate a new random keypair. In stellar lingo, a "seed" is a private key, and
// an "address" is a public key. (Not technically accurate, but you get the picture.)
//
// Seed strings begin with "S" -- "S6H4HQPE6BRZKLK3QNV6LTD5BGS7S6SZPU3PUGMJDJ26V7YRG3FRNPGA"
// Address strings begin with "G" -- "GAUYTZ24ATLEBIV63MXMPOPQO2T6NHI6TQYEXRTFYXWYZ3JOCVO6UYUM"
bob, _ := ms.CreateKeyPair()
log.Print(bob.Seed, bob.Address)

// 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(kelly.Seed, bob.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!)
microstellar.FundWithFriendBot(bob.Address)
Make payments and check balances

Amounts in Microstellar are typically represented as strings, to protect users from accidentaly perform 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).

// Pay someone 3 lumens.
ms.PayNative(kelly.Seed, bob.Address, "3")

// Set the memo field on a payment.
err := ms.Pay(kelly.Seed, bob.Address, "3",
  microstellar.Opts().WithMemoText("thanks for the fish"))

// Find out where the transaction was submitted.
if err == nil {
  fmt.Printf("Transaction submitted to ledger: %d", ms.Response().Ledger)
}

// Get kelly's balance.
account, _ := ms.LoadAccount(kelly.Address)
log.Printf("Native Balance: %v XLM", account.GetNativeBalance())
Work with credit assets
// Create a custom asset with the code "USD" issued by some trusted issuer.
USD := microstellar.NewAsset("USD", chaseBank.address, Credit4Type)

// Create a trust line from an account to the asset, with a limit of 10000.
ms.CreateTrustLine(kelly.Seed, USD, "10000")

// Make a payment in the asset.
ms.Pay(kelly.Seed, mary.Address, USD, "10",
  microstellar.Opts().WithMemo("funny money"))

// Require trustlines to be authorized buy issuer.
ms.SetFlags(issuer.Seed, microstellar.FlagAuthRequired)

// Authorize a trustline after it's been created
ms.AllowTrust(issuer.Seed, mary.Address, "USD", true)
Multisignature transactions
// Add Bob as a signer to Kelly's account with the key weight 1.
ms.AddSigner(kelly.Seed, bob.Address, 1)

// Add Mary as a signer to Kelly's account.
ms.AddSigner(kelly.Seed, mary.Address, 1)

// Set the low, medium, and high thresholds of KElly's account. (Here we require a minimum
// total signing weight of 2 for all operations.)
ms.SetThresholds(kelly.Seed, 2, 2, 2)

// Disable Kelly's master key, so only Bob and Mary can sign her transactions.
ms.SetMasterWeight(kelly.Seed,
   microstellar.Opts().
     WithSigner(kelly.Seed).
     WithSigner(mary.Seed))

// 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(kelly.Address, pizzahut.Address, USD, "20".
  microstellar.Opts().
    WithSigner(mary.Seed).
    WithSigner(kelly.Seed))

Trade assets on the Stellar Distributed Exchange (DEX)
// Sell 100 USD for lumens on the DEX at 2 lumens/USD.
err := ms.CreateOffer(bob.Seed, USD, NativeAsset, "2", "100",
  Opts().MakePassive())

// No takers, update the offer.
err := ms.UpdateOffer(bob.Seed, offerID, USD, NativeAsset, "3", "150")

// Get the order book for all USD -> Lumen trades on the DEX.
orderBook, err := ms.LoadOrderBook(USD, microstellar.NativeAsset)

// Get all offers made by Bob.
offers, err := ms.LoadOffers(bob.Seed)
Make path payments with automatic path-finding
// Path payments let you transparently convert currencies. Pay 5000 INR with XLM,
// going through USD and EUR. Spend no more than 40 lumens on this transaction.
err := ms.Pay(kelly.Seed, mary.Address, "5000", INR, // mary gets 5000 INR
  microstellar.Opts().
    WithAsset(XLM, "40"). // we spend no more than 40 XLM
    Through(USD, EUR))    // go through USD and EUR

// Microstellar can automatically find paths for you, if you don't know what paths
// to take beforehand.
err := ms.Pay(kelly.Seed, mary.Address, "5000", INR, // mary receives 5000 INR
  Opts().
    WithAsset(XLM, "40"). // we spend no more than 40 XLM
    FindPathFrom(kelly.Address))
Bundle multiple operations into a single transaction
// Start a mult-op transaction signed by Mary
ms.Start(bob.Address,
  microstellar.Opts().
    WithMemoText("multi-op").
    WithSigner(mary.Seed))

// Set the home domain for Bob's account.
ms.SetHomeDomain(bob.Address, "qubit.sh")

// Attach arbitrary data to Bob's account.
ms.SetData(bob.Address, "foo", []byte("bar"))

// Set Bob's account flags.
ms.SetFlags(bob.Address, microstellar.FlagAuthRequired | microstellar.FlagsAuthImmutable)

// Make some payments
ms.Pay(bob.Address, pizzaHut.Address, USD, "500")
ms.PayNative(bob.Address, mary.Address, "25")

// Sign and submit the transaction.
ms.Submit()

// Load account to see check if it worked.
account, _ := ms.LoadAccount(bob.Address)
foo, ok := account.GetData("foo")
if ok {
  fmt.Printf("Bob's data for foo: %s", string(foo))
}

fmt.Printf("Bob's home domain: %s", account.GetHomeDomain())
Time-bound transactions for smart contracts
// Create a transaction valid between 1 and 8 hours from now.
ms.Start(bob.Address,
  microstellar.Opts().WithTimeBounds(time.Now().After(1*time.Hour), time.Now().After(8.time.Hour)))
ms.Pay(bob.Address, pizzaHut.Address, USD, "500")

// Get the transaction to submit later.
payload := ms.Payload()

// A few hours later...
signedPayload, _ := ms.SignTransaction(payload, bob.Seed)
ms.SubmitTransaction(signedPayload)
Streaming
// Watch for payments to and from address starting from now.
watcher, err := ms.WatchPayments(bob.Address, Opts().WithCursor("now"))

go func() {
  for p := range watcher.Ch {
    log.Printf("Saw payment on Bob's address: %+v", p)
  }
}()

// Stream the ledger for about a second then stop the watcher.
time.Sleep(1 * time.Second)
watcher.Done()

// Watch for transactions from address.
watcher, err := ms.WatchTransactions(kelly.Address, Opts().WithCursor("now"))

// Get the firehose of ledger updates.
watcher, err := ms.WatchLedgers(Opts().WithCursor("now"))

Documentation

Hacking on MicroStellar

Contribution Guidelines

  • We're managing dependencies with dep.
    • Add a new dependency with dep ensure -add ...
  • If you're adding a new feature:
    • Add unit tests
    • Add godoc comments
    • If necessary, update the integration test in macrotest/
    • If necessary, add examples and verify that they show up in godoc

You can also support this project by sending lumens to GDEVC4BOVFMB46UHGJ6NKEBCQVY5WI56GOBWPG3QKS4QV4TKDLPE6AH6.

Environment Setup

This package uses dep to manage dependencies. Before hacking on this package, install all dependencies:

dep ensure

Run tests

Run all unit tests:

go test -v ./...

Run end-to-end integration test:

go run -v macrotest/macrotest.go

Test documentation with:

godoc -v -http=:6060

Then: http://localhost:6060/pkg/github.com/0xfe/microstellar/

Updating dependencies

# Updates dependencies in vendor/ to latest tags/releases
dep ensure -update

# rinse and repeat
go test -v ./...

Versioning

This package uses semver versioning:

git tag v0.1.0
git push --tags

MIT License

Copyright Mohit Muthanna Cheppudira 2018 mohit@muthanna.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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

Examples

Constants

View Source
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)
)
View Source
const (
	OfferCreate        = OfferType(0)
	OfferCreatePassive = OfferType(1)
	OfferUpdate        = OfferType(2)
	OfferDelete        = OfferType(3)
)

The available offer types.

View Source
const (
	SortAscending  = SortOrder(0)
	SortDescending = SortOrder(1)
)

For use with WithSortOrder

View Source
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.

View Source
const (
	EvBeforeSubmit = Event(0)
)

Supported events.

Variables

View Source
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

func DecodeTxToJSON(base64tx string, pretty bool) (string, error)

DecodeTxToJSON converts the base-64 TX to a JSON string.

func ErrorString

func ErrorString(err error, showStackTrace ...bool) string

ErrorString parses the horizon error out of err.

func FundWithFriendBot

func FundWithFriendBot(address string) (string, error)

FundWithFriendBot funds address on the test network with some initial funds.

func ParseAmount

func ParseAmount(v string) (int64, error)

ParseAmount converts a currency amount string to an int64

func ToAmountString

func ToAmountString(v int64) string

ToAmountString converts an int64 amount to a string

func ValidAddress

func ValidAddress(address string) error

ValidAddress returns error if address is an invalid stellar address

func ValidAddressOrSeed

func ValidAddressOrSeed(addressOrSeed string) bool

ValidAddressOrSeed returns true if the string is a valid address or seed

func ValidSeed

func ValidSeed(seed string) error

ValidSeed returns error if the seed is invalid

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

func (account *Account) GetBalance(asset *Asset) string

GetBalance returns the balance for asset in account. If no balance is found for the asset, returns "".

func (*Account) GetData

func (account *Account) GetData(key string) ([]byte, bool)

GetData decodes and returns the base-64 encoded data in "key"

func (*Account) GetMasterWeight

func (account *Account) GetMasterWeight() int32

GetMasterWeight returns the weight of the primary key in the account.

func (*Account) GetNativeBalance

func (account *Account) GetNativeBalance() string

GetNativeBalance returns the balance of the native currency (typically lumens) in the account.

type AccountFlags

type AccountFlags int32

AccountFlags are used by issuers of assets.

type Address

type Address string

Address represents a stellar address or public key

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

func NewAsset(code string, issuer string, assetType AssetType) *Asset

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) Equals

func (this Asset) Equals(that Asset) bool

Equals returns true if "this" and "that" represent the same asset class.

func (Asset) IsNative

func (asset Asset) IsNative() bool

IsNative returns true if the asset is a native asset (e.g., lumens.)

func (Asset) ToStellarAsset

func (asset Asset) ToStellarAsset() build.Asset

ToStellarAsset returns a stellar-go Asset from this one.

func (Asset) Validate

func (asset Asset) Validate() error

Validate returns error if the asset is not valid.

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 BidAsk

type BidAsk struct {
	Price  string `json:"price"`
	Amount string `json:"amount"`
}

BidAsk represents a price and amount for a specific Bid or Ask.

type Error

type Error struct {
	HorizonError horizon.Error
}

Error wraps underlying errors (e.g., horizon)

type Event

type Event int

Event denotes a specific event for a handler.

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

type KeyPair struct {
	Seed    string // private key
	Address string // public key
}

KeyPair represents a key pair for a signer on a stellar account. An account can have multiple signers.

type Ledger

type Ledger horizon.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 MemoType

type MemoType int

MemoType sets the memotype field on the payment request.

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 Offer

type Offer horizon.Offer

Offer is an offer on the DEX.

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 OfferType

type OfferType int

OfferType tells ManagedOffer what operation to perform

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 NewOptions

func NewOptions() *Options

NewOptions creates a new options structure for Tx.

func Opts

func Opts() *Options

Opts is just an alias for NewOptions

func (*Options) FindPathFrom

func (o *Options) FindPathFrom(sourceAddress string) *Options

FindPathFrom enables automatic path finding for path payments. Use sourceAddress to specify the address (not seed) for the source account.

func (*Options) MakePassive

func (o *Options) MakePassive() *Options

MakePassive turns this into a passive offer. Used with LoadOffers.

func (*Options) MultiOp

func (o *Options) MultiOp(sourceAccount string) *Options

MultiOp specifies that this is a multi-op transactions, and sets the fund source account to sourceAccount.

func (*Options) On

func (o *Options) On(event Event, handler *TxHandler) *Options

On attaches a handler to an event. E.g.,

Opts().On(microstellar.EvBeforeSubmit, func(tx) { log.Print(tx); return nil })

func (*Options) SkipSignatures

func (o *Options) SkipSignatures() *Options

SkipSignatures prevents Tx from signing transactions. This is typically done if the transaction is not meant to be submitted.

func (*Options) Through

func (o *Options) Through(asset ...*Asset) *Options

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

func (o *Options) WithAsset(asset *Asset, maxAmount string) *Options

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

func (o *Options) WithContext(context context.Context) *Options

WithContext sets the context.Context for the connection. Used with Watch* methods.

func (*Options) WithCursor

func (o *Options) WithCursor(cursor string) *Options

WithCursor sets the cursor for watchers and queries. Used with Watch* methods and LoadOffers.

func (*Options) WithLimit

func (o *Options) WithLimit(limit uint) *Options

WithLimit sets the limit for queries. Used with LoadOffers.

func (*Options) WithMemoHash

func (o *Options) WithMemoHash(hash [32]byte) *Options

WithMemoHash sets the memoType and memoHash fields on a Transaction. Used with all transactions.

func (*Options) WithMemoID

func (o *Options) WithMemoID(id uint64) *Options

WithMemoID sets the memoType and memoID fields on a Transaction. Used with all transactions.

func (*Options) WithMemoReturn

func (o *Options) WithMemoReturn(hash [32]byte) *Options

WithMemoReturn sets the memoType and memoReturn fields on a Transaction. Used with all transactions.

func (*Options) WithMemoText

func (o *Options) WithMemoText(text string) *Options

WithMemoText sets the memoType and memoText fields on a Transaction. Used with all transactions.

func (*Options) WithSigner

func (o *Options) WithSigner(signerSeed string) *Options

WithSigner adds a signer to Payment. Used with all transactions.

func (*Options) WithSortOrder

func (o *Options) WithSortOrder(order SortOrder) *Options

WithSortOrder sets the sort order of the results. Used with LoadOffers.

func (*Options) WithTimeBounds

func (o *Options) WithTimeBounds(min time.Time, max time.Time) *Options

WithTimeBounds attaches time bounds to the transaction. This means that the transaction can only be submitted between min and max time (as determined by the ledger.)

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

type Payment horizon.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 Seed

type Seed string

Seed represents a stellar seed or private

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 SortOrder

type SortOrder int

SortOrder is used with WithSortOrder

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

func NewTx(networkName string, params ...Params) *Tx

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) Err

func (tx *Tx) Err() error

Err returns the error from the most recent failed operation.

func (*Tx) GetClient

func (tx *Tx) GetClient() *horizon.Client

GetClient returns the underlying horizon client handle.

func (*Tx) IsSigned

func (tx *Tx) IsSigned() bool

IsSigned returns true of the transaction is signed.

func (*Tx) Payload

func (tx *Tx) Payload() (string, error)

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) SetOptions

func (tx *Tx) SetOptions(options *Options)

SetOptions sets the Tx options

func (*Tx) Sign

func (tx *Tx) Sign(keys ...string) error

Sign signs the transaction with every key in keys.

func (*Tx) Start

func (tx *Tx) Start(account string) *Tx

Start begins a new multi-op transaction with fees billed to account

func (*Tx) Submit

func (tx *Tx) Submit() error

Submit sends the transaction to the stellar network.

func (*Tx) WithOptions

func (tx *Tx) WithOptions(options *Options) *Tx

WithOptions sets the Tx options and returns the Tx

type TxHandler

type TxHandler func(data ...interface{}) (bool, error)

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.

type Watcher

type Watcher struct {
	// Call Done to stop watching the ledger. This closes Ch.
	Done func()

	// This is set if the stream terminates unexpectedly. Safe to check
	// after Ch is closed.
	Err *error
}

Watcher is an abstract watcher struct.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL