solana

package module
v1.22.0 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: Apache-2.0 Imports: 34 Imported by: 2,233

README ¶

Solana SDK library for Go

GoDoc GitHub tag (latest SemVer pre-release) Build Status Lint Status TODOs Go Report Card

Go library to interface with Solana JSON RPC and WebSocket interfaces.

More contracts to come.

If you're using/developing Solana programs written in Anchor Framework, you can use anchor-go to generate Golang clients

Contents

Features

  • Full JSON RPC API
  • Full WebSocket JSON streaming API
  • Wallet, account, and keys management
  • Clients for native programs
    • system
    • config
    • stake
    • vote
    • BPF Loader
    • Secp256k1
  • Clients for Solana Program Library (SPL)
  • Metaplex:
    • auction
    • metaplex
    • token-metadata
    • token-vault
    • nft-candy-machine
  • More programs

Current development status

There is currently no stable release. The SDK is actively developed and latest is v1.16.0 which is an alpha release.

The RPC and WS client implementation is based on the Solana RPC API documentation.

Note

  • solana-go is in active development, so all APIs are subject to change.
  • This code is unaudited. Use at your own risk.

Requirements

  • Go 1.24 or later

Installation

$ cd my-project
$ go get github.com/gagliardetto/solana-go@v1.16.0

Pretty-Print transactions/instructions

pretty-printed

Instructions can be pretty-printed with the String() method on a Transaction:

tx, err := solana.NewTransaction(
  []solana.Instruction{
    system.NewTransferInstruction(
      amount,
      accountFrom.PublicKey(),
      accountTo,
    ).Build(),
  },
  recent.Value.Blockhash,
  solana.TransactionPayer(accountFrom.PublicKey()),
)

...

// Pretty print the transaction:
fmt.Println(tx.String())
// OR you can choose a destination and a title:
// tx.EncodeTree(text.NewTreeEncoder(os.Stdout, "Transfer SOL"))

SendAndConfirmTransaction

You can wait for a transaction confirmation using the github.com/gagliardetto/solana-go/rpc/sendAndConfirmTransaction package tools (for a complete example: see here)

// Send transaction, and wait for confirmation:
sig, err := confirm.SendAndConfirmTransaction(
  context.TODO(),
  rpcClient,
  wsClient,
  tx,
)
if err != nil {
  panic(err)
}
spew.Dump(sig)

The above command will send the transaction, and wait for its confirmation.

Address Lookup Tables

Resolve lookups for a transaction:

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/davecgh/go-spew/spew"
	"github.com/gagliardetto/solana-go"
	lookup "github.com/gagliardetto/solana-go/programs/address-lookup-table"
	"github.com/gagliardetto/solana-go/rpc"
	"golang.org/x/time/rate"
)

func main() {
	cluster := rpc.MainNetBeta

	rpcClient := rpc.NewWithCustomRPCClient(rpc.NewWithLimiter(
		cluster.RPC,
		rate.Every(time.Second), // time frame
		5,                       // limit of requests per time frame
	))

	version := uint64(0)
	tx, err := rpcClient.GetTransaction(
		context.Background(),
		solana.MustSignatureFromBase58("24jRjMP3medE9iMqVSPRbkwfe9GdPmLfeftKPuwRHZdYTZJ6UyzNMGGKo4BHrTu2zVj4CgFF3CEuzS79QXUo2CMC"),
		&rpc.GetTransactionOpts{
			MaxSupportedTransactionVersion: &version,
			Encoding:                       solana.EncodingBase64,
		},
	)
	if err != nil {
		panic(err)
	}
	parsed, err := tx.Transaction.GetTransaction()
	if err != nil {
		panic(err)
	}
	processTransactionWithAddressLookups(parsed, rpcClient)
}

func processTransactionWithAddressLookups(txx *solana.Transaction, rpcClient *rpc.Client) {
	if !txx.Message.IsVersioned() {
		fmt.Println("tx is not versioned; only versioned transactions can contain lookups")
		return
	}
	tblKeys := txx.Message.GetAddressTableLookups().GetTableIDs()
	if len(tblKeys) == 0 {
		fmt.Println("no lookup tables in versioned transaction")
		return
	}
	numLookups := txx.Message.GetAddressTableLookups().NumLookups()
	if numLookups == 0 {
		fmt.Println("no lookups in versioned transaction")
		return
	}
	fmt.Println("num lookups:", numLookups)
	fmt.Println("num tbl keys:", len(tblKeys))
	resolutions := make(map[solana.PublicKey]solana.PublicKeySlice)
	for _, key := range tblKeys {
		fmt.Println("Getting table", key)

		info, err := rpcClient.GetAccountInfo(
			context.Background(),
			key,
		)
		if err != nil {
			panic(err)
		}
		fmt.Println("got table "+key.String())

		tableContent, err := lookup.DecodeAddressLookupTableState(info.GetBinary())
		if err != nil {
			panic(err)
		}

		fmt.Println("table content:", spew.Sdump(tableContent))
		fmt.Println("isActive", tableContent.IsActive())

		resolutions[key] = tableContent.Addresses
	}

	err := txx.Message.SetAddressTables(resolutions)
	if err != nil {
		panic(err)
	}

	err = txx.Message.ResolveLookups()
	if err != nil {
		panic(err)
	}
	fmt.Println(txx.String())
}

Parse/decode an instruction from a transaction

package main

import (
  "context"
  "encoding/base64"
  "os"
  "reflect"

  "github.com/davecgh/go-spew/spew"
  bin "github.com/gagliardetto/binary"
  "github.com/gagliardetto/solana-go"
  "github.com/gagliardetto/solana-go/programs/system"
  "github.com/gagliardetto/solana-go/rpc"
  "github.com/gagliardetto/solana-go/text"
)

func main() {
  exampleFromGetTransaction()
}

func exampleFromBase64() {
  encoded := "AfjEs3XhTc3hrxEvlnMPkm/cocvAUbFNbCl00qKnrFue6J53AhEqIFmcJJlJW3EDP5RmcMz+cNTTcZHW/WJYwAcBAAEDO8hh4VddzfcO5jbCt95jryl6y8ff65UcgukHNLWH+UQGgxCGGpgyfQVQV02EQYqm4QwzUt2qf9f1gVLM7rI4hwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6ANIF55zOZWROWRkeh+lExxZBnKFqbvIxZDLE7EijjoBAgIAAQwCAAAAOTAAAAAAAAA="

  data, err := base64.StdEncoding.DecodeString(encoded)
  if err != nil {
    panic(err)
  }

  // parse transaction:
  tx, err := solana.TransactionFromDecoder(bin.NewBinDecoder(data))
  if err != nil {
    panic(err)
  }

  decodeSystemTransfer(tx)
}

func exampleFromGetTransaction() {
  endpoint := rpc.TestNet_RPC
  client := rpc.New(endpoint)

  txSig := solana.MustSignatureFromBase58("3hZorctJtD3QLCRV3zF6JM6FDbFR5kAvsuKEG1RH9rWdz8YgnDzAvMWZFjdJgoL8KSNzZnx7aiExm1JEMC8KHfyy")
  {
    out, err := client.GetTransaction(
      context.TODO(),
      txSig,
      &rpc.GetTransactionOpts{
        Encoding: solana.EncodingBase64,
      },
    )
    if err != nil {
      panic(err)
    }

    tx, err := solana.TransactionFromDecoder(bin.NewBinDecoder(out.Transaction.GetBinary()))
    if err != nil {
      panic(err)
    }

    decodeSystemTransfer(tx)
  }
}

func decodeSystemTransfer(tx *solana.Transaction) {
  spew.Dump(tx)

  // Get (for example) the first instruction of this transaction
  // which we know is a `system` program instruction:
  i0 := tx.Message.Instructions[0]

  // Find the program address of this instruction:
  progKey, err := tx.ResolveProgramIDIndex(i0.ProgramIDIndex)
  if err != nil {
    panic(err)
  }

  // Find the accounts of this instruction:
  accounts, err := i0.ResolveInstructionAccounts(&tx.Message)
  if err != nil {
    panic(err)
  }

  // Feed the accounts and data to the system program parser
  // OR see below for alternative parsing when you DON'T know
  // what program the instruction is for / you don't have a parser.
  inst, err := system.DecodeInstruction(accounts, i0.Data)
  if err != nil {
    panic(err)
  }

  // inst.Impl contains the specific instruction type (in this case, `inst.Impl` is a `*system.Transfer`)
  spew.Dump(inst)
  if _, ok := inst.Impl.(*system.Transfer); !ok {
    panic("the instruction is not a *system.Transfer")
  }

  // OR
  {
    // There is a more general instruction decoder: `solana.DecodeInstruction`.
    // It looks up the decoder for `progKey` in a central registry, so it
    // works for any program ID regardless of what you know at compile time.
    //
    // Each `programs/<name>` package registers its decoder via init(),
    // which only runs when the package is imported. If you are not
    // already using the package's builders (e.g. `system.NewTransferInstruction`),
    // blank-import it so the decoder is available - same idiom as
    // database/sql drivers:
    //
    //     import (
    //         _ "github.com/gagliardetto/solana-go/programs/system"
    //         _ "github.com/gagliardetto/solana-go/programs/token"
    //         // ...add more as needed
    //     )
    //
    // For a program that solana-go does not ship (e.g. a custom Anchor
    // program), register its decoder yourself:
    //
    //     solana.MustRegisterInstructionDecoder(myProgramID, myDecoderFunc)
    decodedInstruction, err := solana.DecodeInstruction(
      progKey,
      accounts,
      i0.Data,
    )
    if err != nil {
      panic(err)
    }
    // The returned `decodedInstruction` is the decoded instruction.
    spew.Dump(decodedInstruction)

    // decodedInstruction == inst
    if !reflect.DeepEqual(inst, decodedInstruction) {
      panic("they are NOT equal (this would never happen)")
    }
  }

  {
    // pretty-print whole transaction:
    _, err := tx.EncodeTree(text.NewTreeEncoder(os.Stdout, text.Bold("TEST TRANSACTION")))
    if err != nil {
      panic(err)
    }
  }
}

Borsh encoding/decoding

You can use the github.com/gagliardetto/binary package for encoding/decoding borsh-encoded data:

Decoder:

  resp, err := client.GetAccountInfo(
    context.TODO(),
    pubKey,
  )
  if err != nil {
    panic(err)
  }

  borshDec := bin.NewBorshDecoder(resp.GetBinary())
  var meta token_metadata.Metadata
  err = borshDec.Decode(&meta)
  if err != nil {
    panic(err)
  }

Encoder:

buf := new(bytes.Buffer)
borshEncoder := bin.NewBorshEncoder(buf)
err := borshEncoder.Encode(meta)
if err != nil {
  panic(err)
}
// fmt.Print(buf.Bytes())

ZSTD account data encoding

You can request account data to be encoded with base64+zstd in the Encoding parameter:

resp, err := client.GetAccountInfoWithOpts(
  context.TODO(),
  pubKey,
  &rpc.GetAccountInfoOpts{
    Encoding:   solana.EncodingBase64Zstd,
    Commitment: rpc.CommitmentFinalized,
  },
)
if err != nil {
  panic(err)
}
spew.Dump(resp)

var mint token.Mint
err = bin.NewDecoder(resp.GetBinary()).Decode(&mint)
if err != nil {
  panic(err)
}
spew.Dump(mint)

Working with rate-limited RPC providers

package main

import (
  "context"

  "golang.org/x/time/rate"
  "github.com/davecgh/go-spew/spew"
  "github.com/gagliardetto/solana-go/rpc"
)

func main() {
  cluster := rpc.MainNetBeta
  client := rpc.NewWithCustomRPCClient(rpc.NewWithLimiter(
		cluster.RPC,
		rate.Every(time.Second), // time frame
		5,                       // limit of requests per time frame
	))

  out, err := client.GetVersion(
    context.TODO(),
  )
  if err != nil {
    panic(err)
  }
  spew.Dump(out)
}

Custom Headers for authenticating with RPC providers

package main

import (
  "context"

  "golang.org/x/time/rate"
  "github.com/davecgh/go-spew/spew"
  "github.com/gagliardetto/solana-go/rpc"
)

func main() {
  cluster := rpc.MainNetBeta
  client := rpc.NewWithHeaders(
    cluster.RPC,
    map[string]string{
      "x-api-key": "...",
    },
  )

  out, err := client.GetVersion(
    context.TODO(),
  )
  if err != nil {
    panic(err)
  }
  spew.Dump(out)
}

The data will AUTOMATICALLY get decoded and returned (the right decoder will be used) when you call the resp.GetBinary() method.

Timeouts and Custom HTTP Clients

You can use a timeout context:

ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
acc, err := rpcClient.GetAccountInfoWithOpts(
  ctx,
  accountID,
  &rpc.GetAccountInfoOpts{
    Commitment: rpc.CommitmentProcessed,
  },
)

Or you can initialize the RPC client using a custom HTTP client using rpc.NewWithCustomRPCClient:

import (
  "net"
  "net/http"
  "time"

  "github.com/gagliardetto/solana-go/rpc"
  "github.com/gagliardetto/solana-go/rpc/jsonrpc"
)

func NewHTTPTransport(
  timeout time.Duration,
  maxIdleConnsPerHost int,
  keepAlive time.Duration,
) *http.Transport {
  return &http.Transport{
    IdleConnTimeout:     timeout,
    MaxIdleConnsPerHost: maxIdleConnsPerHost,
    Proxy:               http.ProxyFromEnvironment,
    Dial: (&net.Dialer{
      Timeout:   timeout,
      KeepAlive: keepAlive,
    }).Dial,
  }
}

// NewHTTP returns a new Client from the provided config.
func NewHTTP(
  timeout time.Duration,
  maxIdleConnsPerHost int,
  keepAlive time.Duration,
) *http.Client {
  tr := NewHTTPTransport(
    timeout,
    maxIdleConnsPerHost,
    keepAlive,
  )

  return &http.Client{
    Timeout:   timeout,
    Transport: tr,
  }
}

// NewRPC creates a new Solana JSON RPC client.
func NewRPC(rpcEndpoint string) *rpc.Client {
  var (
    defaultMaxIdleConnsPerHost = 10
    defaultTimeout             = 25 * time.Second
    defaultKeepAlive           = 180 * time.Second
  )
  opts := &jsonrpc.RPCClientOpts{
    HTTPClient: NewHTTP(
      defaultTimeout,
      defaultMaxIdleConnsPerHost,
      defaultKeepAlive,
    ),
  }
  rpcClient := jsonrpc.NewClientWithOpts(rpcEndpoint, opts)
  return rpc.NewWithCustomRPCClient(rpcClient)
}

Examples

Create account (wallet)
package main

import (
  "context"
  "fmt"

  "github.com/gagliardetto/solana-go"
  "github.com/gagliardetto/solana-go/rpc"
)

func main() {
  // Create a new account:
  account := solana.NewWallet()
  fmt.Println("account private key:", account.PrivateKey)
  fmt.Println("account public key:", account.PublicKey())

  // Create a new RPC client:
  client := rpc.New(rpc.TestNet_RPC)

  // Airdrop 1 SOL to the new account:
  out, err := client.RequestAirdrop(
    context.TODO(),
    account.PublicKey(),
    solana.LAMPORTS_PER_SOL*1,
    rpc.CommitmentFinalized,
  )
  if err != nil {
    panic(err)
  }
  fmt.Println("airdrop transaction signature:", out)
}
Load/parse private and public keys
{
  // Load private key from a json file generated with
  // $ solana-keygen new --outfile=standard.solana-keygen.json
  privateKey, err := solana.PrivateKeyFromSolanaKeygenFile("/path/to/standard.solana-keygen.json")
  if err != nil {
    panic(err)
  }
  fmt.Println("private key:", privateKey.String())
  // To get the public key, you need to call the `PublicKey()` method:
  publicKey := privateKey.PublicKey()
  // To get the base58 string of a public key, you can call the `String()` method:
  fmt.Println("public key:", publicKey.String())
}

{
  // Load private key from base58:
  {
    privateKey, err := solana.PrivateKeyFromBase58("66cDvko73yAf8LYvFMM3r8vF5vJtkk7JKMgEKwkmBC86oHdq41C7i1a2vS3zE1yCcdLLk6VUatUb32ZzVjSBXtRs")
    if err != nil {
      panic(err)
    }
    fmt.Println("private key:", privateKey.String())
    fmt.Println("public key:", privateKey.PublicKey().String())
  }
  // OR:
  {
    privateKey := solana.MustPrivateKeyFromBase58("66cDvko73yAf8LYvFMM3r8vF5vJtkk7JKMgEKwkmBC86oHdq41C7i1a2vS3zE1yCcdLLk6VUatUb32ZzVjSBXtRs")
    _ = privateKey
  }
}

{
  // Generate a new key pair:
  {
    privateKey, err := solana.NewRandomPrivateKey()
    if err != nil {
      panic(err)
    }
    _ = privateKey
  }
  {
    { // Generate a new private key (a Wallet struct is just a wrapper around a private key)
      account := solana.NewWallet()
      _ = account
    }
  }
}

{
  // Parse a public key from a base58 string:
  {
    publicKey, err := solana.PublicKeyFromBase58("F8UvVsKnzWyp2nF8aDcqvQ2GVcRpqT91WDsAtvBKCMt9")
    if err != nil {
      panic(err)
    }
    _ = publicKey
  }
  // OR:
  {
    publicKey := solana.MustPublicKeyFromBase58("F8UvVsKnzWyp2nF8aDcqvQ2GVcRpqT91WDsAtvBKCMt9")
    _ = publicKey
  }
}
Transfer Sol from one wallet to another wallet
package main

import (
  "context"
  "fmt"
  "os"
  "time"

  "github.com/davecgh/go-spew/spew"
  "github.com/gagliardetto/solana-go"
  "github.com/gagliardetto/solana-go/programs/system"
  "github.com/gagliardetto/solana-go/rpc"
  confirm "github.com/gagliardetto/solana-go/rpc/sendAndConfirmTransaction"
  "github.com/gagliardetto/solana-go/rpc/jsonrpc"
  "github.com/gagliardetto/solana-go/rpc/ws"
  "github.com/gagliardetto/solana-go/text"
)

func main() {
  // Create a new RPC client:
  rpcClient := rpc.New(rpc.DevNet_RPC)

  // Create a new WS client (used for confirming transactions)
  wsClient, err := ws.Connect(context.Background(), rpc.DevNet_WS)
  if err != nil {
    panic(err)
  }

  // Load the account that you will send funds FROM:
  accountFrom, err := solana.PrivateKeyFromSolanaKeygenFile("/path/to/.config/solana/id.json")
  if err != nil {
    panic(err)
  }
  fmt.Println("accountFrom private key:", accountFrom)
  fmt.Println("accountFrom public key:", accountFrom.PublicKey())

  // The public key of the account that you will send sol TO:
  accountTo := solana.MustPublicKeyFromBase58("TODO")
  // The amount to send (in lamports);
  // 1 sol = 1000000000 lamports
  amount := uint64(3333)

  if true {
    // Airdrop 1 sol to the account so it will have something to transfer:
    out, err := rpcClient.RequestAirdrop(
      context.TODO(),
      accountFrom.PublicKey(),
      solana.LAMPORTS_PER_SOL*1,
      rpc.CommitmentFinalized,
    )
    if err != nil {
      panic(err)
    }
    fmt.Println("airdrop transaction signature:", out)
    time.Sleep(time.Second * 5)
  }
  //---------------

  recent, err := rpcClient.GetLatestBlockhash(context.TODO(), rpc.CommitmentFinalized)
  if err != nil {
    panic(err)
  }

  tx, err := solana.NewTransaction(
    []solana.Instruction{
      system.NewTransferInstruction(
        amount,
        accountFrom.PublicKey(),
        accountTo,
      ).Build(),
    },
    recent.Value.Blockhash,
    solana.TransactionPayer(accountFrom.PublicKey()),
  )
  if err != nil {
    panic(err)
  }

  _, err = tx.Sign(
    func(key solana.PublicKey) *solana.PrivateKey {
      if accountFrom.PublicKey().Equals(key) {
        return &accountFrom
      }
      return nil
    },
  )
  if err != nil {
    panic(fmt.Errorf("unable to sign transaction: %w", err))
  }
  spew.Dump(tx)
  // Pretty print the transaction:
  tx.EncodeTree(text.NewTreeEncoder(os.Stdout, "Transfer SOL"))

  // Send transaction, and wait for confirmation:
  sig, err := confirm.SendAndConfirmTransaction(
    context.TODO(),
    rpcClient,
    wsClient,
    tx,
  )
  if err != nil {
    panic(err)
  }
  spew.Dump(sig)

  // Or just send the transaction WITHOUT waiting for confirmation:
  // sig, err := rpcClient.SendTransactionWithOpts(
  //   context.TODO(),
  //   tx,
  //   false,
  //   rpc.CommitmentFinalized,
  // )
  // if err != nil {
  //   panic(err)
  // }
  // spew.Dump(sig)
}

RPC Methods

All RPC methods from the Solana JSON RPC API are supported. Each method has a testable example in rpc/example_test.go that is rendered on pkg.go.dev.

WebSocket Subscriptions

All WebSocket subscriptions from the Solana WebSocket API are supported. Each subscription has a testable example in rpc/ws/example_test.go that is rendered on pkg.go.dev.

Contributing

We encourage everyone to contribute, submit issues, PRs, discuss. Every kind of help is welcome.

Please read CONTRIBUTING.md for guidelines on commit messages, semver policy, linting, and CI checks.

Before opening a PR, run:

go test ./... -count=1
golangci-lint run

Both must pass in CI.

License

Apache 2.0

Credits

  • Gopher logo was originally created by Takuya Ueda (https://twitter.com/tenntenn). Licensed under the Creative Commons 3.0 Attributions license.

Documentation ¶

Index ¶

Constants ¶

View Source
const (
	// There are 1-billion lamports in one SOL.
	LAMPORTS_PER_SOL uint64 = 1000000000

	SolDecimals uint8 = 9
)
View Source
const (
	// Number of bytes in a pubkey.
	PublicKeyLength = 32
	// Maximum length of derived pubkey seed.
	MaxSeedLength = 32
	// Maximum number of seeds.
	MaxSeeds = 16
	// Number of bytes in a signature.
	SignatureLength = 64

	// Number of bytes in a private key.
	PrivateKeyLength = voied25519.PrivateKeySize
)
View Source
const (
	AccountsTypeIndex = "Fee"
	AccountsTypeKey   = "Key"
)
View Source
const NonceStateSize = 80

NonceStateSize is the serialized size, in bytes, of a nonce account's data. It is constant regardless of whether the account is initialized: the runtime always allocates this many bytes. Mirrors solana_nonce::state::State::size().

View Source
const PDA_MARKER = "ProgramDerivedAddress"
View Source
const SolanaDerivationPath = "m/44'/501'/0'/0'"

SolanaDerivationPath is the default BIP-44 derivation path used by Phantom and most Solana wallets when generating a key from a BIP-39 mnemonic: m/44'/501'/0'/0'.

Variables ¶

View Source
var (
	// Create new accounts, allocate account data, assign accounts to owning programs,
	// transfer lamports from System Program owned accounts and pay transacation fees.
	SystemProgramID = MustPublicKeyFromBase58("11111111111111111111111111111111")

	// Add configuration data to the chain and the list of public keys that are permitted to modify it.
	ConfigProgramID = MustPublicKeyFromBase58("Config1111111111111111111111111111111111111")

	// Create and manage accounts representing stake and rewards for delegations to validators.
	StakeProgramID = MustPublicKeyFromBase58("Stake11111111111111111111111111111111111111")

	// Create and manage accounts that track validator voting state and rewards.
	VoteProgramID = MustPublicKeyFromBase58("Vote111111111111111111111111111111111111111")

	BPFLoaderDeprecatedProgramID = MustPublicKeyFromBase58("BPFLoader1111111111111111111111111111111111")
	// Deploys, upgrades, and executes programs on the chain.
	BPFLoaderProgramID            = MustPublicKeyFromBase58("BPFLoader2111111111111111111111111111111111")
	BPFLoaderUpgradeableProgramID = MustPublicKeyFromBase58("BPFLoaderUpgradeab1e11111111111111111111111")

	// Verify secp256k1 public key recovery operations (ecrecover).
	Secp256k1ProgramID = MustPublicKeyFromBase58("KeccakSecp256k11111111111111111111111111111")

	FeatureProgramID = MustPublicKeyFromBase58("Feature111111111111111111111111111111111111")

	ComputeBudget = MustPublicKeyFromBase58("ComputeBudget111111111111111111111111111111")

	// Create and manage address lookup tables.
	AddressLookupTableProgramID = MustPublicKeyFromBase58("AddressLookupTab1e1111111111111111111111111")
)
View Source
var (
	// A Token program on the Solana blockchain.
	// This program defines a common implementation for Fungible and Non Fungible tokens.
	TokenProgramID = MustPublicKeyFromBase58("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")

	Token2022ProgramID = MustPublicKeyFromBase58("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb")

	// A Uniswap-like exchange for the Token program on the Solana blockchain,
	// implementing multiple automated market maker (AMM) curves.
	TokenSwapProgramID = MustPublicKeyFromBase58("SwaPpA9LAaLfeLi3a68M4DjnLqgtticKg6CnyNwgAC8")
	TokenSwapFeeOwner  = MustPublicKeyFromBase58("HfoTxFR1Tm6kGmWgYWD6J7YHVy1UwqSULUGVLXkJqaKN")

	// A lending protocol for the Token program on the Solana blockchain inspired by Aave and Compound.
	TokenLendingProgramID = MustPublicKeyFromBase58("LendZqTs8gn5CTSJU1jWKhKuVpjJGom45nnwPb2AMTi")

	// This program defines the convention and provides the mechanism for mapping
	// the user's wallet address to the associated token accounts they hold.
	SPLAssociatedTokenAccountProgramID = MustPublicKeyFromBase58("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL")

	// The Memo program is a simple program that validates a string of UTF-8 encoded characters
	// and verifies that any accounts provided are signers of the transaction.
	// The program also logs the memo, as well as any verified signer addresses,
	// to the transaction log, so that anyone can easily observe memos
	// and know they were approved by zero or more addresses
	// by inspecting the transaction log from a trusted provider.
	MemoProgramID = MustPublicKeyFromBase58("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr")

	// MemoProgramIDV1 is the deprecated v1 Memo program.
	// Some legacy transactions still reference this program ID.
	MemoProgramIDV1 = MustPublicKeyFromBase58("Memo1UhkJRfHyvLMcVucJwxXeuD728EqVDDwQDxFMNo")
)

SPL:

View Source
var (
	SolMint    = MustPublicKeyFromBase58("So11111111111111111111111111111111111111111")
	WrappedSol = MustPublicKeyFromBase58("So11111111111111111111111111111111111111112")
)
View Source
var (
	// Owner address for sysvar accounts.
	SysVarPubkey = MustPublicKeyFromBase58("Sysvar1111111111111111111111111111111111111")

	// The Clock sysvar contains data on cluster time,
	// including the current slot, epoch, and estimated wall-clock Unix timestamp.
	// It is updated every slot.
	SysVarClockPubkey = MustPublicKeyFromBase58("SysvarC1ock11111111111111111111111111111111")

	// The EpochRewards sysvar contains epoch rewards distribution data.
	SysVarEpochRewardsPubkey = MustPublicKeyFromBase58("SysvarEpochRewards1111111111111111111111111")

	// The EpochSchedule sysvar contains epoch scheduling constants that are set in genesis,
	// and enables calculating the number of slots in a given epoch,
	// the epoch for a given slot, etc.
	// (Note: the epoch schedule is distinct from the leader schedule)
	SysVarEpochSchedulePubkey = MustPublicKeyFromBase58("SysvarEpochSchedu1e111111111111111111111111")

	// The Fees sysvar contains the fee calculator for the current slot.
	// It is updated every slot, based on the fee-rate governor.
	SysVarFeesPubkey = MustPublicKeyFromBase58("SysvarFees111111111111111111111111111111111")

	// The Instructions sysvar contains the serialized instructions in a Message while that Message is being processed.
	// This allows program instructions to reference other instructions in the same transaction.
	SysVarInstructionsPubkey = MustPublicKeyFromBase58("Sysvar1nstructions1111111111111111111111111")

	// The LastRestartSlot sysvar contains the last restart slot.
	SysVarLastRestartSlotPubkey = MustPublicKeyFromBase58("SysvarLastRestartS1ot1111111111111111111111")

	// The RecentBlockhashes sysvar contains the active recent blockhashes as well as their associated fee calculators.
	// It is updated every slot.
	// Entries are ordered by descending block height,
	// so the first entry holds the most recent block hash,
	// and the last entry holds an old block hash.
	SysVarRecentBlockHashesPubkey = MustPublicKeyFromBase58("SysvarRecentB1ockHashes11111111111111111111")

	// The Rent sysvar contains the rental rate.
	// Currently, the rate is static and set in genesis.
	// The Rent burn percentage is modified by manual feature activation.
	SysVarRentPubkey = MustPublicKeyFromBase58("SysvarRent111111111111111111111111111111111")

	// The Rewards sysvar.
	SysVarRewardsPubkey = MustPublicKeyFromBase58("SysvarRewards111111111111111111111111111111")

	// The SlotHashes sysvar contains the most recent hashes of the slot's parent banks.
	// It is updated every slot.
	SysVarSlotHashesPubkey = MustPublicKeyFromBase58("SysvarS1otHashes111111111111111111111111111")

	// The SlotHistory sysvar contains a bitvector of slots present over the last epoch. It is updated every slot.
	SysVarSlotHistoryPubkey = MustPublicKeyFromBase58("SysvarS1otHistory11111111111111111111111111")

	// The StakeHistory sysvar contains the history of cluster-wide stake activations and de-activations per epoch.
	// It is updated at the start of every epoch.
	SysVarStakeHistoryPubkey = MustPublicKeyFromBase58("SysvarStakeHistory1111111111111111111111111")

	// The stake config account is used to store parameters and settings that govern the behavior of staking on the Solana network.
	SysVarStakeConfigPubkey = MustPublicKeyFromBase58("StakeConfig11111111111111111111111111111111")
)

From https://github.com/anza-xyz/solana-sdk/blob/master/sdk-ids/src/lib.rs

View Source
var ErrAddressTablesNotSet = errors.New(
	"address tables not set for versioned message with lookups; " +
		"fetch each table id returned by Message.GetAddressTableLookups().GetTableIDs() " +
		"(e.g. via rpc.Client.GetMultipleAccounts, decoding each account with " +
		"addresslookuptable.DecodeAddressLookupTableState) " +
		"and pass the resolved {tableID -> []PublicKey} map to Message.SetAddressTables",
)

ErrAddressTablesNotSet is returned by `(*Message).AccountMetaList`, `(*Message).ResolveLookups`, and friends when the message is a versioned (V0+) transaction with one or more address-table lookups but the actual table contents have not been provided yet via `(*Message).SetAddressTables`. Callers can use `errors.Is` to detect this specific condition (see #280) without scraping the error text.

View Source
var ErrAlreadyResolved = fmt.Errorf("lookups already resolved")
View Source
var ErrInstructionDecoderNotFound = errors.New("instruction decoder not found")
View Source
var ErrMaxSeedLengthExceeded = errors.New("max seed length exceeded")
View Source
var ErrNonceUninitialized = errors.New("nonce account is uninitialized")

ErrNonceUninitialized is returned by Authorize when the nonce account has not been initialized.

View Source
var TokenMetadataProgramID = MustPublicKeyFromBase58("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s")

Functions ¶

func DecimalsInBigInt ¶

func DecimalsInBigInt(decimal uint32) *big.Int

func DecodeInstruction ¶

func DecodeInstruction(programID PublicKey, accounts []*AccountMeta, data []byte) (any, error)

func GetAddedRemovedPubkeys ¶ added in v1.1.0

func GetAddedRemovedPubkeys(previous PublicKeySlice, next PublicKeySlice) (added PublicKeySlice, removed PublicKeySlice)

GetAddedRemovedPubkeys accepts two slices of pubkeys (`previous` and `next`), and returns two slices: - `added` is the slice of pubkeys that are present in `next` but NOT present in `previous`. - `removed` is the slice of pubkeys that are present in `previous` but are NOT present in `next`.

func IsAnyOfEncodingType ¶ added in v0.3.5

func IsAnyOfEncodingType(candidate EncodingType, allowed ...EncodingType) bool

IsAnyOfEncodingType checks whether the provided `candidate` is any of the `allowed`.

func IsOnCurve ¶ added in v1.0.4

func IsOnCurve(b []byte) bool

Check if the provided `b` is on the ed25519 curve.

func IsSanitizeError ¶ added in v1.17.0

func IsSanitizeError(err error) bool

IsSanitizeError reports whether err is a sanitization validation error.

func LamportsPerSignatureOf ¶ added in v1.22.0

func LamportsPerSignatureOf(data []byte) (uint64, bool)

LamportsPerSignatureOf decodes a nonce account's data and returns the per-signature fee it records, or (0, false) when uninitialized or undecodable.

Mirrors nonce_account::lamports_per_signature_of, which likewise does NOT verify the account owner; this function only takes the data bytes and cannot. Pass data you have already confirmed belongs to a System-owned nonce account (e.g. via GetSystemAccountKind or VerifyNonceAccount), or treat the result as advisory.

func MustRegisterInstructionDecoder ¶ added in v1.17.0

func MustRegisterInstructionDecoder(programID PublicKey, decoder InstructionDecoder)

MustRegisterInstructionDecoder is like RegisterInstructionDecoder but panics on error. Intended for use in init() functions where error handling is not possible.

func RegisterInstructionDecoder ¶

func RegisterInstructionDecoder(programID PublicKey, decoder InstructionDecoder) error

RegisterInstructionDecoder registers a decoder for the given programID. Returns an error if a different decoder is already registered for that programID. Re-registering the same decoder function is a no-op.

func ValidatePrivateKey ¶ added in v1.12.0

func ValidatePrivateKey(b []byte) (bool, error)

Types ¶

type AccountMeta ¶

type AccountMeta struct {
	PublicKey  PublicKey
	IsWritable bool
	IsSigner   bool
}

func Meta ¶ added in v0.4.0

func Meta(
	pubKey PublicKey,
) *AccountMeta

Meta intializes a new AccountMeta with the provided pubKey.

func NewAccountMeta ¶ added in v0.4.0

func NewAccountMeta(
	pubKey PublicKey,
	WRITE bool,
	SIGNER bool,
) *AccountMeta

func (*AccountMeta) SIGNER ¶ added in v0.4.0

func (meta *AccountMeta) SIGNER() *AccountMeta

SIGNER sets IsSigner to true.

func (*AccountMeta) WRITE ¶ added in v0.4.0

func (meta *AccountMeta) WRITE() *AccountMeta

WRITE sets IsWritable to true.

type AccountMetaSlice ¶ added in v0.4.0

type AccountMetaSlice []*AccountMeta

func (*AccountMetaSlice) Append ¶ added in v0.4.0

func (slice *AccountMetaSlice) Append(account *AccountMeta)

func (AccountMetaSlice) Get ¶ added in v1.1.0

func (slice AccountMetaSlice) Get(index int) *AccountMeta

Get returns the AccountMeta at the desired index. If the index is not present, it returns nil.

func (AccountMetaSlice) GetAccounts ¶ added in v0.4.0

func (slice AccountMetaSlice) GetAccounts() []*AccountMeta

func (AccountMetaSlice) GetKeys ¶ added in v1.2.0

func (slice AccountMetaSlice) GetKeys() PublicKeySlice

GetKeys returns the pubkeys of all AccountMeta.

func (AccountMetaSlice) GetSigners ¶ added in v0.4.0

func (slice AccountMetaSlice) GetSigners() []*AccountMeta

GetSigners returns the accounts that are signers.

func (AccountMetaSlice) Len ¶ added in v0.4.4

func (slice AccountMetaSlice) Len() int

func (*AccountMetaSlice) SetAccounts ¶ added in v0.4.0

func (slice *AccountMetaSlice) SetAccounts(accounts []*AccountMeta) error

func (AccountMetaSlice) SplitFrom ¶ added in v0.4.4

func (slice AccountMetaSlice) SplitFrom(index int) (AccountMetaSlice, AccountMetaSlice)

type AccountsGettable ¶ added in v0.4.0

type AccountsGettable interface {
	GetAccounts() (accounts []*AccountMeta)
}

type AccountsSettable ¶ added in v0.4.0

type AccountsSettable 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 Base64 ¶ added in v1.12.0

type Base64 []byte

func (Base64) MarshalJSON ¶ added in v1.12.0

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

func (*Base64) UnmarshalJSON ¶ added in v1.12.0

func (t *Base64) 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.
	// NOTE: it is actually a uint8, but using a uint16 because uint8 is treated as a byte everywhere,
	// and that can be an issue.
	ProgramIDIndex uint16 `json:"programIdIndex"`

	// List of ordered indices into the message.accountKeys array indicating which accounts to pass to the program.
	// NOTE: it is actually a []uint8, but using a uint16 because []uint8 is treated as a []byte everywhere,
	// and that can be an issue.
	Accounts []uint16 `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) ([]*AccountMeta, error)

type Data ¶

type Data struct {
	Content  []byte
	Encoding EncodingType
}

func (Data) MarshalJSON ¶

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

func (Data) MarshalWithEncoder ¶ added in v1.2.0

func (obj Data) MarshalWithEncoder(encoder *bin.Encoder) (err error)

func (Data) String ¶

func (t Data) String() string

func (*Data) UnmarshalJSON ¶

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

func (*Data) UnmarshalWithDecoder ¶ added in v1.2.0

func (obj *Data) UnmarshalWithDecoder(decoder *bin.Decoder) (err error)

type DurableNonce ¶ added in v1.22.0

type DurableNonce Hash

DurableNonce is the 32-byte value stored in an initialized nonce account and used as the recent_blockhash field of a durable-nonce transaction.

Although it is used in the recent_blockhash slot, it is NOT a real blockhash: it is derived from one via DurableNonceFromBlockhash with a domain prefix.

func DurableNonceFromBlockhash ¶ added in v1.22.0

func DurableNonceFromBlockhash(blockhash Hash) DurableNonce

DurableNonceFromBlockhash derives a durable nonce from a blockhash, computing sha256("DURABLE_NONCE" || blockhash). Mirrors DurableNonce::from_blockhash.

func (DurableNonce) AsHash ¶ added in v1.22.0

func (d DurableNonce) AsHash() Hash

AsHash returns the durable nonce as a Hash, i.e. the value to place in a transaction's recent_blockhash field. Mirrors DurableNonce::as_hash.

func (DurableNonce) Equals ¶ added in v1.22.0

func (d DurableNonce) Equals(other DurableNonce) bool

Equals reports whether two durable nonces are equal.

func (DurableNonce) IsZero ¶ added in v1.22.0

func (d DurableNonce) IsZero() bool

IsZero reports whether the durable nonce is the zero value.

func (DurableNonce) String ¶ added in v1.22.0

func (d DurableNonce) String() string

type DurationMilliseconds ¶ added in v1.7.0

type DurationMilliseconds int64

DurationMilliseconds represents a duration in milliseconds.

func (DurationMilliseconds) Duration ¶ added in v1.7.0

func (res DurationMilliseconds) Duration() time.Duration

func (DurationMilliseconds) String ¶ added in v1.7.0

func (res DurationMilliseconds) String() string

type DurationSeconds ¶ added in v1.0.1

type DurationSeconds int64

DurationSeconds represents a duration in seconds.

func (DurationSeconds) Duration ¶ added in v1.0.1

func (res DurationSeconds) Duration() time.Duration

func (DurationSeconds) String ¶ added in v1.0.1

func (res DurationSeconds) String() string

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: you're probably looking for EncodingJSONParsed
)

type FeeCalculator ¶ added in v1.22.0

type FeeCalculator struct {
	LamportsPerSignature uint64
}

FeeCalculator records the cost, in lamports per signature, to process a transaction. Mirrors solana-sdk fee-calculator's FeeCalculator.

func (FeeCalculator) MarshalWithEncoder ¶ added in v1.22.0

func (obj FeeCalculator) MarshalWithEncoder(encoder *bin.Encoder) (err error)

func (*FeeCalculator) UnmarshalWithDecoder ¶ added in v1.22.0

func (obj *FeeCalculator) UnmarshalWithDecoder(decoder *bin.Decoder) (err error)

type GenericInstruction ¶ added in v0.5.0

type GenericInstruction struct {
	AccountValues AccountMetaSlice
	ProgID        PublicKey
	DataBytes     []byte
}

func NewInstruction ¶ added in v0.5.0

func NewInstruction(
	programID PublicKey,
	accounts AccountMetaSlice,
	data []byte,
) *GenericInstruction

NewInstruction creates a generic instruction with the provided programID, accounts, and data bytes.

func (*GenericInstruction) Accounts ¶ added in v0.5.0

func (in *GenericInstruction) Accounts() []*AccountMeta

func (*GenericInstruction) Data ¶ added in v0.5.0

func (in *GenericInstruction) Data() ([]byte, error)

func (*GenericInstruction) ProgramID ¶ added in v0.5.0

func (in *GenericInstruction) ProgramID() PublicKey

type Hash ¶

type Hash PublicKey

func HashFromBase58 ¶

func HashFromBase58(in string) (Hash, error)

HashFromBase58 decodes a base58 string into a Hash.

func HashFromBytes ¶ added in v1.0.2

func HashFromBytes(in []byte) Hash

HashFromBytes decodes a byte slice into a Hash.

func MustHashFromBase58 ¶

func MustHashFromBase58(in string) Hash

MustHashFromBase58 decodes a base58 string into a Hash. Panics on error.

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) MarshalText ¶ added in v1.6.0

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

MarshalText implements encoding.TextMarshaler.

func (Hash) String ¶

func (ha Hash) String() string

func (*Hash) UnmarshalJSON ¶

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

func (*Hash) UnmarshalText ¶ added in v1.6.0

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

UnmarshalText implements encoding.TextUnmarshaler.

type Instruction ¶

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

type InstructionDecoder ¶

type InstructionDecoder func(instructionAccounts []*AccountMeta, data []byte) (any, 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 PublicKeySlice `json:"accountKeys"` // static keys; static keys + dynamic keys if after resolution (i.e. call to `ResolveLookups()`)

	// 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"`

	// List of address table lookups used to load additional accounts for this transaction.
	AddressTableLookups MessageAddressTableLookupSlice `json:"addressTableLookups"`
	// contains filtered or unexported fields
}

func (*Message) Account ¶ added in v1.8.0

func (m *Message) Account(index uint16) (PublicKey, error)

Account returns the account at the given index.

func (*Message) AccountMetaList ¶

func (m *Message) AccountMetaList() (AccountMetaSlice, error)

func (*Message) AddAddressTableLookup ¶ added in v1.7.0

func (mx *Message) AddAddressTableLookup(lookup MessageAddressTableLookup) *Message

AddAddressTableLookup adds a new lookup to the message.

func (*Message) EncodeToTree ¶ added in v0.4.0

func (mx *Message) EncodeToTree(txTree treeout.Branches)

func (*Message) GetAccountIndex ¶ added in v1.9.0

func (m *Message) GetAccountIndex(account PublicKey) (uint16, error)

GetAccountIndex returns the index of the given account (first occurrence of the account).

func (*Message) GetAddressTableLookupAccounts ¶ added in v1.8.0

func (mx *Message) GetAddressTableLookupAccounts() (PublicKeySlice, error)

GetAddressTableLookupAccounts associates the lookups with the accounts in the actual address tables, and returns the accounts. NOTE: you need to call `SetAddressTables` before calling this method, so that the lookups can be associated with the accounts in the address tables.

func (*Message) GetAddressTableLookups ¶ added in v1.7.0

func (mx *Message) GetAddressTableLookups() MessageAddressTableLookupSlice

GetAddressTableLookups returns the lookups used by this message.

func (*Message) GetAddressTables ¶ added in v1.7.0

func (mx *Message) GetAddressTables() map[PublicKey]PublicKeySlice

GetAddressTables returns the actual address tables used by this message. NOTE: you must have called `SetAddressTable` before being able to use this method.

func (*Message) GetAllKeys ¶ added in v1.8.0

func (mx *Message) GetAllKeys() (keys PublicKeySlice, err error)

GetAllKeys returns ALL the message's account keys (including the keys from resolved address lookup tables).

func (*Message) GetIxSigners ¶ added in v1.18.0

func (m *Message) GetIxSigners(ixIndex int) PublicKeySlice

GetIxSigners returns the set of account keys that are both signers and referenced as accounts (not program) in the instruction at the given index.

func (*Message) GetVersion ¶ added in v1.7.0

func (m *Message) GetVersion() MessageVersion

GetVersion returns the message version.

func (*Message) HasAccount ¶ added in v1.2.0

func (m *Message) HasAccount(account PublicKey) (bool, error)

func (*Message) HasDuplicates ¶ added in v1.17.0

func (m *Message) HasDuplicates() bool

HasDuplicates checks if the message has duplicate account keys. Uses O(n^2) comparison but requires no heap allocation, which is faster for the typically small number of accounts in a message. Ported from solana-sdk/message/legacy.rs has_duplicates().

func (*Message) IsInstructionAccount ¶ added in v1.18.0

func (m *Message) IsInstructionAccount(index uint16) bool

IsInstructionAccount returns true if the given account index is referenced as an account (not a program) in any instruction.

func (*Message) IsResolved ¶ added in v1.11.0

func (mx *Message) IsResolved() bool

func (*Message) IsSigner ¶

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

func (*Message) IsVersioned ¶ added in v1.7.0

func (m *Message) IsVersioned() bool

func (*Message) IsWritable ¶

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

func (*Message) IsWritableStatic ¶ added in v1.13.0

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

IsWritableStatic checks if the account is a writable account in the static accounts list, ignoring the accounts in the address table lookups.

func (*Message) MarshalBinary ¶ added in v0.3.5

func (mx *Message) MarshalBinary() ([]byte, error)

func (Message) MarshalJSON ¶ added in v1.8.4

func (mx Message) MarshalJSON() ([]byte, error)

func (*Message) MarshalLegacy ¶ added in v1.7.0

func (mx *Message) MarshalLegacy() ([]byte, error)

func (*Message) MarshalV0 ¶ added in v1.7.0

func (mx *Message) MarshalV0() ([]byte, error)

func (Message) MarshalWithEncoder ¶ added in v0.4.0

func (mx Message) MarshalWithEncoder(encoder *bin.Encoder) error

func (*Message) NumLookups ¶ added in v1.8.0

func (mx *Message) NumLookups() int

func (*Message) NumReadonlyAccounts ¶ added in v1.18.0

func (m *Message) NumReadonlyAccounts() int

NumReadonlyAccounts returns the total number of readonly accounts (signed + unsigned) in the static account list.

func (*Message) NumWritableLookups ¶ added in v1.8.0

func (mx *Message) NumWritableLookups() int

func (*Message) Program ¶ added in v1.8.0

func (m *Message) Program(programIDIndex uint16) (PublicKey, error)

Program returns the program key at the given index.

func (*Message) ProgramIDs ¶ added in v1.18.0

func (m *Message) ProgramIDs() PublicKeySlice

ProgramIDs returns the deduplicated list of program IDs used by the message's instructions.

func (*Message) ProgramPosition ¶ added in v1.18.0

func (m *Message) ProgramPosition(index uint16) (int, bool)

ProgramPosition returns the 0-based position of the account at the given index among all program IDs invoked by the message. Returns (pos, true) if found, or (0, false) if the account is not a program ID.

func (*Message) ResolveLookups ¶ added in v1.8.0

func (mx *Message) ResolveLookups() (err error)

ResolveLookups resolves the address table lookups, and appends the resolved accounts to the `message.AccountKeys` field. NOTE: you need to call `SetAddressTables` before calling this method.

func (*Message) ResolveLookupsWith ¶ added in v1.13.0

func (mx *Message) ResolveLookupsWith(writable, readonly PublicKeySlice) (err error)

ResolveLookupsWith resolves the address table lookups with the provided writable and readonly accounts, assuming that the order of the accounts is correct.

func (*Message) ResolveProgramIDIndex ¶

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

ResolveProgramIDIndex resolves the program ID index to a program ID. DEPRECATED: use `Program(index)` instead.

func (*Message) Sanitize ¶ added in v1.17.0

func (m *Message) Sanitize() error

Sanitize validates the structural integrity of a Message. Ported from solana-sdk/message: legacy.rs sanitize() and v0/mod.rs sanitize().

func (*Message) SetAddressTableLookups ¶ added in v1.7.0

func (mx *Message) SetAddressTableLookups(lookups []MessageAddressTableLookup) *Message

SetAddressTableLookups (re)sets the lookups used by this message.

func (*Message) SetAddressTables ¶ added in v1.7.0

func (mx *Message) SetAddressTables(tables map[PublicKey]PublicKeySlice) error

SetAddressTables sets the actual address tables used by this message. Use `mx.GetAddressTableLookups().GetTableIDs()` to get the list of all address table IDs. NOTE: you can call this once.

func (*Message) SetVersion ¶ added in v1.7.0

func (m *Message) SetVersion(version MessageVersion) (*Message, error)

SetVersion sets the message version. This method forces the message to be encoded in the specified version. NOTE: if you set lookups, the version will default to V0.

func (*Message) Signers ¶ added in v1.2.0

func (m *Message) Signers() PublicKeySlice

Signers returns the pubkeys of all accounts that are signers.

func (Message) ToBase64 ¶ added in v1.3.0

func (mx Message) ToBase64() string

func (*Message) UnmarshalBase64 ¶ added in v1.7.0

func (mx *Message) UnmarshalBase64(b64 string) error

func (*Message) UnmarshalJSON ¶ added in v1.19.0

func (mx *Message) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the message from JSON and determines its version. The Solana RPC emits `addressTableLookups` only for versioned (V0+) messages; its presence in the JSON is what distinguishes V0 from legacy, since the private `version` field has no wire representation.

func (*Message) UnmarshalLegacy ¶ added in v1.7.0

func (mx *Message) UnmarshalLegacy(decoder *bin.Decoder) (err error)

func (*Message) UnmarshalV0 ¶ added in v1.7.0

func (mx *Message) UnmarshalV0(decoder *bin.Decoder) (err error)

func (*Message) UnmarshalWithDecoder ¶ added in v0.4.0

func (mx *Message) UnmarshalWithDecoder(decoder *bin.Decoder) (err error)

func (*Message) Writable ¶ added in v1.2.0

func (m *Message) Writable() (out PublicKeySlice, err error)

Writable returns the pubkeys of all accounts that are writable.

type MessageAddressTableLookup ¶ added in v1.7.0

type MessageAddressTableLookup struct {
	AccountKey      PublicKey       `json:"accountKey"` // The account key of the address table.
	WritableIndexes Uint8SliceAsNum `json:"writableIndexes"`
	ReadonlyIndexes Uint8SliceAsNum `json:"readonlyIndexes"`
}

type MessageAddressTableLookupSlice ¶ added in v1.7.0

type MessageAddressTableLookupSlice []MessageAddressTableLookup

func (MessageAddressTableLookupSlice) GetTableIDs ¶ added in v1.7.0

func (lookups MessageAddressTableLookupSlice) GetTableIDs() PublicKeySlice

GetTableIDs returns the list of all address table IDs.

func (MessageAddressTableLookupSlice) NumLookups ¶ added in v1.7.0

func (lookups MessageAddressTableLookupSlice) NumLookups() int

NumLookups returns the number of accounts from all the lookups.

func (MessageAddressTableLookupSlice) NumWritableLookups ¶ added in v1.8.0

func (lookups MessageAddressTableLookupSlice) NumWritableLookups() int

NumWritableLookups returns the number of writable accounts across all the lookups (all the address tables).

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"`
}

func (*MessageHeader) EncodeToTree ¶ added in v0.4.0

func (header *MessageHeader) EncodeToTree(mxBranch treeout.Branches)

type MessageVersion ¶ added in v1.7.0

type MessageVersion int
const (
	MessageVersionLegacy MessageVersion = 0 // default
	MessageVersionV0     MessageVersion = 1 // v0
)

type MissingRequiredSignatureError ¶ added in v1.22.0

type MissingRequiredSignatureError struct {
	// Authority is the nonce account's current authority whose signature is
	// required.
	Authority PublicKey
}

MissingRequiredSignatureError is returned by Authorize when the current nonce authority is not among the provided signers.

func (*MissingRequiredSignatureError) Error ¶ added in v1.22.0

type NonceData ¶ added in v1.22.0

type NonceData struct {
	// Authority is the address allowed to sign transactions that consume and
	// advance this nonce.
	Authority PublicKey
	// DurableNonce is the current nonce value.
	DurableNonce DurableNonce
	// FeeCalculator records the fee in effect when the nonce was last advanced.
	FeeCalculator FeeCalculator
}

NonceData is the initialized data of a durable transaction nonce account.

func NewNonceData ¶ added in v1.22.0

func NewNonceData(authority PublicKey, durableNonce DurableNonce, lamportsPerSignature uint64) NonceData

NewNonceData builds nonce data from an authority, durable nonce and the lamports-per-signature fee. Mirrors Data::new.

func VerifyNonceAccount ¶ added in v1.22.0

func VerifyNonceAccount(owner PublicKey, data []byte, recentBlockhash Hash) (*NonceData, bool)

VerifyNonceAccount decodes a system-owned nonce account and verifies that recentBlockhash matches its current nonce, returning the nonce data when valid. The account owner must be the System program. Mirrors nonce_account::verify_nonce_account.

func (NonceData) Blockhash ¶ added in v1.22.0

func (d NonceData) Blockhash() Hash

Blockhash returns the hash to use as a transaction's recent_blockhash when spending this nonce. Mirrors Data::blockhash.

func (NonceData) LamportsPerSignature ¶ added in v1.22.0

func (d NonceData) LamportsPerSignature() uint64

LamportsPerSignature returns the per-signature fee recorded for the next transaction that uses this nonce. Mirrors Data::get_lamports_per_signature.

func (NonceData) MarshalWithEncoder ¶ added in v1.22.0

func (d NonceData) MarshalWithEncoder(encoder *bin.Encoder) (err error)

func (*NonceData) UnmarshalWithDecoder ¶ added in v1.22.0

func (d *NonceData) UnmarshalWithDecoder(decoder *bin.Decoder) (err error)

type NonceState ¶ added in v1.22.0

type NonceState struct {
	Kind NonceStateKind
	// Data is meaningful only when Kind == NonceStateInitialized.
	Data NonceData
}

NonceState is the state of a durable transaction nonce account: a discriminated union that is either Uninitialized or Initialized with NonceData.

func NewInitializedNonceState ¶ added in v1.22.0

func NewInitializedNonceState(authority PublicKey, durableNonce DurableNonce, lamportsPerSignature uint64) NonceState

NewInitializedNonceState builds an initialized nonce state. Mirrors State::new_initialized.

func (NonceState) IsInitialized ¶ added in v1.22.0

func (s NonceState) IsInitialized() bool

IsInitialized reports whether the nonce account has been initialized.

func (NonceState) MarshalWithEncoder ¶ added in v1.22.0

func (s NonceState) MarshalWithEncoder(encoder *bin.Encoder) (err error)

func (*NonceState) UnmarshalWithDecoder ¶ added in v1.22.0

func (s *NonceState) UnmarshalWithDecoder(decoder *bin.Decoder) (err error)

type NonceStateKind ¶ added in v1.22.0

type NonceStateKind uint32

NonceStateKind identifies whether a nonce account has been initialized.

const (
	NonceStateUninitialized NonceStateKind = 0
	NonceStateInitialized   NonceStateKind = 1
)

type NonceVersion ¶ added in v1.22.0

type NonceVersion uint32

NonceVersion identifies the version of a nonce account's state. Only Current nonces have durable-nonce and blockhash domains separated and can therefore authorize durable-nonce transactions.

const (
	NonceVersionLegacy  NonceVersion = 0
	NonceVersionCurrent NonceVersion = 1
)

type NonceVersions ¶ added in v1.22.0

type NonceVersions struct {
	Version NonceVersion
	State   NonceState
}

NonceVersions wraps a NonceState together with its version. It is the type stored in a nonce account's data. Mirrors solana_nonce::versions::Versions.

func DecodeNonceVersions ¶ added in v1.22.0

func DecodeNonceVersions(data []byte) (*NonceVersions, error)

DecodeNonceVersions decodes a nonce account's data into NonceVersions. Any trailing bytes (e.g. the zero padding present because the account is allocated at NonceStateSize) are ignored. The account-verification helpers use decodeNonceVersionsStrict instead, to match upstream bincode semantics.

func NewNonceVersions ¶ added in v1.22.0

func NewNonceVersions(state NonceState) NonceVersions

NewNonceVersions wraps a state in a Current version. Mirrors Versions::new.

func (NonceVersions) Authorize ¶ added in v1.22.0

func (v NonceVersions) Authorize(signers []PublicKey, newAuthority PublicKey) (NonceVersions, error)

Authorize sets a new authority on the nonce account. The current authority must be present in signers. The version variant is preserved because the durable_nonce field is not changed here. Mirrors Versions::authorize.

func (NonceVersions) LamportsPerSignature ¶ added in v1.22.0

func (v NonceVersions) LamportsPerSignature() (uint64, bool)

LamportsPerSignature returns the per-signature fee of an initialized nonce, or (0, false) when uninitialized.

func (NonceVersions) MarshalAccountData ¶ added in v1.22.0

func (v NonceVersions) MarshalAccountData() ([]byte, error)

MarshalAccountData returns the on-chain account data for this nonce, zero- padded to NonceStateSize bytes the way the runtime allocates it.

func (NonceVersions) MarshalBinary ¶ added in v1.22.0

func (v NonceVersions) MarshalBinary() ([]byte, error)

MarshalBinary returns the bincode-serialized nonce versions (8 bytes when uninitialized, NonceStateSize bytes when initialized).

func (NonceVersions) MarshalWithEncoder ¶ added in v1.22.0

func (v NonceVersions) MarshalWithEncoder(encoder *bin.Encoder) (err error)

func (*NonceVersions) UnmarshalBinary ¶ added in v1.22.0

func (v *NonceVersions) UnmarshalBinary(data []byte) error

UnmarshalBinary decodes nonce versions from bincode-serialized bytes, satisfying encoding.BinaryUnmarshaler as the counterpart to MarshalBinary. Like DecodeNonceVersions it tolerates trailing bytes (e.g. account padding).

func (*NonceVersions) UnmarshalWithDecoder ¶ added in v1.22.0

func (v *NonceVersions) UnmarshalWithDecoder(decoder *bin.Decoder) (err error)

func (NonceVersions) Upgrade ¶ added in v1.22.0

func (v NonceVersions) Upgrade() (NonceVersions, bool)

Upgrade migrates a Legacy nonce into the Current durable-nonce domain. It returns (_, false) when there is nothing to upgrade: the nonce is already Current, or it is an uninitialized Legacy nonce (which is upgraded on initialization instead). Mirrors Versions::upgrade.

func (NonceVersions) VerifyRecentBlockhash ¶ added in v1.22.0

func (v NonceVersions) VerifyRecentBlockhash(recentBlockhash Hash) (*NonceData, bool)

VerifyRecentBlockhash checks that recentBlockhash matches this nonce and returns the nonce data if so. Legacy versions never verify, because durable nonces in the legacy blockhash domain are invalid. Mirrors Versions::verify_recent_blockhash.

type PK ¶ added in v1.7.0

type PK = PublicKey

PK is a convenience alias for PublicKey

type Padding ¶

type Padding []byte

type PrivateKey ¶

type PrivateKey []byte

func MustPrivateKeyFromBase58 ¶

func MustPrivateKeyFromBase58(in string) PrivateKey

func NewRandomPrivateKey ¶

func NewRandomPrivateKey() (PrivateKey, error)

func PrivateKeyFromBase58 ¶

func PrivateKeyFromBase58(privkey string) (PrivateKey, error)

func PrivateKeyFromMnemonic ¶ added in v1.21.0

func PrivateKeyFromMnemonic(mnemonic, passphrase string) (PrivateKey, error)

PrivateKeyFromMnemonic derives a PrivateKey from a BIP-39 mnemonic using the default Solana derivation path (m/44'/501'/0'/0'). The passphrase may be empty; when set, it must match the passphrase used when the mnemonic was generated.

func PrivateKeyFromMnemonicAtPath ¶ added in v1.21.0

func PrivateKeyFromMnemonicAtPath(mnemonic, passphrase, path string) (PrivateKey, error)

PrivateKeyFromMnemonicAtPath derives a PrivateKey from a BIP-39 mnemonic at the given SLIP-0010 derivation path. All path segments must be hardened (suffixed with ' or h); SLIP-0010 does not define non-hardened derivation for ed25519.

func PrivateKeyFromSeedAtPath ¶ added in v1.21.0

func PrivateKeyFromSeedAtPath(seed []byte, path string) (PrivateKey, error)

PrivateKeyFromSeedAtPath derives a PrivateKey from a 16..64 byte seed (typically a 64 byte BIP-39 seed) using the given SLIP-0010 derivation path. All path segments must be hardened.

func PrivateKeyFromSolanaKeygenFile ¶

func PrivateKeyFromSolanaKeygenFile(file string) (PrivateKey, error)

func PrivateKeyFromSolanaKeygenFileBytes ¶ added in v1.12.0

func PrivateKeyFromSolanaKeygenFileBytes(content []byte) (PrivateKey, error)

func (PrivateKey) IsValid ¶ added in v1.12.0

func (k PrivateKey) IsValid() bool

IsValid returns whether the private key is valid.

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

func (PrivateKey) Validate ¶ added in v1.12.0

func (k PrivateKey) Validate() error

type PublicKey ¶

type PublicKey [PublicKeyLength]byte

func CreateProgramAddress ¶ added in v0.4.0

func CreateProgramAddress(seeds [][]byte, programID PublicKey) (PublicKey, error)

Create a program address. Ported from https://github.com/solana-labs/solana/blob/216983c50e0a618facc39aa07472ba6d23f1b33a/sdk/program/src/pubkey.rs#L204

func FindAssociatedTokenAddress ¶ added in v0.4.0

func FindAssociatedTokenAddress(
	wallet PublicKey,
	mint PublicKey,
) (PublicKey, uint8, error)

func FindAssociatedTokenAddressWithProgram ¶ added in v1.17.0

func FindAssociatedTokenAddressWithProgram(
	wallet PublicKey,
	mint PublicKey,
	tokenProgram PublicKey,
) (PublicKey, uint8, error)

FindAssociatedTokenAddressWithProgram returns the associated token account PDA for the provided wallet, mint, and token program.

func FindProgramAddress ¶ added in v0.4.0

func FindProgramAddress(seed [][]byte, programID PublicKey) (PublicKey, uint8, error)

Find a valid program address and its corresponding bump seed.

func FindTokenMetadataAddress ¶ added in v1.0.2

func FindTokenMetadataAddress(mint PublicKey) (PublicKey, uint8, error)

FindTokenMetadataAddress returns the token metadata program-derived address given a SPL token mint address.

func GetAssociatedAuthority ¶ added in v1.12.0

func GetAssociatedAuthority(programID PublicKey, marketAddr PublicKey) (PublicKey, uint8, error)

Get the marketAuthority(PDA) from the Market Initialization

func MPK ¶ added in v1.7.0

func MPK(in string) PublicKey

MPK is a convenience alias for MustPublicKeyFromBase58

func MustPublicKeyFromBase58 ¶

func MustPublicKeyFromBase58(in string) PublicKey

func PublicKeyFromBase58 ¶

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

PublicKeyFromBase58 creates a PublicKey from a base58 encoded string. NOTE: it will accept on- and off-curve pubkeys.

func PublicKeyFromBytes ¶

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

PublicKeyFromBytes creates a PublicKey from a byte slice that must be 32 bytes long. NOTE: it will accept on- and off-curve pubkeys.

func (PublicKey) Bytes ¶ added in v0.4.0

func (p PublicKey) Bytes() []byte

func (PublicKey) Equals ¶

func (p PublicKey) Equals(pb PublicKey) bool

func (PublicKey) IsAnyOf ¶ added in v1.8.0

func (p PublicKey) IsAnyOf(keys ...PublicKey) bool

IsAnyOf checks if p is equals to any of the provided keys.

func (PublicKey) IsOnCurve ¶ added in v1.0.4

func (p PublicKey) IsOnCurve() bool

Check if a `Pubkey` is on the voied25519 curve.

func (PublicKey) IsZero ¶

func (p PublicKey) IsZero() bool

IsZero returns whether the public key is zero. NOTE: the System Program public key is also zero.

func (PublicKey) MarshalBSON ¶ added in v1.8.2

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

MarshalBSON implements the bson.Marshaler interface.

func (PublicKey) MarshalBSONValue ¶ added in v1.8.2

func (p PublicKey) MarshalBSONValue() (bson.Type, []byte, error)

MarshalBSONValue implements the bson.ValueMarshaler interface.

func (PublicKey) MarshalJSON ¶

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

func (PublicKey) MarshalText ¶ added in v0.3.4

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

func (*PublicKey) Set ¶ added in v1.4.0

func (p *PublicKey) Set(s string) (err error)

func (PublicKey) Short ¶ added in v1.1.0

func (p PublicKey) Short(n int) string

Short returns a shortened pubkey string, only including the first n chars, ellipsis, and the last n characters. NOTE: this is ONLY for visual representation for humans, and cannot be used for anything else.

func (PublicKey) String ¶

func (p PublicKey) String() string

func (PublicKey) ToPointer ¶ added in v0.4.0

func (p PublicKey) ToPointer() *PublicKey

ToPointer returns a pointer to the pubkey.

func (*PublicKey) UnmarshalBSON ¶ added in v1.8.2

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

UnmarshalBSON implements the bson.Unmarshaler interface.

func (*PublicKey) UnmarshalBSONValue ¶ added in v1.8.2

func (p *PublicKey) UnmarshalBSONValue(t bson.Type, data []byte) (err error)

UnmarshalBSONValue implements the bson.ValueUnmarshaler interface.

func (*PublicKey) UnmarshalJSON ¶

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

func (*PublicKey) UnmarshalText ¶ added in v0.3.4

func (p *PublicKey) UnmarshalText(data []byte) error

func (PublicKey) Verify ¶ added in v1.7.0

func (p PublicKey) Verify(message []byte, signature Signature) bool

type PublicKeySlice ¶ added in v0.4.0

type PublicKeySlice []PublicKey

func (PublicKeySlice) Added ¶ added in v1.7.0

Added returns the elements that are present in `b` but not in `a`.

func (*PublicKeySlice) Append ¶ added in v0.4.0

func (slice *PublicKeySlice) Append(pubkeys ...PublicKey)

func (PublicKeySlice) Contains ¶ added in v1.7.0

func (slice PublicKeySlice) Contains(pubkey PublicKey) bool

Contains returns true if the slice contains the provided pubkey.

func (PublicKeySlice) ContainsAll ¶ added in v1.7.0

func (slice PublicKeySlice) ContainsAll(pubkeys PublicKeySlice) bool

ContainsAll returns true if all the provided pubkeys are present in the slice.

func (PublicKeySlice) ContainsAny ¶ added in v1.7.0

func (slice PublicKeySlice) ContainsAny(pubkeys ...PublicKey) bool

ContainsAny returns true if any of the provided pubkeys are present in the slice.

func (PublicKeySlice) Dedupe ¶ added in v1.7.0

func (slice PublicKeySlice) Dedupe() PublicKeySlice

Dedupe returns a new slice with all duplicate pubkeys removed.

func (PublicKeySlice) Equals ¶ added in v1.7.0

func (slice PublicKeySlice) Equals(other PublicKeySlice) bool

Equals returns true if the two PublicKeySlices are equal (same order of same keys).

func (PublicKeySlice) First ¶ added in v1.7.0

func (slice PublicKeySlice) First() *PublicKey

First returns the first element of the slice. Returns nil if the slice is empty.

func (PublicKeySlice) GetAddedRemoved ¶ added in v1.7.0

func (prev PublicKeySlice) GetAddedRemoved(next PublicKeySlice) (added PublicKeySlice, removed PublicKeySlice)

GetAddedRemoved compares to the `next` pubkey slice, and returns two slices: - `added` is the slice of pubkeys that are present in `next` but NOT present in `previous`. - `removed` is the slice of pubkeys that are present in `previous` but are NOT present in `next`.

func (PublicKeySlice) Has ¶ added in v0.4.0

func (slice PublicKeySlice) Has(pubkey PublicKey) bool

func (PublicKeySlice) Intersect ¶ added in v1.7.0

func (prev PublicKeySlice) Intersect(next PublicKeySlice) PublicKeySlice

Intersect returns the intersection of two PublicKeySlices, i.e. the elements that are in both PublicKeySlices. The returned PublicKeySlice is sorted and deduped.

func (PublicKeySlice) Last ¶ added in v1.7.0

func (slice PublicKeySlice) Last() *PublicKey

Last returns the last element of the slice. Returns nil if the slice is empty.

func (PublicKeySlice) Len ¶ added in v1.7.0

func (slice PublicKeySlice) Len() int

func (PublicKeySlice) Less ¶ added in v1.7.0

func (slice PublicKeySlice) Less(i, j int) bool

func (PublicKeySlice) Removed ¶ added in v1.7.0

Removed returns the elements that are present in `a` but not in `b`.

func (PublicKeySlice) Same ¶ added in v1.7.0

func (slice PublicKeySlice) Same(other PublicKeySlice) bool

Same returns true if the two slices contain the same public keys, but not necessarily in the same order.

func (PublicKeySlice) Sort ¶ added in v1.7.0

func (slice PublicKeySlice) Sort()

Sort sorts the slice.

func (PublicKeySlice) Split ¶ added in v1.1.0

func (slice PublicKeySlice) Split(chunkSize int) []PublicKeySlice

Split splits the slice into chunks of the specified size.

func (PublicKeySlice) Swap ¶ added in v1.7.0

func (slice PublicKeySlice) Swap(i, j int)

func (PublicKeySlice) ToBase58 ¶ added in v1.7.0

func (slice PublicKeySlice) ToBase58() []string

func (PublicKeySlice) ToBytes ¶ added in v1.7.0

func (slice PublicKeySlice) ToBytes() [][]byte

func (PublicKeySlice) ToPointers ¶ added in v1.7.0

func (slice PublicKeySlice) ToPointers() []*PublicKey

func (*PublicKeySlice) UniqueAppend ¶ added in v0.4.0

func (slice *PublicKeySlice) UniqueAppend(pubkey PublicKey) bool

UniqueAppend appends the provided pubkey only if it is not already present in the slice. Returns true when the provided pubkey wasn't already present.

type Signature ¶

type Signature [64]byte

func MustSignatureFromBase58 ¶

func MustSignatureFromBase58(in string) Signature

MustSignatureFromBase58 decodes a base58 string into a Signature. Panics on error.

func SignatureFromBase58 ¶

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

SignatureFromBase58 decodes a base58 string into a Signature.

func SignatureFromBytes ¶ added in v1.2.0

func SignatureFromBytes(in []byte) (out Signature)

SignatureFromBytes decodes a byte slice into a Signature.

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) MarshalText ¶ added in v1.6.0

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

func (Signature) String ¶

func (p Signature) String() string

func (*Signature) UnmarshalJSON ¶

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

func (*Signature) UnmarshalText ¶ added in v1.6.0

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

func (Signature) Verify ¶ added in v1.2.0

func (s Signature) Verify(pubkey PublicKey, msg []byte) bool

Verify checks that the signature is valid for the given public key and message.

type SystemAccountKind ¶ added in v1.22.0

type SystemAccountKind int

SystemAccountKind classifies a system-program-owned account.

const (
	SystemAccountKindSystem SystemAccountKind = iota
	SystemAccountKindNonce
)

func GetSystemAccountKind ¶ added in v1.22.0

func GetSystemAccountKind(owner PublicKey, data []byte) (SystemAccountKind, bool)

GetSystemAccountKind classifies a system-program-owned account as a plain system account or an initialized nonce account, returning (_, false) for any other account (wrong owner, or data that is neither empty nor a valid initialized nonce). Mirrors nonce_account::get_system_account_kind.

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 MustTransactionFromDecoder ¶ added in v0.4.1

func MustTransactionFromDecoder(decoder *bin.Decoder) *Transaction

MustTransactionFromDecoder decodes a transaction from a decoder. Panics on error.

func NewTransaction ¶

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

func TransactionFromBase58 ¶ added in v1.11.0

func TransactionFromBase58(b58 string) (*Transaction, error)

func TransactionFromBase64 ¶ added in v1.11.0

func TransactionFromBase64(b64 string) (*Transaction, error)

func TransactionFromBytes ¶ added in v1.11.0

func TransactionFromBytes(data []byte) (*Transaction, error)

func TransactionFromDecoder ¶ added in v0.4.0

func TransactionFromDecoder(decoder *bin.Decoder) (*Transaction, error)

TransactionFromDecoder decodes a transaction from a decoder.

func (*Transaction) AccountMetaList ¶

func (t *Transaction) AccountMetaList() ([]*AccountMeta, error)

func (*Transaction) EncodeToTree ¶ added in v0.4.0

func (tx *Transaction) EncodeToTree(parent treeout.Branches)

func (*Transaction) EncodeTree ¶ added in v0.4.0

func (tx *Transaction) EncodeTree(encoder *text.TreeEncoder) (int, error)

func (*Transaction) GetAccountIndex ¶ added in v1.9.0

func (t *Transaction) GetAccountIndex(account PublicKey) (uint16, error)

func (*Transaction) GetNonceAccount ¶ added in v1.17.0

func (tx *Transaction) GetNonceAccount() (PublicKey, bool)

GetNonceAccount returns the public key of the nonce account if this transaction uses a durable nonce. The nonce account is the first account of the first instruction (the AdvanceNonceAccount instruction). Returns the zero PublicKey and false if this is not a nonce transaction.

func (*Transaction) GetProgramIDs ¶ added in v1.11.0

func (tx *Transaction) GetProgramIDs() (PublicKeySlice, error)

func (*Transaction) HasAccount ¶ added in v1.2.0

func (t *Transaction) HasAccount(account PublicKey) (bool, error)

func (*Transaction) IsSigner ¶

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

func (*Transaction) IsVote ¶ added in v1.13.0

func (tx *Transaction) IsVote() bool

func (*Transaction) IsWritable ¶

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

func (*Transaction) MarshalBinary ¶ added in v0.3.5

func (tx *Transaction) MarshalBinary() ([]byte, error)

func (Transaction) MarshalWithEncoder ¶ added in v0.4.0

func (tx Transaction) MarshalWithEncoder(encoder *bin.Encoder) error

func (Transaction) MustToBase64 ¶ added in v1.3.0

func (tx Transaction) MustToBase64() string

func (*Transaction) NumReadonlyAccounts ¶ added in v1.11.0

func (tx *Transaction) NumReadonlyAccounts() int

func (*Transaction) NumSigners ¶ added in v1.11.0

func (tx *Transaction) NumSigners() int

func (*Transaction) NumWriteableAccounts ¶ added in v1.11.0

func (tx *Transaction) NumWriteableAccounts() int

func (*Transaction) PartialSign ¶ added in v1.7.0

func (tx *Transaction) PartialSign(getter privateKeyGetter) (out []Signature, err error)

func (*Transaction) ResolveProgramIDIndex ¶

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

func (*Transaction) Sanitize ¶ added in v1.17.0

func (tx *Transaction) Sanitize() error

Sanitize validates the structural integrity of a Transaction. It checks that the signature count matches the message header and that the message itself is valid. Ported from solana-sdk/transaction: lib.rs and versioned/mod.rs sanitize().

func (*Transaction) Sign ¶

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

func (*Transaction) String ¶ added in v1.2.0

func (tx *Transaction) String() string

String returns a human-readable string representation of the transaction data. To disable colors, set "github.com/gagliardetto/solana-go/text".DisableColors = true

func (Transaction) ToBase64 ¶ added in v1.3.0

func (tx Transaction) ToBase64() (string, error)

func (*Transaction) UnmarshalBase64 ¶ added in v1.7.0

func (tx *Transaction) UnmarshalBase64(b64 string) error

UnmarshalBase64 decodes a base64 encoded transaction.

func (*Transaction) UnmarshalWithDecoder ¶ added in v0.4.0

func (tx *Transaction) UnmarshalWithDecoder(decoder *bin.Decoder) (err error)

func (*Transaction) UsesDurableNonce ¶ added in v1.17.0

func (tx *Transaction) UsesDurableNonce() bool

UsesDurableNonce checks whether this transaction uses a durable nonce by inspecting the first instruction. Returns true if the first instruction is a System Program AdvanceNonceAccount instruction. Ported from solana-sdk/transaction: uses_durable_nonce().

func (*Transaction) VerifySignatures ¶ added in v1.2.0

func (tx *Transaction) VerifySignatures() error

VerifySignatures verifies all the signatures in the transaction against the pubkeys of the signers.

func (*Transaction) VerifyWithResults ¶ added in v1.17.0

func (tx *Transaction) VerifyWithResults() ([]bool, error)

VerifyWithResults verifies each signature independently and returns a per-signature boolean result. Ported from solana-sdk/transaction/lib.rs verify_with_results().

type TransactionBuilder ¶ added in v0.4.0

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

func NewTransactionBuilder ¶ added in v0.4.0

func NewTransactionBuilder() *TransactionBuilder

NewTransactionBuilder creates a new instruction builder.

func (*TransactionBuilder) AddInstruction ¶ added in v0.4.0

func (builder *TransactionBuilder) AddInstruction(instruction Instruction) *TransactionBuilder

AddInstruction adds the provided instruction to the builder.

func (*TransactionBuilder) Build ¶ added in v0.4.0

func (builder *TransactionBuilder) Build() (*Transaction, error)

Build builds and returns a *Transaction.

func (*TransactionBuilder) SetFeePayer ¶ added in v0.4.0

func (builder *TransactionBuilder) SetFeePayer(feePayer PublicKey) *TransactionBuilder

Set transaction fee payer. If not set, defaults to first signer account of the first instruction.

func (*TransactionBuilder) SetRecentBlockHash ¶ added in v0.4.0

func (builder *TransactionBuilder) SetRecentBlockHash(recentBlockHash Hash) *TransactionBuilder

SetRecentBlockHash sets the recent blockhash for the instruction builder.

func (*TransactionBuilder) WithOpt ¶ added in v0.4.0

WithOpt adds a TransactionOption.

type TransactionOption ¶

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

func TransactionAddressTables ¶ added in v1.8.0

func TransactionAddressTables(tables map[PublicKey]PublicKeySlice) TransactionOption

func TransactionPayer ¶

func TransactionPayer(payer PublicKey) TransactionOption

type Uint8SliceAsNum ¶ added in v1.8.4

type Uint8SliceAsNum []uint8

Uint8SliceAsNum is a slice of uint8s that can be marshaled as numbers instead of a byte slice.

func (Uint8SliceAsNum) MarshalJSON ¶ added in v1.8.4

func (slice Uint8SliceAsNum) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

type UnixTimeMilliseconds ¶ added in v1.5.0

type UnixTimeMilliseconds int64

UnixTimeMilliseconds represents a UNIX millisecond-resolution timestamp.

func (UnixTimeMilliseconds) String ¶ added in v1.5.0

func (res UnixTimeMilliseconds) String() string

func (UnixTimeMilliseconds) Time ¶ added in v1.5.0

func (res UnixTimeMilliseconds) Time() time.Time

type UnixTimeSeconds ¶ added in v0.5.0

type UnixTimeSeconds int64

UnixTimeSeconds represents a UNIX second-resolution timestamp.

func (UnixTimeSeconds) String ¶ added in v0.5.1

func (res UnixTimeSeconds) String() string

func (UnixTimeSeconds) Time ¶ added in v0.5.0

func (res UnixTimeSeconds) Time() time.Time

type Wallet ¶ added in v0.4.2

type Wallet struct {
	PrivateKey PrivateKey
}

Wallet is a wrapper around a PrivateKey

func NewWallet ¶ added in v0.4.2

func NewWallet() *Wallet

func NewWalletFromMnemonic ¶ added in v1.21.0

func NewWalletFromMnemonic(mnemonic, passphrase string) (*Wallet, error)

NewWalletFromMnemonic creates a Wallet whose private key is derived from a BIP-39 mnemonic using the default Solana derivation path m/44'/501'/0'/0'.

func WalletFromPrivateKeyBase58 ¶ added in v0.4.2

func WalletFromPrivateKeyBase58(privateKey string) (*Wallet, error)

func (*Wallet) PublicKey ¶ added in v0.4.2

func (a *Wallet) PublicKey() PublicKey

Directories ¶

Path Synopsis
cmd
slnc command
programs
token-2022/zkencryption
Package zkencryption ports the deterministic key-derivation functions from solana-zk-sdk (zk-sdk/src/encryption) to Go.
Package zkencryption ports the deterministic key-derivation functions from solana-zk-sdk (zk-sdk/src/encryption) to Go.
token-2022/zkencryption/examples/deriveKeys command
Command deriveKeys shows how to deterministically derive the two key materials used by the Token-2022 confidential-transfer extension from a Solana signer: the ElGamal secret key and the AES (AeKey) key.
Command deriveKeys shows how to deterministically derive the two key materials used by the Token-2022 confidential-transfer extension from a Solana signer: the ElGamal secret key and the AES (AeKey) key.
rpc
examples/createMint command
createMint builds and submits the two-instruction transaction that creates a new SPL Token mint on devnet:
createMint builds and submits the two-instruction transaction that creates a new SPL Token mint on devnet:
jsonrpc
Package jsonrpc provides a JSON-RPC 2.0 client that sends JSON-RPC requests and receives JSON-RPC responses using HTTP.
Package jsonrpc provides a JSON-RPC 2.0 client that sends JSON-RPC requests and receives JSON-RPC responses using HTTP.
ws

Jump to

Keyboard shortcuts

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