solana

package
v1.10.4 Latest Latest
Warning

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

Go to latest
Published: May 1, 2024 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// PollRate is the rate at which blocks should be polled at.
	PollRate = (time.Second / slotsPerSec) / 2
)

Variables

View Source
var (
	ErrTooManySeeds          = errors.New("too many seeds")
	ErrMaxSeedLengthExceeded = errors.New("max seed length exceeded")

	ErrInvalidPublicKey = errors.New("invalid public key")
)
View Source
var (
	CommitmentProcessed = Commitment{Commitment: confirmationStatusProcessed}
	CommitmentConfirmed = Commitment{Commitment: confirmationStatusConfirmed}
	CommitmentFinalized = Commitment{Commitment: confirmationStatusFinalized}
)
View Source
var (
	ErrNoAccountInfo     = errors.New("no account info")
	ErrSignatureNotFound = errors.New("signature not found")
	ErrBlockNotAvailable = errors.New("block not available")
	ErrStaleData         = errors.New("rpc data is stale")
	ErrNoBalance         = errors.New("no balance")
)
View Source
var (
	ErrIncorrectProgram     = errors.New("incorrect program")
	ErrIncorrectInstruction = errors.New("incorrect instruction")
)

Functions

func CreateProgramAddress

func CreateProgramAddress(program ed25519.PublicKey, seeds ...[]byte) (ed25519.PublicKey, error)

CreateProgramAddress mirrors the implementation of the Solana SDK's CreateProgramAddress.

ProgramAddresses are public keys that _do not_ lie on the ed25519 curve to ensure that there is no associated private key. In the event that the program and seed parameters result in a valid public key, ErrInvalidPublicKey is returned.

Reference: https://github.com/solana-labs/solana/blob/5548e599fe4920b71766e0ad1d121755ce9c63d5/sdk/program/src/pubkey.rs#L158

func FindProgramAddress

func FindProgramAddress(program ed25519.PublicKey, seeds ...[]byte) (ed25519.PublicKey, error)

FindProgramAddress mirrors the implementation of the Solana SDK's FindProgramAddress. It only returns the address.

Reference: https://github.com/solana-labs/solana/blob/5548e599fe4920b71766e0ad1d121755ce9c63d5/sdk/program/src/pubkey.rs#L234

func FindProgramAddressAndBump

func FindProgramAddressAndBump(program ed25519.PublicKey, seeds ...[]byte) (ed25519.PublicKey, uint8, error)

FindProgramAddressAndBump mirrors the implementation of the Solana SDK's FindProgramAddress. It returns the address and bump seed.

Reference: https://github.com/solana-labs/solana/blob/5548e599fe4920b71766e0ad1d121755ce9c63d5/sdk/program/src/pubkey.rs#L234

Types

type AccountInfo

type AccountInfo struct {
	Data       []byte
	Owner      ed25519.PublicKey
	Lamports   uint64
	Executable bool
}

AccountInfo contains the Solana account information (not to be confused with a TokenAccount)

type AccountMeta

type AccountMeta struct {
	PublicKey  ed25519.PublicKey
	IsSigner   bool
	IsWritable bool
	// contains filtered or unexported fields
}

AccountMeta represents the account information required for building transactions.

func NewAccountMeta

func NewAccountMeta(pub ed25519.PublicKey, isSigner bool) AccountMeta

NewAccountMeta creates a new AccountMeta representing a writable account.

func NewReadonlyAccountMeta

func NewReadonlyAccountMeta(pub ed25519.PublicKey, isSigner bool) AccountMeta

NewAccountMeta creates a new AccountMeta representing a readonly account.

type Block

type Block struct {
	Hash       []byte
	PrevHash   []byte
	ParentSlot uint64
	Slot       uint64

	BlockTime    *time.Time
	Transactions []BlockTransaction
}

type BlockTransaction

type BlockTransaction struct {
	Transaction Transaction
	Err         *TransactionError
	Meta        *TransactionMeta
}

type Blockhash

type Blockhash [sha256.Size]byte

type Client

type Client interface {
	GetAccountInfo(ed25519.PublicKey, Commitment) (AccountInfo, error)
	GetAccountDataAfterBlock(ed25519.PublicKey, uint64) ([]byte, uint64, error)
	GetBalance(ed25519.PublicKey) (uint64, error)
	GetBlock(slot uint64) (*Block, error)
	GetBlockSignatures(slot uint64) ([]string, error)
	GetBlockTime(block uint64) (time.Time, error)
	GetConfirmationStatus(Signature, Commitment) (bool, error)
	GetConfirmedBlock(slot uint64) (*Block, error)
	GetConfirmedBlocksWithLimit(start, limit uint64) ([]uint64, error)
	GetConfirmedTransaction(Signature) (ConfirmedTransaction, error)
	GetMinimumBalanceForRentExemption(size uint64) (lamports uint64, err error)
	GetLatestBlockhash() (Blockhash, error)
	GetSignatureStatus(Signature, Commitment) (*SignatureStatus, error)
	GetSignatureStatuses([]Signature) ([]*SignatureStatus, error)
	GetSignaturesForAddress(owner ed25519.PublicKey, commitment Commitment, limit uint64, before, until string) ([]*TransactionSignature, error)
	GetSlot(Commitment) (uint64, error)
	GetTokenAccountBalance(ed25519.PublicKey) (uint64, uint64, error)
	GetTokenAccountsByOwner(owner, mint ed25519.PublicKey) ([]ed25519.PublicKey, error)
	GetTransaction(Signature, Commitment) (ConfirmedTransaction, error)
	GetTransactionTokenBalances(Signature) (TransactionTokenBalances, error)
	GetFilteredProgramAccounts(program ed25519.PublicKey, offset uint, filterValue []byte) ([]string, uint64, error)
	RequestAirdrop(ed25519.PublicKey, uint64, Commitment) (Signature, error)
	SubmitTransaction(Transaction, Commitment) (Signature, error)
}

Client provides an interaction with the Solana JSON RPC API.

Reference: https://docs.solana.com/apps/jsonrpc-api

func New

func New(endpoint string) Client

New returns a client using the specified endpoint.

func NewWithRPCOptions

func NewWithRPCOptions(endpoint string, opts *jsonrpc.RPCClientOpts) Client

NewWithRPCOptions returns a client configured with the specified RPC options.

type Commitment

type Commitment struct {
	Commitment string `json:"commitment"`
}

type CompiledInstruction

type CompiledInstruction struct {
	ProgramIndex byte
	Accounts     []byte
	Data         []byte
}

CompiledInstruction represents an instruction that has been compiled into a transaction.

type ConfirmedTransaction

type ConfirmedTransaction struct {
	Slot        uint64
	BlockTime   *time.Time
	Transaction Transaction
	Err         *TransactionError
	Meta        *TransactionMeta
}

type CustomError

type CustomError int

CustomError is the numerical error returned by a non-system program.

func (CustomError) Error

func (c CustomError) Error() string

type Environment

type Environment string
const (
	EnvironmentDev  Environment = "https://api.devnet.solana.com"
	EnvironmentTest Environment = "https://api.testnet.solana.com"
	EnvironmentProd Environment = "https://api.mainnet-beta.solana.com"
)
type Header struct {
	NumSignatures     byte
	NumReadonlySigned byte
	NumReadOnly       byte
}

type Instruction

type Instruction struct {
	Program  ed25519.PublicKey
	Accounts []AccountMeta
	Data     []byte
}

Instruction represents a transaction instruction.

func NewInstruction

func NewInstruction(program, data ed25519.PublicKey, accounts ...AccountMeta) Instruction

NewInstruction creates a new instruction.

type InstructionError

type InstructionError struct {
	Index int
	Err   error
}

InstructionError indicates an instruction returned an error in a transaction.

func (InstructionError) CustomError

func (i InstructionError) CustomError() *CustomError

func (InstructionError) Error

func (i InstructionError) Error() string

func (InstructionError) ErrorKey

func (InstructionError) JSONString

func (i InstructionError) JSONString() string

type InstructionErrorKey

type InstructionErrorKey string

InstructionErrorKey is the string keys returned in an instruction error.

Source: https://github.com/solana-labs/solana/blob/4e2754341514cd181ae3f373cc2548bd22e918b8/sdk/program/src/instruction.rs#L23

const (
	InstructionErrorGenericError                   InstructionErrorKey = "GenericError"
	InstructionErrorInvalidArgument                InstructionErrorKey = "InvalidArgument"
	InstructionErrorInvalidInstructionData         InstructionErrorKey = "InvalidInstructionData"
	InstructionErrorInvalidAccountData             InstructionErrorKey = "InvalidAccountData"
	InstructionErrorAccountDataTooSmall            InstructionErrorKey = "AccountDataTooSmall"
	InstructionErrorInsufficientFunds              InstructionErrorKey = "InsufficientFunds"
	InstructionErrorIncorrectProgramID             InstructionErrorKey = "IncorrectProgramId"
	InstructionErrorMissingRequiredSignature       InstructionErrorKey = "MissingRequiredSignature"
	InstructionErrorAccountAlreadyInitialized      InstructionErrorKey = "AccountAlreadyInitialized"
	InstructionErrorUninitializedAccount           InstructionErrorKey = "UninitializedAccount"
	InstructionErrorUnbalancedInstruction          InstructionErrorKey = "UnbalancedInstruction"
	InstructionErrorModifiedProgramID              InstructionErrorKey = "ModifiedProgramId"
	InstructionErrorExternalAccountLamportSpend    InstructionErrorKey = "ExternalAccountLamportSpend"
	InstructionErrorExternalAccountDataModified    InstructionErrorKey = "ExternalAccountDataModified"
	InstructionErrorReadonlyLamportChange          InstructionErrorKey = "ReadonlyLamportChange"
	InstructionErrorReadonlyDataModified           InstructionErrorKey = "ReadonlyDataModified"
	InstructionErrorDuplicateAccountIndex          InstructionErrorKey = "DuplicateAccountIndex"
	InstructionErrorExecutableModified             InstructionErrorKey = "ExecutableModified"
	InstructionErrorRentEpochModified              InstructionErrorKey = "RentEpochModified"
	InstructionErrorNotEnoughAccountKeys           InstructionErrorKey = "NotEnoughAccountKeys"
	InstructionErrorAccountDataSizeChanged         InstructionErrorKey = "AccountDataSizeChanged"
	InstructionErrorAccountNotExecutable           InstructionErrorKey = "AccountNotExecutable"
	InstructionErrorAccountBorrowFailed            InstructionErrorKey = "AccountBorrowFailed"
	InstructionErrorAccountBorrowOutstanding       InstructionErrorKey = "AccountBorrowOutstanding"
	InstructionErrorDuplicateAccountOutOfSync      InstructionErrorKey = "DuplicateAccountOutOfSync"
	InstructionErrorCustom                         InstructionErrorKey = "Custom"
	InstructionErrorInvalidError                   InstructionErrorKey = "InvalidError"
	InstructionErrorExecutableDataModified         InstructionErrorKey = "ExecutableDataModified"
	InstructionErrorExecutableLamportChange        InstructionErrorKey = "ExecutableLamportChange"
	InstructionErrorExecutableAccountNotRentExempt InstructionErrorKey = "ExecutableAccountNotRentExempt"
	InstructionErrorUnsupportedProgramID           InstructionErrorKey = "UnsupportedProgramId"
	InstructionErrorCallDepth                      InstructionErrorKey = "CallDepth"
	InstructionErrorMissingAccount                 InstructionErrorKey = "MissingAccount"
	InstructionErrorReentrancyNotAllowed           InstructionErrorKey = "ReentrancyNotAllowed"
	InstructionErrorMaxSeedLengthExceeded          InstructionErrorKey = "MaxSeedLengthExceeded"
	InstructionErrorInvalidSeeds                   InstructionErrorKey = "InvalidSeeds"
	InstructionErrorInvalidRealloc                 InstructionErrorKey = "InvalidRealloc"
)

type LoadedAddresses

type LoadedAddresses struct {
	Writable []string `json:"writable"`
	Readonly []string `json:"readonly"`
}

type Message

type Message struct {
	Header          Header
	Accounts        []ed25519.PublicKey
	RecentBlockhash Blockhash
	Instructions    []CompiledInstruction
}

func (Message) Marshal

func (m Message) Marshal() []byte

func (*Message) Unmarshal

func (m *Message) Unmarshal(b []byte) (err error)

type Signature

type Signature [ed25519.SignatureSize]byte

type SignatureStatus

type SignatureStatus struct {
	Slot        uint64
	ErrorResult *TransactionError

	// Confirmations will be nil if the transaction has been rooted.
	Confirmations      *int
	ConfirmationStatus string
}

func (SignatureStatus) Confirmed

func (s SignatureStatus) Confirmed() bool

func (SignatureStatus) Finalized

func (s SignatureStatus) Finalized() bool

type SortableAccountMeta

type SortableAccountMeta []AccountMeta

SortableAccountMeta is a sortable []AccountMeta based on the solana transaction account sorting rules.

Reference: https://docs.solana.com/transaction#account-addresses-format

func (SortableAccountMeta) Len

func (s SortableAccountMeta) Len() int

Len is the number of elements in the collection.

func (SortableAccountMeta) Less

func (s SortableAccountMeta) Less(i int, j int) bool

Less reports whether the element with index i should sort before the element with index j.

func (SortableAccountMeta) Swap

func (s SortableAccountMeta) Swap(i int, j int)

Swap swaps the elements with indexes i and j.

type TokenAmount

type TokenAmount struct {
	Amount   string `json:"amount"`   // example: "49801500000",
	Decimals uint64 `json:"decimals"` // example: 5,
}

type TokenBalance

type TokenBalance struct {
	AccountIndex uint64      `json:"accountIndex"` // example: 2,
	Mint         string      `json:"mint"`         // example: "kinXdEcpDQeHPEuQnqmUgtYykqKGVFq6CeVX5iAHJq6",
	TokenAmount  TokenAmount `json:"uiTokenAmount"`
}

type Transaction

type Transaction struct {
	Signatures []Signature
	Message    Message
}

func NewTransaction

func NewTransaction(payer ed25519.PublicKey, instructions ...Instruction) Transaction

func (Transaction) Marshal

func (t Transaction) Marshal() []byte

func (*Transaction) SetBlockhash

func (t *Transaction) SetBlockhash(bh Blockhash)

func (*Transaction) Sign

func (t *Transaction) Sign(signers ...ed25519.PrivateKey) error

func (*Transaction) Signature

func (t *Transaction) Signature() []byte

func (*Transaction) String

func (t *Transaction) String() string

func (*Transaction) Unmarshal

func (t *Transaction) Unmarshal(b []byte) error

type TransactionError

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

TransactionError contains the transaction error details.

func NewTransactionError

func NewTransactionError(key TransactionErrorKey) *TransactionError

func ParseRPCError

func ParseRPCError(err *jsonrpc.RPCError) (*TransactionError, error)

ParseRPCError parses the jsonrpc.RPCError returned from a method.

func ParseTransactionError

func ParseTransactionError(raw interface{}) (*TransactionError, error)

ParseTransactionError parses the JSON error returned from the "err" field in various RPC methods and fields.

func TransactionErrorFromInstructionError

func TransactionErrorFromInstructionError(err *InstructionError) (*TransactionError, error)

func (TransactionError) Error

func (t TransactionError) Error() string

func (TransactionError) ErrorKey

func (TransactionError) InstructionError

func (t TransactionError) InstructionError() *InstructionError

func (TransactionError) JSONString

func (t TransactionError) JSONString() (string, error)

type TransactionErrorKey

type TransactionErrorKey string

TransactionErrorKey is the string key returned in a transaction error.

Source: https://github.com/solana-labs/solana/blob/fc2bf2d3b669d1c6655ae48b0a05f470938f3676/sdk/src/transaction/mod.rs#L37

const (
	TransactionErrorInternal TransactionErrorKey = "Internal" // Internal error

	TransactionErrorAccountInUse                 TransactionErrorKey = "AccountInUse"                 // An account is already being processed in another transaction in a way that does not support parallelism
	TransactionErrorAccountLoadedTwice           TransactionErrorKey = "AccountLoadedTwice"           // A `Pubkey` appears twice in the transaction's `account_keys`.  Instructions can reference `Pubkey`s more than once but the message must contain a list with no duplicate keys
	TransactionErrorAccountNotFound              TransactionErrorKey = "AccountNotFound"              // Attempt to debit an account but found no record of a prior credit.
	TransactionErrorProgramAccountNotFound       TransactionErrorKey = "ProgramAccountNotFound"       // Attempt to load a program that does not exist
	TransactionErrorInsufficientFundsForFee      TransactionErrorKey = "InsufficientFundsForFee"      // The from `Pubkey` does not have sufficient balance to pay the fee to schedule the transaction
	TransactionErrorInvalidAccountForFee         TransactionErrorKey = "InvalidAccountForFee"         // This account may not be used to pay transaction fees
	TransactionErrorDuplicateSignature           TransactionErrorKey = "DuplicateSignature"           // The bank has seen this transaction before. This can occur under normal operation when a UDP packet is duplicated, as a user error from a client not updating its `recent_blockhash`, or as a double-spend attack.
	TransactionErrorBlockhashNotFound            TransactionErrorKey = "BlockhashNotFound"            // The bank has not seen the given `recent_blockhash` or the transaction is too old and the `recent_blockhash` has been discarded.
	TransactionErrorInstructionError             TransactionErrorKey = "InstructionError"             // An error occurred while processing an instruction. The first element of the tuple indicates the instruction index in which the error occurred.
	TransactionErrorCallChainTooDeep             TransactionErrorKey = "CallChainTooDeep"             // Loader call chain is too deep
	TransactionErrorMissingSignatureForFee       TransactionErrorKey = "MissingSignatureForFee"       // Transaction requires a fee but has no signature present
	TransactionErrorInvalidAccountIndex          TransactionErrorKey = "InvalidAccountIndex"          // Transaction contains an invalid account reference
	TransactionErrorSignatureFailure             TransactionErrorKey = "SignatureFailure"             // Transaction did not pass signature verification
	TransactionErrorInvalidProgramForExecution   TransactionErrorKey = "InvalidProgramForExecution"   // This program may not be used for executing instructions
	TransactionErrorSanitizeFailure              TransactionErrorKey = "SanitizeFailure"              // Transaction failed to sanitize accounts offsets correctly implies that account locks are not taken for this TX, and should not be unlocked.
	TransactionErrorClusterMaintenance           TransactionErrorKey = "ClusterMaintenance"           // Transactions are currently disabled due to cluster maintenance
	TransactionErrorAccountBorrowOutstanding     TransactionErrorKey = "AccountBorrowOutstanding"     // Transaction processing left an account with an outstanding borrowed reference
	TransactionErrorWouldExceedMaxBlockCostLimit TransactionErrorKey = "WouldExceedMaxBlockCostLimit" // Transaction could not fit into current block without exceeding the Max Block Cost Limit
	TransactionErrorUnsupportedVersion           TransactionErrorKey = "UnsupportedVersion"           // Transaction version is unsupported
	TransactionErrorInvalidWritableAccount       TransactionErrorKey = "InvalidWritableAccount"       // Transaction loads a writable account that cannot be written
)

type TransactionMeta

type TransactionMeta struct {
	Err               interface{}     `json:"err"`
	Fee               uint64          `json:"fee"`
	PreBalances       []uint64        `json:"preBalances"`
	PostBalances      []uint64        `json:"postBalances"`
	PreTokenBalances  []TokenBalance  `json:"preTokenBalances"`
	PostTokenBalances []TokenBalance  `json:"postTokenBalances"`
	LoadedAddresses   LoadedAddresses `json:"loadedAddresses"`
}

type TransactionSignature

type TransactionSignature struct {
	Signature Signature
	Slot      uint64
	BlockTime *time.Time
	Err       *TransactionError
	Memo      *string
}

func (TransactionSignature) ToBase58

func (s TransactionSignature) ToBase58() string

type TransactionTokenBalances

type TransactionTokenBalances struct {
	Accounts          []string
	PreTokenBalances  []TokenBalance
	PostTokenBalances []TokenBalance
	Slot              uint64
	BlockTime         *time.Time
}

Directories

Path Synopsis
timelock
v1

Jump to

Keyboard shortcuts

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