Git Product home page Git Product logo

solana-go-sdk's Introduction

Solana Go SDK

GitHub go.mod Go version GitHub release (latest SemVer)

Guide

Getting Started

Installing

go get -v github.com/blocto/solana-go-sdk

Example

Hello World

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/blocto/solana-go-sdk/client"
	"github.com/blocto/solana-go-sdk/rpc"
)

func main() {
	c := client.NewClient(rpc.MainnetRPCEndpoint)

	// If you would like to customize the http client used to make the
	// requests you could do something like this
	// c := client.New(rpc.WithEndpoint(rpc.MainnetRPCEndpoint),rpc.WithHTTPClient(customHTTPClient))

	resp, err := c.GetVersion(context.TODO())
	if err != nil {
		log.Fatalf("failed to version info, err: %v", err)
	}

	fmt.Println("version", resp.SolanaCore)
}

RPC

All interfaces of rpc follow the solana's json-rpc docs.

The implementation of client in this project separate into two parts, rpc and wrapped. The wrapped only returns main result value and the rpc returns whole rpc response. You can switch it by yourself for different situation. Take getBalance as example:

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/blocto/solana-go-sdk/client"
	"github.com/blocto/solana-go-sdk/rpc"
)

func main() {
	c := client.NewClient(rpc.DevnetRPCEndpoint)

	// get balance
	balance, err := c.GetBalance(
		context.TODO(),
		"RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7",
	)
	if err != nil {
		log.Fatalf("failed to get balance, err: %v", err)
	}
	fmt.Printf("balance: %v\n", balance)

	// get balance with sepcific commitment
	balance, err = c.GetBalanceWithConfig(
		context.TODO(),
		"RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7",
		rpc.GetBalanceConfig{
			Commitment: rpc.CommitmentProcessed,
		},
	)
	if err != nil {
		log.Fatalf("failed to get balance with cfg, err: %v", err)
	}
	fmt.Printf("balance: %v\n", balance)

	// for advanced usage. fetch full rpc response
	res, err := c.RpcClient.GetBalance(
		context.TODO(),
		"RNfp4xTbBb4C3kcv2KqtAj8mu4YhMHxqm1Skg9uchZ7",
	)
	if err != nil {
		log.Fatalf("failed to get balance via rpc client, err: %v", err)
	}
	fmt.Printf("response: %+v\n", res)
}

Programing model & Program

There are some important tpyes in solana.

  • Program

resides in the program/ folder.

  • Pubkey (a basic identity of key)

resides in the common/ folder.

  • Insturciton (contain many pubkeys and program ID)
  • Message (contain many instructions)
  • Transaction (contain a message and many signatures)
  • Account (a pub/pri keypair )

reside in the types/ folder.

More Example

for more examples, follow examples/ folder

solana-go-sdk's People

Contributors

adelowo avatar andy74139 avatar aphoh avatar crossle avatar defactojob avatar ffc0 avatar olegfomenko avatar omarkilani avatar pyvirus avatar thiagosantana-mb avatar trisato avatar yihau avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

solana-go-sdk's Issues

transfer

Is there any difference between the types.NewMessage and types.CreateRawTransactionParam

Get mint address for a given address

Hey I need a way of identifying what type of tokens the address is for so I need a way of querying a given public address to get it's mint address.

If I create a new client what method do I use to get the tokens mint address ?

c := client.NewClient(rpc.MainnetRPCEndpoint)

Thanks 👍

How to get the balance for the token?

How to get the balance for the token for the specific address?

are we using ATA account? but I can't get to the next step.
the gitbook show the transfer part but not showing the balance.

Replacing METAPLEX functions (anchor)

Hey! First of all, thanks for a great library.
The question is: how can I replace this function from metaplex code?

const getMetadata = async (
  mint: anchor.web3.PublicKey,
): Promise<anchor.web3.PublicKey> => {
  return (
    await anchor.web3.PublicKey.findProgramAddress(
      [
        Buffer.from('metadata'),
        TOKEN_METADATA_PROGRAM_ID.toBuffer(),
        mint.toBuffer(),
      ],
      TOKEN_METADATA_PROGRAM_ID,
    )
  )[0];
};

Create Metadata Accounts -"Program log: Incorrect account owner"

failed to send tx, err: rpc response error: {
"code": -32002,
"message": "Transaction simulation failed: Error processing Instruction 2: custom program error: 0x39",
"data": {
"accounts": null,
"err": {
"InstructionError": [
2,
{
"Custom": 57
}
]
},
"logs": [
"Program 11111111111111111111111111111111 invoke [1]",
"Program 11111111111111111111111111111111 success",
"Program GxhenTpDpvFWdVkiaoCd3W1RMpCVzswe9mLnRexMNUbb invoke [1]",
"Program log: Instruction: InitializeMint",
"Program GxhenTpDpvFWdVkiaoCd3W1RMpCVzswe9mLnRexMNUbb consumed 2923 of 1400000 compute units",
"Program GxhenTpDpvFWdVkiaoCd3W1RMpCVzswe9mLnRexMNUbb success",
"Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s invoke [1]",
"Program log: (Deprecated as of 1.1.0) Instruction: Create Metadata Accounts",
"Program log: Incorrect account owner",
"Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s consumed 4273 of 1397077 compute units",
"Program metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s failed: custom program error: 0x39"
],
"unitsConsumed": 2923
}
}

Could help with the error.

Querying a wallets transactions

Hey, a few days ago I asked how I can use your library to query the transactions for a given wallet and I didn't understand your answer.

I need to retrieve transactions for a wallet and paginate through them.

Can I use your library to do this and if so how?

Getting an error during the creation of Associated Token Account

I have been trying to create an Associated Token Account using the code given in the documents. The feePayer and Alice are the Private Keys from a previously created account. My mint public key was created in a previous step and it has a few lamports as balance.

I am getting the below error:

send raw tx error, err: rpc response error: {"code":-32002,"message":"Transaction simulation failed: Attempt to debit an account but found no record of a prior credit.","data":{"accounts":null,"err":"AccountNotFound","logs":[]}}

Is there anything I am doing wrong?

sending multiple transactions as ACID transactions

Hello again :)

I was just wondering, is there a way to do ACID transaction with your library?

For example, if I was to send tether tokens to addresses A and B from address C, could I do an ACID transaction to ensure that the tokens get sent to both address A and B otherwise the transaction would roll back if the one didn't succeed?

You guys should start billing me for all your time in answering all my questions ;)

thanks heaps

GetAccountInfo RPC With Base64 Encoding Returns `base64` In Account Data

Attempting to retrieve account information with base64 encoding doesn't actually return the base64 encoded data of the account, it just returns base64 instead of the actual base64 encoded data.

The following example can be used to reproduce this behavior on the latest commit.

package main

import (
	"log"

	"github.com/portto/solana-go-sdk/client"
)

func main() {
	rpcClient := client.NewClient(client.MainnetRPCEndpoint)
	res, err := rpcClient.GetAccountInfo("3De2PXiySuPXb8qxSXMjP7QSmXYeVt89TJTzjBa1mtMx", client.GetAccountInfoConfig{Encoding: "base64"})
	if err != nil {
		log.Fatal(err)
	}
	log.Println("data: ", res.Data)
}

Output: 2021/05/07 00:30:22 data: [ base64]

go get: "verifying module: checksum mismatch"

This problem seems to exist even if i clean the module cache

go clean -modcache

And it seems to be problematic for v1.1.0 and v1.0.0

(base) λ  ~/src/airdrop-go git:(master) ✗
go get -v github.com/portto/solana-go-sdk v1.0.0
go: downloading github.com/portto/solana-go-sdk v1.1.0
go get github.com/portto/solana-go-sdk: github.com/portto/[email protected]: verifying module: checksum mismatch
	downloaded: h1:FqvwBTpgCQHC4rvCLu0z7ICJd9yQFoJzGD6MPuhstZM=
	sum.golang.org: h1:eiaXN6ChKS3QgwZtBS+5GHkb8gMfTmsD1cB8SkRZ0H4=

SECURITY ERROR
This download does NOT match the one reported by the checksum server.
The bits may have been replaced on the origin server, or an attacker may
have intercepted the download attempt.

For more information, see 'go help module-auth'.
go get v1.0.0: unrecognized import path "v1.0.0": https fetch: Get "https://v1.0.0/?go-get=1": EOF
(base) λ  ~/src/airdrop-go git:(master) ✗
go get -v github.com/portto/[email protected]
go: downloading github.com/portto/solana-go-sdk v1.0.0
go get github.com/portto/[email protected]: github.com/portto/[email protected]: verifying module: checksum mismatch
	downloaded: h1:pnSSO7KMBwc0gI0Twm7vJV8Kdb99WkOpw/qOqwjOngc=
	sum.golang.org: h1:+3QoiL6OnRhb8UkKVkTRXpqWsug5UgRTTV0h7yWycT4=

SECURITY ERROR
This download does NOT match the one reported by the checksum server.
The bits may have been replaced on the origin server, or an attacker may
have intercepted the download attempt.

For more information, see 'go help module-auth'.

Transaction duration

Is it possible that a transaction can take several minutes, hours or even days?

connect to the blockchain

Hey guys, in all of the examples they are not actually using real accounts or tokens or even directly connecting to the block chain. i need to know how I can actually connect to the blockchain to send tokens to other sol addresses.

In all the examples they connect to a simulated blockchain doing this;
c := client.NewClient(rpc.DevnetRPCEndpoint)

I want to connect to the blockchain so I can do real transactions, how do I do this?

Thanks

Updating Token Metadata

Hi!

Thanks for your work in this library. Do you have support for updating the token metadata for the token metadata program?

If not, can you possibly offer me some directions. I can help with a PR.

Can't use this repo with go.mod

main.go:9:2: module github.com/portto/solana-go-sdk@latest found (v1.8.1), but does not contain package github.com/portto/solana-go-sdk/rpc

The reason is that the code under the v1.8.1 tag doesn't contain rpc package.
Can you please create a new tag?

Transaction simulation failed

When I transfer USDT, I got an error Transaction simulation failed: Error processing Instruction 0: custom program error: 0x1.
And by a way, if there is a method that I could decode my raw transaction?

Following is my raw transaction string:

412XQ6QVMhiYhk4pxhVbTEA7B1nd4YFDae4XStAdedoXJx1K3qngHJ2FpXJDj3emf7VdpoKbSEhNv5T24S44qwRCPnRZunUX61pyB1Qyues4Ym6S9SvMXre46RNEpyso55rrvzf6pvK8JNFcorgNr4fFTdMg3e8XHP8gDheoKkVJU5XRzs3Pb9uFS24mKHNnY5T97rHjKAsXSdCm8PTiXHzELZiZTCKRVaf6RgL5idHVhyy1LLBX9vtr5z2VeyA9UdMdbH3y5NEJqVyTmxWhd2MadcsDH2v9yRvGspJsCjnFVYVQag5R7gzqxF7TXJ8CdWLNGPC9pXj9PqNxp5VA1XU6Xyv8178wRwaJW1MGST28wdp7VknkitXzV8qnq1MGKB8rURpDHwoPrHBdWN15BhFJ1KJcM4UvuuvDHBw7Bfv3NacQN3eVS6Rscjc3ahMYN848Q4uV5ZHs8H7CP2QqhFqeafArXoRS72882iuvnmmHbCKoVkbBEmf8zb5cp7w42RNUSyu3ZsCcF5H9gNhdEHNURqovVuBRkSf2fWbntHpyUjPFE41MBummX

how to send the memo tx with the sdk ?

I follow Chido introduction on the discard.
he send me the TS codes example:

await transferTransaction.add(
  new TransactionInstruction({
    keys: [{ pubkey: fromKeypair.publicKey, isSigner: true, isWritable: true }],
    data: Buffer.from('Data to send in transaction', 'utf-8'),
    programId: new PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),
  })
)

I append the memo Instruction in golang:

	Instructions: []types.Instruction{
		sysprog.Transfer(sysprog.TransferParam{
			From:   alice.PublicKey,                                                            // from
			To:     common.PublicKeyFromString("2xNweLHLqrbx4zo1waDvgWJHgsUpPj8Y8icbAFeR4a8i"), // to
			Amount: 1e9,                                                                        // 1 SOL
		}),
		types.Instruction{
			Accounts: []types.AccountMeta{
				{PubKey: alice.PublicKey, IsSigner: true, IsWritable: true},
			},
			ProgramID: common.SystemProgramID,
			Data:      []byte("111111111"),
		},
	},

submit tx, get the error: failed: invalid instruction data

2022/02/10 11:08:56 failed to send tx, err: rpc response error: {"code":-32002,"message":"Transaction simulation failed: Error processing Instruction 1: invalid instruction data","data":{"accounts":null,"err":{"InstructionError":[1,"InvalidInstructionData"]},"logs":["Program 11111111111111111111111111111111 invoke [1]","Program 11111111111111111111111111111111 success","Program 11111111111111111111111111111111 invoke [1]","Program 11111111111111111111111111111111 failed: invalid instruction data"]}}
exit status 1

Please help me. thanks a lot.

GetNonceAccount error

rpc: call error, err: failed to do request, err: Post "": unsupported protocol scheme "", body:

GetNonceAccount has an error

func (sol *solanaClient) GetNonceAccount() (string, error) {
	nonceAccountAddr := "DJyNpXgggw1WGgjTVzFsNjb3fuQZVMqhoakvSBfX9LYx"
	nonceAccount, err := sol.Client.GetNonceAccount(context.Background(), nonceAccountAddr)
	if err != nil {
		log.Fatalf("failed to get nonce account, err: %v", err)
	}
	fmt.Printf("%+v\n", nonceAccount)
	return "", nil
}

timeout inside the context

Can i make the context timeout when creating the transaction (tx) and also sending the tokens, or must the context be epty as done in the example?

Best Way to Unmarshal Data Field in Response?

When I call a method, for example GetAccountInfo and I receive a response, the response unmarshals fields such as lamports, owner, executable etc in human-readable form, but the Data field comes in a byte array.

What is the best/easiest way for me to convert this byte array into a human readable form (such as JSON), specifically if I don't know the specific fields that will be returned?

Private key dependency

https://github.com/portto/solana-go-sdk/blob/3379219af14a083038c96118c7d1d7daa7e21232/docs/_examples/nft/mint-a-nft-with-master-edition-v2/main.go#L21

Sir, I'm actually thinking of moving to production with mainnet config. But if I do so when the buyer(aka feePayer) has to mint then he has to provide is private key as per the code.. But no buyer will wish to provide/expose the private key .

My question is how can I mint an NFT without taking/using the private key of feePayer.

But usage of public key is fine

Sign transaction outside of CreateRawTransaction

Hey really love the SDK, and nice job creating it.

I was wondering if there is the ability to sign a transaction outside of the types.CreateRawTransaction function, and just provide the signature of the raw tx before sending it (if I am using an external service for signing tx).

Best regards,

Address information

Hey guys, I'm back again.

Im needing a way to do the following;

  1. Identify what type of cryptocurrency the given public address belongs to

  2. To see what token addresses the given cryptocurrency address holds.

  3. To identify what token the given token address belongs to.

How can we do this?

Killing a transaction

My last concern is transaction duration.

Normally transactions are very quick using Solana but could there ever be a time when for some reason a transaction is going to take a long time to complete and so in this case could we somehow kill the transaction ?

Cheers :)

Get last few transactions

I like this API however there is one feature I can't seem to find, to get the last say 10 transactions of a particular wallet using it's public address.

I want to be able to retrieve the last 10 transactions at a time and paginate through them all.

Each transaction must have at least the transaction amount, receiver and sender addresses ect.

Is there such a feature in this library and if so could you refer me to it?

If it's not a feature of this library how can I query the Blockchain to access this data?

Create assosiated token account error

Starting solana-go-sdk-main\examples\tour\create-associated-token-account\main.go file (on Devnet rpc endpoint) and receiving that type error:
send raw tx error, err: rpc response error: {"code":-32002,"message":"Transaction simulation failed: Error processing Instruction 0: custom program error: 0x2","data":{"accounts":null,"err":{"InstructionError":[0,{"Custom":2}]},"logs":["Program ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL invoke [1]","Program log: Transfer 2039280 lamports to the associated token account","Program 11111111111111111111111111111111 invoke [2]","Program 11111111111111111111111111111111 success","Program log: Allocate space for the associated token account","Program 11111111111111111111111111111111 invoke [2]","Program 11111111111111111111111111111111 success","Program log: Assign the associated token account to the SPL Token program","Program 11111111111111111111111111111111 invoke [2]","Program 11111111111111111111111111111111 success","Program log: Initialize the associated token account","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [2]","Program log: Instruction: InitializeAccount","Program log: Error: Invalid Mint","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 3069 of 179470 compute units","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA failed: custom program error: 0x2","Program ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL consumed 23599 of 200000 compute units","Program ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL failed: custom program error: 0x2"]}}

Is there any changes in Solana Core or other causes?

Transaction timeouts using context

Hey thanks for answering my questions a couple of days ago.

However now I've got another question.

  1. When we actually send the transaction we are putting in the context inside of it so I was wondering if we could put a timeout in this context?

txhash, err := c.SendTransaction(context.Background(), tx)

  1. The solana Blockchain network has had some issues in the past as the whole block chain has gone down on a couple of occasions. Thus if the whole solana network was to go down again, how would this affect all the existing transactions that were already occurring at the time?

Thanks

Non cash payment facility lisence

Here in Australia we must have a "non cash facility licence" if we are enabling our website users to make payments that are not of physical notes or coin.

However if we use a third party to make the transactions for us then we don't need such a license.

Thus I need to ascertain if this API is the product of a licensed provider like Crypto.com so I can be legally allowed to use it?

Also I was wondering if you could provide me with a website of your company that is offering this API so I can learn about your company?

Thanks

Confirm transactions

Hello, I'm using the below code to get the transaction data.

c := client.NewClient(rpc.MainnetRPCEndpoint)

tr, err := c.GetTransaction(context.Background(), sig)

The problem I'm having is that I don't know how to extract the data out of the response (tr) that I need, as I'm needing the transaction amount, sender and receiver token addresses.

What do I do to get this data from the response (tr)

Thanks

Scott

when the network is down

Hey thanks for answering all my questions.

In my last question I asked you what would happen to all the existing transactions that are in the process of getting executed and then suddenly the network goes down?

HERE IS MY QUESTION

These transactions were already being processed before the network crashed so would these pending transactions get rolled back or would they partially execute, leaving the transmitter 5%, 10%, 15% or 50% out of pocket? Or would these transactions stay in pending status until the network is up again ?

I already know that if the network is down new transactions won't happen, but that was not what i was asking. I'm wanting to know about what would happen to existing transactions that are in the process of being executed.

I'm building a platform that enables people to buy items using tether (USDT) on the Solana blockchain and its absolutely paramount that I understand what will happen to pending transactions when the network goes down because I don't want my users to be out of pocket when the network goes down and then get sued by my users and be liable for thousands of dollars or even go to jail.

The Solana network has gone down like seven times in the last 12 months so I really need to know what will happen to the current pending transactions if this event would occur again. It's very important and I really need an answer to this question otherwise I'm going to have to just use another blockchain network, which i don't want to have to do.

Thanks

Help With Serum

Hi, I Really Love This Library And I've Gone Through The Gitbook.

This Is Not An Issue With The Library, Rather A Call For Help To Get The Right Direction.

I Need To Communicate With The Serum Dex And Using A Private Key, Serum Market ID, Size, Operation (Buy/Sell) And Order Type Constant (IOC) To Execute An Order And Output The Transaction Hash In 1 RPC Command.

Please, Can I Use Your Library To Achieve This? I Would Be Grateful If I Can Be Pointed In The Right Direction.

Thanks In Anticipation.

Transfer NFT

Hi. I was trying to execute the transfer NFT functionality ... But continuously running into errors

failed to send tx, err: rpc response error: {"code":-32002,"message":"Transaction simulation failed: Transaction loads a writable account that cannot be written","data":{"accounts":null,"err":"InvalidWritableAccount","logs":[],"unitsConsumed":0}}
exit status 1

Could you give an example code for transfer like you have provided for Mint NFT?
So that I can find out where I'm going wrong

Missing RPC call for GetTokenAccountsByOwner

Could be wrong about this, but it looks like there is no RPC call available on the client for GetTokenAccountsByOwner. From my experience so far working with NFTs, if you want to get Metaplex data for NFTs in a wallet, you must use GetTokenAccountsByOwner RPC to first retrieve the mint address. Conveniently this package does handle getting and parsing Metaplex data, so perhaps there is a gap in my understanding? Otherwise, I could take a shot at creating a PR for this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.