solana

package
v3.0.0-...-e8b7a4c Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2023 License: GPL-3.0 Imports: 24 Imported by: 0

README

solana router

github

github: https://github.com/deltaswapio/swaprouter/tree/feature/solana-support

router contract

https://github.com/deltaswapio/router-solana-contract

router mechanism

  1. Swapout from solana to other chain

    1.1. Swapout native token SOL call router contract function swapout_native

    pub fn swapout_native(
        ctx: Context<SwapoutNative>,
        to: String,
        lamports: u64,
        to_chainid: u64,
    ) -> Result<()> 
    
    pub struct SwapoutNative<'info> {
    	#[account(mut)]
    	pub signer: Signer<'info>,
    	#[account(mut, owner = *program_id)]
    	pub router_account: Account<'info, RouterAccount>,
    	pub system_program: Program<'info, System>,
    }
    

    1.2. Swapout other token not anytoken call router contract function swapout_transfer

    pub fn swapout_transfer(
        ctx: Context<SwapoutTransfer>,
        to: String,
        amount: u64,
        to_chainid: u64,
    ) -> Result<()>
    
    pub struct SwapoutTransfer<'info> {
    	#[account(mut)]
    	pub signer: Signer<'info>,
    	#[account(owner = *program_id)]
    	pub router_account: Account<'info, RouterAccount>,
    	#[account(mut, has_one = mint)]
    	pub from: Account<'info, TokenAccount>,
    	#[account(mut, has_one = mint)]
    	pub to: Account<'info, TokenAccount>,
    	#[account(mut, owner = *token_program.key)]
    	pub mint: Account<'info, Mint>,
    	pub token_program: Program<'info, Token>,
    }
    

    1.3. Swapout anytoken call router contract function swapout_burn

     pub fn swapout_burn(
        ctx: Context<SwapoutBurn>,
        to: String,
        amount: u64,
        to_chainid: u64,
    ) -> Result<()>
    
    pub struct SwapoutTransfer<'info> {
    	#[account(mut)]
    	pub signer: Signer<'info>,
    	#[account(owner = *program_id)]
    	pub router_account: Account<'info, RouterAccount>,
    	#[account(mut, has_one = mint)]
    	pub from: Account<'info, TokenAccount>,
    	#[account(mut, has_one = mint)]
    	pub to: Account<'info, TokenAccount>,
    	#[account(mut, owner = *token_program.key)]
    	pub mint: Account<'info, Mint>,
    	pub token_program: Program<'info, Token>,
    }
    
  2. Swapin from other chain to solana

    2.1. Swapin native token SOL call router contract function swapin_native

    pub fn swapin_native(
        ctx: Context<SwapinNative>,
        tx: String,
        lamports: u64,
        from_chainid: u64,
    ) -> Result<()>
    
    pub struct SwapinNative<'info> {
    	#[account(mut)]
    	pub mpc: Signer<'info>,
    	#[account(mut, owner = *program_id, has_one = mpc @RouterError::OnlyMPC)]
    	pub router_account: Account<'info, RouterAccount>,
    	#[account(mut)]
    	/// CHECK: corss to account
    	pub to: AccountInfo<'info>,
    	pub system_program: Program<'info, System>,
    }	
    

    2.2. Swapin other token not anytoken call router contract function swapin_transfer

    pub fn swapin_transfer(
        ctx: Context<SwapinTransfer>,
        tx: String,
        amount: u64,
        from_chainid: u64,
    ) -> Result<()>
    
    pub struct SwapinTransfer<'info> {
    	#[account(mut)]
    	pub mpc: Signer<'info>,
    	#[account(owner = *program_id, has_one = mpc @RouterError::OnlyMPC)]
    	pub router_account: Account<'info, RouterAccount>,
    	#[account(mut, has_one = mint)]
    	pub from: Account<'info, TokenAccount>,
    	#[account(mut, has_one = mint)]
    	pub to: Account<'info, TokenAccount>,
    	#[account(mut, owner = *token_program.key)]
    	pub mint: Account<'info, Mint>,
    	pub token_program: Program<'info, Token>,
    }
    

    2.3. Swapin anytoken call router contract function swapout_burn

    pub fn swapin_mint(
        ctx: Context<SwapinMint>,
        tx: String,
        amount: u64,
        from_chainid: u64,
    ) -> Result<()>
    
    pub struct SwapinMint<'info> {
    	#[account(mut)]
    	pub mpc: Signer<'info>,
    	#[account(owner = *program_id, has_one = mpc @RouterError::OnlyMPC)]
    	pub router_account: Account<'info, RouterAccount>,
    	#[account(mut, has_one = mint)]
    	pub to: Account<'info, TokenAccount>,
    	#[account(mut, owner = *token_program.key)]
    	pub mint: Account<'info, Mint>,
    	pub token_program: Program<'info, Token>,
    }
    

solana tools

use -h option to get help info for each tool

# convert publickey HexString to solana address
go run tokens/solana/tools/publicKeyToAddress/main.go -h
# change owner for router contract for mpc or privatekey signer
go run tokens/solana/tools/changeMpc/main.go -h
# apply owner for router contract for mpc or privatekey signer
go run tokens/solana/tools/applyMpc/main.go -h
# issue new token by mpc or privatekey signer
go run tokens/solana/tools/issueToken/main.go -h
# create new token AssociatedTokenAccount for mpc in router contract to hold new token asset
go run tokens/solana/tools/createRouterOwnerATA/main.go -h
# gen new solana account
go run tokens/solana/tools/genAccount/main.go -h
# enable or disable swap function 
go run tokens/solana/tools/enableSwap/main.go -h
Example:
go run tokens/solana/tools/publicKeyToAddress/main.go -p 0xedbe0d03d8022012a03d5535e8677681dbbd9bbd130a3593388a61454129f5c294
# output
address: DnsySaKza7ggR6RoviWNWb6WGLg6aKtmYo9dbeuhjQoV

about solana

API:https://docs.solana.com/developing/clients/jsonrpc-api cookbook: https://solanacookbook.com/references/token.html#how-to-create-a-token-account contract sdk: https://github.com/coral-xyz/anchor

notice

solana use ED25591 algorithm to create account

devnet
http: https://api.devnet.solana.com chain_id: 245022926

testnet
http: https://api.testnet.solana.com
chain_id: 245022940

mainnet
http: https://api.mainnet-beta.solana.com chain_id: 245022934

js sdk

web3: https://solana-labs.github.io/solana-web3.js/index.html call contract: https://www.npmjs.com/package/@project-serum/anchor

after run anchor build (@See https://github.com/deltaswapio/router-solana-contract) copy router-solana-contract/target/idl/router.json to project

#Example
const provider = anchor.AnchorProvider.env();
anchor.setProvider(provider);
connection = provider.connection;

const idl = JSON.parse(
	fs.readFileSync("./target/idl/router.json", "utf8")
);
let programId = new anchor.web3.PublicKey("9t6JfntGXehxm7qzLZ71BisNNYCMAiRUgoECvZATVpos");
router_program = new anchor.Program(idl, programId, provider);

More Example at https://github.com/deltaswapio/router-solana-contract/blob/main/app/client.js

scan tx in solana
go run tokens/solana/tools/scanTx/main.go -h
subscribe event logs
package main

import (
	"context"

	"github.com/davecgh/go-spew/spew"
	"github.com/gagliardetto/solana-go"
	"github.com/gagliardetto/solana-go/rpc"
	"github.com/gagliardetto/solana-go/rpc/ws"
)

func main() {
	client, err := ws.Connect(context.Background(), rpc.MainNetBeta_WS)
	if err != nil {
		panic(err)
	}
	defer client.Close()
	program := solana.MustPublicKeyFromBase58("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin") // serum

	{
		// Subscribe to log events that mention the provided pubkey:
		sub, err := client.LogsSubscribeMentions(
			program,
			rpc.CommitmentRecent,
		)
		if err != nil {
			panic(err)
		}
		defer sub.Unsubscribe()

		for {
			got, err := sub.Recv()
			if err != nil {
				panic(err)
			}
			spew.Dump(got)
		}
	}
}

doc https://docs.solana.com/developing/clients/jsonrpc-api#logssubscribe sdk https://github.com/gagliardetto/solana-go

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// RPCCall alias of tokens.RPCCall
	RPCCall = tokens.RPCCall
)

Functions

func PublicKeyToAddress

func PublicKeyToAddress(pubKeyHex string) (string, error)

func SupportChainID

func SupportChainID(chainID *big.Int) bool

SupportChainID support chainID

Types

type Bridge

Bridge solana bridge

func NewCrossChainBridge

func NewCrossChainBridge() *Bridge

NewCrossChainBridge new bridge

func (*Bridge) AirDrop

func (b *Bridge) AirDrop(publicKey string, amount uint64) (string, error)

AirDrop

func (*Bridge) BuildApplyMpcTransaction

func (b *Bridge) BuildApplyMpcTransaction(routerContract, routerMPC, routerPDA, newMpcAddress string) (*types.Transaction, error)

func (*Bridge) BuildChangeMpcTransaction

func (b *Bridge) BuildChangeMpcTransaction(routerContract, routerMPC, routerPDA, newMpcAddress string) (*types.Transaction, error)

func (*Bridge) BuildEnableSwapTransaction

func (b *Bridge) BuildEnableSwapTransaction(routerContract, routerMPC, routerPDA string, enable bool) (*types.Transaction, error)

func (*Bridge) BuildMintSPLTransaction

func (b *Bridge) BuildMintSPLTransaction(amount uint64, mintAddr, toAddr, minterAddr string) (*types.Transaction, error)

BuildMintSPLTransaction build mint spl token tx

func (*Bridge) BuildRawTransaction

func (b *Bridge) BuildRawTransaction(args *tokens.BuildTxArgs) (rawTx interface{}, err error)

BuildRawTransaction impl

func (*Bridge) BuildSendSPLTransaction

func (b *Bridge) BuildSendSPLTransaction(amount uint64, sourceAddr, destAddr, fromAddr string) (*types.Transaction, error)

BuildSendSPLTransaction build send spl token tx

func (*Bridge) BuildSendSolanaTransaction

func (b *Bridge) BuildSendSolanaTransaction(lamports uint64, fromAddress, toAddress string) (*types.Transaction, error)

BuildSendSolanaTransaction build send solana tx

func (*Bridge) BuildSwapinMintTransaction

func (b *Bridge) BuildSwapinMintTransaction(args *tokens.BuildTxArgs, tokenCfg *tokens.TokenConfig) (*types.Transaction, error)

BuildSwapinMintTransaction build swapin mint tx

func (*Bridge) BuildSwapinNativeTransaction

func (b *Bridge) BuildSwapinNativeTransaction(args *tokens.BuildTxArgs, tokenCfg *tokens.TokenConfig) (*types.Transaction, error)

BuildSwapinNativeTransaction build swapin native tx

func (*Bridge) BuildSwapinTransferTransaction

func (b *Bridge) BuildSwapinTransferTransaction(args *tokens.BuildTxArgs, tokenCfg *tokens.TokenConfig) (*types.Transaction, error)

BuildSwapinTransferTransaction build swapin transfer tx

func (*Bridge) GetAccountInfo

func (b *Bridge) GetAccountInfo(account, encoding string) (result *types.GetAccountInfoResult, err error)

GetAccountInfo get account info

func (*Bridge) GetBalance

func (b *Bridge) GetBalance(publicKey string) (*big.Int, error)

GetBalance get balance

func (*Bridge) GetBlock

func (b *Bridge) GetBlock(slot uint64, fullTx bool) (result *types.GetBlockResult, err error)

GetBlock get block

func (*Bridge) GetBlockHeight

func (b *Bridge) GetBlockHeight() (uint64, error)

GetBlockHeight

func (*Bridge) GetBlocks

func (b *Bridge) GetBlocks(start, end uint64) (*[]uint64, error)

func (*Bridge) GetCurrentThreshold

func (b *Bridge) GetCurrentThreshold() (*uint64, error)

func (*Bridge) GetEpochInfo

func (b *Bridge) GetEpochInfo() (*types.GetEpochInfoResult, error)

func (*Bridge) GetFeeForMessage

func (b *Bridge) GetFeeForMessage(blockhash, message string) (result uint64, err error)

GetFeeForMessage get fee for message This method is only available in solana-core v1.9 or newer. Please use getFees for solana-core v1.8

func (*Bridge) GetFees

func (b *Bridge) GetFees() (result *types.GetFeesResult, err error)

GetFees get fees

func (*Bridge) GetLatestBlockNumber

func (b *Bridge) GetLatestBlockNumber() (uint64, error)

GetLatestBlockNumber call getSlot

func (*Bridge) GetLatestBlockNumberOf

func (b *Bridge) GetLatestBlockNumberOf(url string) (uint64, error)

GetLatestBlockNumberOf call getSlot

func (*Bridge) GetLatestBlockhash

func (b *Bridge) GetLatestBlockhash() (result *types.GetLatestBlockhashResult, err error)

GetLatestBlockhash get latest block hash This method is only available in solana-core v1.9 or newer. Please use getRecentBlockhash for solana-core v1.8

func (*Bridge) GetMPCAddress

func (b *Bridge) GetMPCAddress(programID string) (types.PublicKey, error)

GetMPCAddress query

func (*Bridge) GetMinimumBalanceForRentExemption

func (b *Bridge) GetMinimumBalanceForRentExemption(datalength uint64) (uint64, error)

getMinimumBalanceForRentExemption

func (*Bridge) GetNonceAccountInfo

func (b *Bridge) GetNonceAccountInfo(account string) (result *types.GetNonceAccountInfoResult, err error)

func (*Bridge) GetProgramAccounts

func (b *Bridge) GetProgramAccounts(account, encoding string, filters []map[string]interface{}) (result types.GetProgramAccountsResult, err error)

GetProgramAccounts get program accounts

func (*Bridge) GetRecentBlockhash

func (b *Bridge) GetRecentBlockhash() (result *types.GetRecentBlockhashResult, err error)

GetRecentBlockhash get recent block hash

func (*Bridge) GetRouterAccount

func (b *Bridge) GetRouterAccount(programID string) (*RouterAccount, error)

GetRouterAccount query

func (*Bridge) GetSignatureStatuses

func (b *Bridge) GetSignatureStatuses(sigs []string, searchTransactionHistory bool) (result *types.GetSignatureStatusesResult, err error)

GetSignatureStatuses get signature statuses

func (*Bridge) GetTokenBalance

func (b *Bridge) GetTokenBalance(tokenAccount string) (result *types.GetTokenAmountResult, err error)

GetTokenBalance query

func (*Bridge) GetTokenDecimals

func (b *Bridge) GetTokenDecimals(tokenMint string) (uint8, error)

GetTokenDecimals query

func (*Bridge) GetTokenSupply

func (b *Bridge) GetTokenSupply(tokenMint string) (result *types.GetTokenAmountResult, err error)

GetTokenSupply query

func (*Bridge) GetTransaction

func (b *Bridge) GetTransaction(txHash string) (result interface{}, err error)

GetTransaction impl

func (*Bridge) GetTransactionStatus

func (b *Bridge) GetTransactionStatus(txHash string) (*tokens.TxStatus, error)

GetTransactionStatus impl

func (*Bridge) GetTxBlockInfo

func (b *Bridge) GetTxBlockInfo(txHash string) (blockHeight, blockTime uint64)

GetTxBlockInfo impl NonceSetter interface

func (*Bridge) InitAfterConfig

func (b *Bridge) InitAfterConfig()

####### NEW IMPLEMENT ###########################################

func (*Bridge) InitRouterInfo

func (b *Bridge) InitRouterInfo(routerContract, routerVersion string) (err error)

func (*Bridge) IsBlockhashValid

func (b *Bridge) IsBlockhashValid(blockhash string) (bool, error)

IsBlockhashValid

func (*Bridge) IsMinter

func (b *Bridge) IsMinter(tokenMint, minterAddr string) (bool, error)

IsMinter query

func (*Bridge) IsNative

func (b *Bridge) IsNative(address string) bool

func (*Bridge) IsValidAddress

func (b *Bridge) IsValidAddress(address string) bool

IsValidAddress impl check address

func (*Bridge) MPCSignTransaction

func (b *Bridge) MPCSignTransaction(rawTx interface{}, args *tokens.BuildTxArgs) (signTx interface{}, txHash string, err error)

MPCSignTransaction impl

func (*Bridge) PublicKeyToAddress

func (b *Bridge) PublicKeyToAddress(pubKeyHex string) (string, error)

PublicKeyToAddress impl

func (*Bridge) RegisterSwap

func (b *Bridge) RegisterSwap(txHash string, args *tokens.RegisterArgs) ([]*tokens.SwapTxInfo, []error)

RegisterSwap impl

func (*Bridge) SendSignedTransaction

func (b *Bridge) SendSignedTransaction(tx *types.Transaction, opts *types.SendTransactionOptions) (txHash string, err error)

SendSignedTransaction call sendTransaction

func (*Bridge) SendTransaction

func (b *Bridge) SendTransaction(signedTx interface{}) (txHash string, err error)

SendTransaction impl

func (*Bridge) SetGatewayConfig

func (b *Bridge) SetGatewayConfig(gatewayCfg *tokens.GatewayConfig)

SetGatewayConfig set gateway config

func (*Bridge) SetTokenConfig

func (b *Bridge) SetTokenConfig(tokenAddr string, tokenCfg *tokens.TokenConfig)

SetTokenConfig set token config

func (*Bridge) SignTransactionWithPrivateKey

func (b *Bridge) SignTransactionWithPrivateKey(rawTx interface{}, privKey string) (signTx interface{}, txHash string, err error)

SignTransactionWithPrivateKey sign tx with ECDSA private key

func (*Bridge) SimulateTransaction

func (b *Bridge) SimulateTransaction(tx *types.Transaction) (result *types.SimulateTransactionResponse, err error)

SimulateTransaction simulate tx

func (*Bridge) VerifyMPCPubKey

func (b *Bridge) VerifyMPCPubKey(mpcAddress, mpcPubkey string) error

VerifyMPCPubKey verify mpc address and public key is matching

func (*Bridge) VerifyMsgHash

func (b *Bridge) VerifyMsgHash(rawTx interface{}, msgHashes []string) (err error)

VerifyMsgHash impl

func (*Bridge) VerifyTransaction

func (b *Bridge) VerifyTransaction(txHash string, args *tokens.VerifyArgs) (*tokens.SwapTxInfo, error)

VerifyTransaction impl

type RouterAccount

type RouterAccount struct {
	MPC  types.PublicKey `json:"mpc"`
	Bump uint8           `json:"bump"`
}

RouterAccount struct

Jump to

Keyboard shortcuts

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