Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add solana staking #27

Merged
merged 2 commits into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 191 additions & 0 deletions examples/solana/build_staking_operation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
package main

import (
"context"
"fmt"
"log"
"math/big"
"os"
"path/filepath"
"strings"
"time"

"github.com/btcsuite/btcutil/base58"
"github.com/coinbase/coinbase-sdk-go/pkg/coinbase"

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

var (
networkID = "solana-devnet"
amount = big.NewFloat(0.1)
rpcURL = "https://api.devnet.solana.com"
defaultPrivKeyPath = filepath.Join(home(), ".config/solana/id.json")
)

func main() {
ctx := context.Background()

walletAddress := os.Args[2]

privKeys := []string{defaultPrivKeyPath}
if keys := os.Getenv("SOL_PRIVATE_KEYS"); keys != "" {
privKeys = strings.Split(keys, ",")
}

signers := make([]solana.PrivateKey, len(privKeys))
for i, pk := range privKeys {
privKey, err := solana.PrivateKeyFromSolanaKeygenFile(pk)
if err != nil {
log.Fatalf("private key %s does not exist or is invalid", privKey)
}

signers[i] = privKey
}

client, err := coinbase.NewClient(
coinbase.WithAPIKeyFromJSON(os.Args[1]),
)
if err != nil {
log.Fatalf("error creating coinbase client: %v", err)
}

address := coinbase.NewExternalAddress(networkID, walletAddress)

balance, err := client.GetStakeableBalance(ctx, coinbase.Sol, address)
if err != nil {
log.Fatalf("error getting balance: %v", err)
}

log.Printf("Stakeable balance: %s\n\n", balance.Amount().String())

stakingOperation, err := client.BuildStakeOperation(ctx, amount, coinbase.Sol, address)
if err != nil {
log.Fatalf("error building staking operation: %v", err)
}

log.Printf("Staking operation ID: %s\n\n", stakingOperation.ID())

for _, transaction := range stakingOperation.Transactions() {
log.Printf("Tx unsigned payload: %s\n\n", transaction.UnsignedPayload())

signedTx, err := signSolTransaction(transaction.UnsignedPayload(), signers)
if err != nil {
log.Fatalf("error signing transaction: %v", err)
}

log.Printf("Signed tx: %s\n\n", signedTx)

sig, err := broadcastSolTransaction(ctx, signedTx)
if err != nil {
log.Fatalf("error broadcasting transaction: %v", err)
}

log.Printf("Broadcasted tx: %s\n\n", getTxLink(stakingOperation.NetworkID(), sig))
}
}

func signSolTransaction(unsignedTx string, signers []solana.PrivateKey) (string, error) {
data := base58.Decode(unsignedTx)

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

// clear signatures: https://github.com/gagliardetto/solana-go/issues/186
tx.Signatures = nil

if _, err = tx.Sign(func(key solana.PublicKey) *solana.PrivateKey {
for _, candidate := range signers {
if candidate.PublicKey().Equals(key) {
return &candidate
}
}

return nil
}); err != nil {
return "", fmt.Errorf("error signing transaction: %w", err)
}

marshaledTx, err := tx.MarshalBinary()
if err != nil {
return "", fmt.Errorf("error marshaling transaction: %w", err)
}

base58EncodedSignedTx := base58.Encode(marshaledTx)

return base58EncodedSignedTx, nil
}

func broadcastSolTransaction(ctx context.Context, signedTx string) (string, error) {
var (
sig solana.Signature
err error
)

cluster := rpc.Cluster{
RPC: rpcURL,
}

rpcClient := rpc.New(cluster.RPC)

data := base58.Decode(signedTx)

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

opts := rpc.TransactionOpts{
SkipPreflight: false,
PreflightCommitment: rpc.CommitmentFinalized,
}

fmt.Println("Sending transaction...")

maxRetries := 20

for maxRetries > 0 {
fmt.Printf("Trying again [%d] Sending transaction...\n", 21-maxRetries)

sig, err = rpcClient.SendTransactionWithOpts(ctx, tx, opts)
if err != nil {
time.Sleep(3 * time.Second)
maxRetries--

continue
}

break
}

if err != nil {
return "", fmt.Errorf("failed to send transaction: %w", err)
}

return sig.String(), nil
}

func getTxLink(networkID, signature string) string {
if networkID == "solana-mainnet" {
return fmt.Sprintf("https://explorer.solana.com/tx/%s", signature)
} else if networkID == "solana-devnet" {
return fmt.Sprintf("https://explorer.solana.com/tx/%s?cluster=devnet", signature)
}

return ""
}

func home() string {
home, err := os.UserHomeDir()
if err != nil {
log.Fatal("unable to get user homedir")
}

return home
}
38 changes: 30 additions & 8 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,61 @@ module github.com/coinbase/coinbase-sdk-go
go 1.22.5

require (
github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce
github.com/ethereum/go-ethereum v1.14.8
github.com/gagliardetto/binary v0.8.0
github.com/gagliardetto/solana-go v1.10.0
github.com/stretchr/testify v1.9.0
gopkg.in/square/go-jose.v2 v2.6.0
gopkg.in/validator.v2 v2.0.1
)

require (
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/StackExchange/wmi v1.2.1 // indirect
filippo.io/edwards25519 v1.0.0-rc.1 // indirect
github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 // indirect
github.com/bits-and-blooms/bitset v1.10.0 // indirect
github.com/blendle/zapdriver v1.3.1 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.4 // indirect
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/consensys/bavard v0.1.13 // indirect
github.com/consensys/gnark-crypto v0.12.1 // indirect
github.com/crate-crypto/go-kzg-4844 v1.0.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/deckarep/golang-set/v2 v2.6.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
github.com/ethereum/c-kzg-4844 v1.0.0 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/fatih/color v1.16.0 // indirect
github.com/gagliardetto/treeout v0.1.4 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/rpc v1.2.0 // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/holiman/uint256 v1.3.1 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.16.0 // indirect
github.com/logrusorgru/aurora v2.0.3+incompatible // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
github.com/mmcloughlin/addchain v0.4.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mostynb/zstdpool-freelist v0.0.0-20201229113212-927304c0c3b1 // indirect
github.com/mr-tron/base58 v1.2.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect
github.com/streamingfast/logging v0.0.0-20230608130331-f22c91403091 // indirect
github.com/stretchr/objx v0.5.2 // indirect
github.com/supranational/blst v0.3.11 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
go.mongodb.org/mongo-driver v1.11.0 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
go.uber.org/ratelimit v0.2.0 // indirect
go.uber.org/zap v1.21.0 // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.23.0 // indirect
golang.org/x/term v0.23.0 // indirect
golang.org/x/time v0.5.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
rsc.io/tmplfunc v0.0.3 // indirect
)
Loading