horizon

package
v0.0.0-...-3597e88 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2020 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package horizon provides client access to a horizon server, allowing an application to post transactions and lookup ledger information.

Create an instance of `Client` to customize the server used, or alternatively use `DefaultTestNetClient` or `DefaultPublicNetClient` to access the SDF run horizon servers.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrResultCodesNotPopulated is the error returned from a call to
	// ResultCodes() against a `Problem` value that doesn't have the
	// "result_codes" extra field populated when it is expected to be.
	ErrResultCodesNotPopulated = errors.New("result_codes not populated")

	// ErrEnvelopeNotPopulated is the error returned from a call to
	// Envelope() against a `Problem` value that doesn't have the
	// "envelope_xdr" extra field populated when it is expected to be.
	ErrEnvelopeNotPopulated = errors.New("envelope_xdr not populated")
)
View Source
var DefaultPublicNetClient = &Client{
	URL:  "https://horizon.stellar.org",
	HTTP: http.DefaultClient,
}

DefaultPublicNetClient is a default client to connect to public network

View Source
var DefaultTestNetClient = &Client{
	URL:  "https://horizon-testnet.stellar.org",
	HTTP: http.DefaultClient,
}

DefaultTestNetClient is a default client to connect to test network

Functions

This section is empty.

Types

type Account

type Account struct {
	Links struct {
		Self         Link `json:"self"`
		Transactions Link `json:"transactions"`
		Operations   Link `json:"operations"`
		Payments     Link `json:"payments"`
		Effects      Link `json:"effects"`
		Offers       Link `json:"offers"`
	} `json:"_links"`

	HistoryAccount
	Sequence             string            `json:"sequence"`
	SubentryCount        int32             `json:"subentry_count"`
	InflationDestination string            `json:"inflation_destination,omitempty"`
	HomeDomain           string            `json:"home_domain,omitempty"`
	Thresholds           AccountThresholds `json:"thresholds"`
	Flags                AccountFlags      `json:"flags"`
	Balances             []Balance         `json:"balances"`
	Signers              []Signer          `json:"signers"`
	Data                 map[string]string `json:"data"`
}

func (Account) GetCreditBalance

func (a Account) GetCreditBalance(code, issuer string) string

func (*Account) GetData

func (this *Account) GetData(key string) ([]byte, error)

GetData returns decoded value for a given key. If the key does not exist, empty slice will be returned.

func (Account) GetNativeBalance

func (a Account) GetNativeBalance() string

func (*Account) MustGetData

func (this *Account) MustGetData(key string) []byte

MustGetData returns decoded value for a given key. If the key does not exist, empty slice will be returned. If there is an error decoding a value, it will panic.

type AccountFlags

type AccountFlags struct {
	AuthRequired  bool `json:"auth_required"`
	AuthRevocable bool `json:"auth_revocable"`
}

type AccountThresholds

type AccountThresholds struct {
	LowThreshold  byte `json:"low_threshold"`
	MedThreshold  byte `json:"med_threshold"`
	HighThreshold byte `json:"high_threshold"`
}

type Asset

type Asset struct {
	Type   string `json:"asset_type"`
	Code   string `json:"asset_code,omitempty"`
	Issuer string `json:"asset_issuer,omitempty"`
}

type At

type At string

At is a paging parameter that can be used to override the URL loaded in a remote method call to horizon.

type Balance

type Balance struct {
	Balance string `json:"balance"`
	Limit   string `json:"limit,omitempty"`
	Asset
}

type Client

type Client struct {
	// URL of Horizon server to connect
	URL string

	// HTTP client to make requests with
	HTTP HTTP
	// contains filtered or unexported fields
}

Client struct contains data required to connect to Horizon instance

func (*Client) HomeDomainForAccount

func (c *Client) HomeDomainForAccount(aid string) (string, error)

HomeDomainForAccount returns the home domain for the provided strkey-encoded account id.

func (*Client) LoadAccount

func (c *Client) LoadAccount(accountID string) (account Account, err error)

LoadAccount loads the account state from horizon. err can be either error object or horizon.Error object.

func (*Client) LoadAccountOffers

func (c *Client) LoadAccountOffers(accountID string, params ...interface{}) (offers OffersPage, err error)

LoadAccountOffers loads the account offers from horizon. err can be either error object or horizon.Error object.

func (*Client) LoadMemo

func (c *Client) LoadMemo(p *Payment) (err error)

LoadMemo loads memo for a transaction in Payment

func (*Client) LoadOrderBook

func (c *Client) LoadOrderBook(selling Asset, buying Asset, params ...interface{}) (orderBook OrderBookSummary, err error)

LoadOrderBook loads order book for given selling and buying assets.

func (*Client) Root

func (c *Client) Root() (root Root, err error)

Root loads the root endpoint of horizon

func (*Client) SequenceForAccount

func (c *Client) SequenceForAccount(
	accountID string,
) (xdr.SequenceNumber, error)

SequenceForAccount implements build.SequenceProvider

func (*Client) StreamLedgers

func (c *Client) StreamLedgers(ctx context.Context, cursor *Cursor, handler LedgerHandler) (err error)

StreamLedgers streams incoming ledgers. Use context.WithCancel to stop streaming or context.Background() if you want to stream indefinitely.

Example
client := DefaultPublicNetClient
cursor := Cursor("now")

ctx, cancel := context.WithCancel(context.Background())

go func() {
	// Stop streaming after 60 seconds.
	time.Sleep(60 * time.Second)
	cancel()
}()

err := client.StreamLedgers(ctx, &cursor, func(l Ledger) {
	fmt.Println(l.Sequence)
})

if err != nil {
	fmt.Println(err)
}
Output:

func (*Client) StreamPayments

func (c *Client) StreamPayments(ctx context.Context, accountID string, cursor *Cursor, handler PaymentHandler) (err error)

StreamPayments streams incoming payments. Use context.WithCancel to stop streaming or context.Background() if you want to stream indefinitely.

func (*Client) StreamTransactions

func (c *Client) StreamTransactions(ctx context.Context, accountID string, cursor *Cursor, handler TransactionHandler) (err error)

StreamTransactions streams incoming transactions. Use context.WithCancel to stop streaming or context.Background() if you want to stream indefinitely.

func (*Client) SubmitTransaction

func (c *Client) SubmitTransaction(transactionEnvelopeXdr string) (response TransactionSuccess, err error)

SubmitTransaction submits a transaction to the network. err can be either error object or horizon.Error object.

Example
client := DefaultPublicNetClient
transactionEnvelopeXdr := "AAAAABSxFjMo7qcQlJBlrZQypSqYsHA5hHaYxk5hFXwiehh6AAAAZAAIdakAAABZAAAAAAAAAAAAAAABAAAAAAAAAAEAAAAAFLEWMyjupxCUkGWtlDKlKpiwcDmEdpjGTmEVfCJ6GHoAAAAAAAAAAACYloAAAAAAAAAAASJ6GHoAAABAp0FnKOQ9lJPDXPTh/a91xoZ8BaznwLj59sdDGK94eGzCOk7oetw7Yw50yOSZg2mqXAST6Agc9Ao/f5T9gB+GCw=="

response, err := client.SubmitTransaction(transactionEnvelopeXdr)
if err != nil {
	fmt.Println(err)
	herr, isHorizonError := err.(*Error)
	if isHorizonError {
		resultCodes, err := herr.ResultCodes()
		if err != nil {
			fmt.Println("failed to extract result codes from horizon response")
			return
		}
		fmt.Println(resultCodes)
	}
	return
}

fmt.Println("Success")
fmt.Println(response)
Output:

type ClientInterface

type ClientInterface interface {
	Root() (Root, error)
	HomeDomainForAccount(aid string) (string, error)
	LoadAccount(accountID string) (Account, error)
	LoadAccountOffers(accountID string, params ...interface{}) (offers OffersPage, err error)
	LoadMemo(p *Payment) error
	LoadOrderBook(selling Asset, buying Asset, params ...interface{}) (orderBook OrderBookSummary, err error)
	StreamLedgers(ctx context.Context, cursor *Cursor, handler LedgerHandler) error
	StreamPayments(ctx context.Context, accountID string, cursor *Cursor, handler PaymentHandler) error
	StreamTransactions(ctx context.Context, accountID string, cursor *Cursor, handler TransactionHandler) error
	SubmitTransaction(txeBase64 string) (TransactionSuccess, error)
}

type Cursor

type Cursor string

Cursor represents `cursor` param in queries

type Error

type Error struct {
	Response *http.Response
	Problem  Problem
}

Error struct contains the problem returned by Horizon

func (*Error) Envelope

func (herr *Error) Envelope() (*xdr.TransactionEnvelope, error)

Envelope extracts the transaction envelope that triggered this error from the extra fields.

func (Error) Error

func (herr Error) Error() string

func (*Error) ResultCodes

func (herr *Error) ResultCodes() (*TransactionResultCodes, error)

ResultCodes extracts a result code summary from the error, if possible.

type HTTP

type HTTP interface {
	Do(req *http.Request) (resp *http.Response, err error)
	Get(url string) (resp *http.Response, err error)
	PostForm(url string, data url.Values) (resp *http.Response, err error)
}

HTTP represents the HTTP client that a horizon client uses to communicate

type HistoryAccount

type HistoryAccount struct {
	ID        string `json:"id"`
	PT        string `json:"paging_token"`
	AccountID string `json:"account_id"`
}

type Ledger

type Ledger struct {
	Links struct {
		Self         Link `json:"self"`
		Transactions Link `json:"transactions"`
		Operations   Link `json:"operations"`
		Payments     Link `json:"payments"`
		Effects      Link `json:"effects"`
	} `json:"_links"`
	ID               string    `json:"id"`
	PT               string    `json:"paging_token"`
	Hash             string    `json:"hash"`
	PrevHash         string    `json:"prev_hash,omitempty"`
	Sequence         int32     `json:"sequence"`
	TransactionCount int32     `json:"transaction_count"`
	OperationCount   int32     `json:"operation_count"`
	ClosedAt         time.Time `json:"closed_at"`
	TotalCoins       string    `json:"total_coins"`
	FeePool          string    `json:"fee_pool"`
	BaseFee          int32     `json:"base_fee_in_stroops"`
	BaseReserve      int32     `json:"base_reserve_in_stroops"`
	MaxTxSetSize     int32     `json:"max_tx_set_size"`
	ProtocolVersion  int32     `json:"protocol_version"`
}

type LedgerHandler

type LedgerHandler func(Ledger)

LedgerHandler is a function that is called when a new ledger is received

type Limit

type Limit uint

Limit represents `limit` param in queries

type Link struct {
	Href      string `json:"href"`
	Templated bool   `json:"templated,omitempty"`
}

type MockClient

type MockClient struct {
	mock.Mock
}

MockClient is a mockable horizon client.

func (*MockClient) HomeDomainForAccount

func (m *MockClient) HomeDomainForAccount(aid string) (string, error)

HomeDomainForAccount is a mocking a method

func (*MockClient) LoadAccount

func (m *MockClient) LoadAccount(accountID string) (Account, error)

LoadAccount is a mocking a method

func (*MockClient) LoadAccountOffers

func (m *MockClient) LoadAccountOffers(accountID string, params ...interface{}) (offers OffersPage, err error)

LoadAccountOffers is a mocking a method

func (*MockClient) LoadMemo

func (m *MockClient) LoadMemo(p *Payment) error

LoadMemo is a mocking a method

func (*MockClient) LoadOrderBook

func (m *MockClient) LoadOrderBook(selling Asset, buying Asset, params ...interface{}) (orderBook OrderBookSummary, err error)

LoadOrderBook is a mocking a method

func (*MockClient) Root

func (m *MockClient) Root() (Root, error)

Root is a mocking a method

func (*MockClient) StreamLedgers

func (m *MockClient) StreamLedgers(ctx context.Context, cursor *Cursor, handler LedgerHandler) error

StreamLedgers is a mocking a method

func (*MockClient) StreamPayments

func (m *MockClient) StreamPayments(ctx context.Context, accountID string, cursor *Cursor, handler PaymentHandler) error

StreamPayments is a mocking a method

func (*MockClient) StreamTransactions

func (m *MockClient) StreamTransactions(ctx context.Context, accountID string, cursor *Cursor, handler TransactionHandler) error

StreamTransactions is a mocking a method

func (*MockClient) SubmitTransaction

func (m *MockClient) SubmitTransaction(txeBase64 string) (TransactionSuccess, error)

SubmitTransaction is a mocking a method

type Offer

type Offer struct {
	Links struct {
		Self       Link `json:"self"`
		OfferMaker Link `json:"offer_maker"`
	} `json:"_links"`

	ID      int64  `json:"id"`
	PT      string `json:"paging_token"`
	Seller  string `json:"seller"`
	Selling Asset  `json:"selling"`
	Buying  Asset  `json:"buying"`
	Amount  string `json:"amount"`
	PriceR  Price  `json:"price_r"`
	Price   string `json:"price"`
}

type OffersPage

type OffersPage struct {
	Links struct {
		Self Link `json:"self"`
		Next Link `json:"next"`
		Prev Link `json:"prev"`
	} `json:"_links"`
	Embedded struct {
		Records []Offer `json:"records"`
	} `json:"_embedded"`
}

type Order

type Order string

Order represents `order` param in queries

const (
	OrderAsc  Order = "asc"
	OrderDesc Order = "desc"
)

type OrderBookSummary

type OrderBookSummary struct {
	Bids    []PriceLevel `json:"bids"`
	Asks    []PriceLevel `json:"asks"`
	Selling Asset        `json:"base"`
	Buying  Asset        `json:"counter"`
}

type Payment

type Payment struct {
	ID          string `json:"id"`
	Type        string `json:"type"`
	PagingToken string `json:"paging_token"`

	Links struct {
		Transaction struct {
			Href string `json:"href"`
		} `json:"transaction"`
	} `json:"_links"`

	// create_account fields
	Account         string `json:"account"`
	StartingBalance string `json:"starting_balance"`

	// payment/path_payment fields
	From        string `json:"from"`
	To          string `json:"to"`
	AssetType   string `json:"asset_type"`
	AssetCode   string `json:"asset_code"`
	AssetIssuer string `json:"asset_issuer"`
	Amount      string `json:"amount"`

	// transaction fields
	Memo struct {
		Type  string `json:"memo_type"`
		Value string `json:"memo"`
	}
}

type PaymentHandler

type PaymentHandler func(Payment)

PaymentHandler is a function that is called when a new payment is received

type Price

type Price struct {
	N int32 `json:"n"`
	D int32 `json:"d"`
}

type PriceLevel

type PriceLevel struct {
	PriceR Price  `json:"price_r"`
	Price  string `json:"price"`
	Amount string `json:"amount"`
}

type Problem

type Problem struct {
	Type     string                     `json:"type"`
	Title    string                     `json:"title"`
	Status   int                        `json:"status"`
	Detail   string                     `json:"detail,omitempty"`
	Instance string                     `json:"instance,omitempty"`
	Extras   map[string]json.RawMessage `json:"extras,omitempty"`
}

func (Problem) ToProblem

func (prob Problem) ToProblem() problem.P

ToProblem converts the Prolem to a problem.P

type Root

type Root struct {
	Links struct {
		Account             Link `json:"account"`
		AccountTransactions Link `json:"account_transactions"`
		Friendbot           Link `json:"friendbot"`
		Metrics             Link `json:"metrics"`
		OrderBook           Link `json:"order_book"`
		Self                Link `json:"self"`
		Transaction         Link `json:"transaction"`
		Transactions        Link `json:"transactions"`
	} `json:"_links"`

	HorizonVersion       string `json:"horizon_version"`
	StellarCoreVersion   string `json:"core_version"`
	HorizonSequence      int32  `json:"history_latest_ledger"`
	HistoryElderSequence int32  `json:"history_elder_ledger"`
	CoreSequence         int32  `json:"core_latest_ledger"`
	CoreElderSequence    int32  `json:"core_elder_ledger"`
	NetworkPassphrase    string `json:"network_passphrase"`
	ProtocolVersion      int32  `json:"protocol_version"`
}

type Signer

type Signer struct {
	PublicKey string `json:"public_key"`
	Weight    int32  `json:"weight"`
	Key       string `json:"key"`
	Type      string `json:"type"`
}

type Transaction

type Transaction struct {
	ID              string    `json:"id"`
	PagingToken     string    `json:"paging_token"`
	Hash            string    `json:"hash"`
	Ledger          int32     `json:"ledger"`
	LedgerCloseTime time.Time `json:"created_at"`
	Account         string    `json:"source_account"`
	AccountSequence string    `json:"source_account_sequence"`
	FeePaid         string    `json:"fee_paid"`
	OperationCount  int32     `json:"operation_count"`
	EnvelopeXdr     string    `json:"envelope_xdr"`
	ResultXdr       string    `json:"result_xdr"`
	ResultMetaXdr   string    `json:"result_meta_xdr"`
	FeeMetaXdr      string    `json:"fee_meta_xdr"`
	MemoType        string    `json:"memo_type"`
	Memo            string    `json:"memo,omitempty"`
	Signatures      []string  `json:"signatures"`
	ValidAfter      string    `json:"valid_after,omitempty"`
	ValidBefore     string    `json:"valid_before,omitempty"`
}

type TransactionHandler

type TransactionHandler func(Transaction)

TransactionHandler is a function that is called when a new transaction is received

type TransactionResultCodes

type TransactionResultCodes struct {
	TransactionCode string   `json:"transaction"`
	OperationCodes  []string `json:"operations,omitempty"`
}

TransactionResultCodes represent a summary of result codes returned from a single xdr TransactionResult

type TransactionSuccess

type TransactionSuccess struct {
	Links struct {
		Transaction Link `json:"transaction"`
	} `json:"_links"`
	Hash   string `json:"hash"`
	Ledger int32  `json:"ledger"`
	Env    string `json:"envelope_xdr"`
	Result string `json:"result_xdr"`
	Meta   string `json:"result_meta_xdr"`
}

Jump to

Keyboard shortcuts

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