├── docs ├── .gitignore ├── src │ ├── .vuepress │ │ └── .gitignore │ ├── tour │ │ ├── mint-to.md │ │ ├── token-transfer.md │ │ ├── get-token-account.md │ │ ├── get-token-balance.md │ │ ├── create-mint.md │ │ ├── get-mint.md │ │ ├── get-sol-balance.md │ │ ├── create-token-account.md │ │ ├── request-airdrop.md │ │ ├── create-account.md │ │ └── transfer.md │ ├── nft │ │ ├── get-metadata.md │ │ ├── mint-a-nft.md │ │ └── sign-metadata.md │ ├── programs │ │ ├── 101 │ │ │ ├── data.md │ │ │ ├── hello.md │ │ │ └── accounts.md │ │ └── stake │ │ │ ├── withdraw.md │ │ │ ├── initialize-account.md │ │ │ ├── deactivate.md │ │ │ └── delegate.md │ ├── advanced │ │ ├── memo.md │ │ └── durable-nonce │ │ │ ├── create-nonce-account.md │ │ │ ├── get-nonce-account-by-owner.md │ │ │ ├── use-nonce.md │ │ │ ├── get-nonce-account.md │ │ │ ├── README.md │ │ │ └── upgrade-nonce.md │ ├── README.md │ └── rpc │ │ └── get-signatures-for-address.md ├── _examples │ ├── program │ │ ├── 101 │ │ │ ├── data │ │ │ │ └── program │ │ │ │ │ ├── .gitignore │ │ │ │ │ ├── Cargo.toml │ │ │ │ │ └── src │ │ │ │ │ └── lib.rs │ │ │ ├── hello │ │ │ │ └── program │ │ │ │ │ ├── .gitignore │ │ │ │ │ ├── Cargo.toml │ │ │ │ │ └── src │ │ │ │ │ └── lib.rs │ │ │ └── accounts │ │ │ │ └── program │ │ │ │ ├── .gitignore │ │ │ │ ├── Cargo.toml │ │ │ │ └── src │ │ │ │ └── lib.rs │ │ ├── address-lookup-table │ │ │ ├── get │ │ │ │ └── main.go │ │ │ ├── freeze │ │ │ │ └── main.go │ │ │ ├── deactivate │ │ │ │ └── main.go │ │ │ ├── close │ │ │ │ └── main.go │ │ │ └── extend │ │ │ │ └── main.go │ │ ├── compute-budget │ │ │ ├── set-compute-unit-limit │ │ │ │ └── main.go │ │ │ └── set-compute-unit-price │ │ │ │ └── main.go │ │ ├── stake │ │ │ └── deactivate │ │ │ │ └── main.go │ │ ├── memo │ │ │ └── main.go │ │ ├── metaplex │ │ │ └── token-metadata │ │ │ │ └── sign-metadata │ │ │ │ └── main.go │ │ └── system │ │ │ └── transfer │ │ │ └── main.go │ ├── rpc │ │ ├── get-health │ │ │ └── main.go │ │ ├── get-balance │ │ │ └── main.go │ │ ├── request-airdrop │ │ │ └── main.go │ │ └── get-multiple-accounts │ │ │ └── main.go │ ├── client │ │ ├── get-version │ │ │ └── main.go │ │ ├── get-token-account │ │ │ └── main.go │ │ ├── get-account-info │ │ │ └── main.go │ │ ├── get-token-accounts-by-owner │ │ │ └── main.go │ │ ├── get-slot │ │ │ └── main.go │ │ └── get-balance │ │ │ └── main.go │ ├── tour │ │ ├── get-sol-balance │ │ │ └── main.go │ │ ├── request-airdrop │ │ │ └── main.go │ │ ├── get-token-balance │ │ │ └── main.go │ │ ├── get-token-account │ │ │ └── main.go │ │ ├── get-mint │ │ │ └── main.go │ │ └── transfer-sol │ │ │ └── main.go │ ├── advanced │ │ └── durable-nonce │ │ │ ├── get-nonce-from-nonce-account │ │ │ └── main.go │ │ │ ├── get-nonce-account │ │ │ └── main.go │ │ │ ├── get-nonce-account-by-owner │ │ │ └── main.go │ │ │ ├── upgrade-nonce-account │ │ │ └── main.go │ │ │ └── advance-nonce │ │ │ └── main.go │ └── nft │ │ └── get-metadata │ │ └── main.go └── package.json ├── pkg ├── pointer │ ├── pointer.go │ └── pointer_test.go ├── bincode │ ├── varbyte.go │ └── varbyte_test.go ├── bytes_decoder │ └── decoder.go └── hdwallet │ └── path.go ├── program ├── memoprog │ ├── deprecated.go │ ├── instruction.go │ └── instruction_test.go ├── sysprog │ ├── deprecated.go │ ├── state_test.go │ └── state.go ├── nsprog │ ├── deprecated.go │ ├── state.go │ └── utils.go ├── stakeprog │ └── deprecated.go ├── tokenprog │ ├── deprecated.go │ └── error.go ├── cmptbdgprog │ └── deprecated.go ├── assotokenprog │ ├── deprecated.go │ └── instruction.go ├── metaplex │ ├── tokenmeta │ │ ├── deprecated.go │ │ └── utils.go │ └── token_metadata │ │ └── utils.go ├── token │ └── error.go ├── sysvar │ ├── error.go │ ├── slot_hashes.go │ └── slot_hashes_test.go ├── address_lookup_table │ └── error.go ├── name_service │ ├── state.go │ └── utils.go ├── memo │ ├── instruction.go │ └── instruction_test.go ├── system │ ├── state_test.go │ └── state.go └── secp256k1 │ └── instruction_test.go ├── rpc ├── get_genesis_hash.go ├── get_block_time.go ├── get_slot_leaders.go ├── get_first_available_block.go ├── get_health.go ├── get_identity.go ├── minimum_ledger_slot.go ├── get_version.go ├── options_test.go ├── get_inflation_rate.go ├── get_block_commitment.go ├── get_cluster_nodes.go ├── get_slot.go ├── get_recent_prioritization_fees.go ├── options.go ├── get_epoch_schedule.go ├── minimum_ledger_slot_test.go ├── get_first_available_block_test.go ├── get_block_height.go ├── get_slot_leader.go ├── get_genesis_hash_test.go ├── get_transaction_count.go ├── get_identity_test.go ├── get_balance.go ├── request_aridrop.go ├── get_blocks.go ├── get_version_test.go ├── get_blocks_with_limit.go ├── get_inflation_rate_test.go ├── get_minimum_balance_for_rent_exemption.go ├── is_blockhash_valid.go ├── get_token_account_balance.go ├── get_epoch_info.go ├── get_epoch_schedule_test.go ├── get_account_info.go ├── get_inflation_governor.go ├── get_fee_for_message.go ├── get_token_supply.go ├── get_slot_test.go ├── get_multiple_accounts.go ├── send_transaction.go ├── get_block_height_test.go ├── get_signature_statuses.go ├── get_cluster_nodes_test.go ├── get_transaction_count_test.go ├── get_inflation_reward.go ├── get_block_production.go ├── get_token_account_by_owner.go ├── get_latest_blockhash.go ├── get_minimum_balance_for_rent_exemption_test.go ├── client_test.go ├── get_vote_accounts.go ├── get_blocks_test.go ├── get_signatures_for_address.go ├── get_slot_leaders_test.go ├── get_block_commitment_test.go ├── is_blockhash_valid_test.go ├── request_aridrop_test.go └── get_inflation_governor_test.go ├── client ├── rpc_get_genesis_hash.go ├── token.go ├── rpc_get_block_time.go ├── rpc_get_identity.go ├── rpc_get_version.go ├── rpc_get_first_available_block.go ├── rpc_get_slot_leaders.go ├── rpc_minimum_ledger_slot.go ├── rpc_get_health.go ├── rpc_minimum_ledger_slot_test.go ├── rpc_get_first_available_block_test.go ├── rpc_get_genesis_hash_test.go ├── rpc_get_recent_prioritization_fees.go ├── rpc_get_identity_test.go ├── rpc_get_version_test.go ├── rpc_get_slot.go ├── rpc_get_epoch_info.go ├── system.go ├── rpc_get_epoch_info_test.go ├── rpc_get_slot_leader.go ├── rpc_get_transaction_count.go ├── rpc_request_airdrop.go ├── rpc_get_block_time_test.go ├── rpc_get_cluster_node.go ├── rpc_get_signatures_for_address.go ├── rpc_get_minimum_balance_for_rent_exemption.go ├── rpc_get_slot_test.go ├── rpc_get_cluster_node_test.go ├── rpc_get_transaction_count_test.go ├── client_test.go ├── rpc_get_minimum_balance_for_rent_exemption_test.go ├── rpc_test.go ├── rpc_get_vote_accounts_test.go ├── rpc_get_slot_leaders_test.go ├── rpc_is_blockhash_valid.go ├── rpc_get_health_test.go ├── rpc_send_transaction.go ├── rpc_request_airdrop_test.go └── rpc_get_balance.go ├── types └── instruction.go ├── go.mod ├── .github └── workflows │ ├── code-scanning.yml │ ├── golangci-lint.yml │ ├── go.yml │ └── docs.yml ├── common ├── system_var.go └── program_id.go ├── LICENSE ├── internal └── client_test │ └── case.go └── go.sum /docs/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .temp 3 | .cache 4 | -------------------------------------------------------------------------------- /docs/src/.vuepress/.gitignore: -------------------------------------------------------------------------------- 1 | .temp 2 | .cache 3 | -------------------------------------------------------------------------------- /docs/_examples/program/101/data/program/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /docs/_examples/program/101/hello/program/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /docs/_examples/program/101/accounts/program/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /docs/src/tour/mint-to.md: -------------------------------------------------------------------------------- 1 | # Mint To 2 | 3 | @[code](@/tour/mint-to/main.go) 4 | -------------------------------------------------------------------------------- /docs/src/nft/get-metadata.md: -------------------------------------------------------------------------------- 1 | # Get Token Metadata 2 | 3 | @[code](@/nft/get-metadata/main.go) 4 | -------------------------------------------------------------------------------- /pkg/pointer/pointer.go: -------------------------------------------------------------------------------- 1 | package pointer 2 | 3 | func Get[T any](v T) *T { 4 | return &v 5 | } 6 | -------------------------------------------------------------------------------- /docs/src/nft/mint-a-nft.md: -------------------------------------------------------------------------------- 1 | # Mint A NFT 2 | 3 | @[code](@/nft/mint-a-nft-with-master-edition/main.go) -------------------------------------------------------------------------------- /docs/src/programs/stake/withdraw.md: -------------------------------------------------------------------------------- 1 | # Withdraw 2 | 3 | @[code](@/program/stake/withdraw/main.go) 4 | -------------------------------------------------------------------------------- /docs/src/tour/token-transfer.md: -------------------------------------------------------------------------------- 1 | # Token Transfer 2 | 3 | @[code](@/tour/token-transfer/main.go) 4 | -------------------------------------------------------------------------------- /docs/src/tour/get-token-account.md: -------------------------------------------------------------------------------- 1 | # Get Token Account 2 | 3 | @[code](@/tour/get-token-account/main.go) 4 | -------------------------------------------------------------------------------- /docs/src/tour/get-token-balance.md: -------------------------------------------------------------------------------- 1 | # Get Token Balance 2 | 3 | @[code](@/tour/get-token-balance/main.go) 4 | -------------------------------------------------------------------------------- /docs/src/tour/create-mint.md: -------------------------------------------------------------------------------- 1 | # Create Mint 2 | 3 | create a new token 4 | 5 | @[code](@/tour/create-mint/main.go) 6 | -------------------------------------------------------------------------------- /docs/src/tour/get-mint.md: -------------------------------------------------------------------------------- 1 | # Get Mint 2 | 3 | get detail from a exist mint 4 | 5 | @[code](@/tour/get-mint/main.go) 6 | -------------------------------------------------------------------------------- /program/memoprog/deprecated.go: -------------------------------------------------------------------------------- 1 | // Deprecated: please use github.com/blocto/solana-go-sdk/program/memo 2 | package memoprog 3 | -------------------------------------------------------------------------------- /program/sysprog/deprecated.go: -------------------------------------------------------------------------------- 1 | // Deprecated: please use github.com/blocto/solana-go-sdk/program/system 2 | package sysprog 3 | -------------------------------------------------------------------------------- /docs/src/programs/stake/initialize-account.md: -------------------------------------------------------------------------------- 1 | # Initialize Account 2 | 3 | @[code](@/program/stake/initialize-account/main.go) 4 | -------------------------------------------------------------------------------- /program/nsprog/deprecated.go: -------------------------------------------------------------------------------- 1 | // Deprecated: please use github.com/blocto/solana-go-sdk/program/name_service 2 | package nsprog 3 | -------------------------------------------------------------------------------- /program/stakeprog/deprecated.go: -------------------------------------------------------------------------------- 1 | // Deprecated: please use github.com/blocto/solana-go-sdk/program/stake 2 | package stakeprog 3 | -------------------------------------------------------------------------------- /program/tokenprog/deprecated.go: -------------------------------------------------------------------------------- 1 | // Deprecated: please use github.com/blocto/solana-go-sdk/program/token 2 | package tokenprog 3 | -------------------------------------------------------------------------------- /program/cmptbdgprog/deprecated.go: -------------------------------------------------------------------------------- 1 | // Deprecated: please use github.com/blocto/solana-go-sdk/program/compute_budget 2 | package cmptbdgprog 3 | -------------------------------------------------------------------------------- /docs/src/advanced/memo.md: -------------------------------------------------------------------------------- 1 | # Add Memo 2 | 3 | You can add a memo to your transaction by memo instruction 4 | 5 | @[code](@/program/memo/main.go) 6 | -------------------------------------------------------------------------------- /docs/src/advanced/durable-nonce/create-nonce-account.md: -------------------------------------------------------------------------------- 1 | # Create Nonce Account 2 | 3 | @[code](@/advanced/durable-nonce/create-nonce-account/main.go) 4 | -------------------------------------------------------------------------------- /program/assotokenprog/deprecated.go: -------------------------------------------------------------------------------- 1 | // Deprecated: please use github.com/blocto/solana-go-sdk/program/associated_token_account 2 | package assotokenprog 3 | -------------------------------------------------------------------------------- /program/metaplex/tokenmeta/deprecated.go: -------------------------------------------------------------------------------- 1 | // Deprecated: please use github.com/blocto/solana-go-sdk/program/metaplex/token_metadata 2 | package tokenmeta 3 | -------------------------------------------------------------------------------- /docs/src/README.md: -------------------------------------------------------------------------------- 1 | # Solana Development With Go 2 | 3 | Here is a book to help someone build something on [Solana](https://github.com/solana-labs/solana) with Go. 4 | -------------------------------------------------------------------------------- /docs/src/advanced/durable-nonce/get-nonce-account-by-owner.md: -------------------------------------------------------------------------------- 1 | # Get Nonce Account By Owner 2 | 3 | @[code](@/advanced/durable-nonce/get-nonce-account-by-owner/main.go) 4 | -------------------------------------------------------------------------------- /docs/src/nft/sign-metadata.md: -------------------------------------------------------------------------------- 1 | # Sign Metadata 2 | 3 | to convert a unverified creator to a verifeid creator. 4 | 5 | @[code](@/program/metaplex/token-metadata/sign-metadata/main.go) -------------------------------------------------------------------------------- /docs/src/programs/101/data.md: -------------------------------------------------------------------------------- 1 | # Data 2 | 3 | ### client 4 | @[code](@/program/101/data/client/main.go) 5 | 6 | ### program 7 | @[code](@/program/101/data/program/src/lib.rs) 8 | -------------------------------------------------------------------------------- /docs/src/programs/101/hello.md: -------------------------------------------------------------------------------- 1 | # Hello 2 | 3 | ### client 4 | @[code](@/program/101/hello/client/main.go) 5 | 6 | ### program 7 | @[code](@/program/101/hello/program/src/lib.rs) 8 | -------------------------------------------------------------------------------- /docs/src/tour/get-sol-balance.md: -------------------------------------------------------------------------------- 1 | # Get Balance 2 | 3 | get sol balance 4 | 5 | @[code](@/rpc/get-balance/main.go) 6 | 7 | ::: tip 8 | 1 SOL = 10^9 lamports 9 | ::: 10 | -------------------------------------------------------------------------------- /docs/src/programs/101/accounts.md: -------------------------------------------------------------------------------- 1 | # Accounts 2 | 3 | ### client 4 | @[code](@/program/101/accounts/client/main.go) 5 | 6 | ### program 7 | @[code](@/program/101/accounts/program/src/lib.rs) 8 | -------------------------------------------------------------------------------- /docs/src/advanced/durable-nonce/use-nonce.md: -------------------------------------------------------------------------------- 1 | # Use Nonce 2 | 3 | @[code](@/advanced/durable-nonce/use-nonce/main.go) 4 | 5 | ::: tip 6 | 7 | You need to query nonce again after you used. 8 | 9 | ::: 10 | -------------------------------------------------------------------------------- /program/token/error.go: -------------------------------------------------------------------------------- 1 | package token 2 | 3 | import "errors" 4 | 5 | var ( 6 | ErrInvalidAccountOwner = errors.New("invalid account owner") 7 | ErrInvalidAccountDataSize = errors.New("invalid account data size") 8 | ) 9 | -------------------------------------------------------------------------------- /program/sysvar/error.go: -------------------------------------------------------------------------------- 1 | package sysvar 2 | 3 | import "errors" 4 | 5 | var ( 6 | ErrInvalidAccountOwner = errors.New("invalid account owner") 7 | ErrInvalidAccountDataSize = errors.New("invalid account data size") 8 | ) 9 | -------------------------------------------------------------------------------- /program/tokenprog/error.go: -------------------------------------------------------------------------------- 1 | package tokenprog 2 | 3 | import "errors" 4 | 5 | var ( 6 | ErrInvalidAccountOwner = errors.New("invalid account owner") 7 | ErrInvalidAccountDataSize = errors.New("invalid account data size") 8 | ) 9 | -------------------------------------------------------------------------------- /docs/src/programs/stake/deactivate.md: -------------------------------------------------------------------------------- 1 | # Deactivate (unstake) 2 | 3 | ::: tip 4 | Activation requires waiting for 1 epoch. You can use `solana-test-validator --slot-per-epoch ` for test. 5 | ::: 6 | 7 | @[code](@/program/stake/deactivate/main.go) 8 | -------------------------------------------------------------------------------- /docs/src/programs/stake/delegate.md: -------------------------------------------------------------------------------- 1 | # Delegate (stake) 2 | 3 | ::: tip 4 | Activation requires waiting for 1 epoch. You can use `solana-test-validator --slot-per-epoch ` for test. 5 | ::: 6 | 7 | @[code](@/program/stake/delegate-stake/main.go) 8 | -------------------------------------------------------------------------------- /docs/src/tour/create-token-account.md: -------------------------------------------------------------------------------- 1 | # Create Token Account 2 | 3 | ## Associated Token Account (Recommended) 4 | 5 | @[code](@/tour/create-associated-token-account/main.go) 6 | 7 | ## Random 8 | 9 | @[code](@/tour/create-random-token-account/main.go) 10 | -------------------------------------------------------------------------------- /docs/src/advanced/durable-nonce/get-nonce-account.md: -------------------------------------------------------------------------------- 1 | # Get Nonce Account 2 | 3 | ## Nonce Account 4 | 5 | @[code](@/advanced/durable-nonce/get-nonce-account/main.go) 6 | 7 | ## Only Nonce 8 | 9 | @[code](@/advanced/durable-nonce/get-nonce-from-nonce-account/main.go) 10 | -------------------------------------------------------------------------------- /docs/_examples/program/101/data/program/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["yihau "] 3 | edition = "2021" 4 | name = "data" 5 | version = "0.1.0" 6 | 7 | [dependencies] 8 | solana-program = "=1.14.17" 9 | 10 | [lib] 11 | crate-type = ["cdylib", "lib"] 12 | -------------------------------------------------------------------------------- /docs/_examples/program/101/hello/program/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["yihau "] 3 | edition = "2021" 4 | name = "hello" 5 | version = "0.1.0" 6 | 7 | [dependencies] 8 | solana-program = "=1.14.17" 9 | 10 | [lib] 11 | crate-type = ["cdylib", "lib"] 12 | -------------------------------------------------------------------------------- /docs/_examples/program/101/accounts/program/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["yihau "] 3 | edition = "2021" 4 | name = "accounts" 5 | version = "0.1.0" 6 | 7 | [dependencies] 8 | solana-program = "=1.14.17" 9 | 10 | [lib] 11 | crate-type = ["cdylib", "lib"] 12 | -------------------------------------------------------------------------------- /docs/src/tour/request-airdrop.md: -------------------------------------------------------------------------------- 1 | # Request Airdrop 2 | 3 | Request some airdrop for testing. 4 | 5 | @[code](@/tour/request-airdrop/main.go) 6 | 7 | ::: tip 8 | you can look up this tx on [https://explorer.solana.com/?cluster=devnet](https://explorer.solana.com/?cluster=devnet) 9 | ::: 10 | -------------------------------------------------------------------------------- /program/address_lookup_table/error.go: -------------------------------------------------------------------------------- 1 | package address_lookup_table 2 | 3 | import "errors" 4 | 5 | var ( 6 | ErrInvalidAccountOwner = errors.New("invalid account owner") 7 | ErrInvalidAccountDataSize = errors.New("invalid account data size") 8 | ErrInvalidAccountData = errors.New("invalid account data") 9 | ) 10 | -------------------------------------------------------------------------------- /rpc/get_genesis_hash.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetGenesisHashResponse JsonRpcResponse[string] 8 | 9 | // GetGenesisHash returns the genesis hash 10 | func (c *RpcClient) GetGenesisHash(ctx context.Context) (JsonRpcResponse[string], error) { 11 | return call[JsonRpcResponse[string]](c, ctx, "getGenesisHash") 12 | } 13 | -------------------------------------------------------------------------------- /rpc/get_block_time.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetBlockTimeResponse JsonRpcResponse[*int64] 8 | 9 | // GetBlockTime returns the estimated production time of a block. 10 | func (c *RpcClient) GetBlockTime(ctx context.Context, slot uint64) (JsonRpcResponse[*int64], error) { 11 | return call[JsonRpcResponse[*int64]](c, ctx, "getBlockTime", slot) 12 | } 13 | -------------------------------------------------------------------------------- /docs/_examples/program/101/hello/program/src/lib.rs: -------------------------------------------------------------------------------- 1 | use solana_program::{ 2 | account_info::AccountInfo, entrypoint, entrypoint::ProgramResult, msg, pubkey::Pubkey, 3 | }; 4 | 5 | entrypoint!(process_instruction); 6 | 7 | fn process_instruction( 8 | _program_id: &Pubkey, 9 | _accounts: &[AccountInfo], 10 | _instruction_data: &[u8], 11 | ) -> ProgramResult { 12 | msg!("hello"); 13 | Ok(()) 14 | } 15 | -------------------------------------------------------------------------------- /docs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "docs", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "license": "MIT", 6 | "scripts": { 7 | "docs:dev": "vuepress dev src", 8 | "docs:build": "vuepress build src" 9 | }, 10 | "devDependencies": { 11 | "@snippetors/vuepress-plugin-code-copy": "^1.1.2", 12 | "@vuepress/plugin-back-to-top": "^2.0.0-beta.35", 13 | "vuepress": "^2.0.0-beta.35" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /client/rpc_get_genesis_hash.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | // GetGenesisHash returns the genesis hash 10 | func (c *Client) GetGenesisHash(ctx context.Context) (string, error) { 11 | return process( 12 | func() (rpc.JsonRpcResponse[string], error) { 13 | return c.RpcClient.GetGenesisHash(ctx) 14 | }, 15 | forward[string], 16 | ) 17 | } 18 | -------------------------------------------------------------------------------- /docs/src/advanced/durable-nonce/README.md: -------------------------------------------------------------------------------- 1 | # Durable Nonce 2 | 3 | A transaction includes a recent blockhash. The recent blockhash will expire after 150 blocks. (arpox. 2 min) 4 | To get rid of it, you can use durable nonce. 5 | 6 | ## Mechanism 7 | 8 | We can trigger the mechanism by 9 | 10 | 1. use the `nonce` which stored in a nonce account as a recent blockhash 11 | 2. make `nonce advance` instruction is the first instruciton 12 | -------------------------------------------------------------------------------- /docs/_examples/rpc/get-health/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | ok, err := c.GetHealth(context.TODO()) 15 | if err != nil { 16 | log.Fatalf("failed to get health, err: %v", err) 17 | } 18 | 19 | fmt.Println(ok) 20 | } 21 | -------------------------------------------------------------------------------- /rpc/get_slot_leaders.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import "context" 4 | 5 | type GetSlotLeadersResponse JsonRpcResponse[[]string] 6 | 7 | // GetSlotLeaders returns the slot leaders for a given slot range 8 | // (limit: 1~5000) 9 | func (c *RpcClient) GetSlotLeaders(ctx context.Context, startSlot uint64, limit uint64) (JsonRpcResponse[[]string], error) { 10 | return call[JsonRpcResponse[[]string]](c, ctx, "getSlotLeaders", startSlot, limit) 11 | } 12 | -------------------------------------------------------------------------------- /client/token.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/program/token" 7 | ) 8 | 9 | func (c *Client) GetTokenAccount(ctx context.Context, base58Addr string) (token.TokenAccount, error) { 10 | accountInfo, err := c.GetAccountInfo(ctx, base58Addr) 11 | if err != nil { 12 | return token.TokenAccount{}, err 13 | } 14 | return token.DeserializeTokenAccount(accountInfo.Data, accountInfo.Owner) 15 | } 16 | -------------------------------------------------------------------------------- /rpc/get_first_available_block.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetFirstAvailableBlockResponse JsonRpcResponse[uint64] 8 | 9 | // GetFirstAvailableBlock returns the slot of the lowest confirmed block that has not been purged from the ledger 10 | func (c *RpcClient) GetFirstAvailableBlock(ctx context.Context) (JsonRpcResponse[uint64], error) { 11 | return call[JsonRpcResponse[uint64]](c, ctx, "getFirstAvailableBlock") 12 | } 13 | -------------------------------------------------------------------------------- /rpc/get_health.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetHealthResponse JsonRpcResponse[string] 8 | 9 | // GetHealthResponse returns the current health of the node. A healthy node is one that is within HEALTH_CHECK_SLOT_DISTANCE slots of the latest cluster confirmed slot. 10 | func (c *RpcClient) GetHealth(ctx context.Context) (JsonRpcResponse[string], error) { 11 | return call[JsonRpcResponse[string]](c, ctx, "getHealth") 12 | } 13 | -------------------------------------------------------------------------------- /client/rpc_get_block_time.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | // GetBlockTime returns the estimated production time of a block. 10 | func (c *Client) GetBlockTime(ctx context.Context, slot uint64) (*int64, error) { 11 | return process( 12 | func() (rpc.JsonRpcResponse[*int64], error) { 13 | return c.RpcClient.GetBlockTime(ctx, slot) 14 | }, 15 | forward[*int64], 16 | ) 17 | } 18 | -------------------------------------------------------------------------------- /client/rpc_get_identity.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | // GetIdentity returns the identity pubkey for the current node 10 | func (c *Client) GetIdentity(ctx context.Context) (rpc.GetIdentity, error) { 11 | return process( 12 | func() (rpc.JsonRpcResponse[rpc.GetIdentity], error) { 13 | return c.RpcClient.GetIdentity(ctx) 14 | }, 15 | forward[rpc.GetIdentity], 16 | ) 17 | } 18 | -------------------------------------------------------------------------------- /client/rpc_get_version.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | // GetVersion returns the current solana versions running on the node 10 | func (c *Client) GetVersion(ctx context.Context) (rpc.GetVersion, error) { 11 | return process( 12 | func() (rpc.JsonRpcResponse[rpc.GetVersion], error) { 13 | return c.RpcClient.GetVersion(ctx) 14 | }, 15 | forward[rpc.GetVersion], 16 | ) 17 | } 18 | -------------------------------------------------------------------------------- /rpc/get_identity.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetIdentityResponse JsonRpcResponse[GetIdentity] 8 | 9 | type GetIdentity struct { 10 | Identity string `json:"identity"` 11 | } 12 | 13 | // GetIdentity returns the identity pubkey for the current node 14 | func (c *RpcClient) GetIdentity(ctx context.Context) (JsonRpcResponse[GetIdentity], error) { 15 | return call[JsonRpcResponse[GetIdentity]](c, ctx, "getIdentity") 16 | } 17 | -------------------------------------------------------------------------------- /types/instruction.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "github.com/blocto/solana-go-sdk/common" 4 | 5 | type CompiledInstruction struct { 6 | ProgramIDIndex int 7 | Accounts []int 8 | Data []byte 9 | } 10 | 11 | type Instruction struct { 12 | ProgramID common.PublicKey 13 | Accounts []AccountMeta 14 | Data []byte 15 | } 16 | 17 | type AccountMeta struct { 18 | PubKey common.PublicKey 19 | IsSigner bool 20 | IsWritable bool 21 | } 22 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/blocto/solana-go-sdk 2 | 3 | go 1.19 4 | 5 | require ( 6 | filippo.io/edwards25519 v1.0.0-rc.1 7 | github.com/mr-tron/base58 v1.2.0 8 | github.com/near/borsh-go v0.3.2-0.20220516180422-1ff87d108454 9 | github.com/stretchr/testify v1.7.0 10 | ) 11 | 12 | require ( 13 | github.com/davecgh/go-spew v1.1.1 // indirect 14 | github.com/pmezard/go-difflib v1.0.0 // indirect 15 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect 16 | ) 17 | -------------------------------------------------------------------------------- /.github/workflows/code-scanning.yml: -------------------------------------------------------------------------------- 1 | name: code scanning 2 | 3 | on: 4 | pull_request: 5 | schedule: 6 | - cron: 0 1 * * 4 7 | 8 | jobs: 9 | scan: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v3 14 | 15 | - name: Initialize 16 | uses: github/codeql-action/init@v2 17 | with: 18 | languages: go 19 | 20 | - name: Analyze 21 | uses: github/codeql-action/analyze@v2 -------------------------------------------------------------------------------- /docs/_examples/client/get-version/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.MainnetRPCEndpoint) 14 | 15 | resp, err := c.GetVersion(context.TODO()) 16 | if err != nil { 17 | log.Fatalf("failed to version info, err: %v", err) 18 | } 19 | 20 | fmt.Println("version", resp.SolanaCore) 21 | } 22 | -------------------------------------------------------------------------------- /pkg/bincode/varbyte.go: -------------------------------------------------------------------------------- 1 | package bincode 2 | 3 | import ( 4 | "encoding/binary" 5 | ) 6 | 7 | func UintToVarLenBytes(l uint64) []byte { 8 | if l == 0 { 9 | return []byte{0x0} 10 | } 11 | b := make([]byte, binary.MaxVarintLen64) 12 | binary.PutUvarint(b, l) 13 | trimTrailingZeroByte(&b) 14 | return b 15 | } 16 | 17 | func trimTrailingZeroByte(b *[]byte) { 18 | for len(*b) > 0 { 19 | if (*b)[len(*b)-1] != 0 { 20 | break 21 | } 22 | *b = (*b)[:len(*b)-1] 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /docs/src/advanced/durable-nonce/upgrade-nonce.md: -------------------------------------------------------------------------------- 1 | # Upgrade Nonce 2 | 3 | Due to [2022/06/01 Solana outage](https://solana.com/news/06-01-22-solana-mainnet-beta-outage-report-2). All nonce account should be upgraded. You can update it either 4 | 5 | 1. Advance Nonce (need origin authority signature) 6 | 7 | @[code](@/advanced/durable-nonce/advance-nonce/main.go) 8 | 9 | 2. Upgrade Nonce (you can use a random fee payer) 10 | 11 | @[code](@/advanced/durable-nonce/upgrade-nonce-account/main.go) 12 | -------------------------------------------------------------------------------- /rpc/minimum_ledger_slot.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type MinimumLedgerSlotResponse JsonRpcResponse[uint64] 8 | 9 | // MinimumLedgerSlot returns the lowest slot that the node has information about in its ledger. 10 | // This value may increase over time if the node is configured to purge older ledger data 11 | func (c *RpcClient) MinimumLedgerSlot(ctx context.Context) (JsonRpcResponse[uint64], error) { 12 | return call[JsonRpcResponse[uint64]](c, ctx, "minimumLedgerSlot") 13 | } 14 | -------------------------------------------------------------------------------- /client/rpc_get_first_available_block.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | // GetFirstAvailableBlock returns the slot of the lowest confirmed block that has not been purged from the ledger 10 | func (c *Client) GetFirstAvailableBlock(ctx context.Context) (uint64, error) { 11 | return process( 12 | func() (rpc.JsonRpcResponse[uint64], error) { 13 | return c.RpcClient.GetFirstAvailableBlock(ctx) 14 | }, 15 | forward[uint64], 16 | ) 17 | } 18 | -------------------------------------------------------------------------------- /client/rpc_get_slot_leaders.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | // GetSlotLeaders returns the slot leaders for a given slot range 10 | // (limit: 1~5000) 11 | func (c *Client) GetSlotLeaders(ctx context.Context, startSlot uint64, limit uint64) ([]string, error) { 12 | return process( 13 | func() (rpc.JsonRpcResponse[[]string], error) { 14 | return c.RpcClient.GetSlotLeaders(ctx, startSlot, limit) 15 | }, 16 | forward[[]string], 17 | ) 18 | } 19 | -------------------------------------------------------------------------------- /docs/_examples/rpc/get-balance/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | balance, err := c.GetBalance( 15 | context.TODO(), 16 | "9qeP9DmjXAmKQc4wy133XZrQ3Fo4ejsYteA7X4YFJ3an", 17 | ) 18 | if err != nil { 19 | log.Fatalf("failed to request airdrop, err: %v", err) 20 | } 21 | fmt.Println(balance) 22 | } 23 | -------------------------------------------------------------------------------- /docs/_examples/tour/get-sol-balance/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | balance, err := c.GetBalance( 15 | context.TODO(), 16 | "9qeP9DmjXAmKQc4wy133XZrQ3Fo4ejsYteA7X4YFJ3an", 17 | ) 18 | if err != nil { 19 | log.Fatalf("failed to request airdrop, err: %v", err) 20 | } 21 | fmt.Println(balance) 22 | } 23 | -------------------------------------------------------------------------------- /docs/_examples/client/get-token-account/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | 15 | tokenAccount, err := c.GetTokenAccount(context.Background(), "81Ck4pb8sZVYacLVHh4KbyiYHX8qnR4JvuZcyPiJN5cc") 16 | if err != nil { 17 | log.Fatalf("failed to get token account, err: %v", err) 18 | } 19 | 20 | fmt.Printf("%+v\n", tokenAccount) 21 | } 22 | -------------------------------------------------------------------------------- /pkg/pointer/pointer_test.go: -------------------------------------------------------------------------------- 1 | package pointer 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestGet(t *testing.T) { 10 | type args struct { 11 | v uint64 12 | } 13 | tests := []struct { 14 | name string 15 | args args 16 | want *uint64 17 | }{ 18 | { 19 | args: args{ 20 | v: 1, 21 | }, 22 | want: Get[uint64](1), 23 | }, 24 | } 25 | for _, tt := range tests { 26 | t.Run(tt.name, func(t *testing.T) { 27 | assert.Equal(t, tt.want, Get[uint64](1)) 28 | }) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /.github/workflows/golangci-lint.yml: -------------------------------------------------------------------------------- 1 | name: golangci-lint 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | permissions: 12 | contents: read 13 | 14 | jobs: 15 | golangci: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@v3 19 | 20 | - uses: actions/setup-go@v3 21 | with: 22 | go-version: 1.19 23 | 24 | - name: golangci-lint 25 | uses: golangci/golangci-lint-action@v3 26 | with: 27 | version: latest -------------------------------------------------------------------------------- /rpc/get_version.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import "context" 4 | 5 | type GetVersionResponse JsonRpcResponse[GetVersion] 6 | 7 | // GetVersionResult is a part of raw rpc response of `getVersion` 8 | type GetVersion struct { 9 | SolanaCore string `json:"solana-core"` 10 | FeatureSet *uint32 `json:"feature-set"` 11 | } 12 | 13 | // GetVersion returns the current solana versions running on the node 14 | func (c *RpcClient) GetVersion(ctx context.Context) (JsonRpcResponse[GetVersion], error) { 15 | return call[JsonRpcResponse[GetVersion]](c, ctx, "getVersion") 16 | } 17 | -------------------------------------------------------------------------------- /rpc/options_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "net/http" 5 | "testing" 6 | "time" 7 | 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestOption_WithHTTPClient(t *testing.T) { 12 | 13 | h := &http.Client{ 14 | Timeout: time.Minute * 20, 15 | } 16 | 17 | c := New(WithHTTPClient(h)) 18 | 19 | require.Equal(t, h, c.httpClient) 20 | } 21 | 22 | func TestOption_WithEndpoint(t *testing.T) { 23 | 24 | endpoint := DevnetRPCEndpoint 25 | 26 | c := New(WithEndpoint(endpoint)) 27 | 28 | require.Equal(t, endpoint, c.endpoint) 29 | } 30 | -------------------------------------------------------------------------------- /client/rpc_minimum_ledger_slot.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | // MinimumLedgerSlot returns the lowest slot that the node has information about in its ledger. 10 | // This value may increase over time if the node is configured to purge older ledger data 11 | func (c *Client) MinimumLedgerSlot(ctx context.Context) (uint64, error) { 12 | return process( 13 | func() (rpc.JsonRpcResponse[uint64], error) { 14 | return c.RpcClient.MinimumLedgerSlot(ctx) 15 | }, 16 | forward[uint64], 17 | ) 18 | } 19 | -------------------------------------------------------------------------------- /docs/_examples/rpc/request-airdrop/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | sig, err := c.RequestAirdrop( 15 | context.TODO(), 16 | "9qeP9DmjXAmKQc4wy133XZrQ3Fo4ejsYteA7X4YFJ3an", // address 17 | 1e9, // lamports (1 SOL = 10^9 lamports) 18 | ) 19 | if err != nil { 20 | log.Fatalf("failed to request airdrop, err: %v", err) 21 | } 22 | fmt.Println(sig) 23 | } 24 | -------------------------------------------------------------------------------- /docs/_examples/tour/request-airdrop/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | sig, err := c.RequestAirdrop( 15 | context.TODO(), 16 | "9qeP9DmjXAmKQc4wy133XZrQ3Fo4ejsYteA7X4YFJ3an", // address 17 | 1e9, // lamports (1 SOL = 10^9 lamports) 18 | ) 19 | if err != nil { 20 | log.Fatalf("failed to request airdrop, err: %v", err) 21 | } 22 | fmt.Println(sig) 23 | } 24 | -------------------------------------------------------------------------------- /docs/_examples/client/get-account-info/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | 15 | // get account info 16 | accountInfo, err := c.GetAccountInfo( 17 | context.TODO(), 18 | "F5RYi7FMPefkc7okJNh21Hcsch7RUaLVr8Rzc8SQqxUb", 19 | ) 20 | if err != nil { 21 | log.Fatalf("failed to get balance, err: %v", err) 22 | } 23 | fmt.Printf("accountInfo: %v\n", accountInfo) 24 | } 25 | -------------------------------------------------------------------------------- /docs/src/tour/create-account.md: -------------------------------------------------------------------------------- 1 | # Create Account 2 | 3 | An account is a basic identity on chain. 4 | 5 | ## Create a new account 6 | 7 | @[code{15-15}](@/tour/create-account/main.go) 8 | 9 | ## Recover from a key 10 | 11 | ### Base58 12 | 13 | @[code{22-22}](@/tour/create-account/main.go) 14 | 15 | ### Bytes 16 | 17 | @[code{28-36}](@/tour/create-account/main.go) 18 | 19 | ### BIP 39 20 | 21 | @[code{42-44}](@/tour/create-account/main.go) 22 | 23 | ### BIP 44 24 | 25 | @[code{50-54}](@/tour/create-account/main.go) 26 | 27 | ## Full Code 28 | 29 | @[code](@/tour/create-account/main.go) 30 | -------------------------------------------------------------------------------- /docs/_examples/advanced/durable-nonce/get-nonce-from-nonce-account/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | 15 | nonceAccountAddr := "DJyNpXgggw1WGgjTVzFsNjb3fuQZVMqhoakvSBfX9LYx" 16 | nonce, err := c.GetNonceFromNonceAccount(context.Background(), nonceAccountAddr) 17 | if err != nil { 18 | log.Fatalf("failed to get nonce account, err: %v", err) 19 | } 20 | 21 | fmt.Println("nonce", nonce) 22 | } 23 | -------------------------------------------------------------------------------- /docs/src/tour/transfer.md: -------------------------------------------------------------------------------- 1 | # Transfer 2 | 3 | We will build a transaction to transfer our SOL out. 4 | 5 | A quick guide for a transaction is that: 6 | 7 | 1. a transactions is composed by some signatures + a message 8 | 2. a message is composed by one or more instructions + a blockhash 9 | 10 | ## Full Code 11 | 12 | @[code](@/tour/transfer-sol/main.go) 13 | 14 | ::: tip 15 | 16 | 1. `fee payer` and `from` can be different wallets but both of them need to sign the transaction 17 | 2. a transaction can composed by many instructions so you can do something like A => B, B => C, C => A and D is the fee payer. 18 | ::: 19 | -------------------------------------------------------------------------------- /docs/src/rpc/get-signatures-for-address.md: -------------------------------------------------------------------------------- 1 | # Get Signatures For Address 2 | 3 | Fetch tx histroy. 4 | 5 | ## All 6 | 7 | @[code{16-23}](@/rpc/get-signature-for-address/main.go) 8 | 9 | ## Limit 10 | 11 | @[code{25-38}](@/rpc/get-signature-for-address/main.go) 12 | 13 | ## Range 14 | 15 | context: 16 | 17 | @[code{40-52}](@/rpc/get-signature-for-address/main.go) 18 | 19 | 20 | ### Before 21 | 22 | @[code{54-68}](@/rpc/get-signature-for-address/main.go) 23 | 24 | ### Until 25 | 26 | @[code{70-85}](@/rpc/get-signature-for-address/main.go) 27 | 28 | ## Full Code 29 | 30 | @[code](@/rpc/get-signature-for-address/main.go) 31 | -------------------------------------------------------------------------------- /rpc/get_inflation_rate.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import "context" 4 | 5 | type GetInflationRateResponse JsonRpcResponse[GetInflationRate] 6 | 7 | type GetInflationRate struct { 8 | Epoch uint64 `json:"epoch"` 9 | Foundation float64 `json:"foundation"` 10 | Total float64 `json:"total"` 11 | Validator float64 `json:"validator"` 12 | } 13 | 14 | // GetInflationRate returns the specific inflation values for the current epoch 15 | func (c *RpcClient) GetInflationRate(ctx context.Context) (JsonRpcResponse[GetInflationRate], error) { 16 | return call[JsonRpcResponse[GetInflationRate]](c, ctx, "getInflationRate") 17 | } 18 | -------------------------------------------------------------------------------- /docs/_examples/client/get-token-accounts-by-owner/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | 15 | tokenAccounts, err := c.GetTokenAccountsByOwner(context.Background(), "9aE476sH92Vz7DMPyq5WLPkrKWivxeuTKEFKd2sZZcde") 16 | if err != nil { 17 | log.Fatalf("failed to get token accounts, err: %v", err) 18 | } 19 | 20 | for pubkey, tokenAccount := range tokenAccounts { 21 | fmt.Printf("%v => %+v\n", pubkey.ToBase58(), tokenAccount) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /client/rpc_get_health.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | // GetHealthResponse returns the current health of the node. A healthy node is one that is within HEALTH_CHECK_SLOT_DISTANCE slots of the latest cluster confirmed slot. 10 | func (c *Client) GetHealth(ctx context.Context) (bool, error) { 11 | res, err := process( 12 | func() (rpc.JsonRpcResponse[string], error) { 13 | return c.RpcClient.GetHealth(ctx) 14 | }, 15 | forward[string], 16 | ) 17 | if err != nil { 18 | return false, err 19 | } 20 | if res != "ok" { 21 | return false, err 22 | } 23 | return true, nil 24 | } 25 | -------------------------------------------------------------------------------- /rpc/get_block_commitment.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetBlockCommitmentResponse JsonRpcResponse[GetBlockCommitment] 8 | 9 | // GetBlockCommitmentResult is a part of raw rpc response of `getBlockCommitment` 10 | type GetBlockCommitment struct { 11 | Commitment *[]uint64 `json:"commitment"` 12 | TotalStake uint64 `json:"totalStake"` 13 | } 14 | 15 | // GetBlockCommitment returns commitment for particular block 16 | func (c *RpcClient) GetBlockCommitment(ctx context.Context, slot uint64) (JsonRpcResponse[GetBlockCommitment], error) { 17 | return call[JsonRpcResponse[GetBlockCommitment]](c, ctx, "getBlockCommitment", slot) 18 | } 19 | -------------------------------------------------------------------------------- /docs/_examples/rpc/get-multiple-accounts/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/blocto/solana-go-sdk/client" 8 | "github.com/blocto/solana-go-sdk/rpc" 9 | "github.com/davecgh/go-spew/spew" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | accountInfos, err := c.GetMultipleAccounts( 15 | context.Background(), 16 | []string{ 17 | "AngPj3DQh1zNW68E1sa2yWfy71D6mcd7iwzhbLiLMxcR", 18 | "4T2BWArMHpFiwAMkMsJUCxa5ux9vYZBnVigJznxzbeVx", 19 | }, 20 | ) 21 | if err != nil { 22 | log.Fatalf("failed to get multiple account infos, err: %v", err) 23 | } 24 | 25 | spew.Dump(accountInfos) 26 | } 27 | -------------------------------------------------------------------------------- /rpc/get_cluster_nodes.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import "context" 4 | 5 | type GetClusterNodesResponse JsonRpcResponse[GetClusterNodes] 6 | 7 | type GetClusterNodes []GetClusterNode 8 | 9 | type GetClusterNode struct { 10 | Pubkey string 11 | Gossip *string 12 | Tpu *string 13 | Rpc *string 14 | Version *string 15 | FeatureSet *uint32 16 | ShredVersion *uint16 17 | } 18 | 19 | // GetClusterNodes returns information about all the nodes participating in the cluster 20 | func (c *RpcClient) GetClusterNodes(ctx context.Context) (JsonRpcResponse[GetClusterNodes], error) { 21 | return call[JsonRpcResponse[GetClusterNodes]](c, ctx, "getClusterNodes") 22 | } 23 | -------------------------------------------------------------------------------- /pkg/bincode/varbyte_test.go: -------------------------------------------------------------------------------- 1 | package bincode 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestUintToVarLenBytes(t *testing.T) { 9 | type args struct { 10 | l uint64 11 | } 12 | tests := []struct { 13 | name string 14 | args args 15 | want []byte 16 | }{ 17 | { 18 | args: args{l: 127}, 19 | want: []byte{0x7f}, 20 | }, 21 | { 22 | args: args{l: 128}, 23 | want: []byte{0x80, 0x01}, 24 | }, 25 | } 26 | for _, tt := range tests { 27 | t.Run(tt.name, func(t *testing.T) { 28 | if got := UintToVarLenBytes(tt.args.l); !reflect.DeepEqual(got, tt.want) { 29 | t.Errorf("Uint64ToVarLenBytes() = %v, want %v", got, tt.want) 30 | } 31 | }) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /client/rpc_minimum_ledger_slot_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestClient_MinimumLedgerSlot(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"minimumLedgerSlot"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":84044778,"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewClient(url) 19 | return c.MinimumLedgerSlot( 20 | context.TODO(), 21 | ) 22 | }, 23 | ExpectedValue: uint64(84044778), 24 | ExpectedError: nil, 25 | }, 26 | }, 27 | ) 28 | } 29 | -------------------------------------------------------------------------------- /rpc/get_slot.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetSlotResponse JsonRpcResponse[uint64] 8 | 9 | // GetSlotConfig is a option config for `getSlot` 10 | type GetSlotConfig struct { 11 | Commitment Commitment `json:"commitment,omitempty"` 12 | } 13 | 14 | // GetSlot returns the SOL balance 15 | func (c *RpcClient) GetSlot(ctx context.Context) (JsonRpcResponse[uint64], error) { 16 | return call[JsonRpcResponse[uint64]](c, ctx, "getSlot") 17 | } 18 | 19 | // GetSlotWithConfig returns the SOL balance 20 | func (c *RpcClient) GetSlotWithConfig(ctx context.Context, cfg GetSlotConfig) (JsonRpcResponse[uint64], error) { 21 | return call[JsonRpcResponse[uint64]](c, ctx, "getSlot", cfg) 22 | } 23 | -------------------------------------------------------------------------------- /rpc/get_recent_prioritization_fees.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetRecentPrioritizationFeesResponse JsonRpcResponse[PrioritizationFees] 8 | 9 | type PrioritizationFee struct { 10 | Slot uint64 `json:"slot"` 11 | PrioritizationFee uint64 `json:"prioritizationFee"` 12 | } 13 | 14 | type PrioritizationFees []PrioritizationFee 15 | 16 | // GetRecentPrioritizationFees returns a list of prioritization fees from recent blocks. 17 | func (c *RpcClient) GetRecentPrioritizationFees(ctx context.Context, addresses []string) (JsonRpcResponse[PrioritizationFees], error) { 18 | return call[JsonRpcResponse[PrioritizationFees]](c, ctx, "getRecentPrioritizationFees", addresses) 19 | } 20 | -------------------------------------------------------------------------------- /client/rpc_get_first_available_block_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestClient_GetFirstAvailableBlock(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getFirstAvailableBlock"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":100,"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewClient(url) 19 | return c.GetFirstAvailableBlock( 20 | context.TODO(), 21 | ) 22 | }, 23 | ExpectedValue: uint64(100), 24 | ExpectedError: nil, 25 | }, 26 | }, 27 | ) 28 | } 29 | -------------------------------------------------------------------------------- /rpc/options.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "net/http" 5 | ) 6 | 7 | // Option is a configuration type for the Client 8 | type Option func(*RpcClient) 9 | 10 | // HTTPClient is an Option type that allows you provide your own HTTP client 11 | func WithHTTPClient(h *http.Client) Option { 12 | return func(r *RpcClient) { 13 | r.httpClient = h 14 | } 15 | } 16 | 17 | // WithEndpoint is an Option that allows you configure the rpc endpoint that our 18 | // client will point to 19 | func WithEndpoint(endpoint string) Option { 20 | return func(r *RpcClient) { 21 | r.endpoint = endpoint 22 | } 23 | } 24 | 25 | func setDefaultOptions(r *RpcClient) { 26 | r.httpClient = &http.Client{} 27 | r.endpoint = MainnetRPCEndpoint 28 | } 29 | -------------------------------------------------------------------------------- /program/nsprog/state.go: -------------------------------------------------------------------------------- 1 | package nsprog 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/blocto/solana-go-sdk/common" 7 | ) 8 | 9 | type NameRecordHeader struct { 10 | ParentName common.PublicKey 11 | Owner common.PublicKey 12 | Class common.PublicKey 13 | Data []byte 14 | } 15 | 16 | func NameRecordHeaderFromData(data []byte) (NameRecordHeader, error) { 17 | if len(data) < 96 { 18 | return NameRecordHeader{}, fmt.Errorf("data length should bigger than 96") 19 | } 20 | return NameRecordHeader{ 21 | ParentName: common.PublicKeyFromBytes(data[:32]), 22 | Owner: common.PublicKeyFromBytes(data[32:64]), 23 | Class: common.PublicKeyFromBytes(data[64:96]), 24 | Data: data[96:], 25 | }, nil 26 | } 27 | -------------------------------------------------------------------------------- /program/name_service/state.go: -------------------------------------------------------------------------------- 1 | package name_service 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/blocto/solana-go-sdk/common" 7 | ) 8 | 9 | type NameRecordHeader struct { 10 | ParentName common.PublicKey 11 | Owner common.PublicKey 12 | Class common.PublicKey 13 | Data []byte 14 | } 15 | 16 | func NameRecordHeaderFromData(data []byte) (NameRecordHeader, error) { 17 | if len(data) < 96 { 18 | return NameRecordHeader{}, fmt.Errorf("data length should bigger than 96") 19 | } 20 | return NameRecordHeader{ 21 | ParentName: common.PublicKeyFromBytes(data[:32]), 22 | Owner: common.PublicKeyFromBytes(data[32:64]), 23 | Class: common.PublicKeyFromBytes(data[64:96]), 24 | Data: data[96:], 25 | }, nil 26 | } 27 | -------------------------------------------------------------------------------- /program/memo/instruction.go: -------------------------------------------------------------------------------- 1 | package memo 2 | 3 | import ( 4 | "github.com/blocto/solana-go-sdk/common" 5 | "github.com/blocto/solana-go-sdk/types" 6 | ) 7 | 8 | type BuildMemoParam struct { 9 | SignerPubkeys []common.PublicKey 10 | Memo []byte 11 | } 12 | 13 | func BuildMemo(param BuildMemoParam) types.Instruction { 14 | accounts := make([]types.AccountMeta, 0, len(param.SignerPubkeys)) 15 | for _, signerPubkey := range param.SignerPubkeys { 16 | accounts = append(accounts, types.AccountMeta{ 17 | PubKey: signerPubkey, 18 | IsSigner: true, 19 | IsWritable: false, 20 | }) 21 | } 22 | return types.Instruction{ 23 | ProgramID: common.MemoProgramID, 24 | Accounts: accounts, 25 | Data: param.Memo, 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /program/memoprog/instruction.go: -------------------------------------------------------------------------------- 1 | package memoprog 2 | 3 | import ( 4 | "github.com/blocto/solana-go-sdk/common" 5 | "github.com/blocto/solana-go-sdk/types" 6 | ) 7 | 8 | type BuildMemoParam struct { 9 | SignerPubkeys []common.PublicKey 10 | Memo []byte 11 | } 12 | 13 | func BuildMemo(param BuildMemoParam) types.Instruction { 14 | accounts := make([]types.AccountMeta, 0, len(param.SignerPubkeys)) 15 | for _, signerPubkey := range param.SignerPubkeys { 16 | accounts = append(accounts, types.AccountMeta{ 17 | PubKey: signerPubkey, 18 | IsSigner: true, 19 | IsWritable: false, 20 | }) 21 | } 22 | return types.Instruction{ 23 | ProgramID: common.MemoProgramID, 24 | Accounts: accounts, 25 | Data: param.Memo, 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /client/rpc_get_genesis_hash_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestClient_GetGenesisHash(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getGenesisHash"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":"EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG","id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewClient(url) 19 | return c.GetGenesisHash( 20 | context.TODO(), 21 | ) 22 | }, 23 | ExpectedValue: "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG", 24 | ExpectedError: nil, 25 | }, 26 | }, 27 | ) 28 | } 29 | -------------------------------------------------------------------------------- /client/rpc_get_recent_prioritization_fees.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/common" 7 | "github.com/blocto/solana-go-sdk/rpc" 8 | ) 9 | 10 | // GetRecentPrioritizationFees returns a list of prioritization fees from recent blocks. 11 | func (c *Client) GetRecentPrioritizationFees(ctx context.Context, addresses []common.PublicKey) (rpc.PrioritizationFees, error) { 12 | return process( 13 | func() (rpc.JsonRpcResponse[rpc.PrioritizationFees], error) { 14 | a := make([]string, 0, len(addresses)) 15 | for _, address := range addresses { 16 | a = append(a, address.ToBase58()) 17 | } 18 | return c.RpcClient.GetRecentPrioritizationFees(ctx, a) 19 | }, 20 | forward[rpc.PrioritizationFees], 21 | ) 22 | } 23 | -------------------------------------------------------------------------------- /rpc/get_epoch_schedule.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import "context" 4 | 5 | type GetEpochScheduleResponse JsonRpcResponse[GetEpochSchedule] 6 | 7 | type GetEpochSchedule struct { 8 | FirstNormalEpoch uint64 `json:"firstNormalEpoch"` 9 | FirstNormalSlot uint64 `json:"firstNormalSlot"` 10 | LeaderScheduleSlotOffset uint64 `json:"leaderScheduleSlotOffset"` 11 | SlotsPerEpoch uint64 `json:"slotsPerEpoch"` 12 | Warmup bool `json:"warmup"` 13 | } 14 | 15 | // GetEpochSchedule returns epoch schedule information from this cluster's genesis config 16 | func (c *RpcClient) GetEpochSchedule(ctx context.Context) (JsonRpcResponse[GetEpochSchedule], error) { 17 | return call[JsonRpcResponse[GetEpochSchedule]](c, ctx, "getEpochSchedule") 18 | } 19 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | main: 13 | strategy: 14 | matrix: 15 | go: 16 | - 1.19 17 | os: 18 | - ubuntu-20.04 19 | - ubuntu-22.04 20 | - macos-11 21 | - macos-12 22 | - windows-2019 23 | - windows-2022 24 | runs-on: ${{ matrix.os }} 25 | steps: 26 | - name: Checkout 27 | uses: actions/checkout@v3 28 | 29 | - name: Set up Go 30 | uses: actions/setup-go@v3 31 | with: 32 | go-version: ${{ matrix.go }} 33 | 34 | - name: Build 35 | run: go build -v ./... 36 | 37 | - name: Test 38 | run: go test -v ./... 39 | -------------------------------------------------------------------------------- /rpc/minimum_ledger_slot_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestMinimumLedgerSlot(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"minimumLedgerSlot"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":84044778,"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.MinimumLedgerSlot( 20 | context.TODO(), 21 | ) 22 | }, 23 | ExpectedValue: JsonRpcResponse[uint64]{ 24 | JsonRpc: "2.0", 25 | Id: 1, 26 | Error: nil, 27 | Result: 84044778, 28 | }, 29 | ExpectedError: nil, 30 | }, 31 | }, 32 | ) 33 | } 34 | -------------------------------------------------------------------------------- /docs/_examples/tour/get-token-balance/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | 15 | // should pass a token account address 16 | balance, decimals, err := c.GetTokenAccountBalance( 17 | context.Background(), 18 | "HeCBh32JJ8DxcjTyc6q46tirHR8hd2xj3mGoAcQ7eduL", 19 | ) 20 | if err != nil { 21 | log.Fatalln("get balance error", err) 22 | } 23 | // the smallest unit like lamports 24 | fmt.Println("balance", balance) 25 | // the decimals of mint which token account holds 26 | fmt.Println("decimals", decimals) 27 | 28 | // if you want use a normal unit, you can do 29 | // balance / 10^decimals 30 | } 31 | -------------------------------------------------------------------------------- /rpc/get_first_available_block_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetFirstAvailableBlock(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getFirstAvailableBlock"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":0,"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetFirstAvailableBlock( 20 | context.TODO(), 21 | ) 22 | }, 23 | ExpectedValue: JsonRpcResponse[uint64]{ 24 | JsonRpc: "2.0", 25 | Id: 1, 26 | Error: nil, 27 | Result: 0, 28 | }, 29 | ExpectedError: nil, 30 | }, 31 | }, 32 | ) 33 | } 34 | -------------------------------------------------------------------------------- /docs/_examples/advanced/durable-nonce/get-nonce-account/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | nonceAccountAddr := "DJyNpXgggw1WGgjTVzFsNjb3fuQZVMqhoakvSBfX9LYx" 15 | nonceAccount, err := c.GetNonceAccount(context.Background(), nonceAccountAddr) 16 | if err != nil { 17 | log.Fatalf("failed to get nonce account, err: %v", err) 18 | } 19 | fmt.Printf("%+v\n", nonceAccount) 20 | /* 21 | type NonceAccount struct { 22 | Version uint32 23 | State uint32 24 | AuthorizedPubkey common.PublicKey 25 | Nonce common.PublicKey 26 | FeeCalculator FeeCalculator 27 | } 28 | */ 29 | } 30 | -------------------------------------------------------------------------------- /rpc/get_block_height.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetBlockHeightResponse JsonRpcResponse[uint64] 8 | 9 | // GetBlockHeightConfig is a option config for `getBlockHeight` 10 | type GetBlockHeightConfig struct { 11 | Commitment Commitment `json:"commitment,omitempty"` 12 | } 13 | 14 | // GetBlockHeight returns the current block height of the node 15 | func (c *RpcClient) GetBlockHeight(ctx context.Context) (JsonRpcResponse[uint64], error) { 16 | return call[JsonRpcResponse[uint64]](c, ctx, "getBlockHeight") 17 | } 18 | 19 | // GetBlockHeightWithConfig returns the current block height of the node 20 | func (c *RpcClient) GetBlockHeightWithConfig(ctx context.Context, cfg GetBlockHeightConfig) (JsonRpcResponse[uint64], error) { 21 | return call[JsonRpcResponse[uint64]](c, ctx, "getBlockHeight", cfg) 22 | } 23 | -------------------------------------------------------------------------------- /client/rpc_get_identity_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | "github.com/blocto/solana-go-sdk/rpc" 9 | ) 10 | 11 | func TestClient_GetIdentity(t *testing.T) { 12 | client_test.TestAll( 13 | t, 14 | []client_test.Param{ 15 | { 16 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getIdentity"}`, 17 | ResponseBody: `{"jsonrpc":"2.0","result":{"identity":"BjHeMczor9oycGJHLepRTCU2LpkZNtpy2mdQKianx1EJ"},"id":1}`, 18 | F: func(url string) (any, error) { 19 | c := NewClient(url) 20 | return c.GetIdentity( 21 | context.TODO(), 22 | ) 23 | }, 24 | ExpectedValue: rpc.GetIdentity{ 25 | Identity: "BjHeMczor9oycGJHLepRTCU2LpkZNtpy2mdQKianx1EJ", 26 | }, 27 | ExpectedError: nil, 28 | }, 29 | }, 30 | ) 31 | } 32 | -------------------------------------------------------------------------------- /rpc/get_slot_leader.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetSlotLeaderResponse JsonRpcResponse[string] 8 | 9 | // GetSlotLeaderConfig is a option config for `getSlotLeader` 10 | type GetSlotLeaderConfig struct { 11 | Commitment *Commitment `json:"commitment,omitempty"` 12 | MinContextSlot *uint64 `json:"minContextSlot,omitempty"` 13 | } 14 | 15 | // GetSlotLeader returns the current slot leader 16 | func (c *RpcClient) GetSlotLeader(ctx context.Context) (JsonRpcResponse[string], error) { 17 | return call[JsonRpcResponse[string]](c, ctx, "getSlotLeader") 18 | } 19 | 20 | // GetSlotWithConfig returns the current slot leader 21 | func (c *RpcClient) GetSlotLeaderWithConfig(ctx context.Context, cfg GetSlotLeaderConfig) (JsonRpcResponse[string], error) { 22 | return call[JsonRpcResponse[string]](c, ctx, "getSlotLeader", cfg) 23 | } 24 | -------------------------------------------------------------------------------- /rpc/get_genesis_hash_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetGenesisHash(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getGenesisHash"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":"EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG","id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetGenesisHash( 20 | context.TODO(), 21 | ) 22 | }, 23 | ExpectedValue: JsonRpcResponse[string]{ 24 | JsonRpc: "2.0", 25 | Id: 1, 26 | Error: nil, 27 | Result: "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG", 28 | }, 29 | ExpectedError: nil, 30 | }, 31 | }, 32 | ) 33 | } 34 | -------------------------------------------------------------------------------- /client/rpc_get_version_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | "github.com/blocto/solana-go-sdk/pkg/pointer" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func TestClient_GetVersion(t *testing.T) { 13 | client_test.TestAll( 14 | t, 15 | []client_test.Param{ 16 | { 17 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getVersion"}`, 18 | ResponseBody: `{"jsonrpc":"2.0","result":{"feature-set":1824749018,"solana-core":"1.7.14"},"id":1}`, 19 | F: func(url string) (any, error) { 20 | c := NewClient(url) 21 | return c.GetVersion( 22 | context.TODO(), 23 | ) 24 | }, 25 | ExpectedValue: rpc.GetVersion{ 26 | SolanaCore: "1.7.14", 27 | FeatureSet: pointer.Get[uint32](1824749018), 28 | }, 29 | ExpectedError: nil, 30 | }, 31 | }, 32 | ) 33 | } 34 | -------------------------------------------------------------------------------- /rpc/get_transaction_count.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetTransactionCountResponse JsonRpcResponse[uint64] 8 | 9 | // GetTransactionCountConfig is a option config for `getTransactionCount` 10 | type GetTransactionCountConfig struct { 11 | Commitment Commitment `json:"commitment,omitempty"` 12 | } 13 | 14 | // GetTransactionCount returns the current Transaction count from the ledger 15 | func (c *RpcClient) GetTransactionCount(ctx context.Context) (JsonRpcResponse[uint64], error) { 16 | return call[JsonRpcResponse[uint64]](c, ctx, "getTransactionCount") 17 | } 18 | 19 | // GetTransactionCountWithConfig returns the current Transaction count from the ledger 20 | func (c *RpcClient) GetTransactionCountWithConfig(ctx context.Context, cfg GetTransactionCountConfig) (JsonRpcResponse[uint64], error) { 21 | return call[JsonRpcResponse[uint64]](c, ctx, "getTransactionCount", cfg) 22 | } 23 | -------------------------------------------------------------------------------- /rpc/get_identity_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetIdentity(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getIdentity"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":{"identity":"BjHeMczor9oycGJHLepRTCU2LpkZNtpy2mdQKianx1EJ"},"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetIdentity( 20 | context.TODO(), 21 | ) 22 | }, 23 | ExpectedValue: JsonRpcResponse[GetIdentity]{ 24 | JsonRpc: "2.0", 25 | Id: 1, 26 | Error: nil, 27 | Result: GetIdentity{ 28 | Identity: "BjHeMczor9oycGJHLepRTCU2LpkZNtpy2mdQKianx1EJ", 29 | }, 30 | }, 31 | ExpectedError: nil, 32 | }, 33 | }, 34 | ) 35 | } 36 | -------------------------------------------------------------------------------- /rpc/get_balance.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetBalanceResponse JsonRpcResponse[GetBalance] 8 | 9 | type GetBalance ValueWithContext[uint64] 10 | 11 | // GetBalanceConfig is a option config for `getBalance` 12 | type GetBalanceConfig struct { 13 | Commitment Commitment `json:"commitment,omitempty"` 14 | } 15 | 16 | // GetBalance returns the SOL balance 17 | func (c *RpcClient) GetBalance(ctx context.Context, base58Addr string) (JsonRpcResponse[ValueWithContext[uint64]], error) { 18 | return call[JsonRpcResponse[ValueWithContext[uint64]]](c, ctx, "getBalance", base58Addr) 19 | } 20 | 21 | // GetBalanceWithConfig returns the SOL balance 22 | func (c *RpcClient) GetBalanceWithConfig(ctx context.Context, base58Addr string, cfg GetBalanceConfig) (JsonRpcResponse[ValueWithContext[uint64]], error) { 23 | return call[JsonRpcResponse[ValueWithContext[uint64]]](c, ctx, "getBalance", base58Addr, cfg) 24 | } 25 | -------------------------------------------------------------------------------- /client/rpc_get_slot.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | type GetSlotConfig struct { 10 | Commitment rpc.Commitment 11 | } 12 | 13 | func (c GetSlotConfig) toRpc() rpc.GetSlotConfig { 14 | return rpc.GetSlotConfig{ 15 | Commitment: c.Commitment, 16 | } 17 | } 18 | 19 | // GetSlot get current slot (finalized) 20 | func (c *Client) GetSlot(ctx context.Context) (uint64, error) { 21 | return process( 22 | func() (rpc.JsonRpcResponse[uint64], error) { 23 | return c.RpcClient.GetSlot(ctx) 24 | }, 25 | forward[uint64], 26 | ) 27 | } 28 | 29 | // GetSlotWithConfig get slot by commitment 30 | func (c *Client) GetSlotWithConfig(ctx context.Context, cfg GetSlotConfig) (uint64, error) { 31 | return process( 32 | func() (rpc.JsonRpcResponse[uint64], error) { 33 | return c.RpcClient.GetSlotWithConfig(ctx, cfg.toRpc()) 34 | }, 35 | forward[uint64], 36 | ) 37 | } 38 | -------------------------------------------------------------------------------- /rpc/request_aridrop.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type RequestAirdropResponse JsonRpcResponse[string] 8 | 9 | // RequestAirdropConfig is a option config for `requestAirdrop` 10 | type RequestAirdropConfig struct { 11 | Commitment Commitment `json:"commitment,omitempty"` 12 | } 13 | 14 | // RequestAirdrop requests an airdrop of lamports to a Pubkey 15 | func (c *RpcClient) RequestAirdrop(ctx context.Context, base58Addr string, lamports uint64) (JsonRpcResponse[string], error) { 16 | return call[JsonRpcResponse[string]](c, ctx, "requestAirdrop", base58Addr, lamports) 17 | } 18 | 19 | // RequestAirdropWithConfig requests an airdrop of lamports to a Pubkey 20 | func (c *RpcClient) RequestAirdropWithConfig(ctx context.Context, base58Addr string, lamports uint64, cfg RequestAirdropConfig) (JsonRpcResponse[string], error) { 21 | return call[JsonRpcResponse[string]](c, ctx, "requestAirdrop", base58Addr, lamports, cfg) 22 | } 23 | -------------------------------------------------------------------------------- /pkg/bytes_decoder/decoder.go: -------------------------------------------------------------------------------- 1 | package bytes_decoder 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | ) 7 | 8 | func GetUint64(curr *int, data []byte) (uint64, error) { 9 | if curr == nil { 10 | return 0, fmt.Errorf("index is nil") 11 | } 12 | if data == nil { 13 | return 0, fmt.Errorf("data is nil") 14 | } 15 | if len(data[*curr:]) < 8 { 16 | return 0, fmt.Errorf("insufficient data length") 17 | } 18 | 19 | v := binary.LittleEndian.Uint64(data[*curr : *curr+8]) 20 | *curr += 8 21 | 22 | return v, nil 23 | } 24 | 25 | func GetBytes32(curr *int, data []byte) ([32]byte, error) { 26 | var v [32]byte 27 | 28 | if curr == nil { 29 | return v, fmt.Errorf("index is nil") 30 | } 31 | if data == nil { 32 | return v, fmt.Errorf("data is nil") 33 | } 34 | if len(data[*curr:]) < 32 { 35 | return v, fmt.Errorf("insufficient data length") 36 | } 37 | 38 | copy(v[:], data[*curr:*curr+32]) 39 | *curr += 32 40 | 41 | return v, nil 42 | } 43 | -------------------------------------------------------------------------------- /common/system_var.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | var ( 4 | SysVarPubkey = PublicKeyFromString("Sysvar1111111111111111111111111111111111111") 5 | SysVarClockPubkey = PublicKeyFromString("SysvarC1ock11111111111111111111111111111111") 6 | SysVarRecentBlockhashsPubkey = PublicKeyFromString("SysvarRecentB1ockHashes11111111111111111111") 7 | SysVarRentPubkey = PublicKeyFromString("SysvarRent111111111111111111111111111111111") 8 | SysVarRewardsPubkey = PublicKeyFromString("SysvarRewards111111111111111111111111111111") 9 | SysVarStakeHistoryPubkey = PublicKeyFromString("SysvarStakeHistory1111111111111111111111111") 10 | SysVarInstructionsPubkey = PublicKeyFromString("Sysvar1nstructions1111111111111111111111111") 11 | SysVarSlotHashesPubkey = PublicKeyFromString("SysvarS1otHashes111111111111111111111111111") 12 | StakeConfigPubkey = PublicKeyFromString("StakeConfig11111111111111111111111111111111") 13 | ) 14 | -------------------------------------------------------------------------------- /rpc/get_blocks.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import "context" 4 | 5 | type GetBlocksResponse JsonRpcResponse[[]uint64] 6 | 7 | // GetBlocksConfig is a option config for `getBlocks` 8 | type GetBlocksConfig struct { 9 | Commitment Commitment `json:"commitment,omitempty"` 10 | } 11 | 12 | // GetBlocks returns a list of confirmed blocks between two slots 13 | // Max range allowed is 500,000 slot 14 | func (c *RpcClient) GetBlocks(ctx context.Context, startSlot uint64, endSlot uint64) (JsonRpcResponse[[]uint64], error) { 15 | return call[JsonRpcResponse[[]uint64]](c, ctx, "getBlocks", startSlot, endSlot) 16 | } 17 | 18 | // GetBlocks returns a list of confirmed blocks between two slots 19 | // Max range allowed is 500,000 slot 20 | func (c *RpcClient) GetBlocksWithConfig(ctx context.Context, startSlot uint64, endSlot uint64, cfg GetBlocksConfig) (JsonRpcResponse[[]uint64], error) { 21 | return call[JsonRpcResponse[[]uint64]](c, ctx, "getBlocks", startSlot, endSlot, cfg) 22 | } 23 | -------------------------------------------------------------------------------- /rpc/get_version_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | "github.com/blocto/solana-go-sdk/pkg/pointer" 9 | ) 10 | 11 | func TestGetVersion(t *testing.T) { 12 | client_test.TestAll( 13 | t, 14 | []client_test.Param{ 15 | { 16 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getVersion"}`, 17 | ResponseBody: `{"jsonrpc":"2.0","result":{"feature-set":1824749018,"solana-core":"1.7.14"},"id":1}`, 18 | F: func(url string) (any, error) { 19 | c := NewRpcClient(url) 20 | return c.GetVersion( 21 | context.TODO(), 22 | ) 23 | }, 24 | ExpectedValue: JsonRpcResponse[GetVersion]{ 25 | JsonRpc: "2.0", 26 | Id: 1, 27 | Error: nil, 28 | Result: GetVersion{ 29 | SolanaCore: "1.7.14", 30 | FeatureSet: pointer.Get[uint32](1824749018), 31 | }, 32 | }, 33 | ExpectedError: nil, 34 | }, 35 | }, 36 | ) 37 | } 38 | -------------------------------------------------------------------------------- /rpc/get_blocks_with_limit.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import "context" 4 | 5 | type GetBlocksWithLimitResponse JsonRpcResponse[[]uint64] 6 | 7 | // GetBlocksWithLimitConfig is a option config for `getBlocksWithLimit` 8 | type GetBlocksWithLimitConfig struct { 9 | Commitment Commitment `json:"commitment,omitempty"` 10 | } 11 | 12 | // GetBlocksWithLimit eturns a list of confirmed blocks starting at the given slot 13 | func (c *RpcClient) GetBlocksWithLimit(ctx context.Context, startSlot uint64, limit uint64) (JsonRpcResponse[[]uint64], error) { 14 | return call[JsonRpcResponse[[]uint64]](c, ctx, "getBlocksWithLimit", startSlot, limit) 15 | } 16 | 17 | // GetBlocksWithLimit eturns a list of confirmed blocks starting at the given slot 18 | func (c *RpcClient) GetBlocksWithLimitWithConfig(ctx context.Context, startSlot uint64, limit uint64, cfg GetBlocksWithLimitConfig) (JsonRpcResponse[[]uint64], error) { 19 | return call[JsonRpcResponse[[]uint64]](c, ctx, "getBlocksWithLimit", startSlot, limit, cfg) 20 | } 21 | -------------------------------------------------------------------------------- /docs/_examples/program/address-lookup-table/get/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/common" 10 | "github.com/blocto/solana-go-sdk/program/address_lookup_table" 11 | "github.com/blocto/solana-go-sdk/rpc" 12 | ) 13 | 14 | func main() { 15 | c := client.NewClient(rpc.DevnetRPCEndpoint) 16 | 17 | lookupTablePubkey := common.PublicKeyFromString("3LZbwptsCkv5R5uu1GNZKiX9SoC6egNG8NXg9zH5ZVM9") 18 | 19 | accountInfo, err := c.GetAccountInfo(context.Background(), lookupTablePubkey.ToBase58()) 20 | if err != nil { 21 | log.Fatalf("failed to get account info, err: %v", err) 22 | } 23 | fmt.Println(accountInfo.Data) 24 | 25 | addressLookupTable, err := address_lookup_table.DeserializeLookupTable(accountInfo.Data, accountInfo.Owner) 26 | if err != nil { 27 | log.Fatalf("failed to deserialized account, err: %v", err) 28 | } 29 | 30 | fmt.Printf("%+v\n", addressLookupTable) 31 | } 32 | -------------------------------------------------------------------------------- /docs/_examples/tour/get-token-account/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/program/token" 10 | "github.com/blocto/solana-go-sdk/rpc" 11 | ) 12 | 13 | func main() { 14 | c := client.NewClient(rpc.DevnetRPCEndpoint) 15 | 16 | // token account address 17 | getAccountInfoResponse, err := c.GetAccountInfo(context.TODO(), "HeCBh32JJ8DxcjTyc6q46tirHR8hd2xj3mGoAcQ7eduL") 18 | if err != nil { 19 | log.Fatalf("failed to get account info, err: %v", err) 20 | } 21 | 22 | tokenAccount, err := token.TokenAccountFromData(getAccountInfoResponse.Data) 23 | if err != nil { 24 | log.Fatalf("failed to parse data to a token account, err: %v", err) 25 | } 26 | 27 | fmt.Printf("%+v\n", tokenAccount) 28 | // {Mint:F6tecPzBMF47yJ2EN6j2aGtE68yR5jehXcZYVZa6ZETo Owner:9aE476sH92Vz7DMPyq5WLPkrKWivxeuTKEFKd2sZZcde Amount:100000000 Delegate: State:1 IsNative: DelegatedAmount:0 CloseAuthority:} 29 | } 30 | -------------------------------------------------------------------------------- /client/rpc_get_epoch_info.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | type GetEpochInfo struct { 10 | AbsoluteSlot uint64 11 | BlockHeight uint64 12 | Epoch uint64 13 | SlotIndex uint64 14 | SlotsInEpoch uint64 15 | TransactionCount *uint64 16 | } 17 | 18 | // GetEpochInfo returns information about the current epoch 19 | func (c *Client) GetEpochInfo(ctx context.Context) (GetEpochInfo, error) { 20 | return process( 21 | func() (rpc.JsonRpcResponse[rpc.GetEpochInfo], error) { 22 | return c.RpcClient.GetEpochInfo(ctx) 23 | }, 24 | convertGetEpochInfo, 25 | ) 26 | } 27 | 28 | func convertGetEpochInfo(v rpc.GetEpochInfo) (GetEpochInfo, error) { 29 | return GetEpochInfo{ 30 | AbsoluteSlot: v.AbsoluteSlot, 31 | BlockHeight: v.BlockHeight, 32 | Epoch: v.Epoch, 33 | SlotIndex: v.SlotIndex, 34 | SlotsInEpoch: v.SlotsInEpoch, 35 | TransactionCount: v.TransactionCount, 36 | }, nil 37 | } 38 | -------------------------------------------------------------------------------- /docs/_examples/program/101/data/program/src/lib.rs: -------------------------------------------------------------------------------- 1 | use solana_program::{ 2 | account_info::AccountInfo, entrypoint, entrypoint::ProgramResult, msg, 3 | program_error::ProgramError, pubkey::Pubkey, 4 | }; 5 | 6 | entrypoint!(process_instruction); 7 | 8 | fn process_instruction( 9 | _program_id: &Pubkey, 10 | _accounts: &[AccountInfo], 11 | instruction_data: &[u8], 12 | ) -> ProgramResult { 13 | let (selector, rest) = instruction_data 14 | .split_first() 15 | .ok_or(ProgramError::InvalidInstructionData)?; 16 | 17 | match selector { 18 | 0 => msg!(&format!( 19 | "first instruction is called. remaining data: {:?}", 20 | rest, 21 | )), 22 | 1 => msg!(&format!( 23 | "second instruction is called. remaining data: {:?}", 24 | rest, 25 | )), 26 | _ => { 27 | msg!("invalid called"); 28 | return Err(ProgramError::InvalidInstructionData); 29 | } 30 | } 31 | 32 | Ok(()) 33 | } 34 | -------------------------------------------------------------------------------- /docs/_examples/tour/get-mint/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/common" 10 | "github.com/blocto/solana-go-sdk/program/token" 11 | "github.com/blocto/solana-go-sdk/rpc" 12 | ) 13 | 14 | var mintPubkey = common.PublicKeyFromString("F6tecPzBMF47yJ2EN6j2aGtE68yR5jehXcZYVZa6ZETo") 15 | 16 | func main() { 17 | c := client.NewClient(rpc.DevnetRPCEndpoint) 18 | 19 | getAccountInfoResponse, err := c.GetAccountInfo(context.TODO(), mintPubkey.ToBase58()) 20 | if err != nil { 21 | log.Fatalf("failed to get account info, err: %v", err) 22 | } 23 | 24 | mintAccount, err := token.MintAccountFromData(getAccountInfoResponse.Data) 25 | if err != nil { 26 | log.Fatalf("failed to parse data to a mint account, err: %v", err) 27 | } 28 | 29 | fmt.Printf("%+v\n", mintAccount) 30 | // {MintAuthority:9aE476sH92Vz7DMPyq5WLPkrKWivxeuTKEFKd2sZZcde Supply:0 Decimals:8 IsInitialized:true FreezeAuthority:} 31 | } 32 | -------------------------------------------------------------------------------- /program/sysvar/slot_hashes.go: -------------------------------------------------------------------------------- 1 | package sysvar 2 | 3 | import ( 4 | "github.com/blocto/solana-go-sdk/common" 5 | "github.com/blocto/solana-go-sdk/pkg/bytes_decoder" 6 | ) 7 | 8 | type SlotHash struct { 9 | Slot uint64 10 | Hash [32]byte 11 | } 12 | 13 | type SlotHashes []SlotHash 14 | 15 | func DeserializeSlotHashes(data []byte, owner common.PublicKey) (SlotHashes, error) { 16 | if owner != common.SysVarPubkey { 17 | return SlotHashes{}, ErrInvalidAccountOwner 18 | } 19 | 20 | current := 0 21 | len, err := bytes_decoder.GetUint64(¤t, data) 22 | if err != nil { 23 | return SlotHashes{}, err 24 | } 25 | 26 | v := make([]SlotHash, 0, len) 27 | for i := uint64(0); i < len; i++ { 28 | slot, err := bytes_decoder.GetUint64(¤t, data) 29 | if err != nil { 30 | return SlotHashes{}, err 31 | } 32 | hash, err := bytes_decoder.GetBytes32(¤t, data) 33 | if err != nil { 34 | return SlotHashes{}, err 35 | } 36 | 37 | v = append(v, SlotHash{Slot: slot, Hash: hash}) 38 | } 39 | return v, nil 40 | } 41 | -------------------------------------------------------------------------------- /rpc/get_inflation_rate_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetInflationRate(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getInflationRate"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":{"epoch":200,"foundation":0.0,"total":0.06956826778571164,"validator":0.06956826778571164},"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetInflationRate(context.TODO()) 20 | }, 21 | ExpectedValue: JsonRpcResponse[GetInflationRate]{ 22 | JsonRpc: "2.0", 23 | Id: 1, 24 | Error: nil, 25 | Result: GetInflationRate{ 26 | Epoch: 200, 27 | Foundation: 0.0, 28 | Total: 0.06956826778571164, 29 | Validator: 0.06956826778571164, 30 | }, 31 | }, 32 | ExpectedError: nil, 33 | }, 34 | }, 35 | ) 36 | } 37 | -------------------------------------------------------------------------------- /rpc/get_minimum_balance_for_rent_exemption.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetMinimumBalanceForRentExemptionResponse JsonRpcResponse[uint64] 8 | 9 | type GetMinimumBalanceForRentExemptionConfig struct { 10 | Commitment Commitment `json:"commitment,omitempty"` 11 | } 12 | 13 | // GetMinimumBalanceForRentExemption returns minimum balance required to make account rent exempt 14 | func (c *RpcClient) GetMinimumBalanceForRentExemption(ctx context.Context, dataLen uint64) (JsonRpcResponse[uint64], error) { 15 | return call[JsonRpcResponse[uint64]](c, ctx, "getMinimumBalanceForRentExemption", dataLen) 16 | } 17 | 18 | // GetMinimumBalanceForRentExemptionWithConfig returns minimum balance required to make account rent exempt 19 | func (c *RpcClient) GetMinimumBalanceForRentExemptionWithConfig(ctx context.Context, dataLen uint64, cfg GetMinimumBalanceForRentExemptionConfig) (JsonRpcResponse[uint64], error) { 20 | return call[JsonRpcResponse[uint64]](c, ctx, "getMinimumBalanceForRentExemption", dataLen, cfg) 21 | } 22 | -------------------------------------------------------------------------------- /client/system.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | 7 | "github.com/blocto/solana-go-sdk/common" 8 | "github.com/blocto/solana-go-sdk/program/system" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | "github.com/mr-tron/base58" 11 | ) 12 | 13 | func (c *Client) GetNonceAccount(ctx context.Context, base58Addr string) (system.NonceAccount, error) { 14 | accu, err := c.GetAccountInfo(ctx, base58Addr) 15 | if err != nil { 16 | return system.NonceAccount{}, err 17 | } 18 | if accu.Owner != common.SystemProgramID { 19 | return system.NonceAccount{}, errors.New("owner mismatch") 20 | } 21 | return system.NonceAccountDeserialize(accu.Data) 22 | } 23 | 24 | func (c *Client) GetNonceFromNonceAccount(ctx context.Context, base58Addr string) (string, error) { 25 | accuInfo, err := c.GetAccountInfoWithConfig(ctx, base58Addr, GetAccountInfoConfig{ 26 | DataSlice: &rpc.DataSlice{ 27 | Offset: 40, 28 | Length: 32, 29 | }, 30 | }) 31 | if err != nil { 32 | return "", err 33 | } 34 | return base58.Encode(accuInfo.Data), nil 35 | } 36 | -------------------------------------------------------------------------------- /rpc/is_blockhash_valid.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type IsBlockhashValidResponse JsonRpcResponse[IsBlockhashValid] 8 | 9 | type IsBlockhashValid ValueWithContext[bool] 10 | 11 | // IsBlockhashValidConfig is a option config for `IsBlockhashValid` 12 | type IsBlockhashValidConfig struct { 13 | Commitment Commitment `json:"commitment,omitempty"` 14 | } 15 | 16 | // IsBlockhashValid get the fee the network will charge for a particular Message 17 | func (c *RpcClient) IsBlockhashValid(ctx context.Context, message string) (JsonRpcResponse[ValueWithContext[bool]], error) { 18 | return call[JsonRpcResponse[ValueWithContext[bool]]](c, ctx, "isBlockhashValid", message) 19 | } 20 | 21 | // IsBlockhashValidWithConfig get the fee the network will charge for a particular Message 22 | func (c *RpcClient) IsBlockhashValidWithConfig(ctx context.Context, message string, cfg IsBlockhashValidConfig) (JsonRpcResponse[ValueWithContext[bool]], error) { 23 | return call[JsonRpcResponse[ValueWithContext[bool]]](c, ctx, "isBlockhashValid", message, cfg) 24 | } 25 | -------------------------------------------------------------------------------- /client/rpc_get_epoch_info_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | "github.com/blocto/solana-go-sdk/pkg/pointer" 9 | ) 10 | 11 | func TestClient_GetEpochInfo(t *testing.T) { 12 | client_test.TestAll( 13 | t, 14 | []client_test.Param{ 15 | { 16 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getEpochInfo"}`, 17 | ResponseBody: `{"jsonrpc":"2.0","result":{"absoluteSlot":86715160,"blockHeight":84901536,"epoch":200,"slotIndex":315160,"slotsInEpoch":432000,"transactionCount":2265984079},"id":1}`, 18 | F: func(url string) (any, error) { 19 | c := NewClient(url) 20 | return c.GetEpochInfo(context.TODO()) 21 | }, 22 | ExpectedValue: GetEpochInfo{ 23 | AbsoluteSlot: 86715160, 24 | BlockHeight: 84901536, 25 | Epoch: 200, 26 | SlotIndex: 315160, 27 | SlotsInEpoch: 432000, 28 | TransactionCount: pointer.Get[uint64](2265984079), 29 | }, 30 | ExpectedError: nil, 31 | }, 32 | }, 33 | ) 34 | } 35 | -------------------------------------------------------------------------------- /client/rpc_get_slot_leader.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | type GetSlotLeaderConfig struct { 10 | Commitment *rpc.Commitment 11 | MinContextSlot *uint64 12 | } 13 | 14 | func (c GetSlotLeaderConfig) toRpc() rpc.GetSlotLeaderConfig { 15 | return rpc.GetSlotLeaderConfig{ 16 | Commitment: c.Commitment, 17 | MinContextSlot: c.MinContextSlot, 18 | } 19 | } 20 | 21 | // GetSlotLeader returns the current slot leader 22 | func (c *Client) GetSlotLeader(ctx context.Context) (string, error) { 23 | return process( 24 | func() (rpc.JsonRpcResponse[string], error) { 25 | return c.RpcClient.GetSlotLeader(ctx) 26 | }, 27 | forward[string], 28 | ) 29 | } 30 | 31 | // GetSlotWithConfig returns the current slot leader 32 | func (c *Client) GetSlotLeaderWithConfig(ctx context.Context, cfg GetSlotLeaderConfig) (string, error) { 33 | return process( 34 | func() (rpc.JsonRpcResponse[string], error) { 35 | return c.RpcClient.GetSlotLeaderWithConfig(ctx, cfg.toRpc()) 36 | }, 37 | forward[string], 38 | ) 39 | } 40 | -------------------------------------------------------------------------------- /docs/_examples/program/101/accounts/program/src/lib.rs: -------------------------------------------------------------------------------- 1 | use solana_program::{ 2 | account_info::{next_account_info, AccountInfo}, 3 | entrypoint, 4 | entrypoint::ProgramResult, 5 | msg, 6 | pubkey::Pubkey, 7 | }; 8 | 9 | entrypoint!(process_instruction); 10 | 11 | fn process_instruction( 12 | _program_id: &Pubkey, 13 | accounts: &[AccountInfo], 14 | _instruction_data: &[u8], 15 | ) -> ProgramResult { 16 | let account_info_iter = &mut accounts.iter(); 17 | 18 | let first_account_info = next_account_info(account_info_iter)?; 19 | msg!(&format!( 20 | "first: {} isSigner: {}, isWritable: {}", 21 | first_account_info.key.to_string(), 22 | first_account_info.is_signer, 23 | first_account_info.is_writable, 24 | )); 25 | 26 | let second_account_info = next_account_info(account_info_iter)?; 27 | msg!(&format!( 28 | "second: {} isSigner: {}, isWritable: {}", 29 | second_account_info.key.to_string(), 30 | second_account_info.is_signer, 31 | second_account_info.is_writable, 32 | )); 33 | 34 | Ok(()) 35 | } 36 | -------------------------------------------------------------------------------- /rpc/get_token_account_balance.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import "context" 4 | 5 | type GetTokenAccountBalanceResponse JsonRpcResponse[ValueWithContext[TokenAccountBalance]] 6 | 7 | type GetTokenAccountBalance ValueWithContext[TokenAccountBalance] 8 | 9 | type GetTokenAccountBalanceConfig struct { 10 | Commitment Commitment `json:"commitment,omitempty"` 11 | } 12 | 13 | // GetTokenAccountBalance returns the token balance of an SPL Token account 14 | func (c *RpcClient) GetTokenAccountBalance(ctx context.Context, base58Addr string) (JsonRpcResponse[ValueWithContext[TokenAccountBalance]], error) { 15 | return call[JsonRpcResponse[ValueWithContext[TokenAccountBalance]]](c, ctx, "getTokenAccountBalance", base58Addr) 16 | } 17 | 18 | // GetTokenAccountBalance returns the token balance of an SPL Token account 19 | func (c *RpcClient) GetTokenAccountBalanceWithConfig(ctx context.Context, base58Addr string, cfg GetTokenAccountBalanceConfig) (JsonRpcResponse[ValueWithContext[TokenAccountBalance]], error) { 20 | return call[JsonRpcResponse[ValueWithContext[TokenAccountBalance]]](c, ctx, "getTokenAccountBalance", base58Addr, cfg) 21 | } 22 | -------------------------------------------------------------------------------- /client/rpc_get_transaction_count.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | type GetTransactionCountConfig struct { 10 | Commitment rpc.Commitment 11 | } 12 | 13 | func (c GetTransactionCountConfig) toRpc() rpc.GetTransactionCountConfig { 14 | return rpc.GetTransactionCountConfig{ 15 | Commitment: c.Commitment, 16 | } 17 | } 18 | 19 | // GetTransactionCount returns the current Transaction count from the ledger 20 | func (c *Client) GetTransactionCount(ctx context.Context) (uint64, error) { 21 | return process( 22 | func() (rpc.JsonRpcResponse[uint64], error) { 23 | return c.RpcClient.GetTransactionCount(ctx) 24 | }, 25 | forward[uint64], 26 | ) 27 | } 28 | 29 | // GetTransactionCount returns the current Transaction count from the ledger 30 | func (c *Client) GetTransactionCountWithConfig(ctx context.Context, cfg GetTransactionCountConfig) (uint64, error) { 31 | return process( 32 | func() (rpc.JsonRpcResponse[uint64], error) { 33 | return c.RpcClient.GetTransactionCountWithConfig(ctx, cfg.toRpc()) 34 | }, 35 | forward[uint64], 36 | ) 37 | } 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 blocto 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /rpc/get_epoch_info.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import "context" 4 | 5 | type GetEpochInfoResponse JsonRpcResponse[GetEpochInfo] 6 | 7 | type GetEpochInfo struct { 8 | AbsoluteSlot uint64 `json:"absoluteSlot"` 9 | BlockHeight uint64 `json:"blockHeight"` 10 | Epoch uint64 `json:"epoch"` 11 | SlotIndex uint64 `json:"slotIndex"` 12 | SlotsInEpoch uint64 `json:"slotsInEpoch"` 13 | TransactionCount *uint64 `json:"transactionCount"` 14 | } 15 | 16 | // GetEpochInfoConfig is a option config for `getEpochInfo` 17 | type GetEpochInfoConfig struct { 18 | Commitment Commitment `json:"commitment,omitempty"` 19 | } 20 | 21 | // GetEpochInfo returns the SOL balance 22 | func (c *RpcClient) GetEpochInfo(ctx context.Context) (JsonRpcResponse[GetEpochInfo], error) { 23 | return call[JsonRpcResponse[GetEpochInfo]](c, ctx, "getEpochInfo") 24 | } 25 | 26 | // GetEpochInfoWithConfig returns the SOL balance 27 | func (c *RpcClient) GetEpochInfoWithConfig(ctx context.Context, cfg GetEpochInfoConfig) (JsonRpcResponse[GetEpochInfo], error) { 28 | return call[JsonRpcResponse[GetEpochInfo]](c, ctx, "getEpochInfo", cfg) 29 | } 30 | -------------------------------------------------------------------------------- /rpc/get_epoch_schedule_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetEpochSchedule(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getEpochSchedule"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":{"firstNormalEpoch":0,"firstNormalSlot":0,"leaderScheduleSlotOffset":432000,"slotsPerEpoch":432000,"warmup":false},"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetEpochSchedule( 20 | context.TODO(), 21 | ) 22 | }, 23 | ExpectedValue: JsonRpcResponse[GetEpochSchedule]{ 24 | JsonRpc: "2.0", 25 | Id: 1, 26 | Error: nil, 27 | Result: GetEpochSchedule{ 28 | FirstNormalEpoch: 0, 29 | FirstNormalSlot: 0, 30 | LeaderScheduleSlotOffset: 432000, 31 | SlotsPerEpoch: 432000, 32 | Warmup: false, 33 | }, 34 | }, 35 | ExpectedError: nil, 36 | }, 37 | }, 38 | ) 39 | } 40 | -------------------------------------------------------------------------------- /client/rpc_request_airdrop.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | type RequestAirdropConfig struct { 10 | Commitment rpc.Commitment 11 | } 12 | 13 | func (c RequestAirdropConfig) toRpc() rpc.RequestAirdropConfig { 14 | return rpc.RequestAirdropConfig{ 15 | Commitment: c.Commitment, 16 | } 17 | } 18 | 19 | // RequestAirdrop requests an airdrop of lamports to a Pubkey 20 | func (c *Client) RequestAirdrop(ctx context.Context, base58Addr string, lamports uint64) (string, error) { 21 | return process( 22 | func() (rpc.JsonRpcResponse[string], error) { 23 | return c.RpcClient.RequestAirdrop(ctx, base58Addr, lamports) 24 | }, 25 | forward[string], 26 | ) 27 | } 28 | 29 | // RequestAirdrop requests an airdrop of lamports to a Pubkey 30 | func (c *Client) RequestAirdropWithConfig(ctx context.Context, base58Addr string, lamports uint64, cfg RequestAirdropConfig) (string, error) { 31 | return process( 32 | func() (rpc.JsonRpcResponse[string], error) { 33 | return c.RpcClient.RequestAirdropWithConfig( 34 | ctx, 35 | base58Addr, 36 | lamports, 37 | cfg.toRpc(), 38 | ) 39 | }, 40 | forward[string], 41 | ) 42 | } 43 | -------------------------------------------------------------------------------- /rpc/get_account_info.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetAccountResponse JsonRpcResponse[GetAccountInfo] 8 | 9 | type GetAccountInfo ValueWithContext[AccountInfo] 10 | 11 | // GetAccountInfoConfig is an option config for `getAccountInfo` 12 | type GetAccountInfoConfig struct { 13 | Commitment Commitment `json:"commitment,omitempty"` 14 | Encoding AccountEncoding `json:"encoding,omitempty"` 15 | DataSlice *DataSlice `json:"dataSlice,omitempty"` 16 | } 17 | 18 | // GetAccountInfo returns all information associated with the account of provided Pubkey 19 | func (c *RpcClient) GetAccountInfo(ctx context.Context, base58Addr string) (JsonRpcResponse[ValueWithContext[AccountInfo]], error) { 20 | return call[JsonRpcResponse[ValueWithContext[AccountInfo]]](c, ctx, "getAccountInfo", base58Addr) 21 | } 22 | 23 | // GetAccountInfo returns all information associated with the account of provided Pubkey 24 | func (c *RpcClient) GetAccountInfoWithConfig(ctx context.Context, base58Addr string, cfg GetAccountInfoConfig) (JsonRpcResponse[ValueWithContext[AccountInfo]], error) { 25 | return call[JsonRpcResponse[ValueWithContext[AccountInfo]]](c, ctx, "getAccountInfo", base58Addr, cfg) 26 | } 27 | -------------------------------------------------------------------------------- /client/rpc_get_block_time_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | "github.com/blocto/solana-go-sdk/pkg/pointer" 9 | ) 10 | 11 | func TestClient_GetBlockTime(t *testing.T) { 12 | var nilValue *int64 13 | client_test.TestAll( 14 | t, 15 | []client_test.Param{ 16 | 17 | { 18 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getBlockTime", "params":[85588104]}`, 19 | ResponseBody: `{"jsonrpc":"2.0","result":1633531934,"id":1}`, 20 | F: func(url string) (any, error) { 21 | c := NewClient(url) 22 | return c.GetBlockTime( 23 | context.TODO(), 24 | 85588104, 25 | ) 26 | }, 27 | ExpectedValue: pointer.Get[int64](1633531934), 28 | ExpectedError: nil, 29 | }, 30 | { 31 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getBlockTime", "params":[85588104]}`, 32 | ResponseBody: `{"jsonrpc":"2.0","result":null,"id":1}`, 33 | F: func(url string) (any, error) { 34 | c := NewClient(url) 35 | return c.GetBlockTime( 36 | context.TODO(), 37 | 85588104, 38 | ) 39 | }, 40 | ExpectedValue: nilValue, 41 | ExpectedError: nil, 42 | }, 43 | }, 44 | ) 45 | } 46 | -------------------------------------------------------------------------------- /docs/_examples/client/get-slot/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | 15 | var slot uint64 16 | var err error 17 | 18 | // get slot 19 | slot, err = c.GetSlot(context.TODO()) 20 | if err != nil { 21 | log.Fatalf("failed to GetSlot, err: %v", err) 22 | } 23 | fmt.Println("GetSlot", slot) 24 | 25 | // get slot by commitment 26 | slot, err = c.GetSlotWithConfig(context.TODO(), rpc.GetSlotConfig{Commitment: rpc.CommitmentProcessed}) 27 | if err != nil { 28 | log.Fatalf("failed to GetSlotWithConfig, err: %v", err) 29 | } 30 | fmt.Println("GetSlotWithConfig", slot) 31 | 32 | rpcRes, err := c.RpcClient.GetSlot(context.TODO()) 33 | if err != nil { 34 | log.Fatalf("failed to RpcClient.GetSlot, err: %v", err) 35 | } 36 | fmt.Printf("res: %+v\n", rpcRes) 37 | 38 | rpcRes, err = c.RpcClient.GetSlotWithConfig(context.TODO(), rpc.GetSlotConfig{Commitment: rpc.CommitmentProcessed}) 39 | if err != nil { 40 | log.Fatalf("failed to RpcClient.GetSlotWithConfig, err: %v", err) 41 | } 42 | fmt.Printf("res: %+v\n", rpcRes) 43 | } 44 | -------------------------------------------------------------------------------- /rpc/get_inflation_governor.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetInflationGovernorResponse JsonRpcResponse[GetInflationGovernor] 8 | 9 | type GetInflationGovernor struct { 10 | Foundation float64 `json:"foundation"` 11 | FoundationTerm float64 `json:"foundationTerm"` 12 | Initial float64 `json:"initial"` 13 | Taper float64 `json:"taper"` 14 | Terminal float64 `json:"terminal"` 15 | } 16 | 17 | // GetInflationGovernorConfig is a option config for `getInflationGovernor` 18 | type GetInflationGovernorConfig struct { 19 | Commitment Commitment `json:"commitment,omitempty"` 20 | } 21 | 22 | // GetInflationGovernor returns the current inflation governor 23 | func (c *RpcClient) GetInflationGovernor(ctx context.Context) (JsonRpcResponse[GetInflationGovernor], error) { 24 | return call[JsonRpcResponse[GetInflationGovernor]](c, ctx, "getInflationGovernor") 25 | } 26 | 27 | // GetInflationGovernorWithConfig returns the current inflation governor 28 | func (c *RpcClient) GetInflationGovernorWithConfig(ctx context.Context, cfg GetInflationGovernorConfig) (JsonRpcResponse[GetInflationGovernor], error) { 29 | return call[JsonRpcResponse[GetInflationGovernor]](c, ctx, "getInflationGovernor", cfg) 30 | } 31 | -------------------------------------------------------------------------------- /docs/_examples/client/get-balance/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | ) 11 | 12 | func main() { 13 | c := client.NewClient(rpc.DevnetRPCEndpoint) 14 | 15 | // get balance 16 | balance, err := c.GetBalance( 17 | context.TODO(), 18 | "RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", 19 | ) 20 | if err != nil { 21 | log.Fatalf("failed to get balance, err: %v", err) 22 | } 23 | fmt.Printf("balance: %v\n", balance) 24 | 25 | // get balance with sepcific commitment 26 | balance, err = c.GetBalanceWithConfig( 27 | context.TODO(), 28 | "RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", 29 | rpc.GetBalanceConfig{ 30 | Commitment: rpc.CommitmentProcessed, 31 | }, 32 | ) 33 | if err != nil { 34 | log.Fatalf("failed to get balance with cfg, err: %v", err) 35 | } 36 | fmt.Printf("balance: %v\n", balance) 37 | 38 | // for advanced usage. fetch full rpc response 39 | res, err := c.RpcClient.GetBalance( 40 | context.TODO(), 41 | "RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", 42 | ) 43 | if err != nil { 44 | log.Fatalf("failed to get balance via rpc client, err: %v", err) 45 | } 46 | fmt.Printf("response: %+v\n", res) 47 | } 48 | -------------------------------------------------------------------------------- /internal/client_test/case.go: -------------------------------------------------------------------------------- 1 | package client_test 2 | 3 | import ( 4 | "io" 5 | "net/http" 6 | "net/http/httptest" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | type Param struct { 13 | Name string 14 | RequestBody string 15 | ResponseBody string 16 | F func(url string) (any, error) 17 | ExpectedValue any 18 | ExpectedError error 19 | } 20 | 21 | func TestAll(t *testing.T, params []Param) { 22 | for _, param := range params { 23 | t.Run(param.Name, func(t *testing.T) { 24 | Test(t, param) 25 | }) 26 | } 27 | } 28 | 29 | func Test(t *testing.T, param Param) { 30 | // setup test server 31 | server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 32 | // check request body match 33 | body, err := io.ReadAll(req.Body) 34 | assert.Nil(t, err) 35 | assert.JSONEq(t, param.RequestBody, string(body)) 36 | 37 | // check write response body success 38 | n, err := rw.Write([]byte(param.ResponseBody)) 39 | assert.Nil(t, err) 40 | assert.Equal(t, len([]byte(param.ResponseBody)), n) 41 | })) 42 | 43 | // test function 44 | got, err := param.F(server.URL) 45 | assert.Equal(t, param.ExpectedValue, got) 46 | assert.Equal(t, param.ExpectedError, err) 47 | 48 | server.Close() 49 | } 50 | -------------------------------------------------------------------------------- /client/rpc_get_cluster_node.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/common" 7 | "github.com/blocto/solana-go-sdk/rpc" 8 | ) 9 | 10 | type ClusterNode struct { 11 | Pubkey common.PublicKey 12 | Gossip *string 13 | Tpu *string 14 | Rpc *string 15 | Version *string 16 | FeatureSet *uint32 17 | ShredVersion *uint16 18 | } 19 | 20 | // GetClusterNodes returns information about all the nodes participating in the cluster 21 | func (c *Client) GetClusterNodes(ctx context.Context) ([]ClusterNode, error) { 22 | return process( 23 | func() (rpc.JsonRpcResponse[rpc.GetClusterNodes], error) { 24 | return c.RpcClient.GetClusterNodes(ctx) 25 | }, 26 | convertGetClusterNodes, 27 | ) 28 | } 29 | 30 | func convertGetClusterNodes(v rpc.GetClusterNodes) ([]ClusterNode, error) { 31 | output := make([]ClusterNode, 0, len(v)) 32 | for _, info := range v { 33 | output = append(output, ClusterNode{ 34 | Pubkey: common.PublicKeyFromString(info.Pubkey), 35 | Gossip: info.Gossip, 36 | Tpu: info.Tpu, 37 | Rpc: info.Rpc, 38 | Version: info.Version, 39 | FeatureSet: info.FeatureSet, 40 | ShredVersion: info.ShredVersion, 41 | }) 42 | } 43 | return output, nil 44 | } 45 | -------------------------------------------------------------------------------- /rpc/get_fee_for_message.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetFeeForMessageResponse JsonRpcResponse[ValueWithContext[*uint64]] 8 | 9 | type GetFeeForMessage ValueWithContext[*uint64] 10 | 11 | // GetFeeForMessageConfig is a option config for `GetFeeForMessage` 12 | type GetFeeForMessageConfig struct { 13 | Commitment Commitment `json:"commitment,omitempty"` 14 | } 15 | 16 | // NEW: This method is only available in solana-core v1.9 or newer. Please use getFees for solana-core v1.8 17 | // GetFeeForMessage get the fee the network will charge for a particular Message 18 | func (c *RpcClient) GetFeeForMessage(ctx context.Context, message string) (JsonRpcResponse[ValueWithContext[*uint64]], error) { 19 | return call[JsonRpcResponse[ValueWithContext[*uint64]]](c, ctx, "getFeeForMessage", message) 20 | } 21 | 22 | // NEW: This method is only available in solana-core v1.9 or newer. Please use getFees for solana-core v1.8 23 | // GetFeeForMessageWithConfig get the fee the network will charge for a particular Message 24 | func (c *RpcClient) GetFeeForMessageWithConfig(ctx context.Context, message string, cfg GetFeeForMessageConfig) (JsonRpcResponse[ValueWithContext[*uint64]], error) { 25 | return call[JsonRpcResponse[ValueWithContext[*uint64]]](c, ctx, "getFeeForMessage", message, cfg) 26 | } 27 | -------------------------------------------------------------------------------- /client/rpc_get_signatures_for_address.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | type GetSignaturesForAddressConfig struct { 10 | Limit int 11 | Before string 12 | Until string 13 | Commitment rpc.Commitment 14 | } 15 | 16 | func (c GetSignaturesForAddressConfig) toRpc() rpc.GetSignaturesForAddressConfig { 17 | return rpc.GetSignaturesForAddressConfig{ 18 | Limit: c.Limit, 19 | Before: c.Before, 20 | Until: c.Until, 21 | Commitment: c.Commitment, 22 | } 23 | } 24 | 25 | func (c *Client) GetSignaturesForAddress(ctx context.Context, addr string) (rpc.GetSignaturesForAddress, error) { 26 | return process( 27 | func() (rpc.JsonRpcResponse[rpc.GetSignaturesForAddress], error) { 28 | return c.RpcClient.GetSignaturesForAddress(ctx, addr) 29 | }, 30 | forward[rpc.GetSignaturesForAddress], 31 | ) 32 | } 33 | 34 | func (c *Client) GetSignaturesForAddressWithConfig(ctx context.Context, addr string, cfg GetSignaturesForAddressConfig) (rpc.GetSignaturesForAddress, error) { 35 | return process( 36 | func() (rpc.JsonRpcResponse[rpc.GetSignaturesForAddress], error) { 37 | return c.RpcClient.GetSignaturesForAddressWithConfig(ctx, addr, cfg.toRpc()) 38 | }, 39 | forward[rpc.GetSignaturesForAddress], 40 | ) 41 | } 42 | -------------------------------------------------------------------------------- /program/nsprog/utils.go: -------------------------------------------------------------------------------- 1 | package nsprog 2 | 3 | import ( 4 | "crypto/sha256" 5 | 6 | "github.com/blocto/solana-go-sdk/common" 7 | ) 8 | 9 | var TwitterVerificationAuthority = common.PublicKeyFromString("FvPH7PrVrLGKPfqaf3xJodFTjZriqrAXXLTVWEorTFBi") 10 | var TwitterRootParentRegisteryKey = common.PublicKeyFromString("4YcexoW3r78zz16J2aqmukBLRwGq6rAvWzJpkYAXqebv") 11 | var SolTldAuthority = common.PublicKeyFromString("58PwtjSDuFHuUkYjH9BYnnQKHfwo9reZhC2zMJv9JPkx") 12 | 13 | const HashPrefix = "SPL Name Service" 14 | 15 | // GetHashName ... 16 | func GetHashName(name string) []byte { 17 | h := sha256.Sum256([]byte(HashPrefix + name)) 18 | return h[:] 19 | } 20 | 21 | // GetNameAccountKey return the pubkey correspond to name 22 | func GetNameAccountKey(hashName []byte, nameClass, nameParent common.PublicKey) common.PublicKey { 23 | seed := [][]byte{ 24 | hashName, 25 | nameClass.Bytes(), 26 | nameParent.Bytes(), 27 | } 28 | pubkey, _, _ := common.FindProgramAddress(seed, common.SPLNameServiceProgramID) 29 | return pubkey 30 | } 31 | 32 | // GetTwitterRegistryKey return the pubkey corespond to twitter handle 33 | func GetTwitterRegistryKey(twitterHandle string) common.PublicKey { 34 | return GetNameAccountKey( 35 | GetHashName(twitterHandle), 36 | common.PublicKey{}, 37 | TwitterRootParentRegisteryKey, 38 | ) 39 | } 40 | -------------------------------------------------------------------------------- /program/name_service/utils.go: -------------------------------------------------------------------------------- 1 | package name_service 2 | 3 | import ( 4 | "crypto/sha256" 5 | 6 | "github.com/blocto/solana-go-sdk/common" 7 | ) 8 | 9 | var TwitterVerificationAuthority = common.PublicKeyFromString("FvPH7PrVrLGKPfqaf3xJodFTjZriqrAXXLTVWEorTFBi") 10 | var TwitterRootParentRegisteryKey = common.PublicKeyFromString("4YcexoW3r78zz16J2aqmukBLRwGq6rAvWzJpkYAXqebv") 11 | var SolTldAuthority = common.PublicKeyFromString("58PwtjSDuFHuUkYjH9BYnnQKHfwo9reZhC2zMJv9JPkx") 12 | 13 | const HashPrefix = "SPL Name Service" 14 | 15 | // GetHashName ... 16 | func GetHashName(name string) []byte { 17 | h := sha256.Sum256([]byte(HashPrefix + name)) 18 | return h[:] 19 | } 20 | 21 | // GetNameAccountKey return the pubkey correspond to name 22 | func GetNameAccountKey(hashName []byte, nameClass, nameParent common.PublicKey) common.PublicKey { 23 | seed := [][]byte{ 24 | hashName, 25 | nameClass.Bytes(), 26 | nameParent.Bytes(), 27 | } 28 | pubkey, _, _ := common.FindProgramAddress(seed, common.SPLNameServiceProgramID) 29 | return pubkey 30 | } 31 | 32 | // GetTwitterRegistryKey return the pubkey corespond to twitter handle 33 | func GetTwitterRegistryKey(twitterHandle string) common.PublicKey { 34 | return GetNameAccountKey( 35 | GetHashName(twitterHandle), 36 | common.PublicKey{}, 37 | TwitterRootParentRegisteryKey, 38 | ) 39 | } 40 | -------------------------------------------------------------------------------- /client/rpc_get_minimum_balance_for_rent_exemption.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | type GetMinimumBalanceForRentExemptionConfig struct { 10 | Commitment rpc.Commitment 11 | } 12 | 13 | func (c GetMinimumBalanceForRentExemptionConfig) toRpc() rpc.GetMinimumBalanceForRentExemptionConfig { 14 | return rpc.GetMinimumBalanceForRentExemptionConfig{ 15 | Commitment: c.Commitment, 16 | } 17 | } 18 | 19 | // GetMinimumBalanceForRentExemption returns minimum balance required to make account rent exempt 20 | func (c *Client) GetMinimumBalanceForRentExemption(ctx context.Context, dataLen uint64) (uint64, error) { 21 | return process( 22 | func() (rpc.JsonRpcResponse[uint64], error) { 23 | return c.RpcClient.GetMinimumBalanceForRentExemption(ctx, dataLen) 24 | }, 25 | forward[uint64], 26 | ) 27 | } 28 | 29 | // GetMinimumBalanceForRentExemption returns minimum balance required to make account rent exempt 30 | func (c *Client) GetMinimumBalanceForRentExemptionWithConfig(ctx context.Context, dataLen uint64, cfg GetMinimumBalanceForRentExemptionConfig) (uint64, error) { 31 | return process( 32 | func() (rpc.JsonRpcResponse[uint64], error) { 33 | return c.RpcClient.GetMinimumBalanceForRentExemptionWithConfig(ctx, dataLen, cfg.toRpc()) 34 | }, 35 | forward[uint64], 36 | ) 37 | } 38 | -------------------------------------------------------------------------------- /rpc/get_token_supply.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetTokenSupplyResponse JsonRpcResponse[GetTokenSupply] 8 | 9 | type GetTokenSupply ValueWithContext[GetTokenSupplyResultValue] 10 | 11 | // GetTokenSupplyResultValue is a part of `getTokenSupply` raw response 12 | type GetTokenSupplyResultValue struct { 13 | Amount string `json:"amount"` 14 | Decimals uint8 `json:"decimals"` 15 | UIAmountString string `json:"uiAmountString"` 16 | } 17 | 18 | // GetTokenSupplyConfig is option config of `getTokenSupply` 19 | type GetTokenSupplyConfig struct { 20 | Commitment Commitment `json:"commitment,omitempty"` 21 | } 22 | 23 | // GetTokenSupply returns the token balance of an SPL Token account 24 | func (c *RpcClient) GetTokenSupply(ctx context.Context, mintAddr string) (JsonRpcResponse[ValueWithContext[GetTokenSupplyResultValue]], error) { 25 | return call[JsonRpcResponse[ValueWithContext[GetTokenSupplyResultValue]]](c, ctx, "getTokenSupply", mintAddr) 26 | } 27 | 28 | // GetTokenSupply returns the token balance of an SPL Token account 29 | func (c *RpcClient) GetTokenSupplyWithConfig(ctx context.Context, mintAddr string, cfg GetTokenSupplyConfig) (JsonRpcResponse[ValueWithContext[GetTokenSupplyResultValue]], error) { 30 | return call[JsonRpcResponse[ValueWithContext[GetTokenSupplyResultValue]]](c, ctx, "getTokenSupply", mintAddr, cfg) 31 | } 32 | -------------------------------------------------------------------------------- /client/rpc_get_slot_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | "github.com/blocto/solana-go-sdk/rpc" 9 | ) 10 | 11 | func TestClient_GetSlot(t *testing.T) { 12 | client_test.TestAll( 13 | t, 14 | []client_test.Param{ 15 | { 16 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getSlot"}`, 17 | ResponseBody: `{"jsonrpc":"2.0","result":187548524,"id":1}`, 18 | F: func(url string) (any, error) { 19 | c := NewClient(url) 20 | return c.GetSlot( 21 | context.Background(), 22 | ) 23 | }, 24 | ExpectedValue: uint64(187548524), 25 | ExpectedError: nil, 26 | }, 27 | }, 28 | ) 29 | } 30 | 31 | func TestClient_GetSlotWithConfig(t *testing.T) { 32 | client_test.TestAll( 33 | t, 34 | []client_test.Param{ 35 | { 36 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getSlot", "params":[{"commitment": "confirmed"}]}`, 37 | ResponseBody: `{"jsonrpc":"2.0","result":187548524,"id":1}`, 38 | F: func(url string) (any, error) { 39 | c := NewClient(url) 40 | return c.GetSlotWithConfig( 41 | context.Background(), 42 | GetSlotConfig{ 43 | Commitment: rpc.CommitmentConfirmed, 44 | }, 45 | ) 46 | }, 47 | ExpectedValue: uint64(187548524), 48 | ExpectedError: nil, 49 | }, 50 | }, 51 | ) 52 | } 53 | -------------------------------------------------------------------------------- /rpc/get_slot_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetSlot(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getSlot"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":78413497,"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetSlot( 20 | context.TODO(), 21 | ) 22 | }, 23 | ExpectedValue: JsonRpcResponse[uint64]{ 24 | JsonRpc: "2.0", 25 | Id: 1, 26 | Error: nil, 27 | Result: 78413497, 28 | }, 29 | ExpectedError: nil, 30 | }, 31 | { 32 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getSlot", "params":[{"commitment": "processed"}]}`, 33 | ResponseBody: `{"jsonrpc":"2.0","result":78478796,"id":1}`, 34 | F: func(url string) (any, error) { 35 | c := NewRpcClient(url) 36 | return c.GetSlotWithConfig( 37 | context.TODO(), 38 | GetSlotConfig{ 39 | Commitment: CommitmentProcessed, 40 | }, 41 | ) 42 | }, 43 | ExpectedValue: JsonRpcResponse[uint64]{ 44 | JsonRpc: "2.0", 45 | Id: 1, 46 | Error: nil, 47 | Result: 78478796, 48 | }, 49 | ExpectedError: nil, 50 | }, 51 | }, 52 | ) 53 | } 54 | -------------------------------------------------------------------------------- /rpc/get_multiple_accounts.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetMultipleAccountsResponse JsonRpcResponse[GetMultipleAccounts] 8 | 9 | type GetMultipleAccounts ValueWithContext[[]AccountInfo] 10 | 11 | // GetMultipleAccountsConfigEncoding is account's data encode format 12 | type GetMultipleAccountsConfigEncoding string 13 | 14 | // GetMultipleAccountsConfig is an option config for `getAccountInfo` 15 | type GetMultipleAccountsConfig struct { 16 | Commitment Commitment `json:"commitment,omitempty"` 17 | Encoding AccountEncoding `json:"encoding,omitempty"` 18 | DataSlice *DataSlice `json:"dataSlice,omitempty"` 19 | } 20 | 21 | // GetMultipleAccounts returns all information associated with the account of provided Pubkey 22 | func (c *RpcClient) GetMultipleAccounts(ctx context.Context, base58Addrs []string) (JsonRpcResponse[ValueWithContext[[]AccountInfo]], error) { 23 | return call[JsonRpcResponse[ValueWithContext[[]AccountInfo]]](c, ctx, "getMultipleAccounts", base58Addrs) 24 | } 25 | 26 | // GetMultipleAccounts returns all information associated with the account of provided Pubkey 27 | func (c *RpcClient) GetMultipleAccountsWithConfig(ctx context.Context, base58Addrs []string, cfg GetMultipleAccountsConfig) (JsonRpcResponse[ValueWithContext[[]AccountInfo]], error) { 28 | return call[JsonRpcResponse[ValueWithContext[[]AccountInfo]]](c, ctx, "getMultipleAccounts", base58Addrs, cfg) 29 | } 30 | -------------------------------------------------------------------------------- /rpc/send_transaction.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type SendTransactionResponse JsonRpcResponse[string] 8 | 9 | type SendTransactionConfigEncoding string 10 | 11 | const ( 12 | SendTransactionConfigEncodingBase58 SendTransactionConfigEncoding = "base58" 13 | SendTransactionConfigEncodingBase64 SendTransactionConfigEncoding = "base64" 14 | ) 15 | 16 | type SendTransactionConfig struct { 17 | SkipPreflight bool `json:"skipPreflight,omitempty"` // default: false 18 | PreflightCommitment Commitment `json:"preflightCommitment,omitempty"` // default: finalized 19 | Encoding SendTransactionConfigEncoding `json:"encoding,omitempty"` // default: base58 20 | MaxRetries uint64 `json:"maxRetries,omitempty"` 21 | } 22 | 23 | // SendTransaction submits a signed transaction to the cluster for processing 24 | func (c *RpcClient) SendTransaction(ctx context.Context, tx string) (JsonRpcResponse[string], error) { 25 | return call[JsonRpcResponse[string]](c, ctx, "sendTransaction", tx) 26 | } 27 | 28 | // SendTransaction submits a signed transaction to the cluster for processing 29 | func (c *RpcClient) SendTransactionWithConfig(ctx context.Context, tx string, cfg SendTransactionConfig) (JsonRpcResponse[string], error) { 30 | return call[JsonRpcResponse[string]](c, ctx, "sendTransaction", tx, cfg) 31 | } 32 | -------------------------------------------------------------------------------- /client/rpc_get_cluster_node_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/common" 8 | "github.com/blocto/solana-go-sdk/internal/client_test" 9 | "github.com/blocto/solana-go-sdk/pkg/pointer" 10 | ) 11 | 12 | func TestClient_GetClusterNodes(t *testing.T) { 13 | client_test.TestAll( 14 | t, 15 | []client_test.Param{ 16 | { 17 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getClusterNodes"}`, 18 | ResponseBody: `{"jsonrpc":"2.0","result":[{"featureSet":1797267350,"gossip":"127.0.0.1:1024","pubkey":"8gNdbr9dG6oj8bhaQ44icyMYsfG3t1dhXKUJLGVav4tn","rpc":"127.0.0.1:8899","shredVersion":23492,"tpu":"127.0.0.1:1027","version":"1.8.1"}],"id":1}`, 19 | F: func(url string) (any, error) { 20 | c := NewClient(url) 21 | return c.GetClusterNodes( 22 | context.TODO(), 23 | ) 24 | }, 25 | ExpectedValue: []ClusterNode{ 26 | { 27 | Pubkey: common.PublicKeyFromString("8gNdbr9dG6oj8bhaQ44icyMYsfG3t1dhXKUJLGVav4tn"), 28 | Gossip: pointer.Get("127.0.0.1:1024"), 29 | Tpu: pointer.Get("127.0.0.1:1027"), 30 | Rpc: pointer.Get("127.0.0.1:8899"), 31 | Version: pointer.Get("1.8.1"), 32 | FeatureSet: pointer.Get[uint32](1797267350), 33 | ShredVersion: pointer.Get[uint16](23492), 34 | }, 35 | }, 36 | ExpectedError: nil, 37 | }, 38 | }, 39 | ) 40 | } 41 | -------------------------------------------------------------------------------- /rpc/get_block_height_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetBlockHeight(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getBlockHeight"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":83518197,"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetBlockHeight(context.TODO()) 20 | }, 21 | ExpectedValue: JsonRpcResponse[uint64]{ 22 | JsonRpc: "2.0", 23 | Id: 1, 24 | Error: nil, 25 | Result: 83518197, 26 | }, 27 | ExpectedError: nil, 28 | }, 29 | { 30 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getBlockHeight", "params":[{"commitment": "confirmed"}]}`, 31 | ResponseBody: `{"jsonrpc":"2.0","result":83518231,"id":1}`, 32 | F: func(url string) (any, error) { 33 | c := NewRpcClient(url) 34 | return c.GetBlockHeightWithConfig( 35 | context.Background(), 36 | GetBlockHeightConfig{ 37 | Commitment: CommitmentConfirmed, 38 | }, 39 | ) 40 | }, 41 | ExpectedValue: JsonRpcResponse[uint64]{ 42 | JsonRpc: "2.0", 43 | Id: 1, 44 | Error: nil, 45 | Result: 83518231, 46 | }, 47 | ExpectedError: nil, 48 | }, 49 | }, 50 | ) 51 | } 52 | -------------------------------------------------------------------------------- /docs/_examples/nft/get-metadata/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/davecgh/go-spew/spew" 8 | 9 | "github.com/blocto/solana-go-sdk/client" 10 | "github.com/blocto/solana-go-sdk/common" 11 | "github.com/blocto/solana-go-sdk/program/metaplex/token_metadata" 12 | "github.com/blocto/solana-go-sdk/rpc" 13 | ) 14 | 15 | func main() { 16 | // NFT in solana is a normal mint but only mint 1. 17 | // If you want to get its metadata, you need to know where it stored. 18 | // and you can use `tokenmeta.GetTokenMetaPubkey` to get the metadata account key 19 | // here I take a random Degenerate Ape Academy as an example 20 | mint := common.PublicKeyFromString("GphF2vTuzhwhLWBWWvD8y5QLCPp1aQC5EnzrWsnbiWPx") 21 | metadataAccount, err := token_metadata.GetTokenMetaPubkey(mint) 22 | if err != nil { 23 | log.Fatalf("faield to get metadata account, err: %v", err) 24 | } 25 | 26 | // new a client 27 | c := client.NewClient(rpc.MainnetRPCEndpoint) 28 | 29 | // get data which stored in metadataAccount 30 | accountInfo, err := c.GetAccountInfo(context.Background(), metadataAccount.ToBase58()) 31 | if err != nil { 32 | log.Fatalf("failed to get accountInfo, err: %v", err) 33 | } 34 | 35 | // parse it 36 | metadata, err := token_metadata.MetadataDeserialize(accountInfo.Data) 37 | if err != nil { 38 | log.Fatalf("failed to parse metaAccount, err: %v", err) 39 | } 40 | spew.Dump(metadata) 41 | } 42 | -------------------------------------------------------------------------------- /rpc/get_signature_statuses.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetSignatureStatusesResponse JsonRpcResponse[GetSignatureStatuses] 8 | 9 | type GetSignatureStatuses ValueWithContext[SignatureStatuses] 10 | 11 | type SignatureStatus struct { 12 | Slot uint64 `json:"slot"` 13 | Confirmations *uint64 `json:"confirmations"` 14 | ConfirmationStatus *Commitment `json:"confirmationStatus"` 15 | Err any `json:"err"` 16 | } 17 | 18 | type SignatureStatuses []*SignatureStatus 19 | 20 | // GetSignatureStatusesConfig is a option config for `getSignatureStatuses` 21 | type GetSignatureStatusesConfig struct { 22 | SearchTransactionHistory bool `json:"searchTransactionHistory,omitempty"` 23 | } 24 | 25 | // GetSignatureStatuses returns the SOL balance 26 | func (c *RpcClient) GetSignatureStatuses(ctx context.Context, signatures []string) (JsonRpcResponse[ValueWithContext[SignatureStatuses]], error) { 27 | return call[JsonRpcResponse[ValueWithContext[SignatureStatuses]]](c, ctx, "getSignatureStatuses", signatures) 28 | } 29 | 30 | // GetSignatureStatusesWithConfig returns the SOL balance 31 | func (c *RpcClient) GetSignatureStatusesWithConfig(ctx context.Context, signatures []string, cfg GetSignatureStatusesConfig) (JsonRpcResponse[ValueWithContext[SignatureStatuses]], error) { 32 | return call[JsonRpcResponse[ValueWithContext[SignatureStatuses]]](c, ctx, "getSignatureStatuses", signatures, cfg) 33 | } 34 | -------------------------------------------------------------------------------- /client/rpc_get_transaction_count_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | "github.com/blocto/solana-go-sdk/rpc" 9 | ) 10 | 11 | func TestClient_GetTransactionCount(t *testing.T) { 12 | client_test.TestAll( 13 | t, 14 | []client_test.Param{ 15 | { 16 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getTransactionCount"}`, 17 | ResponseBody: `{"jsonrpc":"2.0","result":2168509541,"id":1}`, 18 | F: func(url string) (any, error) { 19 | c := NewClient(url) 20 | return c.GetTransactionCount( 21 | context.TODO(), 22 | ) 23 | }, 24 | ExpectedValue: uint64(2168509541), 25 | ExpectedError: nil, 26 | }, 27 | }, 28 | ) 29 | } 30 | 31 | func TestClient_GetTransactionCountWithConfig(t *testing.T) { 32 | client_test.TestAll( 33 | t, 34 | []client_test.Param{ 35 | { 36 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getTransactionCount", "params":[{"commitment": "processed"}]}`, 37 | ResponseBody: `{"jsonrpc":"2.0","result":2168514398,"id":1}`, 38 | F: func(url string) (any, error) { 39 | c := NewClient(url) 40 | return c.GetTransactionCountWithConfig( 41 | context.TODO(), 42 | GetTransactionCountConfig{ 43 | Commitment: rpc.CommitmentProcessed, 44 | }, 45 | ) 46 | }, 47 | ExpectedValue: uint64(2168514398), 48 | ExpectedError: nil, 49 | }, 50 | }, 51 | ) 52 | } 53 | -------------------------------------------------------------------------------- /program/metaplex/tokenmeta/utils.go: -------------------------------------------------------------------------------- 1 | package tokenmeta 2 | 3 | import ( 4 | "strconv" 5 | 6 | "github.com/blocto/solana-go-sdk/common" 7 | ) 8 | 9 | func GetTokenMetaPubkey(mint common.PublicKey) (common.PublicKey, error) { 10 | metadataAccount, _, err := common.FindProgramAddress( 11 | [][]byte{ 12 | []byte("metadata"), 13 | common.MetaplexTokenMetaProgramID.Bytes(), 14 | mint.Bytes(), 15 | }, 16 | common.MetaplexTokenMetaProgramID, 17 | ) 18 | if err != nil { 19 | return common.PublicKey{}, err 20 | } 21 | return metadataAccount, nil 22 | } 23 | 24 | func GetMasterEdition(mint common.PublicKey) (common.PublicKey, error) { 25 | msaterEdtion, _, err := common.FindProgramAddress( 26 | [][]byte{ 27 | []byte("metadata"), 28 | common.MetaplexTokenMetaProgramID.Bytes(), 29 | mint.Bytes(), 30 | []byte("edition"), 31 | }, 32 | common.MetaplexTokenMetaProgramID, 33 | ) 34 | if err != nil { 35 | return common.PublicKey{}, err 36 | } 37 | return msaterEdtion, nil 38 | } 39 | 40 | func GetEditionMark(mint common.PublicKey, edition uint64) (common.PublicKey, error) { 41 | editionNumber := edition / EDITION_MARKER_BIT_SIZE 42 | pubkey, _, err := common.FindProgramAddress( 43 | [][]byte{ 44 | []byte("metadata"), 45 | common.MetaplexTokenMetaProgramID.Bytes(), 46 | mint.Bytes(), 47 | []byte("edition"), 48 | []byte(strconv.FormatUint(editionNumber, 10)), 49 | }, 50 | common.MetaplexTokenMetaProgramID, 51 | ) 52 | return pubkey, err 53 | } 54 | -------------------------------------------------------------------------------- /rpc/get_cluster_nodes_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | "github.com/blocto/solana-go-sdk/pkg/pointer" 9 | ) 10 | 11 | func TestGetClusterNodes(t *testing.T) { 12 | client_test.TestAll( 13 | t, 14 | []client_test.Param{ 15 | { 16 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getClusterNodes"}`, 17 | ResponseBody: `{"jsonrpc":"2.0","result":[{"featureSet":1797267350,"gossip":"127.0.0.1:1024","pubkey":"8gNdbr9dG6oj8bhaQ44icyMYsfG3t1dhXKUJLGVav4tn","rpc":"127.0.0.1:8899","shredVersion":23492,"tpu":"127.0.0.1:1027","version":"1.8.1"}],"id":1}`, 18 | F: func(url string) (any, error) { 19 | c := NewRpcClient(url) 20 | return c.GetClusterNodes( 21 | context.TODO(), 22 | ) 23 | }, 24 | ExpectedValue: JsonRpcResponse[GetClusterNodes]{ 25 | JsonRpc: "2.0", 26 | Id: 1, 27 | Error: nil, 28 | Result: GetClusterNodes{ 29 | { 30 | Pubkey: "8gNdbr9dG6oj8bhaQ44icyMYsfG3t1dhXKUJLGVav4tn", 31 | Gossip: pointer.Get("127.0.0.1:1024"), 32 | Tpu: pointer.Get("127.0.0.1:1027"), 33 | Rpc: pointer.Get("127.0.0.1:8899"), 34 | Version: pointer.Get("1.8.1"), 35 | FeatureSet: pointer.Get[uint32](1797267350), 36 | ShredVersion: pointer.Get[uint16](23492), 37 | }, 38 | }, 39 | }, 40 | ExpectedError: nil, 41 | }, 42 | }, 43 | ) 44 | } 45 | -------------------------------------------------------------------------------- /program/metaplex/token_metadata/utils.go: -------------------------------------------------------------------------------- 1 | package token_metadata 2 | 3 | import ( 4 | "strconv" 5 | 6 | "github.com/blocto/solana-go-sdk/common" 7 | ) 8 | 9 | func GetTokenMetaPubkey(mint common.PublicKey) (common.PublicKey, error) { 10 | metadataAccount, _, err := common.FindProgramAddress( 11 | [][]byte{ 12 | []byte("metadata"), 13 | common.MetaplexTokenMetaProgramID.Bytes(), 14 | mint.Bytes(), 15 | }, 16 | common.MetaplexTokenMetaProgramID, 17 | ) 18 | if err != nil { 19 | return common.PublicKey{}, err 20 | } 21 | return metadataAccount, nil 22 | } 23 | 24 | func GetMasterEdition(mint common.PublicKey) (common.PublicKey, error) { 25 | msaterEdtion, _, err := common.FindProgramAddress( 26 | [][]byte{ 27 | []byte("metadata"), 28 | common.MetaplexTokenMetaProgramID.Bytes(), 29 | mint.Bytes(), 30 | []byte("edition"), 31 | }, 32 | common.MetaplexTokenMetaProgramID, 33 | ) 34 | if err != nil { 35 | return common.PublicKey{}, err 36 | } 37 | return msaterEdtion, nil 38 | } 39 | 40 | func GetEditionMark(mint common.PublicKey, edition uint64) (common.PublicKey, error) { 41 | editionNumber := edition / EDITION_MARKER_BIT_SIZE 42 | pubkey, _, err := common.FindProgramAddress( 43 | [][]byte{ 44 | []byte("metadata"), 45 | common.MetaplexTokenMetaProgramID.Bytes(), 46 | mint.Bytes(), 47 | []byte("edition"), 48 | []byte(strconv.FormatUint(editionNumber, 10)), 49 | }, 50 | common.MetaplexTokenMetaProgramID, 51 | ) 52 | return pubkey, err 53 | } 54 | -------------------------------------------------------------------------------- /rpc/get_transaction_count_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetTransactionCount(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getTransactionCount"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":2168509541,"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetTransactionCount( 20 | context.TODO(), 21 | ) 22 | }, 23 | ExpectedValue: JsonRpcResponse[uint64]{ 24 | JsonRpc: "2.0", 25 | Id: 1, 26 | Error: nil, 27 | Result: 2168509541, 28 | }, 29 | ExpectedError: nil, 30 | }, 31 | { 32 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getTransactionCount", "params":[{"commitment": "processed"}]}`, 33 | ResponseBody: `{"jsonrpc":"2.0","result":2168514398,"id":1}`, 34 | F: func(url string) (any, error) { 35 | c := NewRpcClient(url) 36 | return c.GetTransactionCountWithConfig( 37 | context.TODO(), 38 | GetTransactionCountConfig{ 39 | Commitment: CommitmentProcessed, 40 | }, 41 | ) 42 | }, 43 | ExpectedValue: JsonRpcResponse[uint64]{ 44 | JsonRpc: "2.0", 45 | Id: 1, 46 | Error: nil, 47 | Result: 2168514398, 48 | }, 49 | ExpectedError: nil, 50 | }, 51 | }, 52 | ) 53 | } 54 | -------------------------------------------------------------------------------- /rpc/get_inflation_reward.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetInflationRewardResponse JsonRpcResponse[[]*GetInflationReward] 8 | 9 | // GetInflationRewardResult is a part of raw rpc response of `getInflationReward` 10 | type GetInflationReward struct { 11 | Epoch uint64 `json:"epoch"` 12 | EffectiveSlot uint64 `json:"effectiveSlot"` 13 | Amount uint64 `json:"amount"` 14 | PostBalance uint64 `json:"postBalance"` 15 | Commission *uint8 `json:"commission"` 16 | } 17 | 18 | // GetInflationRewardConfig is a option config for `getInflationReward` 19 | type GetInflationRewardConfig struct { 20 | Commitment Commitment `json:"commitment,omitempty"` 21 | Epoch uint64 `json:"epoch,omitempty"` 22 | } 23 | 24 | // GetInflationReward returns the inflation reward for a list of addresses for an epoch 25 | func (c *RpcClient) GetInflationReward(ctx context.Context, stakeAccountAddrs []string) (JsonRpcResponse[[]*GetInflationReward], error) { 26 | return call[JsonRpcResponse[[]*GetInflationReward]](c, ctx, "getInflationReward", stakeAccountAddrs) 27 | } 28 | 29 | // GetInflationRewardWithConfig returns the inflation reward for a list of addresses for an epoch 30 | func (c *RpcClient) GetInflationRewardWithConfig(ctx context.Context, stakeAccountAddrs []string, cfg GetInflationRewardConfig) (JsonRpcResponse[[]*GetInflationReward], error) { 31 | return call[JsonRpcResponse[[]*GetInflationReward]](c, ctx, "getInflationReward", stakeAccountAddrs, cfg) 32 | } 33 | -------------------------------------------------------------------------------- /rpc/get_block_production.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetBlockProductionResponse JsonRpcResponse[GetBlockProduction] 8 | 9 | type GetBlockProduction ValueWithContext[GetBlockProductionResponseResultValue] 10 | 11 | type GetBlockProductionResponseResultValue struct { 12 | ByIdentity map[string][]uint64 `json:"byIdentity"` 13 | Range GetBlockProductionRange `json:"range"` 14 | } 15 | 16 | // GetBlockProductionConfig is a option config for `getBlockProduction` 17 | type GetBlockProductionConfig struct { 18 | Commitment Commitment `json:"commitment,omitempty"` 19 | Range *GetBlockProductionRange `json:"range,omitempty"` 20 | Identity string `json:"identity,omitempty"` 21 | } 22 | 23 | type GetBlockProductionRange struct { 24 | FirstSlot uint64 `json:"firstSlot"` 25 | LastSlot uint64 `json:"lastSlot,omitempty"` 26 | } 27 | 28 | // GetBlockProduction returns the current block height of the node 29 | func (c *RpcClient) GetBlockProduction(ctx context.Context) (JsonRpcResponse[GetBlockProduction], error) { 30 | return call[JsonRpcResponse[GetBlockProduction]](c, ctx, "getBlockProduction") 31 | } 32 | 33 | // GetBlockProductionWithConfig returns the current block height of the node 34 | func (c *RpcClient) GetBlockProductionWithConfig(ctx context.Context, cfg GetBlockProductionConfig) (JsonRpcResponse[GetBlockProduction], error) { 35 | return call[JsonRpcResponse[GetBlockProduction]](c, ctx, "getBlockProduction", cfg) 36 | } 37 | -------------------------------------------------------------------------------- /program/memo/instruction_test.go: -------------------------------------------------------------------------------- 1 | package memo 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/common" 8 | "github.com/blocto/solana-go-sdk/types" 9 | ) 10 | 11 | func TestBuildMemo(t *testing.T) { 12 | type args struct { 13 | param BuildMemoParam 14 | } 15 | tests := []struct { 16 | name string 17 | args args 18 | want types.Instruction 19 | }{ 20 | { 21 | args: args{ 22 | param: BuildMemoParam{ 23 | SignerPubkeys: []common.PublicKey{ 24 | common.PublicKeyFromString("S1gner1111111111111111111111111111111111111"), 25 | common.PublicKeyFromString("S1gner1111111111111111111111111111111111112"), 26 | }, 27 | Memo: []byte("👻"), 28 | }, 29 | }, 30 | want: types.Instruction{ 31 | ProgramID: common.MemoProgramID, 32 | Accounts: []types.AccountMeta{ 33 | { 34 | PubKey: common.PublicKeyFromString("S1gner1111111111111111111111111111111111111"), 35 | IsSigner: true, 36 | IsWritable: false, 37 | }, 38 | { 39 | PubKey: common.PublicKeyFromString("S1gner1111111111111111111111111111111111112"), 40 | IsSigner: true, 41 | IsWritable: false, 42 | }, 43 | }, 44 | Data: []byte("👻"), 45 | }, 46 | }, 47 | } 48 | for _, tt := range tests { 49 | t.Run(tt.name, func(t *testing.T) { 50 | if got := BuildMemo(tt.args.param); !reflect.DeepEqual(got, tt.want) { 51 | t.Errorf("BuildMemo() = %v, want %v", got, tt.want) 52 | } 53 | }) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /rpc/get_token_account_by_owner.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetTokenAccountsByOwnerResponse JsonRpcResponse[GetTokenAccountsByOwner] 8 | 9 | type GetTokenAccountsByOwner ValueWithContext[GetProgramAccounts] 10 | 11 | // GetTokenAccountsByOwnerConfig is a option config for `GetTokenAccountsByOwner` 12 | type GetTokenAccountsByOwnerConfig struct { 13 | Commitment Commitment `json:"commitment,omitempty"` 14 | Encoding AccountEncoding `json:"encoding,omitempty"` 15 | DataSlice *DataSlice `json:"dataSlice,omitempty"` 16 | } 17 | 18 | // GetTokenAccountsByOwnerConfigFilter either mint or programId 19 | type GetTokenAccountsByOwnerConfigFilter struct { 20 | Mint string `json:"mint,omitempty"` 21 | ProgramId string `json:"programId,omitempty"` 22 | } 23 | 24 | func (c *RpcClient) GetTokenAccountsByOwner(ctx context.Context, base58Addr string, filter GetTokenAccountsByOwnerConfigFilter) (JsonRpcResponse[ValueWithContext[GetProgramAccounts]], error) { 25 | return call[JsonRpcResponse[ValueWithContext[GetProgramAccounts]]](c, ctx, "getTokenAccountsByOwner", base58Addr, filter) 26 | } 27 | 28 | func (c *RpcClient) GetTokenAccountsByOwnerWithConfig(ctx context.Context, base58Addr string, filter GetTokenAccountsByOwnerConfigFilter, cfg GetTokenAccountsByOwnerConfig) (JsonRpcResponse[ValueWithContext[GetProgramAccounts]], error) { 29 | return call[JsonRpcResponse[ValueWithContext[GetProgramAccounts]]](c, ctx, "getTokenAccountsByOwner", base58Addr, filter, cfg) 30 | } 31 | -------------------------------------------------------------------------------- /program/memoprog/instruction_test.go: -------------------------------------------------------------------------------- 1 | package memoprog 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/common" 8 | "github.com/blocto/solana-go-sdk/types" 9 | ) 10 | 11 | func TestBuildMemo(t *testing.T) { 12 | type args struct { 13 | param BuildMemoParam 14 | } 15 | tests := []struct { 16 | name string 17 | args args 18 | want types.Instruction 19 | }{ 20 | { 21 | args: args{ 22 | param: BuildMemoParam{ 23 | SignerPubkeys: []common.PublicKey{ 24 | common.PublicKeyFromString("S1gner1111111111111111111111111111111111111"), 25 | common.PublicKeyFromString("S1gner1111111111111111111111111111111111112"), 26 | }, 27 | Memo: []byte("👻"), 28 | }, 29 | }, 30 | want: types.Instruction{ 31 | ProgramID: common.MemoProgramID, 32 | Accounts: []types.AccountMeta{ 33 | { 34 | PubKey: common.PublicKeyFromString("S1gner1111111111111111111111111111111111111"), 35 | IsSigner: true, 36 | IsWritable: false, 37 | }, 38 | { 39 | PubKey: common.PublicKeyFromString("S1gner1111111111111111111111111111111111112"), 40 | IsSigner: true, 41 | IsWritable: false, 42 | }, 43 | }, 44 | Data: []byte("👻"), 45 | }, 46 | }, 47 | } 48 | for _, tt := range tests { 49 | t.Run(tt.name, func(t *testing.T) { 50 | if got := BuildMemo(tt.args.param); !reflect.DeepEqual(got, tt.want) { 51 | t.Errorf("BuildMemo() = %v, want %v", got, tt.want) 52 | } 53 | }) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: docs 2 | 3 | on: 4 | # trigger deployment on every push to main branch 5 | push: 6 | branches: [main] 7 | # trigger deployment manually 8 | workflow_dispatch: 9 | 10 | jobs: 11 | docs: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | with: 17 | # fetch all commits to get last updated time or other git log info 18 | fetch-depth: 0 19 | 20 | - name: Setup Node.js 21 | uses: actions/setup-node@v1 22 | with: 23 | # choose node.js version to use 24 | node-version: "16" 25 | 26 | # run build script 27 | - name: install dependencies 28 | working-directory: ./docs 29 | run: npm install 30 | 31 | # run build script 32 | - name: Build VuePress site 33 | working-directory: ./docs 34 | run: npm run docs:build 35 | 36 | # please check out the docs of the workflow for more details 37 | # @see https://github.com/crazy-max/ghaction-github-pages 38 | - name: Deploy to GitHub Pages 39 | uses: crazy-max/ghaction-github-pages@v2 40 | with: 41 | # deploy to gh-pages branch 42 | target_branch: gh-pages 43 | # deploy the default output dir of VuePress 44 | build_dir: docs/src/.vuepress/dist 45 | env: 46 | # @see https://docs.github.com/en/actions/reference/authentication-in-a-workflow#about-the-github_token-secret 47 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 48 | -------------------------------------------------------------------------------- /docs/_examples/advanced/durable-nonce/get-nonce-account-by-owner/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/base64" 6 | "fmt" 7 | "log" 8 | 9 | "github.com/blocto/solana-go-sdk/client" 10 | "github.com/blocto/solana-go-sdk/common" 11 | "github.com/blocto/solana-go-sdk/program/system" 12 | "github.com/blocto/solana-go-sdk/rpc" 13 | ) 14 | 15 | func main() { 16 | c := client.NewClient(rpc.DevnetRPCEndpoint) 17 | 18 | res, err := c.RpcClient.GetProgramAccountsWithConfig( 19 | context.Background(), 20 | common.SystemProgramID.ToBase58(), 21 | rpc.GetProgramAccountsConfig{ 22 | Encoding: rpc.AccountEncodingBase64, 23 | Filters: []rpc.GetProgramAccountsConfigFilter{ 24 | { 25 | DataSize: system.NonceAccountSize, 26 | }, 27 | { 28 | MemCmp: &rpc.GetProgramAccountsConfigFilterMemCmp{ 29 | Offset: 8, 30 | Bytes: "9aE476sH92Vz7DMPyq5WLPkrKWivxeuTKEFKd2sZZcde", // owner address 31 | }, 32 | }, 33 | }, 34 | }, 35 | ) 36 | if err != nil { 37 | log.Fatalf("failed to get program accounts, err: %v", err) 38 | } 39 | 40 | for _, a := range res.Result { 41 | fmt.Println("pubkey", a.Pubkey) 42 | data, err := base64.StdEncoding.DecodeString((a.Account.Data.([]any))[0].(string)) 43 | if err != nil { 44 | log.Fatalf("failed to decode data, err: %v", err) 45 | } 46 | nonceAccount, err := system.NonceAccountDeserialize(data) 47 | if err != nil { 48 | log.Fatalf("failed to parse nonce account, err: %v", err) 49 | } 50 | fmt.Printf("%+v\n", nonceAccount) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /rpc/get_latest_blockhash.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetLatestBlockhashResponse JsonRpcResponse[GetLatestBlockhash] 8 | 9 | type GetLatestBlockhash ValueWithContext[GetLatestBlockhashValue] 10 | 11 | // GetLatestBlockhashResult is a part of raw rpc response of `getLatestBlockhash` 12 | type GetLatestBlockhashValue struct { 13 | Blockhash string `json:"blockhash"` 14 | LatestValidBlockHeight uint64 `json:"lastValidBlockHeight"` 15 | } 16 | 17 | // GetLatestBlockhashConfig is a option config for `getLatestBlockhash` 18 | type GetLatestBlockhashConfig struct { 19 | Commitment Commitment `json:"commitment,omitempty"` 20 | } 21 | 22 | // NEW: This method is only available in solana-core v1.9 or newer. Please use getRecentBlockhash for solana-core v1.8 23 | // GetLatestBlockhash returns the latest blockhash 24 | func (c *RpcClient) GetLatestBlockhash(ctx context.Context) (JsonRpcResponse[ValueWithContext[GetLatestBlockhashValue]], error) { 25 | return call[JsonRpcResponse[ValueWithContext[GetLatestBlockhashValue]]](c, ctx, "getLatestBlockhash") 26 | } 27 | 28 | // NEW: This method is only available in solana-core v1.9 or newer. Please use getRecentBlockhash for solana-core v1.8 29 | // GetLatestBlockhashWithConfig returns the latest blockhash 30 | func (c *RpcClient) GetLatestBlockhashWithConfig(ctx context.Context, cfg GetLatestBlockhashConfig) (JsonRpcResponse[ValueWithContext[GetLatestBlockhashValue]], error) { 31 | return call[JsonRpcResponse[ValueWithContext[GetLatestBlockhashValue]]](c, ctx, "getLatestBlockhash", cfg) 32 | } 33 | -------------------------------------------------------------------------------- /client/client_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/rpc" 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | func Test_checkJsonRpcResponse(t *testing.T) { 12 | type args struct { 13 | res rpc.JsonRpcResponse[rpc.GetBlock] 14 | err error 15 | } 16 | tests := []struct { 17 | name string 18 | args args 19 | expectedErr error 20 | }{ 21 | { 22 | args: args{ 23 | res: rpc.JsonRpcResponse[rpc.GetBlock]{ 24 | JsonRpc: "2.0", 25 | Id: 1, 26 | Result: rpc.GetBlock{}, 27 | }, 28 | err: nil, 29 | }, 30 | expectedErr: nil, 31 | }, 32 | { 33 | args: args{ 34 | res: rpc.JsonRpcResponse[rpc.GetBlock]{ 35 | JsonRpc: "2.0", 36 | Id: 1, 37 | Result: rpc.GetBlock{}, 38 | }, 39 | err: errors.New("rpc error"), 40 | }, 41 | expectedErr: errors.New("rpc error"), 42 | }, 43 | { 44 | args: args{ 45 | res: rpc.JsonRpcResponse[rpc.GetBlock]{ 46 | JsonRpc: "2.0", 47 | Id: 1, 48 | Result: rpc.GetBlock{}, 49 | Error: &rpc.JsonRpcError{ 50 | Code: -1, 51 | Message: "error", 52 | Data: nil, 53 | }, 54 | }, 55 | err: nil, 56 | }, 57 | expectedErr: &rpc.JsonRpcError{ 58 | Code: -1, 59 | Message: "error", 60 | Data: nil, 61 | }, 62 | }, 63 | } 64 | for _, tt := range tests { 65 | t.Run(tt.name, func(t *testing.T) { 66 | err := checkJsonRpcResponse(tt.args.res, tt.args.err) 67 | assert.Equal(t, tt.expectedErr, err) 68 | }) 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /client/rpc_get_minimum_balance_for_rent_exemption_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | "github.com/blocto/solana-go-sdk/rpc" 9 | ) 10 | 11 | func TestClient_GetMinimumBalanceForRentExemption(t *testing.T) { 12 | client_test.TestAll( 13 | t, 14 | []client_test.Param{ 15 | { 16 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getMinimumBalanceForRentExemption", "params":[100]}`, 17 | ResponseBody: `{"jsonrpc":"2.0","result":1586880,"id":1}`, 18 | F: func(url string) (any, error) { 19 | c := NewClient(url) 20 | return c.GetMinimumBalanceForRentExemption( 21 | context.TODO(), 22 | 100, 23 | ) 24 | }, 25 | ExpectedValue: uint64(1586880), 26 | ExpectedError: nil, 27 | }, 28 | }, 29 | ) 30 | } 31 | 32 | func TestClient_GetMinimumBalanceForRentExemptionWithConfig(t *testing.T) { 33 | client_test.TestAll( 34 | t, 35 | []client_test.Param{ 36 | { 37 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getMinimumBalanceForRentExemption", "params":[100, {"commitment": "processed"}]}`, 38 | ResponseBody: `{"jsonrpc":"2.0","result":1586880,"id":1}`, 39 | F: func(url string) (any, error) { 40 | c := NewClient(url) 41 | return c.GetMinimumBalanceForRentExemptionWithConfig( 42 | context.TODO(), 43 | 100, 44 | GetMinimumBalanceForRentExemptionConfig{ 45 | Commitment: rpc.CommitmentProcessed, 46 | }, 47 | ) 48 | }, 49 | ExpectedValue: uint64(1586880), 50 | ExpectedError: nil, 51 | }, 52 | }, 53 | ) 54 | } 55 | -------------------------------------------------------------------------------- /program/assotokenprog/instruction.go: -------------------------------------------------------------------------------- 1 | package assotokenprog 2 | 3 | import ( 4 | "github.com/blocto/solana-go-sdk/common" 5 | "github.com/blocto/solana-go-sdk/types" 6 | "github.com/near/borsh-go" 7 | ) 8 | 9 | type Instruction borsh.Enum 10 | 11 | const ( 12 | InstructionCreate Instruction = iota 13 | InstructionCreateIdempotent 14 | ) 15 | 16 | type CreateAssociatedTokenAccountParam struct { 17 | Funder common.PublicKey 18 | Owner common.PublicKey 19 | Mint common.PublicKey 20 | AssociatedTokenAccount common.PublicKey 21 | } 22 | 23 | // CreateAssociatedTokenAccount is the only instruction in associated token program 24 | func CreateAssociatedTokenAccount(param CreateAssociatedTokenAccountParam) types.Instruction { 25 | data, err := borsh.Serialize(struct { 26 | Instruction Instruction 27 | }{ 28 | Instruction: InstructionCreate, 29 | }) 30 | if err != nil { 31 | panic(err) 32 | } 33 | 34 | return types.Instruction{ 35 | ProgramID: common.SPLAssociatedTokenAccountProgramID, 36 | Accounts: []types.AccountMeta{ 37 | {PubKey: param.Funder, IsSigner: true, IsWritable: true}, 38 | {PubKey: param.AssociatedTokenAccount, IsSigner: false, IsWritable: true}, 39 | {PubKey: param.Owner, IsSigner: false, IsWritable: false}, 40 | {PubKey: param.Mint, IsSigner: false, IsWritable: false}, 41 | {PubKey: common.SystemProgramID, IsSigner: false, IsWritable: false}, 42 | {PubKey: common.TokenProgramID, IsSigner: false, IsWritable: false}, 43 | {PubKey: common.SysVarRentPubkey, IsSigner: false, IsWritable: false}, 44 | }, 45 | Data: data, 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /client/rpc_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "encoding/base64" 5 | "reflect" 6 | "testing" 7 | 8 | "github.com/blocto/solana-go-sdk/common" 9 | "github.com/blocto/solana-go-sdk/rpc" 10 | "github.com/blocto/solana-go-sdk/types" 11 | ) 12 | 13 | func mustDeserializeBase64Tx(t *testing.T, s string) types.Transaction { 14 | b, err := base64.StdEncoding.DecodeString(s) 15 | if err != nil { 16 | t.Errorf("failed to decode base64 string") 17 | } 18 | tx, err := types.TransactionDeserialize(b) 19 | if err != nil { 20 | t.Errorf("failed to deserialize transaction") 21 | } 22 | return tx 23 | } 24 | 25 | func Test_convertReturnData(t *testing.T) { 26 | type args struct { 27 | d rpc.ReturnData 28 | } 29 | tests := []struct { 30 | name string 31 | args args 32 | want ReturnData 33 | wantErr bool 34 | }{ 35 | { 36 | args: args{ 37 | d: rpc.ReturnData{ 38 | ProgramId: "35HSbe2xiLfid5QJeETGnUsGhkAiJWRKPrEGdQQ5xXrP", 39 | Data: []any{"AQIDBAU=", "base64"}, 40 | }, 41 | }, 42 | want: ReturnData{ 43 | ProgramId: common.PublicKeyFromString("35HSbe2xiLfid5QJeETGnUsGhkAiJWRKPrEGdQQ5xXrP"), 44 | Data: []byte{1, 2, 3, 4, 5}, 45 | }, 46 | }, 47 | } 48 | for _, tt := range tests { 49 | t.Run(tt.name, func(t *testing.T) { 50 | got, err := convertReturnData(tt.args.d) 51 | if (err != nil) != tt.wantErr { 52 | t.Errorf("convertReturnData() error = %v, wantErr %v", err, tt.wantErr) 53 | return 54 | } 55 | if !reflect.DeepEqual(got, tt.want) { 56 | t.Errorf("convertReturnData() = %v, want %v", got, tt.want) 57 | } 58 | }) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /program/system/state_test.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/common" 8 | ) 9 | 10 | func TestNonceAccountDeserialize(t *testing.T) { 11 | type args struct { 12 | data []byte 13 | } 14 | tests := []struct { 15 | name string 16 | args args 17 | want NonceAccount 18 | wantErr bool 19 | }{ 20 | { 21 | args: args{ 22 | data: []byte{0, 0, 0, 0, 1, 0, 0, 0, 170, 118, 78, 20, 110, 21, 146, 201, 207, 34, 55, 190, 100, 27, 130, 117, 252, 159, 223, 230, 13, 166, 95, 130, 155, 86, 34, 134, 87, 106, 160, 233, 118, 21, 129, 71, 191, 98, 171, 247, 177, 47, 125, 104, 215, 37, 254, 44, 68, 82, 208, 182, 201, 123, 37, 207, 233, 116, 103, 34, 74, 217, 164, 8, 136, 19, 0, 0, 0, 0, 0, 0}, 23 | }, 24 | want: NonceAccount{ 25 | Version: 0, 26 | State: 1, 27 | AuthorizedPubkey: common.PublicKeyFromString("CUQwQyNDPdGM2KfC7B4NJhrSwDwRjdqKetpwBHe9CvEk"), 28 | Nonce: common.PublicKeyFromString("8wx8PoVMibdYTrfweG2wCFuYz7EhwkaZLm8hutyFgh8T"), 29 | FeeCalculator: FeeCalculator{ 30 | LamportsPerSignature: 5000, 31 | }, 32 | }, 33 | wantErr: false, 34 | }, 35 | } 36 | for _, tt := range tests { 37 | t.Run(tt.name, func(t *testing.T) { 38 | got, err := NonceAccountDeserialize(tt.args.data) 39 | if (err != nil) != tt.wantErr { 40 | t.Errorf("NonceAccountDeserialize() error = %v, wantErr %v", err, tt.wantErr) 41 | return 42 | } 43 | if !reflect.DeepEqual(got, tt.want) { 44 | t.Errorf("NonceAccountDeserialize() = %v, want %v", got, tt.want) 45 | } 46 | }) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /rpc/get_minimum_balance_for_rent_exemption_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetMinimumBalanceForRentExemption(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getMinimumBalanceForRentExemption", "params":[100]}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":1586880,"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetMinimumBalanceForRentExemption( 20 | context.TODO(), 21 | 100, 22 | ) 23 | }, 24 | ExpectedValue: JsonRpcResponse[uint64]{ 25 | JsonRpc: "2.0", 26 | Id: 1, 27 | Error: nil, 28 | Result: 1586880, 29 | }, 30 | ExpectedError: nil, 31 | }, 32 | { 33 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getMinimumBalanceForRentExemption", "params":[100, {"commitment": "processed"}]}`, 34 | ResponseBody: `{"jsonrpc":"2.0","result":1586880,"id":1}`, 35 | F: func(url string) (any, error) { 36 | c := NewRpcClient(url) 37 | return c.GetMinimumBalanceForRentExemptionWithConfig( 38 | context.TODO(), 39 | 100, 40 | GetMinimumBalanceForRentExemptionConfig{ 41 | Commitment: CommitmentProcessed, 42 | }, 43 | ) 44 | }, 45 | ExpectedValue: JsonRpcResponse[uint64]{ 46 | JsonRpc: "2.0", 47 | Id: 1, 48 | Error: nil, 49 | Result: 1586880, 50 | }, 51 | ExpectedError: nil, 52 | }, 53 | }, 54 | ) 55 | } 56 | -------------------------------------------------------------------------------- /program/sysprog/state_test.go: -------------------------------------------------------------------------------- 1 | package sysprog 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/common" 8 | ) 9 | 10 | func TestNonceAccountDeserialize(t *testing.T) { 11 | type args struct { 12 | data []byte 13 | } 14 | tests := []struct { 15 | name string 16 | args args 17 | want NonceAccount 18 | wantErr bool 19 | }{ 20 | { 21 | args: args{ 22 | data: []byte{0, 0, 0, 0, 1, 0, 0, 0, 170, 118, 78, 20, 110, 21, 146, 201, 207, 34, 55, 190, 100, 27, 130, 117, 252, 159, 223, 230, 13, 166, 95, 130, 155, 86, 34, 134, 87, 106, 160, 233, 118, 21, 129, 71, 191, 98, 171, 247, 177, 47, 125, 104, 215, 37, 254, 44, 68, 82, 208, 182, 201, 123, 37, 207, 233, 116, 103, 34, 74, 217, 164, 8, 136, 19, 0, 0, 0, 0, 0, 0}, 23 | }, 24 | want: NonceAccount{ 25 | Version: 0, 26 | State: 1, 27 | AuthorizedPubkey: common.PublicKeyFromString("CUQwQyNDPdGM2KfC7B4NJhrSwDwRjdqKetpwBHe9CvEk"), 28 | Nonce: common.PublicKeyFromString("8wx8PoVMibdYTrfweG2wCFuYz7EhwkaZLm8hutyFgh8T"), 29 | FeeCalculator: FeeCalculator{ 30 | LamportsPerSignature: 5000, 31 | }, 32 | }, 33 | wantErr: false, 34 | }, 35 | } 36 | for _, tt := range tests { 37 | t.Run(tt.name, func(t *testing.T) { 38 | got, err := NonceAccountDeserialize(tt.args.data) 39 | if (err != nil) != tt.wantErr { 40 | t.Errorf("NonceAccountDeserialize() error = %v, wantErr %v", err, tt.wantErr) 41 | return 42 | } 43 | if !reflect.DeepEqual(got, tt.want) { 44 | t.Errorf("NonceAccountDeserialize() = %v, want %v", got, tt.want) 45 | } 46 | }) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /rpc/client_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func Test_preparePayload(t *testing.T) { 10 | type args struct { 11 | params []any 12 | } 13 | tests := []struct { 14 | name string 15 | args args 16 | want string 17 | err error 18 | }{ 19 | { 20 | args: args{ 21 | params: []any{"getBalance", "RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", nil}, 22 | }, 23 | want: `{"id":1,"jsonrpc":"2.0","method":"getBalance","params":["RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7",null]}`, 24 | err: nil, 25 | }, 26 | { 27 | args: args{ 28 | params: []any{"getBalance", "RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", GetBalanceConfig{}}, 29 | }, 30 | want: `{"id":1,"jsonrpc":"2.0","method":"getBalance","params":["RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7",{}]}`, 31 | err: nil, 32 | }, 33 | { 34 | args: args{ 35 | params: []any{"getBalance", "RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", GetBalanceConfig{Commitment: CommitmentFinalized}}, 36 | }, 37 | want: `{"id":1,"jsonrpc":"2.0","method":"getBalance","params":["RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7",{"commitment":"finalized"}]}`, 38 | err: nil, 39 | }, 40 | { 41 | args: args{ 42 | params: []any{"getBalance"}, 43 | }, 44 | want: `{"id":1,"jsonrpc":"2.0","method":"getBalance"}`, 45 | err: nil, 46 | }, 47 | } 48 | for _, tt := range tests { 49 | t.Run(tt.name, func(t *testing.T) { 50 | got, err := preparePayload(tt.args.params) 51 | assert.Equal(t, err, tt.err) 52 | assert.JSONEq(t, string(got), string(tt.want)) 53 | }) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /common/program_id.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | var ( 4 | SystemProgramID = PublicKeyFromString("11111111111111111111111111111111") 5 | ConfigProgramID = PublicKeyFromString("Config1111111111111111111111111111111111111") 6 | StakeProgramID = PublicKeyFromString("Stake11111111111111111111111111111111111111") 7 | VoteProgramID = PublicKeyFromString("Vote111111111111111111111111111111111111111") 8 | BPFLoaderProgramID = PublicKeyFromString("BPFLoader1111111111111111111111111111111111") 9 | Secp256k1ProgramID = PublicKeyFromString("KeccakSecp256k11111111111111111111111111111") 10 | TokenProgramID = PublicKeyFromString("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA") 11 | MemoProgramID = PublicKeyFromString("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr") 12 | SPLAssociatedTokenAccountProgramID = PublicKeyFromString("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL") 13 | SPLNameServiceProgramID = PublicKeyFromString("namesLPneVptA9Z5rqUDD9tMTWEJwofgaYwp8cawRkX") 14 | MetaplexTokenMetaProgramID = PublicKeyFromString("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s") 15 | ComputeBudgetProgramID = PublicKeyFromString("ComputeBudget111111111111111111111111111111") 16 | AddressLookupTableProgramID = PublicKeyFromString("AddressLookupTab1e1111111111111111111111111") 17 | Token2022ProgramID = PublicKeyFromString("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb") 18 | BPFLoaderUpgradeableProgramID = PublicKeyFromString("BPFLoaderUpgradeab1e11111111111111111111111") 19 | ) 20 | -------------------------------------------------------------------------------- /program/sysprog/state.go: -------------------------------------------------------------------------------- 1 | package sysprog 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | 7 | "github.com/blocto/solana-go-sdk/common" 8 | ) 9 | 10 | const FeeCalculatorSize = 8 11 | 12 | type FeeCalculator struct { 13 | LamportsPerSignature uint64 14 | } 15 | 16 | func FeeCalculatorDeserialize(data []byte) (FeeCalculator, error) { 17 | if len(data) < FeeCalculatorSize { 18 | return FeeCalculator{}, fmt.Errorf("fee calculator data size is not enough") 19 | } 20 | lamportsPerSignature := binary.LittleEndian.Uint64(data[:8]) 21 | return FeeCalculator{ 22 | LamportsPerSignature: lamportsPerSignature, 23 | }, nil 24 | } 25 | 26 | const NonceAccountSize = 80 27 | 28 | type NonceAccount struct { 29 | Version uint32 30 | State uint32 31 | AuthorizedPubkey common.PublicKey 32 | Nonce common.PublicKey 33 | FeeCalculator FeeCalculator 34 | } 35 | 36 | func NonceAccountDeserialize(data []byte) (NonceAccount, error) { 37 | if len(data) < NonceAccountSize { 38 | return NonceAccount{}, fmt.Errorf("nonce account data size is not enough") 39 | } 40 | version := binary.LittleEndian.Uint32(data[:4]) 41 | state := binary.LittleEndian.Uint32(data[4:8]) 42 | authorizedPubkey := common.PublicKeyFromBytes(data[8:40]) 43 | nonce := common.PublicKeyFromBytes(data[40:72]) 44 | feeCalculator, err := FeeCalculatorDeserialize(data[72:]) 45 | if err != nil { 46 | return NonceAccount{}, err 47 | } 48 | return NonceAccount{ 49 | Version: version, 50 | State: state, 51 | AuthorizedPubkey: authorizedPubkey, 52 | Nonce: nonce, 53 | FeeCalculator: feeCalculator, 54 | }, nil 55 | } 56 | -------------------------------------------------------------------------------- /program/system/state.go: -------------------------------------------------------------------------------- 1 | package system 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | 7 | "github.com/blocto/solana-go-sdk/common" 8 | ) 9 | 10 | const FeeCalculatorSize = 8 11 | 12 | type FeeCalculator struct { 13 | LamportsPerSignature uint64 14 | } 15 | 16 | func FeeCalculatorDeserialize(data []byte) (FeeCalculator, error) { 17 | if len(data) < FeeCalculatorSize { 18 | return FeeCalculator{}, fmt.Errorf("fee calculator data size is not enough") 19 | } 20 | lamportsPerSignature := binary.LittleEndian.Uint64(data[:8]) 21 | return FeeCalculator{ 22 | LamportsPerSignature: lamportsPerSignature, 23 | }, nil 24 | } 25 | 26 | const NonceAccountSize = 80 27 | 28 | type NonceAccount struct { 29 | Version uint32 30 | State uint32 31 | AuthorizedPubkey common.PublicKey 32 | Nonce common.PublicKey 33 | FeeCalculator FeeCalculator 34 | } 35 | 36 | func NonceAccountDeserialize(data []byte) (NonceAccount, error) { 37 | if len(data) < NonceAccountSize { 38 | return NonceAccount{}, fmt.Errorf("nonce account data size is not enough") 39 | } 40 | version := binary.LittleEndian.Uint32(data[:4]) 41 | state := binary.LittleEndian.Uint32(data[4:8]) 42 | authorizedPubkey := common.PublicKeyFromBytes(data[8:40]) 43 | nonce := common.PublicKeyFromBytes(data[40:72]) 44 | feeCalculator, err := FeeCalculatorDeserialize(data[72:]) 45 | if err != nil { 46 | return NonceAccount{}, err 47 | } 48 | return NonceAccount{ 49 | Version: version, 50 | State: state, 51 | AuthorizedPubkey: authorizedPubkey, 52 | Nonce: nonce, 53 | FeeCalculator: feeCalculator, 54 | }, nil 55 | } 56 | -------------------------------------------------------------------------------- /docs/_examples/program/compute-budget/set-compute-unit-limit/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/blocto/solana-go-sdk/client" 8 | "github.com/blocto/solana-go-sdk/program/compute_budget" 9 | "github.com/blocto/solana-go-sdk/program/memo" 10 | "github.com/blocto/solana-go-sdk/rpc" 11 | "github.com/blocto/solana-go-sdk/types" 12 | ) 13 | 14 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 15 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 16 | 17 | func main() { 18 | c := client.NewClient(rpc.LocalnetRPCEndpoint) 19 | 20 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 21 | if err != nil { 22 | log.Fatalf("failed to get latest blockhash, err: %v", err) 23 | } 24 | 25 | tx, err := types.NewTransaction(types.NewTransactionParam{ 26 | Signers: []types.Account{feePayer}, 27 | Message: types.NewMessage(types.NewMessageParam{ 28 | FeePayer: feePayer.PublicKey, 29 | RecentBlockhash: recentBlockhashResponse.Blockhash, 30 | Instructions: []types.Instruction{ 31 | compute_budget.SetComputeUnitLimit(compute_budget.SetComputeUnitLimitParam{ 32 | Units: 100000, 33 | }), 34 | memo.BuildMemo(memo.BuildMemoParam{ 35 | Memo: []byte("👻"), 36 | }), 37 | }, 38 | }), 39 | }) 40 | if err != nil { 41 | log.Fatalf("failed to new a transaction, err: %v", err) 42 | } 43 | 44 | txhash, err := c.SendTransaction(context.Background(), tx) 45 | if err != nil { 46 | log.Fatalf("failed to send tx, err: %v", err) 47 | } 48 | 49 | log.Println("txhash:", txhash) 50 | } 51 | -------------------------------------------------------------------------------- /pkg/hdwallet/path.go: -------------------------------------------------------------------------------- 1 | package hdwallet 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha512" 6 | "encoding/binary" 7 | "fmt" 8 | "regexp" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | type Key struct { 14 | PrivateKey []byte 15 | ChainCode []byte 16 | } 17 | 18 | func CKDPriv(key Key, index uint32) Key { 19 | buffer := make([]byte, 0, 1+4+len(key.PrivateKey)) 20 | buffer = append(buffer, 0) 21 | buffer = append(buffer, key.PrivateKey...) 22 | v := make([]byte, 4) 23 | binary.BigEndian.PutUint32(v, index) 24 | buffer = append(buffer, v...) 25 | 26 | I := hamc512(key.ChainCode, buffer) 27 | 28 | return Key{ 29 | PrivateKey: I[:32], 30 | ChainCode: I[32:], 31 | } 32 | } 33 | 34 | func CreateMasterKey(seed []byte) Key { 35 | I := hamc512([]byte("ed25519 seed"), seed) 36 | return Key{ 37 | PrivateKey: I[:32], 38 | ChainCode: I[32:], 39 | } 40 | } 41 | 42 | func hamc512(key, data []byte) []byte { 43 | hmac := hmac.New(sha512.New, key) 44 | hmac.Write(data) 45 | return hmac.Sum(nil) 46 | } 47 | 48 | func isValidPath(path string) bool { 49 | r := regexp.MustCompile(`^m{1,1}(/\d+')*$`) 50 | return r.MatchString(path) 51 | } 52 | 53 | func Derived(path string, seed []byte) (Key, error) { 54 | if !isValidPath(path) { 55 | return Key{}, fmt.Errorf("invalid path: %v", path) 56 | } 57 | 58 | key := CreateMasterKey(seed) 59 | 60 | for _, s := range strings.Split(path, "/")[1:] { 61 | v, err := strconv.ParseUint(s[:len(s)-1], 10, 32) 62 | if err != nil { 63 | return Key{}, fmt.Errorf("failed to parse %v as a uint, err: %v", v, err) 64 | } 65 | 66 | key = CKDPriv(key, uint32(v)+1<<31) 67 | } 68 | 69 | return key, nil 70 | } 71 | -------------------------------------------------------------------------------- /docs/_examples/program/compute-budget/set-compute-unit-price/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/blocto/solana-go-sdk/client" 8 | "github.com/blocto/solana-go-sdk/program/compute_budget" 9 | "github.com/blocto/solana-go-sdk/program/memo" 10 | "github.com/blocto/solana-go-sdk/rpc" 11 | "github.com/blocto/solana-go-sdk/types" 12 | ) 13 | 14 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 15 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 16 | 17 | func main() { 18 | c := client.NewClient(rpc.LocalnetRPCEndpoint) 19 | 20 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 21 | if err != nil { 22 | log.Fatalf("failed to get latest blockhash, err: %v", err) 23 | } 24 | 25 | tx, err := types.NewTransaction(types.NewTransactionParam{ 26 | Signers: []types.Account{feePayer}, 27 | Message: types.NewMessage(types.NewMessageParam{ 28 | FeePayer: feePayer.PublicKey, 29 | RecentBlockhash: recentBlockhashResponse.Blockhash, 30 | Instructions: []types.Instruction{ 31 | compute_budget.SetComputeUnitPrice(compute_budget.SetComputeUnitPriceParam{ 32 | MicroLamports: 1_000_000, 33 | }), 34 | memo.BuildMemo(memo.BuildMemoParam{ 35 | Memo: []byte("👻"), 36 | }), 37 | }, 38 | }), 39 | }) 40 | if err != nil { 41 | log.Fatalf("failed to new a transaction, err: %v", err) 42 | } 43 | 44 | txhash, err := c.SendTransaction(context.Background(), tx) 45 | if err != nil { 46 | log.Fatalf("failed to send tx, err: %v", err) 47 | } 48 | 49 | log.Println("txhash:", txhash) 50 | } 51 | -------------------------------------------------------------------------------- /docs/_examples/advanced/durable-nonce/upgrade-nonce-account/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/common" 10 | "github.com/blocto/solana-go-sdk/program/system" 11 | "github.com/blocto/solana-go-sdk/rpc" 12 | "github.com/blocto/solana-go-sdk/types" 13 | ) 14 | 15 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 16 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 17 | 18 | func main() { 19 | c := client.NewClient(rpc.DevnetRPCEndpoint) 20 | 21 | nonceAccountPubkey := common.PublicKeyFromString("DJyNpXgggw1WGgjTVzFsNjb3fuQZVMqhoakvSBfX9LYx") 22 | 23 | // recent blockhash 24 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 25 | if err != nil { 26 | log.Fatalf("failed to get recent blockhash, err: %v", err) 27 | } 28 | 29 | tx, err := types.NewTransaction(types.NewTransactionParam{ 30 | Signers: []types.Account{feePayer}, 31 | Message: types.NewMessage(types.NewMessageParam{ 32 | FeePayer: feePayer.PublicKey, 33 | RecentBlockhash: recentBlockhashResponse.Blockhash, 34 | Instructions: []types.Instruction{ 35 | system.UpgradeNonceAccount(system.UpgradeNonceAccountParam{ 36 | NonceAccountPubkey: nonceAccountPubkey, 37 | }), 38 | }, 39 | }), 40 | }) 41 | if err != nil { 42 | log.Fatalf("failed to new a transaction, err: %v", err) 43 | } 44 | 45 | sig, err := c.SendTransaction(context.Background(), tx) 46 | if err != nil { 47 | log.Fatalf("failed to send tx, err: %v", err) 48 | } 49 | 50 | fmt.Println("txhash", sig) 51 | } 52 | -------------------------------------------------------------------------------- /client/rpc_get_vote_accounts_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/common" 8 | "github.com/blocto/solana-go-sdk/internal/client_test" 9 | ) 10 | 11 | func TestClient_GetVoteAccounts(t *testing.T) { 12 | client_test.TestAll( 13 | t, 14 | []client_test.Param{ 15 | { 16 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getVoteAccounts"}`, 17 | ResponseBody: `{"jsonrpc":"2.0","result":{"current":[{"activatedStake":999999997717120,"commission":0,"epochCredits":[[0,104,0]],"epochVoteAccount":true,"lastVote":134,"nodePubkey":"2RcYr2dvjgdJsbfPfAonBTSi7yU3JwdkHqZJWMCJYFAV","rootSlot":103,"votePubkey":"5wi1m4kquajfcVVavvTuFWoMD4Nri4BJEUjV9pfCrhsp"}],"delinquent":[]},"id":1}`, 18 | F: func(url string) (any, error) { 19 | c := NewClient(url) 20 | return c.GetVoteAccounts( 21 | context.Background(), 22 | ) 23 | }, 24 | ExpectedValue: VoteAccountStatus{ 25 | Current: []VoteAccountInfo{ 26 | { 27 | ActivatedStake: 999999997717120, 28 | Commission: 0, 29 | EpochCredits: []EpochCredits{ 30 | { 31 | Epoch: 0, 32 | Credits: 104, 33 | PreviousCredits: 0, 34 | }, 35 | }, 36 | EpochVoteAccount: true, 37 | LastVote: 134, 38 | NodePubkey: common.PublicKeyFromString("2RcYr2dvjgdJsbfPfAonBTSi7yU3JwdkHqZJWMCJYFAV"), 39 | VotePubkey: common.PublicKeyFromString("5wi1m4kquajfcVVavvTuFWoMD4Nri4BJEUjV9pfCrhsp"), 40 | RootSlot: 103, 41 | }, 42 | }, 43 | Delinquent: []VoteAccountInfo{}, 44 | }, 45 | ExpectedError: nil, 46 | }, 47 | }, 48 | ) 49 | } 50 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | filippo.io/edwards25519 v1.0.0-rc.1 h1:m0VOOB23frXZvAOK44usCgLWvtsxIoMCTBGJZlpmGfU= 2 | filippo.io/edwards25519 v1.0.0-rc.1/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= 3 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/mr-tron/base58 v1.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o= 7 | github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc= 8 | github.com/near/borsh-go v0.3.2-0.20220516180422-1ff87d108454 h1:lFN7TVecCMbCHVNfEofDqqaVsuAlkFyDmmO7EF4nXj4= 9 | github.com/near/borsh-go v0.3.2-0.20220516180422-1ff87d108454/go.mod h1:NeMochZp7jN/pYFuxLkrZtmLqbADmnp/y1+/dL+AsyQ= 10 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 11 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 12 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 13 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 14 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 15 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 16 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 17 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 18 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 19 | -------------------------------------------------------------------------------- /client/rpc_get_slot_leaders_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestClient_GetSlotLeaders(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method": "getSlotLeaders", "params": [264431722, 10]}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":["DUND26mEDfFeaPsVof3YvbXDRvpuQX7HMUJrLgEWzYw4","DUND26mEDfFeaPsVof3YvbXDRvpuQX7HMUJrLgEWzYw4","3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt","3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt","3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt","3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt","BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH","BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH","BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH","BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH"],"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewClient(url) 19 | return c.GetSlotLeaders(context.TODO(), 264431722, 10) 20 | }, 21 | ExpectedValue: []string{ 22 | "DUND26mEDfFeaPsVof3YvbXDRvpuQX7HMUJrLgEWzYw4", 23 | "DUND26mEDfFeaPsVof3YvbXDRvpuQX7HMUJrLgEWzYw4", 24 | "3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt", 25 | "3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt", 26 | "3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt", 27 | "3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt", 28 | "BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH", 29 | "BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH", 30 | "BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH", 31 | "BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH", 32 | }, 33 | ExpectedError: nil, 34 | }, 35 | }, 36 | ) 37 | } 38 | -------------------------------------------------------------------------------- /docs/_examples/program/address-lookup-table/freeze/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/blocto/solana-go-sdk/client" 8 | "github.com/blocto/solana-go-sdk/common" 9 | "github.com/blocto/solana-go-sdk/program/address_lookup_table" 10 | "github.com/blocto/solana-go-sdk/rpc" 11 | "github.com/blocto/solana-go-sdk/types" 12 | ) 13 | 14 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 15 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 16 | 17 | func main() { 18 | c := client.NewClient(rpc.DevnetRPCEndpoint) 19 | 20 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 21 | if err != nil { 22 | log.Fatalf("failed to get latest blockhash, err: %v", err) 23 | } 24 | 25 | lookupTablePubkey := common.PublicKeyFromString("3LZbwptsCkv5R5uu1GNZKiX9SoC6egNG8NXg9zH5ZVM9") 26 | 27 | tx, err := types.NewTransaction(types.NewTransactionParam{ 28 | Signers: []types.Account{feePayer}, 29 | Message: types.NewMessage(types.NewMessageParam{ 30 | FeePayer: feePayer.PublicKey, 31 | RecentBlockhash: recentBlockhashResponse.Blockhash, 32 | Instructions: []types.Instruction{ 33 | address_lookup_table.FreezeLookupTable(address_lookup_table.FreezeLookupTableParams{ 34 | LookupTable: lookupTablePubkey, 35 | Authority: feePayer.PublicKey, 36 | }), 37 | }, 38 | }), 39 | }) 40 | if err != nil { 41 | log.Fatalf("failed to new a transaction, err: %v", err) 42 | } 43 | 44 | txhash, err := c.SendTransaction(context.Background(), tx) 45 | if err != nil { 46 | log.Fatalf("failed to send tx, err: %v", err) 47 | } 48 | 49 | log.Println("txhash:", txhash) 50 | } 51 | -------------------------------------------------------------------------------- /docs/_examples/program/address-lookup-table/deactivate/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/blocto/solana-go-sdk/client" 8 | "github.com/blocto/solana-go-sdk/common" 9 | "github.com/blocto/solana-go-sdk/program/address_lookup_table" 10 | "github.com/blocto/solana-go-sdk/rpc" 11 | "github.com/blocto/solana-go-sdk/types" 12 | ) 13 | 14 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 15 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 16 | 17 | func main() { 18 | c := client.NewClient(rpc.DevnetRPCEndpoint) 19 | 20 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 21 | if err != nil { 22 | log.Fatalf("failed to get latest blockhash, err: %v", err) 23 | } 24 | 25 | lookupTablePubkey := common.PublicKeyFromString("D6vcHD84vc3G9bieBSedSjYobACscF8NTwaLU5Y28sGj") 26 | 27 | tx, err := types.NewTransaction(types.NewTransactionParam{ 28 | Signers: []types.Account{feePayer}, 29 | Message: types.NewMessage(types.NewMessageParam{ 30 | FeePayer: feePayer.PublicKey, 31 | RecentBlockhash: recentBlockhashResponse.Blockhash, 32 | Instructions: []types.Instruction{ 33 | address_lookup_table.DeactivateLookupTable(address_lookup_table.DeactivateLookupTableParams{ 34 | LookupTable: lookupTablePubkey, 35 | Authority: feePayer.PublicKey, 36 | }), 37 | }, 38 | }), 39 | }) 40 | if err != nil { 41 | log.Fatalf("failed to new a transaction, err: %v", err) 42 | } 43 | 44 | txhash, err := c.SendTransaction(context.Background(), tx) 45 | if err != nil { 46 | log.Fatalf("failed to send tx, err: %v", err) 47 | } 48 | 49 | log.Println("txhash:", txhash) 50 | } 51 | -------------------------------------------------------------------------------- /client/rpc_is_blockhash_valid.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | type IsBlockhashValidConfig struct { 10 | Commitment rpc.Commitment 11 | } 12 | 13 | func (c IsBlockhashValidConfig) toRpc() rpc.IsBlockhashValidConfig { 14 | return rpc.IsBlockhashValidConfig{ 15 | Commitment: c.Commitment, 16 | } 17 | } 18 | 19 | func (c *Client) IsBlockhashValid(ctx context.Context, blockhash string) (bool, error) { 20 | return process( 21 | func() (rpc.JsonRpcResponse[rpc.ValueWithContext[bool]], error) { 22 | return c.RpcClient.IsBlockhashValid(ctx, blockhash) 23 | }, 24 | value[bool], 25 | ) 26 | } 27 | 28 | func (c *Client) IsBlockhashValidWithConfig(ctx context.Context, blockhash string, cfg IsBlockhashValidConfig) (bool, error) { 29 | return process( 30 | func() (rpc.JsonRpcResponse[rpc.ValueWithContext[bool]], error) { 31 | return c.RpcClient.IsBlockhashValidWithConfig(ctx, blockhash, cfg.toRpc()) 32 | }, 33 | value[bool], 34 | ) 35 | } 36 | 37 | func (c *Client) IsBlockhashValidAndContext(ctx context.Context, blockhash string) (rpc.ValueWithContext[bool], error) { 38 | return process( 39 | func() (rpc.JsonRpcResponse[rpc.ValueWithContext[bool]], error) { 40 | return c.RpcClient.IsBlockhashValid(ctx, blockhash) 41 | }, 42 | forward[rpc.ValueWithContext[bool]], 43 | ) 44 | } 45 | 46 | func (c *Client) IsBlockhashValidAndContextWithConfig(ctx context.Context, blockhash string, cfg IsBlockhashValidConfig) (rpc.ValueWithContext[bool], error) { 47 | return process( 48 | func() (rpc.JsonRpcResponse[rpc.ValueWithContext[bool]], error) { 49 | return c.RpcClient.IsBlockhashValidWithConfig(ctx, blockhash, cfg.toRpc()) 50 | }, 51 | forward[rpc.ValueWithContext[bool]], 52 | ) 53 | } 54 | -------------------------------------------------------------------------------- /docs/_examples/program/address-lookup-table/close/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/blocto/solana-go-sdk/client" 8 | "github.com/blocto/solana-go-sdk/common" 9 | "github.com/blocto/solana-go-sdk/program/address_lookup_table" 10 | "github.com/blocto/solana-go-sdk/rpc" 11 | "github.com/blocto/solana-go-sdk/types" 12 | ) 13 | 14 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 15 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 16 | 17 | func main() { 18 | c := client.NewClient(rpc.DevnetRPCEndpoint) 19 | 20 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 21 | if err != nil { 22 | log.Fatalf("failed to get latest blockhash, err: %v", err) 23 | } 24 | 25 | lookupTablePubkey := common.PublicKeyFromString("D6vcHD84vc3G9bieBSedSjYobACscF8NTwaLU5Y28sGj") 26 | 27 | tx, err := types.NewTransaction(types.NewTransactionParam{ 28 | Signers: []types.Account{feePayer}, 29 | Message: types.NewMessage(types.NewMessageParam{ 30 | FeePayer: feePayer.PublicKey, 31 | RecentBlockhash: recentBlockhashResponse.Blockhash, 32 | Instructions: []types.Instruction{ 33 | address_lookup_table.CloseLookupTable(address_lookup_table.CloseLookupTableParams{ 34 | LookupTable: lookupTablePubkey, 35 | Authority: feePayer.PublicKey, 36 | Recipient: feePayer.PublicKey, 37 | }), 38 | }, 39 | }), 40 | }) 41 | if err != nil { 42 | log.Fatalf("failed to new a transaction, err: %v", err) 43 | } 44 | 45 | txhash, err := c.SendTransaction(context.Background(), tx) 46 | if err != nil { 47 | log.Fatalf("failed to send tx, err: %v", err) 48 | } 49 | 50 | log.Println("txhash:", txhash) 51 | } 52 | -------------------------------------------------------------------------------- /client/rpc_get_health_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | "github.com/blocto/solana-go-sdk/rpc" 9 | ) 10 | 11 | func TestClient_GetHealth(t *testing.T) { 12 | client_test.TestAll( 13 | t, 14 | []client_test.Param{ 15 | { 16 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getHealth"}`, 17 | ResponseBody: `{"jsonrpc":"2.0","result":"ok","id":1}`, 18 | F: func(url string) (any, error) { 19 | c := NewClient(url) 20 | return c.GetHealth(context.TODO()) 21 | }, 22 | ExpectedValue: true, 23 | ExpectedError: nil, 24 | }, 25 | { 26 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getHealth"}`, 27 | ResponseBody: `{"jsonrpc":"2.0","error":{"code":-32005,"message":"Node is behind by 42 slots","data":{"numSlotsBehind":42}},"id":1}`, 28 | F: func(url string) (any, error) { 29 | c := NewClient(url) 30 | return c.GetHealth(context.TODO()) 31 | }, 32 | ExpectedValue: false, 33 | ExpectedError: &rpc.JsonRpcError{ 34 | Code: -32005, 35 | Message: `Node is behind by 42 slots`, 36 | Data: map[string]any{ 37 | "numSlotsBehind": float64(42), 38 | }, 39 | }, 40 | }, 41 | { 42 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getHealth"}`, 43 | ResponseBody: `{"jsonrpc":"2.0","error":{"code":-32005,"message":"Node is unhealthy","data":{}},"id":1}`, 44 | F: func(url string) (any, error) { 45 | c := NewClient(url) 46 | return c.GetHealth(context.TODO()) 47 | }, 48 | ExpectedValue: false, 49 | ExpectedError: &rpc.JsonRpcError{ 50 | Code: -32005, 51 | Message: `Node is unhealthy`, 52 | Data: map[string]any{}, 53 | }, 54 | }, 55 | }, 56 | ) 57 | } 58 | -------------------------------------------------------------------------------- /docs/_examples/program/stake/deactivate/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/blocto/solana-go-sdk/client" 8 | "github.com/blocto/solana-go-sdk/common" 9 | "github.com/blocto/solana-go-sdk/program/stake" 10 | "github.com/blocto/solana-go-sdk/rpc" 11 | "github.com/blocto/solana-go-sdk/types" 12 | ) 13 | 14 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 15 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 16 | 17 | // 9aE476sH92Vz7DMPyq5WLPkrKWivxeuTKEFKd2sZZcde 18 | var alice, _ = types.AccountFromBase58("4voSPg3tYuWbKzimpQK9EbXHmuyy5fUrtXvpLDMLkmY6TRncaTHAKGD8jUg3maB5Jbrd9CkQg4qjJMyN6sQvnEF2") 19 | 20 | var aliceStakeAccountPubkey = common.PublicKeyFromString("oyRPx4Ejo11J6b4AGaCx9UXUvGzkEmZQoGxKqx4Yp4B") 21 | 22 | func main() { 23 | c := client.NewClient(rpc.LocalnetRPCEndpoint) 24 | 25 | res, err := c.GetLatestBlockhash(context.Background()) 26 | if err != nil { 27 | log.Fatalf("get recent block hash error, err: %v\n", err) 28 | } 29 | tx, err := types.NewTransaction(types.NewTransactionParam{ 30 | Message: types.NewMessage(types.NewMessageParam{ 31 | FeePayer: feePayer.PublicKey, 32 | RecentBlockhash: res.Blockhash, 33 | Instructions: []types.Instruction{ 34 | stake.Deactivate(stake.DeactivateParam{ 35 | Stake: aliceStakeAccountPubkey, 36 | Auth: alice.PublicKey, 37 | }), 38 | }, 39 | }), 40 | Signers: []types.Account{feePayer, alice}, 41 | }) 42 | if err != nil { 43 | log.Fatalf("generate tx error, err: %v\n", err) 44 | } 45 | 46 | txhash, err := c.SendTransaction(context.Background(), tx) 47 | if err != nil { 48 | log.Fatalf("send tx error, err: %v\n", err) 49 | } 50 | 51 | log.Println("txhash:", txhash) 52 | } 53 | -------------------------------------------------------------------------------- /rpc/get_vote_accounts.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import "context" 4 | 5 | type GetVoteAccountsResponse JsonRpcResponse[GetVoteAccounts] 6 | 7 | type GetVoteAccounts struct { 8 | Current VoteAccounts `json:"current"` 9 | Deliquent VoteAccounts `json:"delinquent"` 10 | } 11 | 12 | type VoteAccounts []VoteAccount 13 | 14 | type VoteAccount struct { 15 | VotePubkey string `json:"votePubkey"` 16 | NodePubkey string `json:"nodePubkey"` 17 | ActivatedStake uint64 `json:"activatedStake"` 18 | Commission uint8 `json:"commission"` 19 | EpochVoteAccount bool `json:"epochVoteAccount"` 20 | LastVote uint64 `json:"lastVote"` 21 | EpochCredits [][3]uint64 `json:"epochCredits"` 22 | RootSlot uint64 `json:"rootSlot"` 23 | } 24 | 25 | type GetVoteAccountsConfig struct { 26 | Commitment Commitment `json:"commitment,omitempty"` 27 | VotePubkey string `json:"votePubkey,omitempty"` 28 | KeepUnstakedDelinquents bool `json:"keepUnstakedDelinquents,omitempty"` 29 | DelinquentSlotDistance uint64 `json:"delinquentSlotDistance,omitempty"` 30 | } 31 | 32 | // GetVoteAccounts returns the account info and associated stake for all the voting accounts in the current bank. 33 | func (c *RpcClient) GetVoteAccounts(ctx context.Context) (JsonRpcResponse[GetVoteAccounts], error) { 34 | return call[JsonRpcResponse[GetVoteAccounts]](c, ctx, "getVoteAccounts") 35 | } 36 | 37 | // GetVoteAccountsWithConfig returns the account info and associated stake for all the voting accounts in the current bank. 38 | func (c *RpcClient) GetVoteAccountsWithConfig(ctx context.Context, cfg GetVoteAccountsConfig) (JsonRpcResponse[GetVoteAccounts], error) { 39 | return call[JsonRpcResponse[GetVoteAccounts]](c, ctx, "getVoteAccounts", cfg) 40 | } 41 | -------------------------------------------------------------------------------- /rpc/get_blocks_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetBlocks(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getBlocks", "params":[86686567, 86686578]}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":[86686567,86686572,86686573,86686574,86686575,86686576,86686577,86686578],"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetBlocks( 20 | context.TODO(), 21 | 86686567, 22 | 86686578, 23 | ) 24 | }, 25 | ExpectedValue: JsonRpcResponse[[]uint64]{ 26 | JsonRpc: "2.0", 27 | Id: 1, 28 | Error: nil, 29 | Result: []uint64{86686567, 86686572, 86686573, 86686574, 86686575, 86686576, 86686577, 86686578}, 30 | }, 31 | ExpectedError: nil, 32 | }, 33 | { 34 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getBlocks", "params":[86686567, 86686578, {"commitment": "confirmed"}]}`, 35 | ResponseBody: `{"jsonrpc":"2.0","result":[86686567,86686572,86686573,86686574,86686575,86686576,86686577,86686578],"id":1}`, 36 | F: func(url string) (any, error) { 37 | c := NewRpcClient(url) 38 | return c.GetBlocksWithConfig( 39 | context.TODO(), 40 | 86686567, 41 | 86686578, 42 | GetBlocksConfig{ 43 | Commitment: CommitmentConfirmed, 44 | }, 45 | ) 46 | }, 47 | ExpectedValue: JsonRpcResponse[[]uint64]{ 48 | JsonRpc: "2.0", 49 | Id: 1, 50 | Error: nil, 51 | Result: []uint64{86686567, 86686572, 86686573, 86686574, 86686575, 86686576, 86686577, 86686578}, 52 | }, 53 | ExpectedError: nil, 54 | }, 55 | }, 56 | ) 57 | } 58 | -------------------------------------------------------------------------------- /rpc/get_signatures_for_address.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | type GetSignaturesForAddressResponse JsonRpcResponse[GetSignaturesForAddress] 8 | 9 | type GetSignaturesForAddress []SignatureWithStatus 10 | 11 | type SignatureWithStatus struct { 12 | Signature string `json:"signature"` 13 | Slot uint64 `json:"slot"` 14 | BlockTime *int64 `json:"blockTime"` 15 | Err any `json:"err"` 16 | Memo *string `json:"memo"` 17 | } 18 | 19 | // GetSignaturesForAddressConfig is option config of `getSignaturesForAddress` 20 | type GetSignaturesForAddressConfig struct { 21 | Limit int `json:"limit,omitempty"` // between 1 and 1000, default: 1000 22 | Before string `json:"before,omitempty"` 23 | Until string `json:"until,omitempty"` 24 | Commitment Commitment `json:"commitment,omitempty"` // "processed" is not supported, default is "finalized" 25 | } 26 | 27 | // GetSignaturesForAddress returns confirmed signatures for transactions involving an address backwards 28 | // in time from the provided signature or most recent confirmed block 29 | func (c *RpcClient) GetSignaturesForAddress(ctx context.Context, base58Addr string) (JsonRpcResponse[GetSignaturesForAddress], error) { 30 | return call[JsonRpcResponse[GetSignaturesForAddress]](c, ctx, "getSignaturesForAddress", base58Addr) 31 | } 32 | 33 | // GetSignaturesForAddressWithConfig returns confirmed signatures for transactions involving an address backwards 34 | // in time from the provided signature or most recent confirmed block 35 | func (c *RpcClient) GetSignaturesForAddressWithConfig(ctx context.Context, base58Addr string, cfg GetSignaturesForAddressConfig) (JsonRpcResponse[GetSignaturesForAddress], error) { 36 | return call[JsonRpcResponse[GetSignaturesForAddress]](c, ctx, "getSignaturesForAddress", base58Addr, cfg) 37 | } 38 | -------------------------------------------------------------------------------- /docs/_examples/program/memo/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/blocto/solana-go-sdk/client" 8 | "github.com/blocto/solana-go-sdk/common" 9 | "github.com/blocto/solana-go-sdk/program/memo" 10 | "github.com/blocto/solana-go-sdk/rpc" 11 | "github.com/blocto/solana-go-sdk/types" 12 | ) 13 | 14 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 15 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 16 | 17 | // 9aE476sH92Vz7DMPyq5WLPkrKWivxeuTKEFKd2sZZcde 18 | var alice, _ = types.AccountFromBase58("4voSPg3tYuWbKzimpQK9EbXHmuyy5fUrtXvpLDMLkmY6TRncaTHAKGD8jUg3maB5Jbrd9CkQg4qjJMyN6sQvnEF2") 19 | 20 | func main() { 21 | c := client.NewClient(rpc.DevnetRPCEndpoint) 22 | 23 | // to fetch recent blockhash 24 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 25 | if err != nil { 26 | log.Fatalf("failed to get recent blockhash, err: %v", err) 27 | } 28 | 29 | // create a tx 30 | tx, err := types.NewTransaction(types.NewTransactionParam{ 31 | Signers: []types.Account{feePayer, alice}, 32 | Message: types.NewMessage(types.NewMessageParam{ 33 | FeePayer: feePayer.PublicKey, 34 | RecentBlockhash: recentBlockhashResponse.Blockhash, 35 | Instructions: []types.Instruction{ 36 | // memo instruction 37 | memo.BuildMemo(memo.BuildMemoParam{ 38 | SignerPubkeys: []common.PublicKey{alice.PublicKey}, 39 | Memo: []byte("🐳"), 40 | }), 41 | }, 42 | }), 43 | }) 44 | if err != nil { 45 | log.Fatalf("failed to new a transaction, err: %v", err) 46 | } 47 | 48 | // send tx 49 | txhash, err := c.SendTransaction(context.Background(), tx) 50 | if err != nil { 51 | log.Fatalf("failed to send tx, err: %v", err) 52 | } 53 | 54 | log.Println("txhash:", txhash) 55 | } 56 | -------------------------------------------------------------------------------- /rpc/get_slot_leaders_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetSlotLeaders(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method": "getSlotLeaders", "params": [264431722, 10]}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":["DUND26mEDfFeaPsVof3YvbXDRvpuQX7HMUJrLgEWzYw4","DUND26mEDfFeaPsVof3YvbXDRvpuQX7HMUJrLgEWzYw4","3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt","3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt","3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt","3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt","BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH","BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH","BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH","BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH"],"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetSlotLeaders(context.TODO(), 264431722, 10) 20 | }, 21 | ExpectedValue: JsonRpcResponse[[]string]{ 22 | JsonRpc: "2.0", 23 | Id: 1, 24 | Error: nil, 25 | Result: []string{ 26 | "DUND26mEDfFeaPsVof3YvbXDRvpuQX7HMUJrLgEWzYw4", 27 | "DUND26mEDfFeaPsVof3YvbXDRvpuQX7HMUJrLgEWzYw4", 28 | "3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt", 29 | "3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt", 30 | "3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt", 31 | "3JotfSFPaod4KVK7nj7ULvcq5PjUBdZNVGracNkJNhrt", 32 | "BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH", 33 | "BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH", 34 | "BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH", 35 | "BXAxLMMMUNYfC1z166VjWHR3WjTmqzLxB837o5ghmRtH", 36 | }, 37 | }, 38 | ExpectedError: nil, 39 | }, 40 | }, 41 | ) 42 | } 43 | -------------------------------------------------------------------------------- /client/rpc_send_transaction.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "encoding/base64" 6 | "fmt" 7 | 8 | "github.com/blocto/solana-go-sdk/rpc" 9 | "github.com/blocto/solana-go-sdk/types" 10 | ) 11 | 12 | type SendTransactionConfig struct { 13 | SkipPreflight bool 14 | PreflightCommitment rpc.Commitment 15 | MaxRetries uint64 16 | } 17 | 18 | func (c SendTransactionConfig) toRpc() rpc.SendTransactionConfig { 19 | return rpc.SendTransactionConfig{ 20 | Encoding: rpc.SendTransactionConfigEncodingBase64, 21 | PreflightCommitment: c.PreflightCommitment, 22 | MaxRetries: c.MaxRetries, 23 | SkipPreflight: c.SkipPreflight, 24 | } 25 | } 26 | 27 | // SendTransaction send transaction struct directly 28 | func (c *Client) SendTransaction(ctx context.Context, tx types.Transaction) (string, error) { 29 | rawTx, err := tx.Serialize() 30 | if err != nil { 31 | return "", fmt.Errorf("failed to serialize tx, err: %v", err) 32 | } 33 | return process( 34 | func() (rpc.JsonRpcResponse[string], error) { 35 | return c.RpcClient.SendTransactionWithConfig( 36 | ctx, 37 | base64.StdEncoding.EncodeToString(rawTx), 38 | SendTransactionConfig{}.toRpc(), 39 | ) 40 | }, 41 | forward[string], 42 | ) 43 | } 44 | 45 | // SendTransaction send transaction struct directly 46 | func (c *Client) SendTransactionWithConfig(ctx context.Context, tx types.Transaction, cfg SendTransactionConfig) (string, error) { 47 | rawTx, err := tx.Serialize() 48 | if err != nil { 49 | return "", fmt.Errorf("failed to serialize tx, err: %v", err) 50 | } 51 | return process( 52 | func() (rpc.JsonRpcResponse[string], error) { 53 | return c.RpcClient.SendTransactionWithConfig( 54 | ctx, 55 | base64.StdEncoding.EncodeToString(rawTx), 56 | cfg.toRpc(), 57 | ) 58 | }, 59 | forward[string], 60 | ) 61 | } 62 | -------------------------------------------------------------------------------- /docs/_examples/program/metaplex/token-metadata/sign-metadata/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/common" 10 | "github.com/blocto/solana-go-sdk/program/metaplex/token_metadata" 11 | "github.com/blocto/solana-go-sdk/rpc" 12 | "github.com/blocto/solana-go-sdk/types" 13 | ) 14 | 15 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 16 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 17 | 18 | func main() { 19 | c := client.NewClient(rpc.DevnetRPCEndpoint) 20 | 21 | // mint address 22 | nft := common.PublicKeyFromString("FK8eFRgmqewUzr7R6pYUxSPnSNusYmkhAV4e3pUJYdCd") 23 | 24 | tokenMetadataPubkey, err := token_metadata.GetTokenMetaPubkey(nft) 25 | if err != nil { 26 | log.Fatalf("failed to find a valid token metadata, err: %v", err) 27 | } 28 | 29 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 30 | if err != nil { 31 | log.Fatalf("failed to get recent blockhash, err: %v", err) 32 | } 33 | 34 | tx, err := types.NewTransaction(types.NewTransactionParam{ 35 | Signers: []types.Account{feePayer}, 36 | Message: types.NewMessage(types.NewMessageParam{ 37 | FeePayer: feePayer.PublicKey, 38 | RecentBlockhash: recentBlockhashResponse.Blockhash, 39 | Instructions: []types.Instruction{ 40 | token_metadata.SignMetadata(token_metadata.SignMetadataParam{ 41 | Metadata: tokenMetadataPubkey, 42 | Creator: feePayer.PublicKey, 43 | }), 44 | }, 45 | }), 46 | }) 47 | if err != nil { 48 | log.Fatalf("failed to new a tx, err: %v", err) 49 | } 50 | 51 | sig, err := c.SendTransaction(context.Background(), tx) 52 | if err != nil { 53 | log.Fatalf("failed to send tx, err: %v", err) 54 | } 55 | 56 | fmt.Println(sig) 57 | } 58 | -------------------------------------------------------------------------------- /rpc/get_block_commitment_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetBlockCommitment(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getBlockCommitment", "params":[86708800]}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":{"commitment":null,"totalStake":156502861915805458},"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetBlockCommitment( 20 | context.TODO(), 21 | 86708800, 22 | ) 23 | }, 24 | ExpectedValue: JsonRpcResponse[GetBlockCommitment]{ 25 | JsonRpc: "2.0", 26 | Id: 1, 27 | Error: nil, 28 | Result: GetBlockCommitment{ 29 | Commitment: nil, 30 | TotalStake: 156502861915805458, 31 | }, 32 | }, 33 | ExpectedError: nil, 34 | }, 35 | { 36 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getBlockCommitment", "params":[86708895]}`, 37 | ResponseBody: `{"jsonrpc":"2.0","result":{"commitment":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,140000814436952564],"totalStake":156502861915805458},"id":1}`, 38 | F: func(url string) (any, error) { 39 | c := NewRpcClient(url) 40 | return c.GetBlockCommitment( 41 | context.TODO(), 42 | 86708895, 43 | ) 44 | }, 45 | ExpectedValue: JsonRpcResponse[GetBlockCommitment]{ 46 | JsonRpc: "2.0", 47 | Id: 1, 48 | Error: nil, 49 | Result: GetBlockCommitment{ 50 | Commitment: &[]uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 140000814436952564}, 51 | TotalStake: 156502861915805458, 52 | }, 53 | }, 54 | ExpectedError: nil, 55 | }, 56 | }, 57 | ) 58 | } 59 | -------------------------------------------------------------------------------- /docs/_examples/tour/transfer-sol/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/blocto/solana-go-sdk/client" 8 | "github.com/blocto/solana-go-sdk/common" 9 | "github.com/blocto/solana-go-sdk/program/system" 10 | "github.com/blocto/solana-go-sdk/rpc" 11 | "github.com/blocto/solana-go-sdk/types" 12 | ) 13 | 14 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 15 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 16 | 17 | // 9aE476sH92Vz7DMPyq5WLPkrKWivxeuTKEFKd2sZZcde 18 | var alice, _ = types.AccountFromBase58("4voSPg3tYuWbKzimpQK9EbXHmuyy5fUrtXvpLDMLkmY6TRncaTHAKGD8jUg3maB5Jbrd9CkQg4qjJMyN6sQvnEF2") 19 | 20 | func main() { 21 | c := client.NewClient(rpc.DevnetRPCEndpoint) 22 | 23 | // to fetch recent blockhash 24 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 25 | if err != nil { 26 | log.Fatalf("failed to get recent blockhash, err: %v", err) 27 | } 28 | 29 | // create a transfer tx 30 | tx, err := types.NewTransaction(types.NewTransactionParam{ 31 | Signers: []types.Account{feePayer, alice}, 32 | Message: types.NewMessage(types.NewMessageParam{ 33 | FeePayer: feePayer.PublicKey, 34 | RecentBlockhash: recentBlockhashResponse.Blockhash, 35 | Instructions: []types.Instruction{ 36 | system.Transfer(system.TransferParam{ 37 | From: alice.PublicKey, 38 | To: common.PublicKeyFromString("2xNweLHLqrbx4zo1waDvgWJHgsUpPj8Y8icbAFeR4a8i"), 39 | Amount: 1e8, // 0.1 SOL 40 | }), 41 | }, 42 | }), 43 | }) 44 | if err != nil { 45 | log.Fatalf("failed to new a transaction, err: %v", err) 46 | } 47 | 48 | // send tx 49 | txhash, err := c.SendTransaction(context.Background(), tx) 50 | if err != nil { 51 | log.Fatalf("failed to send tx, err: %v", err) 52 | } 53 | 54 | log.Println("txhash:", txhash) 55 | } 56 | -------------------------------------------------------------------------------- /docs/_examples/program/system/transfer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/blocto/solana-go-sdk/client" 8 | "github.com/blocto/solana-go-sdk/common" 9 | "github.com/blocto/solana-go-sdk/program/system" 10 | "github.com/blocto/solana-go-sdk/rpc" 11 | "github.com/blocto/solana-go-sdk/types" 12 | ) 13 | 14 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 15 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 16 | 17 | // 9aE476sH92Vz7DMPyq5WLPkrKWivxeuTKEFKd2sZZcde 18 | var alice, _ = types.AccountFromBase58("4voSPg3tYuWbKzimpQK9EbXHmuyy5fUrtXvpLDMLkmY6TRncaTHAKGD8jUg3maB5Jbrd9CkQg4qjJMyN6sQvnEF2") 19 | 20 | func main() { 21 | c := client.NewClient(rpc.DevnetRPCEndpoint) 22 | 23 | // to fetch recent blockhash 24 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 25 | if err != nil { 26 | log.Fatalf("failed to get recent blockhash, err: %v", err) 27 | } 28 | 29 | // create a transfer tx 30 | tx, err := types.NewTransaction(types.NewTransactionParam{ 31 | Signers: []types.Account{feePayer, alice}, 32 | Message: types.NewMessage(types.NewMessageParam{ 33 | FeePayer: feePayer.PublicKey, 34 | RecentBlockhash: recentBlockhashResponse.Blockhash, 35 | Instructions: []types.Instruction{ 36 | system.Transfer(system.TransferParam{ 37 | From: alice.PublicKey, 38 | To: common.PublicKeyFromString("2xNweLHLqrbx4zo1waDvgWJHgsUpPj8Y8icbAFeR4a8i"), 39 | Amount: 1e8, // 0.1 SOL 40 | }), 41 | }, 42 | }), 43 | }) 44 | if err != nil { 45 | log.Fatalf("failed to new a transaction, err: %v", err) 46 | } 47 | 48 | // send tx 49 | txhash, err := c.SendTransaction(context.Background(), tx) 50 | if err != nil { 51 | log.Fatalf("failed to send tx, err: %v", err) 52 | } 53 | 54 | log.Println("txhash:", txhash) 55 | } 56 | -------------------------------------------------------------------------------- /program/sysvar/slot_hashes_test.go: -------------------------------------------------------------------------------- 1 | package sysvar 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/blocto/solana-go-sdk/common" 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestDeserializeSlotHashes(t *testing.T) { 11 | type args struct { 12 | data []byte 13 | owner common.PublicKey 14 | } 15 | tests := []struct { 16 | name string 17 | args args 18 | want SlotHashes 19 | err error 20 | }{ 21 | { 22 | args: args{ 23 | data: []byte{}, 24 | owner: common.SystemProgramID, 25 | }, 26 | want: SlotHashes{}, 27 | err: ErrInvalidAccountOwner, 28 | }, 29 | { 30 | args: args{ 31 | data: []byte{ 32 | 3, 0, 0, 0, 0, 0, 0, 0, 33 | 3, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 34 | 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 35 | 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 36 | }, 37 | owner: common.SysVarPubkey, 38 | }, 39 | want: SlotHashes{ 40 | { 41 | Slot: 3, 42 | Hash: [32]byte{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, 43 | }, 44 | { 45 | Slot: 2, 46 | Hash: [32]byte{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}, 47 | }, 48 | { 49 | Slot: 1, 50 | Hash: [32]byte{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, 51 | }, 52 | }, 53 | err: nil, 54 | }, 55 | } 56 | for _, tt := range tests { 57 | t.Run(tt.name, func(t *testing.T) { 58 | got, err := DeserializeSlotHashes(tt.args.data, tt.args.owner) 59 | assert.Equal(t, tt.want, got) 60 | assert.Equal(t, tt.err, err) 61 | }) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /program/secp256k1/instruction_test.go: -------------------------------------------------------------------------------- 1 | package secp256k1 2 | 3 | import ( 4 | "encoding/base64" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | // Creates and checks a KeccakSecp256k1 instruction against the following rust code: 11 | // 12 | // let sk_bytes = base64::decode("bNyQVhCtQ86p9CCtzVkrg3Fm6WJqiYb+dMO4HDtbl6o=").unwrap(); 13 | // let sk = libsecp256k1::SecretKey::parse_slice(&sk_bytes).unwrap(); 14 | // let instr = solana_sdk::secp256k1_instruction::new_secp256k1_instruction(&sk, "message".as_bytes()); 15 | // println!("{}", base64::encode(instr.data)) 16 | // 17 | // As all that's in a KeccakSecp256k1 instruction is the program id and the data (no accounts are passed), 18 | // we just check that the instruction data matches that generated by the rust code 19 | 20 | func TestNewSecp256k1Instruction(t *testing.T) { 21 | //skBytes, err := base64.StdEncoding.DecodeString("bNyQVhCtQ86p9CCtzVkrg3Fm6WJqiYb+dMO4HDtbl6o=") 22 | //assert.NoError(t, err) 23 | //sk := crypto.ToECDSAUnsafe(skBytes) 24 | 25 | //pubkey := crypto.PubkeyToAddress(sk.PublicKey).Bytes() 26 | //t.Log(base64.StdEncoding.EncodeToString(pubkey)) 27 | 28 | pubkey, _ := base64.StdEncoding.DecodeString("rx8O5L8N25rze03Dr4YXi9E+/Ys=") 29 | 30 | //hash := crypto.Keccak256([]byte("message")) 31 | //sig, err := crypto.Sign(hash, sk) 32 | //t.Log(base64.StdEncoding.EncodeToString(sig)) 33 | 34 | sig, _ := base64.StdEncoding.DecodeString("K2mYts9f1v1hJc2kp2nCTZ6hZ9dhoHfADHW9zUCBftFTeN1lYUZEgoUZrklfifnZeWUJUujShZKgYtzoKMaRCgE=") 35 | 36 | instr, err := NewSecp256k1Instruction([][]byte{[]byte("message")}, [][]byte{sig}, [][]byte{pubkey}, 0) 37 | assert.NoError(t, err) 38 | 39 | checkDataStr := "ASAAAAwAAGEABwAArx8O5L8N25rze03Dr4YXi9E+/YsraZi2z1/W/WElzaSnacJNnqFn12Ggd8AMdb3NQIF+0VN43WVhRkSChRmuSV+J+dl5ZQlS6NKFkqBi3OgoxpEKAW1lc3NhZ2U=" 40 | instrDataStr := base64.StdEncoding.EncodeToString(instr.Data) 41 | assert.Equal(t, checkDataStr, instrDataStr) 42 | } 43 | -------------------------------------------------------------------------------- /docs/_examples/advanced/durable-nonce/advance-nonce/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/blocto/solana-go-sdk/client" 9 | "github.com/blocto/solana-go-sdk/common" 10 | "github.com/blocto/solana-go-sdk/program/system" 11 | "github.com/blocto/solana-go-sdk/rpc" 12 | "github.com/blocto/solana-go-sdk/types" 13 | ) 14 | 15 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 16 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 17 | 18 | // 9aE476sH92Vz7DMPyq5WLPkrKWivxeuTKEFKd2sZZcde 19 | var alice, _ = types.AccountFromBase58("4voSPg3tYuWbKzimpQK9EbXHmuyy5fUrtXvpLDMLkmY6TRncaTHAKGD8jUg3maB5Jbrd9CkQg4qjJMyN6sQvnEF2") 20 | 21 | func main() { 22 | c := client.NewClient(rpc.DevnetRPCEndpoint) 23 | 24 | // get nonce account 25 | nonceAccountPubkey := common.PublicKeyFromString("5Covh7EB4HtC5ieeP7GwUH9AHySMmNicBmvXo534wEA8") 26 | 27 | // recent blockhash 28 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 29 | if err != nil { 30 | log.Fatalf("failed to get recent blockhash, err: %v", err) 31 | } 32 | 33 | // create a tx 34 | tx, err := types.NewTransaction(types.NewTransactionParam{ 35 | Signers: []types.Account{feePayer, alice}, 36 | Message: types.NewMessage(types.NewMessageParam{ 37 | FeePayer: feePayer.PublicKey, 38 | RecentBlockhash: recentBlockhashResponse.Blockhash, 39 | Instructions: []types.Instruction{ 40 | system.AdvanceNonceAccount(system.AdvanceNonceAccountParam{ 41 | Nonce: nonceAccountPubkey, 42 | Auth: alice.PublicKey, 43 | }), 44 | }, 45 | }), 46 | }) 47 | if err != nil { 48 | log.Fatalf("failed to new a transaction, err: %v", err) 49 | } 50 | 51 | sig, err := c.SendTransaction(context.Background(), tx) 52 | if err != nil { 53 | log.Fatalf("failed to send tx, err: %v", err) 54 | } 55 | 56 | fmt.Println("txhash", sig) 57 | } 58 | -------------------------------------------------------------------------------- /client/rpc_request_airdrop_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | "github.com/blocto/solana-go-sdk/rpc" 9 | ) 10 | 11 | func TestClient_RequestAirdrop(t *testing.T) { 12 | client_test.TestAll( 13 | t, 14 | []client_test.Param{ 15 | { 16 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"requestAirdrop", "params":["RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", 1]}`, 17 | ResponseBody: `{"jsonrpc":"2.0","result":"2HsNt2iPgHVKzbYxsivEUWutMAzFkJL1YBs7phaBTtKY82sbDLuhzEBqbmGwxBAWTRSiPwkqop8vqWxezkxcuaVW","id":1}`, 18 | F: func(url string) (any, error) { 19 | c := NewClient(url) 20 | return c.RequestAirdrop( 21 | context.TODO(), 22 | "RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", 23 | 1, 24 | ) 25 | }, 26 | ExpectedValue: "2HsNt2iPgHVKzbYxsivEUWutMAzFkJL1YBs7phaBTtKY82sbDLuhzEBqbmGwxBAWTRSiPwkqop8vqWxezkxcuaVW", 27 | ExpectedError: nil, 28 | }, 29 | }, 30 | ) 31 | } 32 | 33 | func TestClient_RequestAirdropWithConfig(t *testing.T) { 34 | client_test.TestAll( 35 | t, 36 | []client_test.Param{ 37 | { 38 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"requestAirdrop", "params":["RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", 1, {"commitment": "processed"}]}`, 39 | ResponseBody: `{"jsonrpc":"2.0","result":"4eAWQLipk6hA7AcRuLUw2VXbiHRVR6HABVcQQqaBuukNNMohWg4ToAn4Qh2RaiFnK1LiUxrGnVgm1n4kpUbB7Yt9","id":1}`, 40 | F: func(url string) (any, error) { 41 | c := NewClient(url) 42 | return c.RequestAirdropWithConfig( 43 | context.TODO(), 44 | "RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", 45 | 1, 46 | RequestAirdropConfig{ 47 | Commitment: rpc.CommitmentProcessed, 48 | }, 49 | ) 50 | }, 51 | ExpectedValue: "4eAWQLipk6hA7AcRuLUw2VXbiHRVR6HABVcQQqaBuukNNMohWg4ToAn4Qh2RaiFnK1LiUxrGnVgm1n4kpUbB7Yt9", 52 | ExpectedError: nil, 53 | }, 54 | }, 55 | ) 56 | } 57 | -------------------------------------------------------------------------------- /rpc/is_blockhash_valid_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestIsBlockhashValid(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"isBlockhashValid", "params":["14PVzxGGU4WQ7qbQffn3XJV1pasafs4wApFUs5sps89N"]}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":{"context":{"slot":112890169},"value":false},"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.IsBlockhashValid(context.TODO(), "14PVzxGGU4WQ7qbQffn3XJV1pasafs4wApFUs5sps89N") 20 | }, 21 | ExpectedValue: JsonRpcResponse[ValueWithContext[bool]]{ 22 | JsonRpc: "2.0", 23 | Id: 1, 24 | Error: nil, 25 | Result: ValueWithContext[bool]{ 26 | Context: Context{ 27 | Slot: 112890169, 28 | }, 29 | Value: false, 30 | }, 31 | }, 32 | ExpectedError: nil, 33 | }, 34 | { 35 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"isBlockhashValid", "params":["14PVzxGGU4WQ7qbQffn3XJV1pasafs4wApFUs5sps89N", {"commitment": "processed"}]}`, 36 | ResponseBody: `{"jsonrpc":"2.0","result":{"context":{"slot":112890231},"value":true},"id":1}`, 37 | F: func(url string) (any, error) { 38 | c := NewRpcClient(url) 39 | return c.IsBlockhashValidWithConfig( 40 | context.TODO(), 41 | "14PVzxGGU4WQ7qbQffn3XJV1pasafs4wApFUs5sps89N", 42 | IsBlockhashValidConfig{ 43 | Commitment: CommitmentProcessed, 44 | }, 45 | ) 46 | }, 47 | ExpectedValue: JsonRpcResponse[ValueWithContext[bool]]{ 48 | JsonRpc: "2.0", 49 | Id: 1, 50 | Error: nil, 51 | Result: ValueWithContext[bool]{ 52 | Context: Context{ 53 | Slot: 112890231, 54 | }, 55 | Value: true, 56 | }, 57 | }, 58 | ExpectedError: nil, 59 | }, 60 | }, 61 | ) 62 | } 63 | -------------------------------------------------------------------------------- /docs/_examples/program/address-lookup-table/extend/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "log" 6 | 7 | "github.com/blocto/solana-go-sdk/client" 8 | "github.com/blocto/solana-go-sdk/common" 9 | "github.com/blocto/solana-go-sdk/program/address_lookup_table" 10 | "github.com/blocto/solana-go-sdk/rpc" 11 | "github.com/blocto/solana-go-sdk/types" 12 | ) 13 | 14 | // FUarP2p5EnxD66vVDL4PWRoWMzA56ZVHG24hpEDFShEz 15 | var feePayer, _ = types.AccountFromBase58("4TMFNY9ntAn3CHzguSAvDNLPRoQTaK3sWbQQXdDXaE6KWRBLufGL6PJdsD2koiEe3gGmMdRK3aAw7sikGNksHJrN") 16 | 17 | func main() { 18 | c := client.NewClient(rpc.DevnetRPCEndpoint) 19 | 20 | recentBlockhashResponse, err := c.GetLatestBlockhash(context.Background()) 21 | if err != nil { 22 | log.Fatalf("failed to get latest blockhash, err: %v", err) 23 | } 24 | 25 | lookupTablePubkey := common.PublicKeyFromString("3LZbwptsCkv5R5uu1GNZKiX9SoC6egNG8NXg9zH5ZVM9") 26 | 27 | tx, err := types.NewTransaction(types.NewTransactionParam{ 28 | Signers: []types.Account{feePayer}, 29 | Message: types.NewMessage(types.NewMessageParam{ 30 | FeePayer: feePayer.PublicKey, 31 | RecentBlockhash: recentBlockhashResponse.Blockhash, 32 | Instructions: []types.Instruction{ 33 | address_lookup_table.ExtendLookupTable(address_lookup_table.ExtendLookupTableParams{ 34 | LookupTable: lookupTablePubkey, 35 | Authority: feePayer.PublicKey, 36 | Payer: &feePayer.PublicKey, 37 | Addresses: []common.PublicKey{ 38 | common.PublicKeyFromString("9aE476sH92Vz7DMPyq5WLPkrKWivxeuTKEFKd2sZZcde"), 39 | common.PublicKeyFromString("2xNweLHLqrbx4zo1waDvgWJHgsUpPj8Y8icbAFeR4a8i"), 40 | }, 41 | }), 42 | }, 43 | }), 44 | }) 45 | if err != nil { 46 | log.Fatalf("failed to new a transaction, err: %v", err) 47 | } 48 | 49 | txhash, err := c.SendTransaction(context.Background(), tx) 50 | if err != nil { 51 | log.Fatalf("failed to send tx, err: %v", err) 52 | } 53 | 54 | log.Println("txhash:", txhash) 55 | } 56 | -------------------------------------------------------------------------------- /client/rpc_get_balance.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/blocto/solana-go-sdk/rpc" 7 | ) 8 | 9 | type GetBalanceConfig struct { 10 | Commitment rpc.Commitment 11 | } 12 | 13 | func (c GetBalanceConfig) toRpc() rpc.GetBalanceConfig { 14 | return rpc.GetBalanceConfig{ 15 | Commitment: c.Commitment, 16 | } 17 | } 18 | 19 | // GetBalance fetch users lamports(SOL) balance 20 | func (c *Client) GetBalance(ctx context.Context, base58Addr string) (uint64, error) { 21 | return process( 22 | func() (rpc.JsonRpcResponse[rpc.ValueWithContext[uint64]], error) { 23 | return c.RpcClient.GetBalance(ctx, base58Addr) 24 | }, 25 | value[uint64], 26 | ) 27 | } 28 | 29 | // GetBalanceWithConfig fetch users lamports(SOL) balance with specific commitment 30 | func (c *Client) GetBalanceWithConfig(ctx context.Context, base58Addr string, cfg GetBalanceConfig) (uint64, error) { 31 | return process( 32 | func() (rpc.JsonRpcResponse[rpc.ValueWithContext[uint64]], error) { 33 | return c.RpcClient.GetBalanceWithConfig(ctx, base58Addr, cfg.toRpc()) 34 | }, 35 | value[uint64], 36 | ) 37 | } 38 | 39 | // GetBalanceAndContext fetch users lamports(SOL) balance 40 | func (c *Client) GetBalanceAndContext(ctx context.Context, base58Addr string) (rpc.ValueWithContext[uint64], error) { 41 | return process( 42 | func() (rpc.JsonRpcResponse[rpc.ValueWithContext[uint64]], error) { 43 | return c.RpcClient.GetBalance(ctx, base58Addr) 44 | }, 45 | forward[rpc.ValueWithContext[uint64]], 46 | ) 47 | } 48 | 49 | // GetBalanceAndContextWithConfig fetch users lamports(SOL) balance with specific commitment 50 | func (c *Client) GetBalanceAndContextWithConfig(ctx context.Context, base58Addr string, cfg GetBalanceConfig) (rpc.ValueWithContext[uint64], error) { 51 | return process( 52 | func() (rpc.JsonRpcResponse[rpc.ValueWithContext[uint64]], error) { 53 | return c.RpcClient.GetBalanceWithConfig(ctx, base58Addr, cfg.toRpc()) 54 | }, 55 | forward[rpc.ValueWithContext[uint64]], 56 | ) 57 | } 58 | -------------------------------------------------------------------------------- /rpc/request_aridrop_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestRequestAirdrop(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"requestAirdrop", "params":["RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", 1]}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":"2HsNt2iPgHVKzbYxsivEUWutMAzFkJL1YBs7phaBTtKY82sbDLuhzEBqbmGwxBAWTRSiPwkqop8vqWxezkxcuaVW","id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.RequestAirdrop( 20 | context.TODO(), 21 | "RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", 22 | 1, 23 | ) 24 | }, 25 | ExpectedValue: JsonRpcResponse[string]{ 26 | JsonRpc: "2.0", 27 | Id: 1, 28 | Error: nil, 29 | Result: "2HsNt2iPgHVKzbYxsivEUWutMAzFkJL1YBs7phaBTtKY82sbDLuhzEBqbmGwxBAWTRSiPwkqop8vqWxezkxcuaVW", 30 | }, 31 | ExpectedError: nil, 32 | }, 33 | { 34 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"requestAirdrop", "params":["RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", 1, {"commitment": "processed"}]}`, 35 | ResponseBody: `{"jsonrpc":"2.0","result":"4eAWQLipk6hA7AcRuLUw2VXbiHRVR6HABVcQQqaBuukNNMohWg4ToAn4Qh2RaiFnK1LiUxrGnVgm1n4kpUbB7Yt9","id":1}`, 36 | F: func(url string) (any, error) { 37 | c := NewRpcClient(url) 38 | return c.RequestAirdropWithConfig( 39 | context.TODO(), 40 | "RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7", 41 | 1, 42 | RequestAirdropConfig{ 43 | Commitment: CommitmentProcessed, 44 | }, 45 | ) 46 | }, 47 | ExpectedValue: JsonRpcResponse[string]{ 48 | JsonRpc: "2.0", 49 | Id: 1, 50 | Error: nil, 51 | Result: "4eAWQLipk6hA7AcRuLUw2VXbiHRVR6HABVcQQqaBuukNNMohWg4ToAn4Qh2RaiFnK1LiUxrGnVgm1n4kpUbB7Yt9", 52 | }, 53 | ExpectedError: nil, 54 | }, 55 | }, 56 | ) 57 | } 58 | -------------------------------------------------------------------------------- /rpc/get_inflation_governor_test.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/blocto/solana-go-sdk/internal/client_test" 8 | ) 9 | 10 | func TestGetInflationGovernor(t *testing.T) { 11 | client_test.TestAll( 12 | t, 13 | []client_test.Param{ 14 | { 15 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getInflationGovernor"}`, 16 | ResponseBody: `{"jsonrpc":"2.0","result":{"foundation":0.05,"foundationTerm":7.0,"initial":0.08,"taper":0.15,"terminal":0.015},"id":1}`, 17 | F: func(url string) (any, error) { 18 | c := NewRpcClient(url) 19 | return c.GetInflationGovernor( 20 | context.TODO(), 21 | ) 22 | }, 23 | ExpectedValue: JsonRpcResponse[GetInflationGovernor]{ 24 | JsonRpc: "2.0", 25 | Id: 1, 26 | Error: nil, 27 | Result: GetInflationGovernor{ 28 | Foundation: 0.05, 29 | FoundationTerm: 7.0, 30 | Initial: 0.08, 31 | Taper: 0.15, 32 | Terminal: 0.015, 33 | }, 34 | }, 35 | ExpectedError: nil, 36 | }, 37 | { 38 | RequestBody: `{"jsonrpc":"2.0", "id":1, "method":"getInflationGovernor", "params":[{"commitment": "processed"}]}`, 39 | ResponseBody: `{"jsonrpc":"2.0","result":{"foundation":0.05,"foundationTerm":7.0,"initial":0.08,"taper":0.15,"terminal":0.015},"id":1}`, 40 | F: func(url string) (any, error) { 41 | c := NewRpcClient(url) 42 | return c.GetInflationGovernorWithConfig( 43 | context.TODO(), 44 | GetInflationGovernorConfig{ 45 | Commitment: CommitmentProcessed, 46 | }, 47 | ) 48 | }, 49 | ExpectedValue: JsonRpcResponse[GetInflationGovernor]{ 50 | JsonRpc: "2.0", 51 | Id: 1, 52 | Error: nil, 53 | Result: GetInflationGovernor{ 54 | Foundation: 0.05, 55 | FoundationTerm: 7.0, 56 | Initial: 0.08, 57 | Taper: 0.15, 58 | Terminal: 0.015, 59 | }, 60 | }, 61 | ExpectedError: nil, 62 | }, 63 | }, 64 | ) 65 | } 66 | --------------------------------------------------------------------------------