stellarnet

package module
v0.0.0-...-42803c1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2021 License: BSD-3-Clause Imports: 29 Imported by: 65

README

stellarnet

Testing

This package uses the vcr package to record http responses. Running

go test

will use the pre-recorded responses to the stellar horizon requests.

To run against the test horizon servers:

go test -live

To record new responses from the test horizon servers:

go test -record

This makes go test very fast (0.02s) as it doesn't hit the network at all. Currently, go test -live or go test -record takes 20s.

Forks

To make a link so the tests use keybase's fork of the horizon client:

ln -s $(GOPATH)/src/github.com/keybase/stellar-org $(GOPATH)/src/github.com/stellar/go

And to remove it:

rm $(GOPATH)/src/github.com/stellar/go

Documentation

Index

Constants

View Source
const (
	// StroopsPerLumen is the number of stroops in a lumen.
	StroopsPerLumen = 10000000
)

Variables

View Source
var ErrAddressNotSeed = errors.New("string provided is an address not a seed")

ErrAddressNotSeed is returned when the string is a stellar address, not a seed.

View Source
var ErrAssetAlreadyExists = errors.New("asset already exists")

ErrAssetAlreadyExists means an asset cannot be created because it already exists

View Source
var ErrAssetNotFound = errors.New("asset not found")

ErrAssetNotFound is returned if no asset matches a code/issuer pair.

View Source
var ErrBadSignature = errors.New("bad signature")

ErrBadSignature is returned if the signature fails verification.

View Source
var ErrDestinationAccountNotFound = errors.New("destination account not found")

ErrDestinationAccountNotFound is returned if there is no stellar account for a destinationaccount address.

View Source
var ErrInvalidOperation = errors.New("invalid stellar URI operation")

ErrInvalidOperation is returned if the URI operation is not supported.

View Source
var ErrInvalidScheme = errors.New("invalid stellar URI scheme")

ErrInvalidScheme is returned if the URI scheme is not web+stellar.

View Source
var ErrMemoExists = errors.New("memo already exists in this tx")

ErrMemoExists is returned if more than one memo is added to a Tx.

View Source
var ErrNoOps = errors.New("no operations in tx")

ErrNoOps means a Tx has no operations.

View Source
var ErrResourceNotFound = errors.New("resource not found")

ErrResourceNotFound is returned if there is no stellar resource found. It is a generic not found error.

View Source
var ErrSeedNotAddress = errors.New("string provided is a seed not an address")

ErrSeedNotAddress is returned when the string is a stellar seed, not an address.

View Source
var ErrSourceAccountNotFound = errors.New("source account not found")

ErrSourceAccountNotFound is returned if there is no stellar account for a source account address.

View Source
var ErrTimeBoundsExist = errors.New("time bounds already exist in this tx")

ErrTimeBoundsExist is returned if more than one time bounds is added to a Tx.

View Source
var ErrTxOpFull = errors.New("tx cannot hold more operations")

ErrTxOpFull is returned if an operation is added to a Tx that has 100 ops in it.

View Source
var ErrUnknownKeypairType = errors.New("unknown keypair type")

ErrUnknownKeypairType is returned if the string parses to an unknown keypair type.

View Source
var TimeoutHandler func()

TimeoutHandler will be called whenever a timeout error happens.

Functions

func AccountMergeAmount

func AccountMergeAmount(operationID string) (amount string, err error)

AccountMergeAmount returns the amount involved in a merge operation. If operationID does not point to a merge operation, the results are undefined.

func AccountSeqno

func AccountSeqno(address AddressStr) (uint64, error)

AccountSeqno returns the account sequence number.

func AssetBaseSummary

func AssetBaseSummary(a AssetBase) string

AssetBaseSummary returns a string summary of an asset.

func AvailableBalance

func AvailableBalance(balance string, subentryCount int) (string, error)

AvailableBalance determines the amount of the balance that could be sent to another account (leaving enough XLM in the sender's account to maintain the minimum balance).

func CheckTxID

func CheckTxID(txID string) (string, error)

CheckTxID validates and canonicalizes a transaction ID Transaction IDs are lowercase hex-encoded 32-byte strings.

func Client

func Client() *legacyClient

Client returns the legacyClient-wrapped horizon client.

func CompareStellarAmounts

func CompareStellarAmounts(amount1, amount2 string) (int, error)

CompareStellarAmounts compares amounts of stellar assets. Returns:

-1 if x <  y
 0 if x == y
+1 if x >  y

func ConvertOutsideToXLM

func ConvertOutsideToXLM(outsideAmount, rate string) (xlmAmount string, err error)

ConvertOutsideToXLM converts an amount of outside currency into an amount of lumens. `rate` is the amount of outside currency that 1 XLM is worth. Example: "0.9389014463" = PLN / XLM The result is rounded to 7 digits past the decimal (which is what XLM supports). The result returned can of a greater magnitude than XLM supports.

func ConvertXLMToOutside

func ConvertXLMToOutside(xlmAmount, rate string) (outsideAmount string, err error)

ConvertXLMToOutside converts an amount of lumens into an amount of outside currency. `rate` is the amount of outside currency that 1 XLM is worth. Example: "0.9389014463" = PLN / XLM The result is rounded to 7 digits past the decimal. The rounding is arbitrary but expected to be sufficient precision.

func CreateTrustline

func CreateTrustline(from SeedStr, assetCode string, assetIssuer AddressStr, limit string, baseFee uint64) (txID string, err error)

CreateTrustline submits a transaction to the stellar network to establish a trustline from an account to an asset.

func DeleteTrustline

func DeleteTrustline(from SeedStr, assetCode string, assetIssuer AddressStr, baseFee uint64) (txID string, err error)

DeleteTrustline submits a transaction to the stellar network to remove a trustline from an account.

func FeeString

func FeeString(fee int32) string

FeeString converts a horizon.Transaction.FeePaid int32 from stroops to a lumens string.

func FmtAmount

func FmtAmount(amount string, precisionTwo bool, rounding FmtRoundingBehavior) (string, error)

FmtAmount formats amount in a clear, precise manner, minimizing the length of the output string when possible.

func FmtCurrency

func FmtCurrency(amount string, rounding FmtRoundingBehavior, symbol string, postfix bool) (string, error)

FmtCurrency returns amount formatted with the currency symbol.

func FmtCurrencyWithCodeSuffix

func FmtCurrencyWithCodeSuffix(amount string, rounding FmtRoundingBehavior, code, symbol string, postfix bool) (string, error)

FmtCurrencyWithCodeSuffix will return a fiat currency amount formatted with its currency code suffix at the end, like "$123.12 CLP"

func GetStellarExchangeRate

func GetStellarExchangeRate(source, destination string) (string, error)

GetStellarExchangeRate takes two amounts, and returns the exchange rate of 1 source unit to destination units. This is useful for comparing two different assets on the Stellar network, say XLM and AnchorUSD.

func HashTx

func HashTx(tx xdr.Transaction) (string, error)

HashTx returns the hex transaction ID using the active network passphrase.

func HashTxEnvelope

func HashTxEnvelope(tx xdr.TransactionEnvelope) (string, error)

HashTxEnvelope returns the hex transaction ID using the active network passphrase.

func HorizonClient

func HorizonClient() *horizonclient.Client

HorizonClient returns the horizon client.

func HorizonStatus

func HorizonStatus() (horizonProtocol.Root, error)

HorizonStatus returns the root status information from the global horizon server.

func HorizonStatusForClient

func HorizonStatusForClient(client *horizonclient.Client) (horizonProtocol.Root, error)

HorizonStatusForClient returns the root status information from client's horizon server.

func IsMasterKeyActive

func IsMasterKeyActive(accountID AddressStr) (bool, error)

IsMasterKeyActive returns whether the account's master key can sign transactions. The return value is true for normal accounts and multi-sig setups. The return value is false for explicitly disabled accounts. The master key is considered active if both:

  • The master key signing weight is non-zero.
  • The combined weight of all signers satisfies the minimum signing weight required to sign an operation. (Any operation at all, not necessarily payment)

func MakeClient

func MakeClient(url string) *horizonclient.Client

MakeClient makes a horizon client. It is used internally for gclient but can be used when the default one in gclient isn't sufficient. For example, stellard uses this func to make clients to check the state of the primary and backup horizon servers. But in general, the gclient one should be used.

func MakeTimeboundsFromTime

func MakeTimeboundsFromTime(minTime time.Time, maxTime time.Time) txnbuild.Timebounds

MakeTimeboundsFromTime creates Timebounds from time.Time values.

func MakeTimeboundsWithMaxTime

func MakeTimeboundsWithMaxTime(maxTime time.Time) txnbuild.Timebounds

MakeTimeboundsWithMaxTime creates Timebounds with maxTime of type time.Time.

func Network

func Network() string

Network returns the horizon network

func NetworkPassphrase

func NetworkPassphrase() string

NetworkPassphrase returns the horizon network "passphrase"

func NewKeyPair

func NewKeyPair() (*keypair.Full, error)

NewKeyPair creates a new random stellar keypair.

func OpSummary

func OpSummary(op xdr.Operation, pastTense bool) string

OpSummary returns a string summary of an operation.

func ParseAmount

func ParseAmount(s string) (*big.Rat, error)

ParseAmount parses a decimal number into a big rational. Used instead of big.Rat.SetString because the latter accepts additional formats like "1/2" and "1e10".

func ParseStellarAmount

func ParseStellarAmount(s string) (int64, error)

ParseStellarAmount parses a decimal number into an int64 suitable for the stellar protocol (7 significant digits). See also stellar/go/amount#ParseInt64

func PathPaymentMaxValue

func PathPaymentMaxValue(amount string) (string, error)

PathPaymentMaxValue returns 105% * amount.

func PathPaymentSourceAmount

func PathPaymentSourceAmount(resultXDR string, opIndex int) (string, error)

PathPaymentSourceAmount unpacks a result XDR string and calculates the amount of the source asset that was spent by adding up all the offers.

func Ping

func Ping() (string, error)

Ping returns a formatted string of info about the horizon server that stellarnet is connected to.

func SendXLM

func SendXLM(from SeedStr, to AddressStr, amount, memoText string) (ledger int32, txid string, attempt int, err error)

SendXLM sends 'amount' lumens from 'from' account to 'to' account. If the recipient has no account yet, this will create it. memoText is a public memo.

func SetClient

func SetClient(c *horizonclient.Client)

SetClient sets the horizon client.

func SetClientAndNetwork

func SetClientAndNetwork(c *horizonclient.Client, n string)

SetClientAndNetwork sets the horizon client and network. Used by stellarnet/testclient.

func SetClientURL

func SetClientURL(url string)

SetClientURL sets the url for the horizon server this client connects to.

func SetClientURLAndNetwork

func SetClientURLAndNetwork(url string, n string)

SetClientURLAndNetwork sets the horizon client URL and network.

func SetNetwork

func SetNetwork(n string)

SetNetwork sets the horizon network.

func SignStellarURI

func SignStellarURI(uri string, seed SeedStr) (signedURI, signatureB64 string, err error)

SignStellarURI signs a stellar+web URI and returns the URI with the signature attached.

func StringFromStellarAmount

func StringFromStellarAmount(v int64) string

StringFromStellarAmount returns an "amount string" from the provided raw int64 value `v`.

func StringFromStellarXdrAmount

func StringFromStellarXdrAmount(v xdr.Int64) string

StringFromStellarXdrAmount returns StringFromStellarAmount with casting to int64.

func TxDetails

func TxDetails(txID string) (horizonProtocol.Transaction, error)

TxDetails gets a horizonProtocol.Transaction for txID.

func TxPayments

func TxPayments(txID string) ([]operations.Payment, error)

TxPayments returns payment operations in a transaction. Note: may not return all payments as the backing response is paginated.

func UnvalidatedStellarURIOriginDomain

func UnvalidatedStellarURIOriginDomain(uri string) (originDomain string, err error)

UnvalidatedStellarURIOriginDomain returns just the origin_domain from a stellar URI. This is just for informational purposes.

func VerifyEnvelope

func VerifyEnvelope(txEnv xdr.TransactionEnvelope) error

VerifyEnvelope verifies that there is a SourceAccount signature in the envelope.

func WithinFactorStellarAmounts

func WithinFactorStellarAmounts(amount1, amount2, maxFactor string) (bool, error)

WithinFactorStellarAmounts returns whether two amounts are within a factor of `maxFactor` of each other. For example maxFactor="0.01" returns whether they are within 1% of each other. <- (abs((a - b) / a) < fac) || (abs((a - b) / b < fac)

func XDRAssetAmountSummary

func XDRAssetAmountSummary(amt xdr.Int64, asset xdr.Asset) string

XDRAssetAmountSummary returns a summary of an amount and an asset.

func XDRAssetSummary

func XDRAssetSummary(x xdr.Asset) string

XDRAssetSummary returns a string summary of an xdr.Asset.

func XDRChangeTrustAssetSummary

func XDRChangeTrustAssetSummary(x xdr.ChangeTrustAsset) string

XDRChangeTrustAssetSummary returns a string summary of an xdr.ChangeTrustAsset.

Types

type Account

type Account struct {
	// contains filtered or unexported fields
}

Account represents a Stellar account.

func NewAccount

func NewAccount(address AddressStr) *Account

NewAccount makes a new Account item for address.

func (*Account) Assets

func (a *Account) Assets() (res []horizonProtocolBase.Asset, complete bool, err error)

Assets returns the assets issued by the account. `complete` is false if there may be more assets.

func (*Account) AvailableBalanceXLM

func (a *Account) AvailableBalanceXLM() (string, error)

AvailableBalanceXLM returns the native lumen balance minus any required minimum balance.

func (*Account) BalanceXLM

func (a *Account) BalanceXLM() (string, error)

BalanceXLM returns the account's lumen balance.

func (*Account) Balances

func (a *Account) Balances() ([]horizonProtocol.Balance, error)

Balances returns all the balances for an account.

func (*Account) Details

func (a *Account) Details() (*AccountDetails, error)

Details returns AccountDetails for this account (minimizing horizon calls).

func (*Account) FindPaymentPaths

func (a *Account) FindPaymentPaths(to AddressStr, assetCode string, assetIssuer AddressStr, amount string) ([]FullPath, error)

FindPaymentPaths searches for path payments from the account object ownere and `to`, for a specific destination asset. It will return an error if the `to` recipient does not have a trustline for the destination asset. It will return paths using any of the `from` account's assets as the source asset.

func (*Account) RecentPayments

func (a *Account) RecentPayments(cursor string, limit int) ([]operations.Payment, error)

RecentPayments returns the account's recent payments. This is a summary of any recent payment transactions (payment, create_account, or account_merge). It does not contain as much information as RecentTransactionsAndOps. It is faster as it is only one request to horizon. cursor is optional. if specified, it is used for pagination. limit is optional. if not specified, default is 10. max limit is 100.

func (*Account) RecentTransactionsAndOps

func (a *Account) RecentTransactionsAndOps() ([]Transaction, error)

RecentTransactionsAndOps returns the account's recent transactions, for all types of transactions.

func (*Account) SubentryCount

func (a *Account) SubentryCount() (int, error)

SubentryCount returns the number of subentries in the account's ledger. Subentries affect the minimum balance.

func (*Account) Transactions

func (a *Account) Transactions(cursor string, limit int) (res []horizonProtocol.Transaction, finalPage bool, err error)

Transactions returns some of the account's transactions. cursor is optional. if specified, it is used for pagination. limit is optional. if not specified, default is 10. max limit is 100.

func (*Account) Trustlines

func (a *Account) Trustlines() ([]Trustline, error)

Trustlines returns all the trustlines for an account.

type AccountDetails

type AccountDetails struct {
	Seqno                string
	SubentryCount        int
	Available            string
	Balances             []horizonProtocol.Balance
	InflationDestination string
}

AccountDetails contains basic details about a stellar account.

type AddressStr

type AddressStr string

AddressStr is a string representation of a public stellar key.

func NewAddressStr

func NewAddressStr(s string) (AddressStr, error)

NewAddressStr ensures that s is a valid stellar address.

func (AddressStr) AccountID

func (s AddressStr) AccountID() (acctID xdr.AccountId, err error)

AccountID converts an AddressStr into an xdr.AccountId.

func (AddressStr) MuxedAccount

func (s AddressStr) MuxedAccount() (xdr.MuxedAccount, error)

MuxedAccount converts an AddressStr into an xdr.MuxedAccount.

func (AddressStr) String

func (s AddressStr) String() string

type AssetBase

type AssetBase interface {
	TypeString() string
	CodeString() string
	IssuerString() string
}

AssetBase is an interface that any of the various data structures can implement.

func PathAssetSliceToAssetBase

func PathAssetSliceToAssetBase(path []PathAsset) []AssetBase

PathAssetSliceToAssetBase converts []PathAsset to []AssetBase.

type AssetEmbed

type AssetEmbed struct {
	Links struct {
		WellKnown hal.Link `json:"toml"`
	} `json:"_links"`
	AssetType   string `json:"asset_type"`
	AssetCode   string `json:"asset_code"`
	AssetIssuer string `json:"asset_issuer"`
	PagingToken string `json:"paging_token"`
	Amount      string `json:"amount"`
	NumAccounts int    `json:"num_accounts"`
	Flags       struct {
		AuthRequired  bool `json:"auth_required"`
		AuthRevocable bool `json:"auth_revocable"`
	} `json:"flags"`
}

AssetEmbed is a single asset in the AssetsPage.

type AssetMinimal

type AssetMinimal struct {
	AssetType   string
	AssetCode   string
	AssetIssuer string
}

AssetMinimal is a bare-bones representation of an asset.

func ChangeTrustXDRToAssetMinimal

func ChangeTrustXDRToAssetMinimal(x xdr.ChangeTrustAsset) (AssetMinimal, error)

ChangeTrustXDRToAssetMinimal transforms xdr.ChangeTrustAsset to AssetMinimal.

func NewAssetMinimal

func NewAssetMinimal(code, issuer string) (AssetMinimal, error)

NewAssetMinimal makes an AssetMinimal, inferring the asset type from the length of the asset code.

func PathPaymentIntermediatePath

func PathPaymentIntermediatePath(envelopeXDR string, opIndex int) ([]AssetMinimal, error)

PathPaymentIntermediatePath unpacks an envelope XDR string to get the intermediate path assets. These are the intermediate assets that we used to form a payment path from the source asset to the destination asset. Note that the source asset and destination asset are not in this list. The order of the assets is from source asset to destination asset.

func XDRToAssetMinimal

func XDRToAssetMinimal(x xdr.Asset) (AssetMinimal, error)

XDRToAssetMinimal transforms xdr.Asset to AssetMinimal.

func (AssetMinimal) CodeString

func (a AssetMinimal) CodeString() string

CodeString implements AssetBase.

func (AssetMinimal) IssuerString

func (a AssetMinimal) IssuerString() string

IssuerString implements AssetBase.

func (AssetMinimal) TypeString

func (a AssetMinimal) TypeString() string

TypeString implements AssetBase.

type AssetSearchArg

type AssetSearchArg struct {
	AssetCode string // this is case sensitive
	IssuerID  string
}

AssetSearchArg is the argument for passing to AssetSearch

type AssetSummary

type AssetSummary struct {
	UnverifiedWellKnownLink string
	AssetType               string
	AssetCode               string
	AssetIssuer             string
	Amount                  string
	NumAccounts             int
}

AssetSummary summarizes the data returned by horizon for an asset. UnverifiedWellKnownLink is a link supplied by the asset issuer that needs verification.

func Asset

func Asset(assetCode string, issuerID AddressStr) (*AssetSummary, error)

Asset returns details about an asset that matches assetCode from issuerID.

func AssetList

func AssetList(cursor string, limit int, order string) (res []AssetSummary, nextCursor string, err error)

AssetList returns a list of assets from horizon (max 200 at a time). Order should be asc or desc. Continue calling this with the same order and the previous cursor to fetch all of them.

func AssetSearch

func AssetSearch(arg AssetSearchArg) (res []AssetSummary, err error)

AssetSearch returns assets from horizon that match either an asset code or an issuerID or both. It will not throw an error if there are no valid matches.

func AssetsWithCode

func AssetsWithCode(assetCode string) ([]AssetSummary, error)

AssetsWithCode returns all assets that use assetCode (e.g. 'USD') and throws an error if there are none.

func (*AssetSummary) CodeString

func (a *AssetSummary) CodeString() string

CodeString implements AssetBase.

func (*AssetSummary) IssuerString

func (a *AssetSummary) IssuerString() string

IssuerString implements AssetBase.

func (*AssetSummary) TypeString

func (a *AssetSummary) TypeString() string

TypeString implements AssetBase.

type AssetsPage

type AssetsPage struct {
	Links struct {
		Self hal.Link `json:"self"`
		Next hal.Link `json:"next"`
		Prev hal.Link `json:"prev"`
	} `json:"_links"`
	Embedded struct {
		Records []AssetEmbed `json:"records"`
	} `json:"_embedded"`
}

AssetsPage is a page of assets.

type Effect

type Effect struct {
	Type   string `json:"type"`
	Amount string `json:"amount"`
}

Effect is a single effect.

type EffectsPage

type EffectsPage struct {
	Embedded struct {
		Records []Effect
	} `json:"_embedded"`
}

EffectsPage is for decoding the effects.

type ErrInvalidParameter

type ErrInvalidParameter struct {
	Key string
}

ErrInvalidParameter is returned when a parameter is invalid.

func (ErrInvalidParameter) Error

func (e ErrInvalidParameter) Error() string

Error implements error for ErrInvalidParameter.

type ErrInvalidWellKnownOrigin

type ErrInvalidWellKnownOrigin struct {
	Wrapped error
}

ErrInvalidWellKnownOrigin is returned when there the well-known stellar.toml file is invalid for the purposes of web+stellar URIs.

func (ErrInvalidWellKnownOrigin) Error

type ErrMissingParameter

type ErrMissingParameter struct {
	Key string
}

ErrMissingParameter is returned when a required parameter is missing.

func (ErrMissingParameter) Error

func (e ErrMissingParameter) Error() string

Error implements error for ErrMissingParameter.

type ErrNetworkWellKnownOrigin

type ErrNetworkWellKnownOrigin struct {
	Wrapped error
}

ErrNetworkWellKnownOrigin is returned when there is a network error fetching the well-known stellar.toml file.

func (ErrNetworkWellKnownOrigin) Error

type Error

type Error struct {
	Display       string
	Details       string
	HorizonError  *horizonclient.Error
	OriginalError error
}

Error provides a hopefully user-friendly default in Error() but with some details that might actually help debug in Verbose().

func (Error) Error

func (e Error) Error() string

Error implements the error interface.

func (Error) Verbose

func (e Error) Verbose() string

Verbose returns additional details about the error.

type FeeStatFetcher

type FeeStatFetcher interface {
	FeeStatFetch() (FeeStatsResponse, error)
}

FeeStatFetcher contains FeeStatFetch, which will get a FeeStatsResponse.

type FeeStatsResponse

type FeeStatsResponse struct {
	LastLedger          string              `json:"last_ledger"`
	LastLedgerBaseFee   string              `json:"last_ledger_base_fee"`
	LedgerCapacityUsage string              `json:"ledger_capacity_usage"`
	FeeCharged          FeeStatsSubResponse `json:"fee_charged"`
	MaxFee              FeeStatsSubResponse `json:"max_fee"`
}

FeeStatsResponse describes the json response from the horizon /fee_stats endpoint (which is unfortunately all strings).

func (FeeStatsResponse) Convert

func (f FeeStatsResponse) Convert() (x NumericFeeStats, err error)

Convert converts a FeeStatsResponse into NumericFeeStats by converting all the strings to the appropriate numeric types.

type FeeStatsSubResponse

type FeeStatsSubResponse struct {
	Min  string `json:"min"`
	Max  string `json:"max"`
	Mode string `json:"mode"`
	P10  string `json:"p10"`
	P20  string `json:"p20"`
	P30  string `json:"p30"`
	P40  string `json:"p40"`
	P50  string `json:"p50"`
	P60  string `json:"p60"`
	P70  string `json:"p70"`
	P80  string `json:"p80"`
	P90  string `json:"p90"`
	P95  string `json:"p95"`
	P99  string `json:"p99"`
}

type FmtRoundingBehavior

type FmtRoundingBehavior int

FmtRoundingBehavior determines how the formatting functions handle excess precision, either rounding up/down, or truncating.

const (

	// Round the amount up or down.  1.234 => 1.23, 1.236 => 1.24
	Round FmtRoundingBehavior
	// Truncate the amount.  1.234 => 1.23, 1.236 => 1.23
	Truncate
)

type FullPath

type FullPath struct {
	SourceAmount           string      `json:"source_amount"`
	SourceAssetType        string      `json:"source_asset_type"`
	SourceAssetCode        string      `json:"source_asset_code"`
	SourceAssetIssuer      string      `json:"source_asset_issuer"`
	Path                   []PathAsset `json:"path"`
	DestinationAmount      string      `json:"destination_amount"`
	DestinationAssetType   string      `json:"destination_asset_type"`
	DestinationAssetCode   string      `json:"destination_asset_code"`
	DestinationAssetIssuer string      `json:"destination_asset_issuer"`
}

FullPath contains a potential path for a path payment.

func (FullPath) DestinationAsset

func (f FullPath) DestinationAsset() AssetMinimal

DestinationAsset returns an AssetMinimal version of the destination asset.

func (FullPath) SameAsset

func (f FullPath) SameAsset() bool

SameAsset returns true if source and destination assets are the same.

func (FullPath) SourceAsset

func (f FullPath) SourceAsset() AssetMinimal

SourceAsset returns an AssetMinimal version of the source asset.

type HTTPGetter

type HTTPGetter interface {
	Get(url string) (resp *http.Response, err error)
}

HTTPGetter is an interface for making GET http requests.

type HorizonFeeStatFetcher

type HorizonFeeStatFetcher struct{}

HorizonFeeStatFetcher is a FeeStatFetcher that uses a live horizon client.

func (*HorizonFeeStatFetcher) FeeStatFetch

func (h *HorizonFeeStatFetcher) FeeStatFetch() (FeeStatsResponse, error)

FeeStatFetch implements FeeStatFetcher.

type Memo

type Memo struct {
	Type       MemoType
	Text       *string
	ID         *uint64
	Hash       *MemoHash
	ReturnHash *MemoHash
}

Memo is very similar to xdr.Memo, but we'd like consumers of stellarnet to not have to know anything about xdr.

func NewMemoFromStrings

func NewMemoFromStrings(in, kind string) (*Memo, error)

NewMemoFromStrings returns a Memo converted from a string to the specified type.

func NewMemoHash

func NewMemoHash(h MemoHash) *Memo

NewMemoHash returns a Memo of type MemoTypeHash.

func NewMemoID

func NewMemoID(n uint64) *Memo

NewMemoID returns a Memo of type MemoTypeID.

func NewMemoNone

func NewMemoNone() *Memo

NewMemoNone returns a Memo of type MemoTypeNone.

func NewMemoReturn

func NewMemoReturn(h MemoHash) *Memo

NewMemoReturn returns a Memo of type MemoTypeReturn.

func NewMemoText

func NewMemoText(s string) *Memo

NewMemoText returns a Memo of type MemoTypeText.

func (*Memo) String

func (m *Memo) String() string

type MemoHash

type MemoHash [32]byte

MemoHash is a 32 byte hash value.

type MemoType

type MemoType int

MemoType is the kind of memo.

const (
	MemoTypeNone MemoType = iota
	MemoTypeText
	MemoTypeID
	MemoTypeHash
	MemoTypeReturn
)

These are the constants for the various memo types.

type NumericFeeStats

type NumericFeeStats struct {
	LastLedger          int32
	LastLedgerBaseFee   uint64
	LedgerCapacityUsage float64
	MinAcceptedFee      uint64
	ModeAcceptedFee     uint64
	P10AcceptedFee      uint64
	P20AcceptedFee      uint64
	P30AcceptedFee      uint64
	P40AcceptedFee      uint64
	P50AcceptedFee      uint64
	P60AcceptedFee      uint64
	P70AcceptedFee      uint64
	P80AcceptedFee      uint64
	P90AcceptedFee      uint64
	P95AcceptedFee      uint64
	P99AcceptedFee      uint64
}

NumericFeeStats is a numeric representation of the fee stats.

func FeeStats

func FeeStats(f FeeStatFetcher) (NumericFeeStats, error)

FeeStats returns NumericFeeStats given a FeeStatFetcher.

type Operation

type Operation struct {
	ID              string    `json:"id"`
	PagingToken     string    `json:"paging_token"`
	SourceAccount   string    `json:"source_account"`
	Type            string    `json:"type"`
	CreatedAt       time.Time `json:"created_at"`
	TransactionHash string    `json:"transaction_hash"`

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

	// payment fields
	AssetType string `json:"asset_type"`
	From      string `json:"from"`
	To        string `json:"to"`
	Amount    string `json:"amount"`
}

Operation is a single operation in a transaction.

type OperationsPage

type OperationsPage struct {
	Links struct {
		Self hal.Link `json:"self"`
		Next hal.Link `json:"next"`
		Prev hal.Link `json:"prev"`
	} `json:"_links"`
	Embedded struct {
		Records []Operation `json:"records"`
	} `json:"_embedded"`
}

OperationsPage is used to unmarshal the results from a transaction's operations endpoint.

type PathAsset

type PathAsset struct {
	AssetType   string `json:"asset_type"`
	AssetCode   string `json:"asset_code"`
	AssetIssuer string `json:"asset_issuer"`
}

PathAsset is a path hop through which a path payment will go to get to its destination.

func (PathAsset) CodeString

func (p PathAsset) CodeString() string

CodeString implements AssetBase.

func (PathAsset) IssuerString

func (p PathAsset) IssuerString() string

IssuerString implements AssetBase.

func (PathAsset) TypeString

func (p PathAsset) TypeString() string

TypeString implements AssetBase.

type PathsPage

type PathsPage struct {
	Links struct {
		Self hal.Link `json:"self"`
		Next hal.Link `json:"next"`
		Prev hal.Link `json:"prev"`
	} `json:"_links"`
	Embedded struct {
		Records []FullPath `json:"records"`
	} `json:"_embedded"`
}

PathsPage is used to unmarshal the results from the /paths endpoint.

type PaymentsPage

type PaymentsPage struct {
	Links struct {
		Self hal.Link `json:"self"`
		Next hal.Link `json:"next"`
		Prev hal.Link `json:"prev"`
	} `json:"_links"`
	Embedded struct {
		Records []operations.Payment `json:"records"`
	} `json:"_embedded"`
}

PaymentsPage is used to unmarshal the results from the account payments endpoint.

type SeedStr

type SeedStr string

SeedStr is a string representation of a private stellar key.

func CreateCustomAsset

func CreateCustomAsset(source SeedStr, assetCode, limit, homeDomain string, xlmPrice string, baseFee uint64) (issuer, distributor SeedStr, err error)

CreateCustomAsset will create a new asset on the network. It will return two new account seeds: one for the issuing account, one for the distribution account.

If an error occurs after the issuer and distributor are funded, the issuer and distributor seeds will be returned along with any error so you can reclaim your funds.

func CreateCustomAssetWithKPs

func CreateCustomAssetWithKPs(source SeedStr, issuerPair, distPair *keypair.Full, assetCode, limit, homeDomain string, xlmPrice string, baseFee uint64) (issuer, distributor SeedStr, err error)

CreateCustomAssetWithKPs will create a new asset on the network using the specified issuerPair as the issuing account and distPair as the distribution account.

You should probably use CreateCustomAsset as it will make new issuer, dist for you, but this one can be handy in tests where you want to specify the issuer, dist keys.

func NewSeedStr

func NewSeedStr(s string) (SeedStr, error)

NewSeedStr ensures that s is a valid stellar seed.

func (SeedStr) Address

func (s SeedStr) Address() (AddressStr, error)

Address returns the public address for a seed.

func (SeedStr) SecureNoLogString

func (s SeedStr) SecureNoLogString() string

SecureNoLogString returns a native string representation of SeedStr. It should not be logged or persisted anywhere.

func (SeedStr) String

func (s SeedStr) String() string

type SequenceProvider

type SequenceProvider interface {
	SequenceForAccount(aid string) (int64, error)
}

SequenceProvider is the interface that other packages may implement to be used with the `AutoSequence` mutator.

type SignResult

type SignResult struct {
	Seqno  uint64
	Signed string // signed transaction (base64)
	TxHash string // transaction hash (hex)
}

SignResult contains the result of signing a transaction.

func AccountMergeTransaction

func AccountMergeTransaction(from SeedStr, to AddressStr,
	seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (res SignResult, err error)

AccountMergeTransaction creates a signed transaction to merge the account `from` into `to`. It will also create the `to` account if it does not already exist. If it does exist, and if the `from` account has custom assets, this transaction will include payments of all of the custom assets, and deletion of the `from` account's trustlines. AccountMergeTransaction will error if the `from` account has a balance for an asset that the `to` account does not "trust."

func CreateAccountXLMTransaction

func CreateAccountXLMTransaction(from SeedStr, to AddressStr, amount, memoText string,
	seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (res SignResult, err error)

CreateAccountXLMTransaction creates a signed transaction to fund an new account 'to' from 'from' with a starting balance of 'amount'.

func CreateAccountXLMTransactionWithMemo

func CreateAccountXLMTransactionWithMemo(from SeedStr, to AddressStr, amount string, memo *Memo, seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (res SignResult, err error)

CreateAccountXLMTransactionWithMemo creates a signed transaction to fund an new account 'to' from 'from' with a starting balance of 'amount'. It supports all memo types.

func CreateTrustlineTransaction

func CreateTrustlineTransaction(from SeedStr, assetCode string, assetIssuer AddressStr, limit string, seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (SignResult, error)

CreateTrustlineTransaction create a signed transaction to establish a trustline from the `from` account to assetCode/assetIssuer.

func DeleteTrustlineTransaction

func DeleteTrustlineTransaction(from SeedStr, assetCode string, assetIssuer AddressStr, seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (SignResult, error)

DeleteTrustlineTransaction create a signed transaction to remove a trustline from the `from` account to assetCode/assetIssuer.

func MakeOfferTransaction

func MakeOfferTransaction(from SeedStr, selling, buying xdr.Asset, amountToSell, price string, seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (SignResult, error)

MakeOfferTransaction creates a new offer transaction.

func PathPaymentTransaction

func PathPaymentTransaction(from SeedStr, to AddressStr, sendAsset AssetBase, sendAmountMax string, destAsset AssetBase, destAmount string, path []AssetBase, memoText string, seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (SignResult, error)

PathPaymentTransaction creates a signed transaction for a path payment.

func PathPaymentTransactionWithMemo

func PathPaymentTransactionWithMemo(from SeedStr, to AddressStr, sendAsset AssetBase, sendAmountMax string, destAsset AssetBase, destAmount string, path []AssetBase, memo *Memo, seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (SignResult, error)

PathPaymentTransactionWithMemo creates a signed transaction for a path payment. It supports all memo types.

func PaymentTransaction

func PaymentTransaction(from SeedStr, to AddressStr, asset AssetBase, amount, memoText string,
	seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (res SignResult, err error)

PaymentTransaction creates a signed transaction to send a payment from 'from' to 'to' for a custom asset.

func PaymentXLMTransaction

func PaymentXLMTransaction(from SeedStr, to AddressStr, amount, memoText string,
	seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (res SignResult, err error)

PaymentXLMTransaction creates a signed transaction to send a payment from 'from' to 'to' for 'amount' lumens.

func PaymentXLMTransactionWithMemo

func PaymentXLMTransactionWithMemo(from SeedStr, to AddressStr, amount string, memo *Memo,
	seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (res SignResult, err error)

PaymentXLMTransactionWithMemo creates a signed transaction to send a payment from 'from' to 'to' for 'amount' lumens. It supports all the memo types.

func RelocateTransaction

func RelocateTransaction(from SeedStr, to AddressStr, toIsFunded bool,
	memoID *uint64, seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (res SignResult, err error)

RelocateTransaction creates a signed transaction to merge the account `from` into `to`. Works even if `to` is not funded but in that case requires 2 XLM temporary reserve. If `toIsFunded` then this is just an account merge transaction. Otherwise the transaction is two operations: [create_account, account_merge].

func SetHomeDomainTransaction

func SetHomeDomainTransaction(from SeedStr, domain string, seqnoProvider SequenceProvider, timeBounds *txnbuild.Timebounds, baseFee uint64) (SignResult, error)

SetHomeDomainTransaction creates a "set options" transaction that will set the home domain for the `from` account.

func SetInflationDestinationTransaction

func SetInflationDestinationTransaction(from SeedStr, to AddressStr, seqnoProvider SequenceProvider,
	timeBounds *txnbuild.Timebounds, baseFee uint64) (SignResult, error)

SetInflationDestinationTransaction creates a "set options" transaction that will set the inflation destination for the `from` account to the `to` account.

func SignEnvelope

func SignEnvelope(from SeedStr, txEnv xdr.TransactionEnvelope) (SignResult, error)

SignEnvelope signs an xdr.TransactionEnvelope.

type SubmitResult

type SubmitResult struct {
	Ledger    int32
	TxID      string
	Attempt   int
	ResultXDR string
}

SubmitResult contains information about a tx after submission to the stellar network.

func Submit

func Submit(signed string) (res SubmitResult, err error)

Submit submits a signed transaction to horizon.

type Transaction

type Transaction struct {
	Internal   TransactionEmbed
	Operations []Operation
}

Transaction contains the TransactionEmbed from the horizon transactions endpoint and all the operations for the transaction.

type TransactionEmbed

type TransactionEmbed struct {
	horizon.Transaction
}

TransactionEmbed is used to get the Links in addition to the horizon.Transaction from the transactions endpoints.

type TransactionsPage

type TransactionsPage struct {
	Links struct {
		Self hal.Link `json:"self"`
		Next hal.Link `json:"next"`
		Prev hal.Link `json:"prev"`
	} `json:"_links"`
	Embedded struct {
		Records []TransactionEmbed `json:"records"`
	} `json:"_embedded"`
}

TransactionsPage is used to unmarshal the results from the account transactions endpoint.

type Trustline

type Trustline struct {
	base.Asset
	Limit string
}

Trustline describes a stellar trustline. It contains an asset and a limit.

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

Tx is a data structure used for making a Stellar transaction. After creating one with NewBaseTx(), add to it with the various Add* functions, and finally, Sign() it.

Any errors that occur during Add* functions are delayed to return when the Sign() function is called in order to make the transaction building code cleaner.

func NewBaseTx

func NewBaseTx(source AddressStr, seqnoProvider SequenceProvider, baseFee uint64) *Tx

NewBaseTx creates a Tx with the common transaction elements.

func (*Tx) AddAccountMergeOp

func (t *Tx) AddAccountMergeOp(to AddressStr)

AddAccountMergeOp adds an account_merge operation to the transaction.

func (*Tx) AddAssetPaymentOp

func (t *Tx) AddAssetPaymentOp(to AddressStr, asset xdr.Asset, amt string)

AddAssetPaymentOp adds a payment operation for a custom asset to the transaction.

func (*Tx) AddBuiltTimeBounds

func (t *Tx) AddBuiltTimeBounds(bt *txnbuild.Timebounds)

AddBuiltTimeBounds adds time bounds to the transaction with a *txnbuild.Timebounds.

func (*Tx) AddCreateAccountOp

func (t *Tx) AddCreateAccountOp(to AddressStr, amt string)

AddCreateAccountOp adds a create_account operation to the transaction.

func (*Tx) AddCreateTrustlineOp

func (t *Tx) AddCreateTrustlineOp(assetCode string, assetIssuer AddressStr, limit string)

AddCreateTrustlineOp adds a change_trust operation that will establish a trustline.

func (*Tx) AddDeleteTrustlineOp

func (t *Tx) AddDeleteTrustlineOp(assetCode string, assetIssuer AddressStr)

AddDeleteTrustlineOp adds a change_trust operation that will remove a trustline.

func (*Tx) AddHomeDomainOp

func (t *Tx) AddHomeDomainOp(domain string)

AddHomeDomainOp adds a set_options operation for setting the home domain for an account.

func (*Tx) AddInflationDestinationOp

func (t *Tx) AddInflationDestinationOp(to AddressStr)

AddInflationDestinationOp adds a set_options operation for the inflation destination to the transaction.

func (*Tx) AddMemo

func (t *Tx) AddMemo(memo *Memo)

AddMemo adds a memo to the transaction. There can only be one memo.

func (*Tx) AddMemoID

func (t *Tx) AddMemoID(id *uint64)

AddMemoID adds an ID memo to the transaction. There can only be one memo.

func (*Tx) AddMemoText

func (t *Tx) AddMemoText(memo string)

AddMemoText adds a text memo to the transaction. There can only be one memo.

func (*Tx) AddOfferOp

func (t *Tx) AddOfferOp(selling, buying xdr.Asset, amountToSell, priceIn string)

AddOfferOp adds a new manage_offer operation to the transaction.

func (*Tx) AddPathPaymentOp

func (t *Tx) AddPathPaymentOp(to AddressStr, sendAsset AssetBase, sendAmountMax string, destAsset AssetBase, destAmount string, path []AssetBase)

AddPathPaymentOp adds a path payment operation to the transaction.

func (*Tx) AddPaymentOp

func (t *Tx) AddPaymentOp(to AddressStr, amt string)

AddPaymentOp adds a payment operation to the transaction.

func (*Tx) AddTimeBounds

func (t *Tx) AddTimeBounds(min, max int64)

AddTimeBounds adds time bounds to the transaction.

func (*Tx) IsFull

func (t *Tx) IsFull() bool

IsFull returns true if there are already 100 operations in the transaction.

func (*Tx) Sign

func (t *Tx) Sign(from SeedStr) (SignResult, error)

Sign builds the transaction and signs it.

type ValidatedStellarURI

type ValidatedStellarURI struct {
	URI                  string
	Operation            string
	OriginDomain         string
	Message              string
	CallbackURL          string
	XDR                  string
	TxEnv                *xdr.TransactionEnvelope
	Recipient            string
	Amount               string
	AssetCode            string
	AssetIssuer          string
	Memo                 string
	MemoType             string
	Signed               bool
	ReplaceSourceAccount bool
	ReplaceSeqnum        bool
	UnknownReplaceFields bool
}

ValidatedStellarURI contains the origin domain that ValidateStellarURI confirmed

func ValidateStellarURI

func ValidateStellarURI(uri string, getter HTTPGetter) (*ValidatedStellarURI, error)

ValidateStellarURI will check the validity of a web+stellar SEP7 URI.

It will check that the parameters are valid and that the payload is signed with the appropriate key.

func (*ValidatedStellarURI) MemoExport

func (v *ValidatedStellarURI) MemoExport() (*Memo, error)

MemoExport returns a Memo type based on Memo, MemoType from the URI.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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