solana

package module
v1.0.1-beta.1 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2021 License: Apache-2.0 Imports: 17 Imported by: 1,055

README

Solana library for Go

Go library to interface with Solana nodes's JSON-RPC interface, Solana's SPL tokens and the Serum DEX instructions. More contracts to come.

Installation

solana-go works using SemVer but in 0 version, which means that the 'minor' will be changed when some broken changes are introduced into the application, and the 'patch' will be changed when a new feature with new changes is added or for bug fixing. As soon as v1.0.0 be released, solana-go will start to use SemVer as usual.

  1. Install from https://github.com/gagliardetto/solana-go/releases

or

  1. Install using Homebrew on macOS
$ brew install dfuse-io/tap/solana-go
  1. Build from source with:
$ go get -u -v github.com/gagliardetto/solana-go/cmd/slnc

Command-line

$ slnc get balance EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
1461600 lamports

$ slnc get account EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
{
  "lamports": 1461600,
  "data": [
    "AQAAABzjWe1aAS4E+hQrnHUaHF6Hz9CgFhuchf/TG3jN/Nj2gCa3xLwWAAAGAQEAAAAqnl7btTwEZ5CY/3sSZRcUQ0/AjFYqmjuGEQXmctQicw==",
    "base64"
  ],
  "owner": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
  "executable": false,
  "rentEpoch": 108
}

$ slnc spl get mint SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt
Supply               9999647664800000
Decimals             6
No mint authority
No freeze authority

$ slnc serum list markets
...
ALEPH/USDT   EmCzMQfXMgNHcnRoFwAdPe1i2SuiSzMj1mx6wu3KN2uA
ALEPH/WUSDC  B37pZmwrwXHjpgvd9hHDAx1yeDsNevTnbbrN9W12BoGK
BTC/USDT     8AcVjMG2LTbpkjNoyq8RwysokqZunkjy3d5JDzxC6BJa
BTC/WUSDC    CAgAeMD7quTdnr6RPa7JySQpjf3irAmefYNdTb6anemq
ETH/USDT     HfCZdJ1wfsWKfYP2qyWdXTT5PWAGWFctzFjLH48U1Hsd
ETH/WUSDC    ASKiV944nKg1W9vsf7hf3fTsjawK6DwLwrnB2LH9n61c
SOL/USDT     8mDuvJJSgoodovMRYArtVVYBbixWYdGzR47GPrRT65YJ
SOL/WUSDC    Cdp72gDcYMCLLk3aDkPxjeiirKoFqK38ECm8Ywvk94Wi
...

$ slnc serum get market 7JCG9TsCx3AErSV3pvhxiW4AbkKRcJ6ZAveRmJwrgQ16
Price    Quantity  Depth
Asks
...
527.06   444.09    ####################
393.314  443.52    ###############
463.158  443.17    ###########
200      442.63    ######
234.503  442.54    ####
50       441.86    ##
61.563   441.47    #
84.377   440.98
-------  --------
10       439.96
193.303  439.24    ##
50       438.94    ##
0.5      438.87    ##
247.891  437.65    #####
458.296  436.99    #########
452.693  435.68    ##############
372.722  435.12    ##################
0.043    431.94    ##################
...

Library usage

Loading an SPL mint


import "github.com/gagliardetto/solana-go/rpc"
import "github.com/gagliardetto/solana-go/token"

	addr := solana.MustPublicKeyFromBase58("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
	cli := rpc.NewClient("http://api.mainnet-beta.solana.com/rpc")

	var m token.Mint
	err := cli.GetAccountDataIn(context.Background(), addr, &m)
	// handle `err`

	json.NewEncoder(os.Stdout).Encode(m)
	// {"OwnerOption":1,
	//  "Owner":"2wmVCSfPxGPjrnMMn7rchp4uaeoTqN39mXFC2zhPdri9",
	//  "Decimals":128,
	//  "IsInitialized":true}

Getting any account's data:


import "github.com/gagliardetto/solana-go/rpc"
import "github.com/gagliardetto/solana-go/token"

	addr := solana.MustPublicKeyFromBase58("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
	cli := rpc.NewClient("http://api.mainnet-beta.solana.com/rpc")

	acct, err := cli.GetAccountInfo(context.Background(), addr)
	// handle `err`

	json.NewEncoder(os.Stdout).Encode(m)
// {
//   "context": {
//     "Slot": 47836700
//   },
//   "value": {
//     "lamports": 1461600,
//     "data": {
//       "data": "AQAAABzjWe1aAS4E+hQrnHUaHF6Hz9CgFhuchf/TG3jN/Nj2gCa3xLwWAAAGAQEAAAAqnl7btTwEZ5CY/3sSZRcUQ0/AjFYqmjuGEQXmctQicw==",
//       "encoding": "base64"
//     },
//     "owner": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
//     "executable": false,
//     "rentEpoch": 109
//   }
// }

Contributing

Any contributions are welcome, use your standard GitHub-fu to pitch in and improve.

License

Apache 2.0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var InstructionDecoderRegistry = map[string]InstructionDecoder{}

Functions

func DecimalsInBigInt

func DecimalsInBigInt(decimal uint32) *big.Int

func DecodeInstruction

func DecodeInstruction(programID PublicKey, accounts []*AccountMeta, data []byte) (interface{}, error)

func NewRandomPrivateKey

func NewRandomPrivateKey() (PublicKey, PrivateKey, error)

func RegisterInstructionDecoder

func RegisterInstructionDecoder(programID PublicKey, decoder InstructionDecoder)

Types

type Account

type Account struct {
	PrivateKey PrivateKey
}

func AccountFromPrivateKeyBase58

func AccountFromPrivateKeyBase58(privateKey string) (*Account, error)

func NewAccount

func NewAccount() *Account

func (*Account) PublicKey

func (a *Account) PublicKey() PublicKey

type AccountMeta

type AccountMeta struct {
	PublicKey  PublicKey
	IsSigner   bool
	IsWritable bool
}

type AccountSettable

type AccountSettable interface {
	SetAccounts(accounts []*AccountMeta) error
}

type Base58

type Base58 []byte

/

func (Base58) MarshalJSON

func (t Base58) MarshalJSON() ([]byte, error)

func (Base58) String

func (t Base58) String() string

func (*Base58) UnmarshalJSON

func (t *Base58) UnmarshalJSON(data []byte) (err error)

type ByteWrapper

type ByteWrapper struct {
	io.Reader
}

/

func (*ByteWrapper) ReadByte

func (w *ByteWrapper) ReadByte() (byte, error)

type CompiledInstruction

type CompiledInstruction struct {
	// Index into the message.accountKeys array indicating the program account that executes this instruction.
	ProgramIDIndex uint8 `json:"programIdIndex"`

	AccountCount bin.Varuint16 `json:"-" bin:"sizeof=Accounts"`
	DataLength   bin.Varuint16 `json:"-" bin:"sizeof=Data"`

	// List of ordered indices into the message.accountKeys array indicating which accounts to pass to the program.
	Accounts []uint8 `json:"accounts"`

	// The program input data encoded in a base-58 string.
	Data Base58 `json:"data"`
}

func (*CompiledInstruction) ResolveInstructionAccounts

func (ci *CompiledInstruction) ResolveInstructionAccounts(message *Message) (out []*AccountMeta)

type Data

type Data struct {
	Content  []byte
	Encoding EncodingType
}

func (Data) MarshalJSON

func (t Data) MarshalJSON() ([]byte, error)

func (Data) String

func (t Data) String() string

func (*Data) UnmarshalJSON

func (t *Data) UnmarshalJSON(data []byte) (err error)

type EncodingType

type EncodingType string
const (
	EncodingBase58     EncodingType = "base58"      // limited to Account data of less than 129 bytes
	EncodingBase64     EncodingType = "base64"      // will return base64 encoded data for Account data of any size
	EncodingBase64Zstd EncodingType = "base64+zstd" // compresses the Account data using Zstandard and base64-encodes the result

	// attempts to use program-specific state parsers to
	// return more human-readable and explicit account state data.
	// If "jsonParsed" is requested but a parser cannot be found,
	// the field falls back to "base64" encoding, detectable when the data field is type <string>.
	// Cannot be used if specifying dataSlice parameters (offset, length).
	EncodingJSONParsed EncodingType = "jsonParsed"

	EncodingJSON EncodingType = "json" // NOTE: not usable in almost-all places.
)

type Hash

type Hash PublicKey

func HashFromBase58

func HashFromBase58(in string) (Hash, error)

func MustHashFromBase58

func MustHashFromBase58(in string) Hash

func (Hash) Equals

func (ha Hash) Equals(pb Hash) bool

func (Hash) IsZero

func (ha Hash) IsZero() bool

func (Hash) MarshalJSON

func (ha Hash) MarshalJSON() ([]byte, error)

func (Hash) String

func (ha Hash) String() string

func (*Hash) UnmarshalJSON

func (ha *Hash) UnmarshalJSON(data []byte) (err error)

type Instruction

type Instruction interface {
	Accounts() []*AccountMeta // returns the list of accounts the instructions requires
	ProgramID() PublicKey     // the programID the instruction acts on
	Data() ([]byte, error)    // the binary encoded instructions
}

type InstructionDecoder

type InstructionDecoder func(instructionAccounts []*AccountMeta, data []byte) (interface{}, error)

InstructionDecoder receives the AccountMeta FOR THAT INSTRUCTION, and not the accounts of the *Message object. Resolve with CompiledInstruction.ResolveInstructionAccounts(message) beforehand.

type Message

type Message struct {
	// List of base-58 encoded public keys used by the transaction,
	// including by the instructions and for signatures.
	// The first `message.header.numRequiredSignatures` public keys must sign the transaction.
	AccountKeys []PublicKey `json:"accountKeys"`

	// Details the account types and signatures required by the transaction.
	Header MessageHeader `json:"header"`

	// A base-58 encoded hash of a recent block in the ledger used to
	// prevent transaction duplication and to give transactions lifetimes.
	RecentBlockhash Hash `json:"recentBlockhash"`

	// List of program instructions that will be executed in sequence
	// and committed in one atomic transaction if all succeed.
	Instructions []CompiledInstruction `json:"instructions"`
}

func (*Message) AccountMetaList

func (m *Message) AccountMetaList() (out []*AccountMeta)

func (*Message) IsSigner

func (m *Message) IsSigner(account PublicKey) bool

func (*Message) IsWritable

func (m *Message) IsWritable(account PublicKey) bool

func (*Message) ResolveProgramIDIndex

func (m *Message) ResolveProgramIDIndex(programIDIndex uint8) (PublicKey, error)

func (*Message) TouchAccount

func (m *Message) TouchAccount(account PublicKey) bool

type MessageHeader

type MessageHeader struct {
	// The total number of signatures required to make the transaction valid.
	// The signatures must match the first `numRequiredSignatures` of `message.account_keys`.
	NumRequiredSignatures uint8 `json:"numRequiredSignatures"`

	// The last numReadonlySignedAccounts of the signed keys are read-only accounts.
	// Programs may process multiple transactions that load read-only accounts within
	// a single PoH entry, but are not permitted to credit or debit lamports or modify
	// account data.
	// Transactions targeting the same read-write account are evaluated sequentially.
	NumReadonlySignedAccounts uint8 `json:"numReadonlySignedAccounts"`

	// The last `numReadonlyUnsignedAccounts` of the unsigned keys are read-only accounts.
	NumReadonlyUnsignedAccounts uint8 `json:"numReadonlyUnsignedAccounts"`
}

type Padding

type Padding []byte

type PrivateKey

type PrivateKey []byte

func MustPrivateKeyFromBase58

func MustPrivateKeyFromBase58(in string) PrivateKey

func PrivateKeyFromBase58

func PrivateKeyFromBase58(privkey string) (PrivateKey, error)

func PrivateKeyFromSolanaKeygenFile

func PrivateKeyFromSolanaKeygenFile(file string) (PrivateKey, error)

func (PrivateKey) PublicKey

func (k PrivateKey) PublicKey() PublicKey

func (PrivateKey) Sign

func (k PrivateKey) Sign(payload []byte) (Signature, error)

func (PrivateKey) String

func (k PrivateKey) String() string

type PublicKey

type PublicKey [32]byte

func MustPublicKeyFromBase58

func MustPublicKeyFromBase58(in string) PublicKey

func PublicKeyFromBase58

func PublicKeyFromBase58(in string) (out PublicKey, err error)

func PublicKeyFromBytes

func PublicKeyFromBytes(in []byte) (out PublicKey)

func (PublicKey) Equals

func (p PublicKey) Equals(pb PublicKey) bool

func (PublicKey) IsZero

func (p PublicKey) IsZero() bool

func (PublicKey) MarshalJSON

func (p PublicKey) MarshalJSON() ([]byte, error)

func (PublicKey) String

func (p PublicKey) String() string

func (*PublicKey) UnmarshalJSON

func (p *PublicKey) UnmarshalJSON(data []byte) (err error)

type Signature

type Signature [64]byte

/

func MustSignatureFromBase58

func MustSignatureFromBase58(in string) Signature

func SignatureFromBase58

func SignatureFromBase58(in string) (out Signature, err error)

func (Signature) Equals

func (sig Signature) Equals(pb Signature) bool

func (Signature) IsZero

func (sig Signature) IsZero() bool

func (Signature) MarshalJSON

func (p Signature) MarshalJSON() ([]byte, error)

func (Signature) String

func (p Signature) String() string

func (*Signature) UnmarshalJSON

func (p *Signature) UnmarshalJSON(data []byte) (err error)

type Transaction

type Transaction struct {
	// A list of base-58 encoded signatures applied to the transaction.
	// The list is always of length `message.header.numRequiredSignatures` and not empty.
	// The signature at index `i` corresponds to the public key at index
	// `i` in `message.account_keys`. The first one is used as the transaction id.
	Signatures []Signature `json:"signatures"`

	// Defines the content of the transaction.
	Message Message `json:"message"`
}

func MustTransactionFromData

func MustTransactionFromData(in []byte) *Transaction

func NewTransaction

func NewTransaction(instructions []Instruction, blockHash Hash, opts ...TransactionOption) (*Transaction, error)

func TransactionFromData

func TransactionFromData(in []byte) (*Transaction, error)

func (*Transaction) AccountMetaList

func (t *Transaction) AccountMetaList() (out []*AccountMeta)

func (*Transaction) IsSigner

func (t *Transaction) IsSigner(account PublicKey) bool

func (*Transaction) IsWritable

func (t *Transaction) IsWritable(account PublicKey) bool

func (*Transaction) ResolveProgramIDIndex

func (t *Transaction) ResolveProgramIDIndex(programIDIndex uint8) (PublicKey, error)

func (*Transaction) Sign

func (t *Transaction) Sign(getter privateKeyGetter) (out []Signature, err error)

func (*Transaction) TouchAccount

func (t *Transaction) TouchAccount(account PublicKey) bool

type TransactionOption

type TransactionOption interface {
	// contains filtered or unexported methods
}

func TransactionPayer

func TransactionPayer(payer PublicKey) TransactionOption

Directories

Path Synopsis
cmd
programs
serum
Code generated by rice embed-go; DO NOT EDIT.
Code generated by rice embed-go; DO NOT EDIT.
token
Code generated by rice embed-go; DO NOT EDIT.
Code generated by rice embed-go; DO NOT EDIT.
rpc
ws

Jump to

Keyboard shortcuts

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