client

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2020 License: MIT Imports: 48 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SDKVersion      = "0.2.8"
	UserAgentHeader = "kin-user-agent"
)

Variables

View Source
var (
	// Query errors.
	ErrAccountExists       = errors.New("account already exists")
	ErrAccountDoesNotExist = errors.New("account does not exist")
	ErrTransactionNotFound = errors.New("transaction not found")

	// Transaction errors.
	ErrMalformed               = errors.New("malformed transaction")
	ErrBadNonce                = errors.New("bad nonce")
	ErrInsufficientBalance     = errors.New("insufficient balance")
	ErrInsufficientFee         = errors.New("insufficient fee")
	ErrSenderDoesNotExist      = errors.New("sender account does not exist")
	ErrDestinationDoesNotExist = errors.New("destination account does not exist")
	ErrInvalidSignature        = errors.New("invalid signature")

	// Invoice Errors
	ErrAlreadyPaid      = errors.New("invoice already paid")
	ErrWrongDestination = errors.New("wrong destination")
	ErrSKUNotFound      = errors.New("sku not found")

	ErrNoSubsidizer        = errors.New("no subsidizer available")
	ErrPayerRequired       = errors.New("payer required")
	ErrTransactionRejected = errors.New("transaction rejected")
	ErrAlreadySubmitted    = errors.New("transaction already submitted")
)

Functions

func EventsHandler

func EventsHandler(secret string, f EventsFunc) http.HandlerFunc

EventsHandler returns an http.HandlerFunc that decodes and verifies an Events webhook call, before forwarding it to the specified EventsFunc.

func KinToQuarks

func KinToQuarks(val string) (int64, error)

KinToQuarks converts a string representation of kin the quark value.

An error is returned if the value string is invalid, or it cannot be accurately represented as quarks. For example, a value smaller than quarks, or a value _far_ greater than the supply.

func MustKinToQuarks

func MustKinToQuarks(val string) int64

MustKinToQuarks calls KinToQuarks, panicking if there's an error.

This should only be used if you know for sure this will not panic.

func QuarksToKin

func QuarksToKin(amount int64) string

QuarksToKin converts an int64 amount of quarks to the string representation of kin.

func SignTransactionHandler

func SignTransactionHandler(env Environment, secret string, f SignTransactionFunc) http.HandlerFunc

SignTransactionHandler returns an http.HandlerFunc that decodes and verifies a signtransaction webhook call, before forwarding it to the specified SignTransactionFunc.

Types

type AccountResolution added in v0.2.3

type AccountResolution int

AccountResolution is used to indicate which type of account resolution should be used if a transaction on Kin 4 fails due to an account being unavailable.

const (
	// AccountResolutionExact indicates no account resolution will be used.
	AccountResolutionExact AccountResolution = iota

	// AccountResolutionPreferred indicates that in the case an account is not found, the client will reattempt
	// submission with any resolved token accounts.
	//
	// When used for a sender key in a payment or earn request, if Agora is able to resolve the original sender public
	// key to a set of token accounts, the original sender will be used as the owner in the Solana transfer
	// instruction and the first resolved token account will be used as the sender.
	//
	// When used for a destination key in a payment or earn request, if Agora is able to resolve the destination key to
	// a set of token accounts, the first resolved token account will be used as the destination in the Solana transfer
	// instruction.
	AccountResolutionPreferred
)

type Client

type Client interface {
	// CreateAccount creates a kin account.
	CreateAccount(ctx context.Context, key PrivateKey, opts ...SolanaOption) (err error)

	// GetBalance returns the balance of a kin account in quarks.
	//
	// ErrAccountDoesNotExist is returned if no account exists.
	GetBalance(ctx context.Context, account PublicKey, opts ...SolanaOption) (quarks int64, err error)

	// ResolveTokenAccounts resolves the token accounts owned by an account on Kin 4.
	ResolveTokenAccounts(ctx context.Context, account PublicKey) ([]PublicKey, error)

	// GetTransaction returns the TransactionData for a given transaction hash.
	//
	// ErrTransactionNotFound is returned if no transaction exists for the hash.
	GetTransaction(ctx context.Context, txHash []byte, opts ...SolanaOption) (data TransactionData, err error)

	// SubmitPayment submits a single payment to a specified kin account.
	SubmitPayment(ctx context.Context, payment Payment, opts ...SolanaOption) (txHash []byte, err error)

	// SubmitEarnBatch submits a batch of earn payments.
	//
	// The batch may be done in on or more transactions.
	SubmitEarnBatch(ctx context.Context, batch EarnBatch, opts ...SolanaOption) (result EarnBatchResult, err error)
}

func New

func New(env Environment, opts ...ClientOption) (Client, error)

New creates a new client.

todo: appIndex optional, can use string memo instead

type ClientOption

type ClientOption func(*clientOpts)

ClientOption configures a Client.

func WithAppIndex

func WithAppIndex(index uint16) ClientOption

WithAppIndex specifies the app index to use when submitting transactions with Invoices, _or_ to use the non-text based memo format.

func WithDefaultCommitment added in v0.2.3

func WithDefaultCommitment(defaultCommitment commonpbv4.Commitment) ClientOption

WithDefaultCommitment specifies a default commitment to use for Kin 4 requests.

func WithDesiredKinVersion added in v0.2.3

func WithDesiredKinVersion(desiredVersion version.KinVersion) ClientOption

WithDesiredKinVersion specifies a minimum version to force Agora to use for testing purposes.

func WithEndpoint

func WithEndpoint(endpoint string) ClientOption

WithEndpoint specifies an endpoint to use.

It cannot be used alongside WithGRPC.

func WithGRPC

func WithGRPC(cc *grpc.ClientConn) ClientOption

WithGRPC specifies a grpc.ClientConn to use.

It cannot be used alongside WithEndpoint.

func WithKinVersion added in v0.2.2

func WithKinVersion(kinVersion version.KinVersion) ClientOption

WithKinVersion specifies the version of Kin to use.

If none is provided, the client will default to using the Kin 3 blockchain.

func WithMaxDelay

func WithMaxDelay(maxDelay time.Duration) ClientOption

WithMaxDelay specifies the maximum delay when retrying.

func WithMaxNonceRetries

func WithMaxNonceRetries(maxSequenceRetries uint) ClientOption

WithMaxNonceRetries specifies the maximum number of times the client will attempt to regenerate a nonce and retry a transaction.

This is independent from WithMaxRetries.

func WithMaxRetries

func WithMaxRetries(maxRetries uint) ClientOption

WithMaxRetries specifies the maximum number of retries the client will perform for transient errors.

func WithMinDelay

func WithMinDelay(minDelay time.Duration) ClientOption

WithMinDelay specifies the minimum delay when retrying.

func WithWhitelister

func WithWhitelister(whitelistKey PrivateKey) ClientOption

WithWhitelister specifies a whitelist key that will be used to co-sign all transactions.

type Earn

type Earn struct {
	Destination PublicKey
	Quarks      int64
	Invoice     *commonpb.Invoice
}

Earn represents a earn payment in an earn batch.

type EarnBatch

type EarnBatch struct {
	Sender  PrivateKey
	Channel *PrivateKey

	Memo string

	Earns []Earn

	// If DedupeID is set, the service will check to see if a transaction
	// was previously submitted with the same DedupeID. If one is found,
	// it will NOT submit the transaction again, and will return the status
	// of the previously submitted transaction.
	//
	// Only available on Kin 4.
	DedupeID []byte
}

EarnBatch is a batch of Earn payments coming from a single sender/source.

type EarnBatchResult

type EarnBatchResult struct {
	TxID []byte

	// If TxError is defined, the transaction failed.
	TxError error

	// EarnErrors contains any available earn-specific error information.
	//
	// EarnErrors may or may not be set if TxError is set.
	EarnErrors []EarnError
}

EarnBatchResult contains the result of an EarnBatch transaction.

type EarnError added in v0.3.0

type EarnError struct {
	EarnIndex int
	Error     error
}

type Environment

type Environment string

Environment specifies the desired Kin environment to use.

const (
	EnvironmentTest Environment = "test"
	EnvironmentProd Environment = "prod"
)

type EventsFunc

type EventsFunc func([]events.Event) error

EventsFunc is a callback function for the Events webhook.

If an error is returned, an InternalServer error is returned to Agora. Agora will retry a limited amount of times when an InternalServerError is returned.

type InternalClient

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

InternalClient is a low level client used for interacting with Agora directly. The API is _not_ stable and is not intend for general use.

It is exposed in case there needs to be low level access to Agora (beyond the gRPC client directly). However, there are no stability guarantees between releases, or during a migration event.

func NewInternalClient

func NewInternalClient(cc *grpc.ClientConn, retrier retry.Retrier, kinVersion version.KinVersion, desiredKinVersion version.KinVersion) *InternalClient

func (*InternalClient) CreateSolanaAccount added in v0.2.3

func (c *InternalClient) CreateSolanaAccount(ctx context.Context, key PrivateKey, commitment commonpbv4.Commitment, subsidizer PrivateKey) (err error)

func (*InternalClient) CreateStellarAccount

func (c *InternalClient) CreateStellarAccount(ctx context.Context, key PrivateKey) error

func (*InternalClient) GetBlockchainVersion

func (c *InternalClient) GetBlockchainVersion(ctx context.Context) (version.KinVersion, error)

func (*InternalClient) GetMinimumBalanceForRentException added in v0.2.3

func (c *InternalClient) GetMinimumBalanceForRentException(ctx context.Context, size uint64) (balance uint64, err error)

func (*InternalClient) GetRecentBlockhash added in v0.2.3

func (c *InternalClient) GetRecentBlockhash(ctx context.Context) (blockhash solana.Blockhash, err error)

func (*InternalClient) GetServiceConfig added in v0.2.3

func (c *InternalClient) GetServiceConfig(ctx context.Context) (resp *transactionpbv4.GetServiceConfigResponse, err error)

func (*InternalClient) GetSolanaAccountInfo added in v0.2.3

func (c *InternalClient) GetSolanaAccountInfo(ctx context.Context, account PublicKey, commitment commonpbv4.Commitment) (accountInfo *accountpbv4.AccountInfo, err error)

func (*InternalClient) GetStellarAccountInfo

func (c *InternalClient) GetStellarAccountInfo(ctx context.Context, account PublicKey) (*accountpb.AccountInfo, error)

func (*InternalClient) GetStellarTransaction added in v0.2.3

func (c *InternalClient) GetStellarTransaction(ctx context.Context, txHash []byte) (data TransactionData, err error)

func (*InternalClient) GetTransaction

func (c *InternalClient) GetTransaction(ctx context.Context, txID []byte, commitment commonpbv4.Commitment) (data TransactionData, err error)

func (*InternalClient) RequestAirdrop added in v0.2.3

func (c *InternalClient) RequestAirdrop(ctx context.Context, publicKey PublicKey, quarks uint64, commitment commonpbv4.Commitment) (txID []byte, err error)

func (*InternalClient) ResolveTokenAccounts added in v0.2.3

func (c *InternalClient) ResolveTokenAccounts(ctx context.Context, publicKey PublicKey) (accounts []PublicKey, err error)

func (*InternalClient) SubmitSolanaTransaction added in v0.2.3

func (c *InternalClient) SubmitSolanaTransaction(ctx context.Context, tx solana.Transaction, il *commonpb.InvoiceList, commitment commonpbv4.Commitment, dedupeId []byte) (result SubmitTransactionResult, err error)

func (*InternalClient) SubmitStellarTransaction

func (c *InternalClient) SubmitStellarTransaction(ctx context.Context, envelopeXDR []byte, invoiceList *commonpb.InvoiceList) (result SubmitTransactionResult, err error)

type Payment

type Payment struct {
	Sender      PrivateKey
	Destination PublicKey
	Type        kin.TransactionType
	Quarks      int64

	Channel *PrivateKey

	Invoice *commonpb.Invoice
	Memo    string

	// If DedupeID is set, the service will check to see if a transaction
	// was previously submitted with the same DedupeID. If one is found,
	// it will NOT submit the transaction again, and will return the status
	// of the previously submitted transaction.
	//
	// Only available on Kin 4.
	DedupeID []byte
}

Payment represents a kin payment.

type PrivateKey

type PrivateKey ed25519.PrivateKey

PrivateKey is an ed25519.PrivateKey.

func NewPrivateKey

func NewPrivateKey() (PrivateKey, error)

NewPrivateKey returns a new PrivateKey from derived from crypto/rand. The public key can be accessed via key.Public().

func PrivateKeyFromString

func PrivateKeyFromString(seed string) (PrivateKey, error)

PrivateKeyFromString parses a provided address, returning a PublicKey if successful.

The address may be either a Stellar encoded seed, or a base58 encoded string.

func (PrivateKey) Base58 added in v0.2.3

func (k PrivateKey) Base58() string

Base58 returns the base58-encoded private key

func (PrivateKey) Public

func (k PrivateKey) Public() PublicKey

Public returns the corresponding PublicKey.

type PublicKey

type PublicKey ed25519.PublicKey

PublicKey is an ed25519.PublicKey.

func PublicKeyFromString

func PublicKeyFromString(address string) (PublicKey, error)

PublicKeyFromString parses a provided address, returning a PublicKey if successful.

The address may be either a Stellar encoded address, or a base58 encoded string.

func (PublicKey) Base58 added in v0.2.3

func (k PublicKey) Base58() string

Base58 returns the base58-encoded public key

func (PublicKey) StellarAddress

func (k PublicKey) StellarAddress() string

StellarAddress returns the stellar address representation of the public key.

type ReadOnlyPayment

type ReadOnlyPayment struct {
	Sender      PublicKey
	Destination PublicKey
	Type        kin.TransactionType
	Quarks      int64

	Invoice *commonpb.Invoice
	Memo    string
}

ReadOnlyPayment represents a kin payment, where none of the private keys are known.

type SignTransactionFunc

type SignTransactionFunc func(SignTransactionRequest, *SignTransactionResponse) error

SignTransactionFunc is a callback function for the SignTransaction webhook.

If an error is returned, an InternalServer error is returned to Agora, and then back to the client.

To reject transactions based on specific invoice failures, use the Mark functions on the SignTransactionResponse.

To reject transactions without reason, use the Reject function on the SignTransactionResponse.

Authorized transactions should be signed with the Sign function.

type SignTransactionRequest

type SignTransactionRequest struct {
	// The Kin Version provided by the client (optional)
	// The UserID provided by the client (optional).
	UserID string
	// The UserPassKey provided by the client (optional).
	UserPasskey string

	// Payments is a set of payments that a client wishes to be signed.
	Payments []ReadOnlyPayment

	// Envelope is included _only_ for further validation by SDK consumers,
	// which is optional.
	//
	// It will only be set on stellar based transactions, and is _not_ a stable API.
	Envelope *xdr.TransactionEnvelope

	// SolanaTransaction is included _only_ for further validation by SDK consumers,
	// which is optional.
	//
	// It will only be set on Solana-based transactions, and is _not_ a stable API.
	SolanaTransaction *solana.Transaction
	// contains filtered or unexported fields
}

SignTransactionRequest contains the transaction and payment data that is requesting to be signed/approved.

func (*SignTransactionRequest) TxHash deprecated

func (s *SignTransactionRequest) TxHash() ([]byte, error)

Deprecated: TxHash() is deprecated. Use TxId() instead. TxHash returns the transaction hash of the transaction being signed.

func (*SignTransactionRequest) TxID added in v0.2.3

func (s *SignTransactionRequest) TxID() ([]byte, error)

TxID returns the ID of the transaction in this request.

It will either be a 32-byte Stellar transaction hash or a 64-byte Solana transaction signature.

type SignTransactionResponse

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

SignTransactionResponse contains the response information related to a request.

It is the primary mechanism in which a SignTransactionRequest can be signed or rejected.

func (*SignTransactionResponse) IsRejected

func (r *SignTransactionResponse) IsRejected() bool

IsRejected returns whether or not the transaction should be rejected, with or without reason.

func (*SignTransactionResponse) MarkAlreadyPaid

func (r *SignTransactionResponse) MarkAlreadyPaid(idx int)

MarkAlreadyPaid marks the Payment at index idx as paid.

This causes the entire transaction to be rejected.

func (*SignTransactionResponse) MarkSKUNotFound

func (r *SignTransactionResponse) MarkSKUNotFound(idx int)

MarkSKUNotFound marks the Payment at index idx as having the an unknown SKU value.

This causes the entire transaction to be rejected.

func (*SignTransactionResponse) MarkWrongDestination

func (r *SignTransactionResponse) MarkWrongDestination(idx int)

MarkWrongDestination marks the Payment at index idx as having the wrong destination.

This causes the entire transaction to be rejected.

func (*SignTransactionResponse) Reject

func (r *SignTransactionResponse) Reject()

Reject indicates the transaction should be rejected, without reason.

func (*SignTransactionResponse) Sign

func (r *SignTransactionResponse) Sign(priv PrivateKey) (err error)

Sign signs the underlying transaction with the specified private key. No-op on Kin 4 transactions.

type SolanaOption added in v0.2.3

type SolanaOption func(opts *solanaOpts)

ClientOption configures a solana-related function call.

func WithAccountResolution added in v0.2.5

func WithAccountResolution(resolution AccountResolution) SolanaOption

WithAccountResolution specifies an account resolution to use for a Kin 4 request. In the case of payments/earn batches, the specified resolution will be used only for the sender.

func WithCommitment added in v0.2.3

func WithCommitment(commitment commonpbv4.Commitment) SolanaOption

WithCommitment specifies a commitment to use for a Kin 4 request.

func WithDestResolution added in v0.2.3

func WithDestResolution(resolution AccountResolution) SolanaOption

WithDestResolution specifies an account resolution to use for Kin 4 payment/earn batch destinations.

func WithSubsidizer added in v0.2.3

func WithSubsidizer(subsidizer PrivateKey) SolanaOption

WithSubsidizer specifies a subsidizer to use for a Kin 4 transaction.

type SubmitTransactionResult added in v0.2.3

type SubmitTransactionResult struct {
	ID            []byte
	Errors        TransactionErrors
	InvoiceErrors []*commonpb.InvoiceError
}

type TransactionData

type TransactionData struct {
	TxID     []byte
	TxState  TransactionState
	Payments []ReadOnlyPayment
	Errors   TransactionErrors
}

TransactionData contains high level metadata and payments contained in a transaction.

type TransactionErrors

type TransactionErrors struct {
	TxError error

	// OpErrors may or may not be set if TxErrors is set. The length of
	// OpErrors will match the number of operations/instructions in the transaction.
	OpErrors []error

	// PaymentErrors may or may not be set if TxErrors is set. If set, the length of
	// PaymentErrors will match the number of payments/transfers in the transaction.
	PaymentErrors []error
}

TransactionErrors contains the error details for a transaction. If TxError is non-nil, the transaction failed.

type TransactionState added in v0.2.3

type TransactionState int
const (
	TransactionStateUnknown TransactionState = iota
	TransactionStateSuccess
	TransactionStateFailed
	TransactionStatePending
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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