solanatracker

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2024 License: MIT Imports: 12 Imported by: 0

README

Solana Swap Go

Go reimplementation of solana-swap-python

Easiest way to add Solana based swaps to your project. Uses the Solana Swap api from https://docs.solanatracker.io

Now supporting

  • Raydium
  • Raydium CPMM
  • Pump.fun
  • Moonshot
  • Orca
  • Jupiter (Private Self Hosted API)

Installation

go get github.com/zewebdev1337/solana-swap-go

Example Usage

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/gagliardetto/solana-go"
	"github.com/gagliardetto/solana-go/rpc"
	solanatracker "github.com/zewebdev1337/solana-swap-go"
)

func main() {
	startTime := time.Now()
	privateKey := "YOUR_SECRET_KEY" // replace with your base58 private key

	// Create a keypair from the secret key
	keypair, err := solana.PrivateKeyFromBase58(privateKey)
	if err != nil {
		log.Fatalf("Error creating keypair: %v", err)
	}

	rpcUrl := "https://solana-rpc.publicnode.com"

	// Initialize a new Solana tracker with the keypair and RPC endpoint
	tracker := solanatracker.NewSolanaTracker(keypair, rpcUrl)

	priorityFee := 0.00005 // priorityFee requires a pointer, thus we store it in a variable

	// Get the swap instructions for the specified tokens, amounts, and other parameters
	swapResponse, err := tracker.GetSwapInstructions(
		"So11111111111111111111111111111111111111112",
		"4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R",
		0.0001,                       // Amount to swap
		30,                           // Slippage
		keypair.PublicKey().String(), // Payer public key
		&priorityFee,                 // Priority fee (Recommended while network is congested)
		false,
	)
	if err != nil {
		// Log and exit if there's an error getting the swap instructions
		log.Fatalf("Error getting swap instructions: %v", err)
	}

	maxRetries := uint(5) // maxRetries requires a pointer, thus we store it in a variable

	// Define the options for the swap transaction
	options := solanatracker.SwapOptions{
		SendOptions: rpc.TransactionOpts{
			SkipPreflight: true,
			MaxRetries:    &maxRetries,
		},
		ConfirmationRetries:        50,
		ConfirmationRetryTimeout:   1000 * time.Millisecond,
		LastValidBlockHeightBuffer: 200,
		Commitment:                 rpc.CommitmentProcessed,
		ResendInterval:             1500 * time.Millisecond,
		ConfirmationCheckInterval:  100 * time.Millisecond,
		SkipConfirmationCheck:      false,
	}

	// Perform the swap transaction with the specified options
	sendTime := time.Now()
	txid, err := tracker.PerformSwap(swapResponse, options)
	endTime := time.Now()
	elapsedTime := endTime.Sub(startTime).Seconds()
	if err != nil {
		fmt.Printf("Swap failed: %v\n", err)
		fmt.Printf("Time elapsed before failure: %.2f seconds\n", elapsedTime)
		// Add retries or additional error handling as needed
	} else {
		fmt.Printf("Transaction ID: %s\n", txid)
		fmt.Printf("Transaction URL: https://solscan.io/tx/%s\n", txid)
		fmt.Printf("Swap completed in %.2f seconds\n", elapsedTime)
		fmt.Printf("Transaction finished in %.2f seconds\n", endTime.Sub(sendTime).Seconds())
	}
}

FAQ

Why should I use this API?

SolanaTracker retrieves all raydium tokens the second they are available, so you can perform fast snipes. They also provide their own hosted Jupiter Swap API with no rate limits and faster market updates.

Is there a fee for using this API?

SolanaTracker charges a 0.5% fee on each successful transaction.

From the original README:

Using this for a public bot or site with a high processing volume? 
Contact us via Discord or email (solanatracker@yzylab.com) and get the fee reduced to 0.1% (only if accepted.)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type SolanaTracker

type SolanaTracker struct {
	BaseURL string            // The base URL for the Solana Swap API
	RPC     string            // The URL for the Solana RPC node.
	Keypair solana.PrivateKey // The private key used for signing transactions.
}

SolanaTracker struct is used to interact with the Solana swap API.

Fields:

  • BaseURL: The base URL for the Solana swap API.
  • RPC: The URL for the Solana RPC node.
  • Keypair: The private key used for signing transactions.

func NewSolanaTracker

func NewSolanaTracker(keypair solana.PrivateKey, rpcURL string) *SolanaTracker

NewSolanaTracker creates a new instance of SolanaTracker with the given keypair and RPC URL.

The base URL for the Solana Swap API is hardcoded as "https://swap-v2.solanatracker.io".

Parameters:

  • keypair: The private key used for signing transactions.
  • rpcURL: The URL for the Solana RPC node.

Returns:

  • *SolanaTracker: A pointer to a new SolanaTracker struct with the provided keypair, rpcURL, and base URL.

func (*SolanaTracker) GetSwapInstructions

func (st *SolanaTracker) GetSwapInstructions(fromToken string, toToken string, fromAmount float64, slippage float64, payer string, priorityFee *float64, forceLegacy bool) (*SwapResponse, error)

GetSwapInstructions fetches the swap instructions from SolanaTracker.

Parameters:

  • fromToken: The address of the token to swap from.
  • toToken: The address of the token to swap to.
  • fromAmount: The amount of token to swap from.
  • slippage: Maximum tolerated price slippage before cancelling.
  • payer: The address of the payer for the swap.
  • priorityFee: The priority fee for the swap transaction.
  • forceLegacy: Wether to force legacy mode.

Returns:

  • SwapResponse: The instructions to perform the swap.
  • (Optional) Error if one occurs.

func (*SolanaTracker) PerformSwap

func (st *SolanaTracker) PerformSwap(swapResponse *SwapResponse, options SwapOptions) (string, error)

PerformSwap sends and confirms a transaction.

Parameters:

  • swapResponse: The swap instructions provided by SolanaTracker.
  • options: The SwapOptions for the transaction

Returns:

  • Signature of the transaction.
  • (Optional) Error if one occurs.

type SwapOptions

type SwapOptions struct {
	SendOptions rpc.TransactionOpts

	/*
		Number of times to retry confirming a transaction.

		If the transaction confirmation fails, the client will retry confirming the transaction this many times before giving up.
	*/
	ConfirmationRetries int

	/*
		Maximum amount of time to wait for transaction confirmation.

		If transaction confirmation takes longer than this timeout, the client will give up and return an error.
	*/
	ConfirmationRetryTimeout time.Duration

	/*
		Number of blocks to buffer when checking the last valid block height.

		Used to ensure that the transaction is still valid when it is confirmed.
	*/
	LastValidBlockHeightBuffer uint64

	/*
		Determines the required commitment level the transaction must have before it is considered successful.

		Default: CommitmentFinalized

		Options:

			- CommitmentFinalized
			- CommitmentConfirmed
			- CommitmentProcessed

		Starting with solana-go@v1.5.5, commitment levels `max`, `recent`, `root`, `single` and `singleGossip` are deprecated.
	*/
	Commitment rpc.CommitmentType

	// Amount of time to wait between resending a transaction.
	ResendInterval time.Duration

	// Amount of time to wait between transaction confirmation status checks.
	ConfirmationCheckInterval time.Duration

	/*
		Whether to skip the transaction confirmation check.

		If true, the client will not wait for the transaction to be confirmed and will return the signature immediately after sending the transaction.
	*/
	SkipConfirmationCheck bool
}

SwapOptions is a struct that contains options that can be used to customize the behavior of the transaction sending and confirmation process.

Fields:

  • SendOptions: A solana-go/rpc.TransactionOpts struct. It includes the preflight commitment level, skipping preflight, and maximum retries.
  • ConfirmationRetries: Number of times to retry confirming a transaction.
  • ConfirmationRetryTimeout: Maximum amount of time to wait for transaction confirmation.
  • LastValidBlockHeightBuffer: Number of blocks to buffer when checking the last valid block height.
  • Determines the required commitment level the transaction must have before it is considered successful.
  • ResendInterval: Amount of time to wait between resending a transaction.
  • ConfirmationCheckInterval: Amount of time to wait between transaction confirmation status checks.
  • SkipConfirmationCheck: Whether to skip the transaction confirmation check.

type SwapResponse

type SwapResponse struct {
	Txn         string `json:"txn"`         // The base64-encoded transaction that needs to be sent.
	ForceLegacy bool   `json:"forceLegacy"` // Whether to force legacy mode for the transaction.
}

SwapResponse is the response from SolanaTracker.

Contains the instructions to perform the swap.

Fields:

  • Txn: The base64-encoded transaction that needs to be sent.
  • ForceLegacy: Whether to force legacy mode for the transaction.

Jump to

Keyboard shortcuts

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