gagliardetto / solana-go

Go SDK library and RPC client for the Solana Blockchain
Apache License 2.0
943 stars 267 forks source link

How to create a Token Account? #117

Open JavinYang opened 2 years ago

JavinYang commented 2 years ago

I want to create a Token Account, but I always report error. I don't know where I made a mistake. Who can help me look at it? Thank you very much.

Error occurred at the last panic position

package main

import (
    "context"
    "fmt"

    "os"

    "github.com/davecgh/go-spew/spew"
    "github.com/gagliardetto/solana-go"
    "github.com/gagliardetto/solana-go/programs/system"
    "github.com/gagliardetto/solana-go/programs/token"

    // "github.com/gagliardetto/solana-go/programs/associated-token-account"
    "time"

    "github.com/gagliardetto/solana-go/rpc"
    confirm "github.com/gagliardetto/solana-go/rpc/sendAndConfirmTransaction"
    "github.com/gagliardetto/solana-go/rpc/ws"
    "github.com/gagliardetto/solana-go/text"
)

func main() {

    adminWallet := createAdminWallet()

    time.Sleep(time.Minute)

    rpcClient := rpc.New(rpc.DevNet_RPC)

    mintAddress, err := solana.PublicKeyFromBase58("EJwZgeZrdC8TXTQbQBoL6bfuAnFUUy1PVCMB4DYPzVaS")
    if err != nil {
        panic(err.Error())
    }

    recentBlock, err := rpcClient.GetRecentBlockhash(context.TODO(), rpc.CommitmentFinalized)
    if err != nil {
        panic(err)
    }

    wsClient, err := ws.Connect(context.Background(), rpc.DevNet_WS)
    if err != nil {
        panic(err)
    }

    lamport, err := rpcClient.GetMinimumBalanceForRentExemption(context.Background(), token.MINT_SIZE, rpc.CommitmentFinalized)
    if err != nil {
        panic(err)
    }

    // create token acount wallet
    wallet := solana.NewWallet()
    // create token acount addr
    tokenAccount := solana.NewWallet()

    // create token acount space
    newAccountIt := system.NewCreateAccountInstruction(
        lamport,
        token.MINT_SIZE,
        wallet.PublicKey(),
        adminWallet.PublicKey(),
        tokenAccount.PublicKey()).Build()

    // init token acount
    initAccountIt := token.NewInitializeAccount3Instruction(
        wallet.PublicKey(),
        tokenAccount.PublicKey(),
        mintAddress).Build()

    tx, err := solana.NewTransaction(
        []solana.Instruction{newAccountIt, initAccountIt},
        recentBlock.Value.Blockhash,
        solana.TransactionPayer(adminWallet.PublicKey()))
    if err != nil {
        panic(err)
    }

    _, err = tx.Sign(
        func(key solana.PublicKey) *solana.PrivateKey {
            if adminWallet.PublicKey().Equals(key) {
                return &adminWallet
            } else if tokenAccount.PublicKey().Equals(key) {
                return &tokenAccount.PrivateKey
            }
            return nil
        },
    )
    if err != nil {
        panic(fmt.Errorf("unable to sign transaction: %w", err))
    }
    spew.Dump(tx)

    fmt.Println("")
    fmt.Println("---------------------------------------------------- 1")
    fmt.Println("")

    tx.EncodeTree(text.NewTreeEncoder(os.Stdout, "Test Test"))
    sig, err := confirm.SendAndConfirmTransaction(
        context.TODO(),
        rpcClient,
        wsClient,
        tx,
    )

    fmt.Println("")
    fmt.Println("---------------------------------------------------- 2")
    fmt.Println("")

        // ⚠️⚠️⚠️ painc occurs here
    if err != nil {
        panic(err)
    }

    spew.Dump(sig)
}

func createAdminWallet() solana.PrivateKey {

    // create new Wallet
    wallet := solana.NewWallet()
    fmt.Println("Wallet private key:", wallet.PrivateKey)
    fmt.Println("Wallet public key:", wallet.PublicKey())

    client := rpc.New(rpc.DevNet_RPC)

    out, err := client.RequestAirdrop(
        context.TODO(),
        wallet.PublicKey(),
        solana.LAMPORTS_PER_SOL*1,
        rpc.CommitmentFinalized,
    )

    if err != nil {
        panic(err)
    }
    fmt.Println("airdrop transaction signature:", out)

    return wallet.PrivateKey
}

and log

Wallet private key: 5q9eqiAVcV2tsMz5pGMKjAS7SxwDjwg5cbEak9Cc9SmxbqWTdFpxUX4jmDMKBm1Yt86Lw761F9jBrRFGhzU8Eiq
Wallet public key: 7mB6CTCBT4PRADjdtxzahi5ip9j2Mez64zKQ5TBzAxHb
airdrop transaction signature: 2ZYCTiYTAWyTCWkpmade2yfSbpwSWnb6ip5KhHhFkJrYhpktwPRBmrwj2zdLC8H3cjY7QwNJtx6xXuBRY7RUHfGa
(*solana.Transaction)(0x1400013f7c0)(   
   ├─ Signatures[len=2]
   │    ├─ 2Ag2n6ND7FF517AsjJ7EUeAc3FYLDQtsaiFz2we4eHVeB7JzoVX3gjBRztxefAy34R1PqELVajRmgk6XkpkZNdjH
   │    └─ vcX3KL4D6qH6LGHhQ6n2ddz87mjzHBTJNqRYEChv9kiJ8aPBUhHnFadsR394jx4f3GhGaCsKt5rrgdLyNUJGggn
   ├─ Message
   │    ├─ Version: legacy
   │    ├─ RecentBlockhash: 57VLKHJWNSEVzBczxHu2nQsQbw3F9pzR8n24TMemiTNZ
   │    ├─ AccountKeys[len=5]
   │    │    ├─ 7mB6CTCBT4PRADjdtxzahi5ip9j2Mez64zKQ5TBzAxHb
   │    │    ├─ 3T9meJbuhCULVyTymx4ZimpSG7yd4bNLo1PWTxD6KQtY
   │    │    ├─ EJwZgeZrdC8TXTQbQBoL6bfuAnFUUy1PVCMB4DYPzVaS
   │    │    ├─ 11111111111111111111111111111111
   │    │    └─ TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA
   │    └─ Header
   │       ├─ NumRequiredSignatures: 2
   │       ├─ NumReadonlySignedAccounts: 0
   │       └─ NumReadonlyUnsignedAccounts: 3
   └─ Instructions[len=2]
      ├─ Program: System 11111111111111111111111111111111
      │    └─ Instruction: CreateAccount
      │       ├─ Params
      │       │    ├─ Lamports: (uint64) 1461600
      │       │    ├─    Space: (uint64) 82
      │       │    └─    Owner: (solana.PublicKey) (len=32 cap=32) 8eRKyruhrcGcRJuGDoqhex6Z4jbrRGDaYxHdHSDdpZmW
      │       └─ Accounts
      │          ├─ Funding: 7mB6CTCBT4PRADjdtxzahi5ip9j2Mez64zKQ5TBzAxHb [WRITE, SIGN] 
      │          └─     New: 3T9meJbuhCULVyTymx4ZimpSG7yd4bNLo1PWTxD6KQtY [WRITE, SIGN] 
      └─ Program: Token TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA
         └─ Instruction: InitializeAccount3
            ├─ Params
            │    └─ Owner: (solana.PublicKey) (len=32 cap=32) 8eRKyruhrcGcRJuGDoqhex6Z4jbrRGDaYxHdHSDdpZmW
            └─ Accounts
               ├─ account: 3T9meJbuhCULVyTymx4ZimpSG7yd4bNLo1PWTxD6KQtY [WRITE, SIGN] 
               └─    mint: EJwZgeZrdC8TXTQbQBoL6bfuAnFUUy1PVCMB4DYPzVaS [] 
)

---------------------------------------------------- 1

   Test Test
   ├─ Signatures[len=2]
   │    ├─ 2Ag2n6ND7FF517AsjJ7EUeAc3FYLDQtsaiFz2we4eHVeB7JzoVX3gjBRztxefAy34R1PqELVajRmgk6XkpkZNdjH
   │    └─ vcX3KL4D6qH6LGHhQ6n2ddz87mjzHBTJNqRYEChv9kiJ8aPBUhHnFadsR394jx4f3GhGaCsKt5rrgdLyNUJGggn
   ├─ Message
   │    ├─ Version: legacy
   │    ├─ RecentBlockhash: 57VLKHJWNSEVzBczxHu2nQsQbw3F9pzR8n24TMemiTNZ
   │    ├─ AccountKeys[len=5]
   │    │    ├─ 7mB6CTCBT4PRADjdtxzahi5ip9j2Mez64zKQ5TBzAxHb
   │    │    ├─ 3T9meJbuhCULVyTymx4ZimpSG7yd4bNLo1PWTxD6KQtY
   │    │    ├─ EJwZgeZrdC8TXTQbQBoL6bfuAnFUUy1PVCMB4DYPzVaS
   │    │    ├─ 11111111111111111111111111111111
   │    │    └─ TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA
   │    └─ Header
   │       ├─ NumRequiredSignatures: 2
   │       ├─ NumReadonlySignedAccounts: 0
   │       └─ NumReadonlyUnsignedAccounts: 3
   └─ Instructions[len=2]
      ├─ Program: System 11111111111111111111111111111111
      │    └─ Instruction: CreateAccount
      │       ├─ Params
      │       │    ├─ Lamports: (uint64) 1461600
      │       │    ├─    Space: (uint64) 82
      │       │    └─    Owner: (solana.PublicKey) (len=32 cap=32) 8eRKyruhrcGcRJuGDoqhex6Z4jbrRGDaYxHdHSDdpZmW
      │       └─ Accounts
      │          ├─ Funding: 7mB6CTCBT4PRADjdtxzahi5ip9j2Mez64zKQ5TBzAxHb [WRITE, SIGN] 
      │          └─     New: 3T9meJbuhCULVyTymx4ZimpSG7yd4bNLo1PWTxD6KQtY [WRITE, SIGN] 
      └─ Program: Token TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA
         └─ Instruction: InitializeAccount3
            ├─ Params
            │    └─ Owner: (solana.PublicKey) (len=32 cap=32) 8eRKyruhrcGcRJuGDoqhex6Z4jbrRGDaYxHdHSDdpZmW
            └─ Accounts
               ├─ account: 3T9meJbuhCULVyTymx4ZimpSG7yd4bNLo1PWTxD6KQtY [WRITE, SIGN] 
               └─    mint: EJwZgeZrdC8TXTQbQBoL6bfuAnFUUy1PVCMB4DYPzVaS [] 

---------------------------------------------------- 2

panic: (*jsonrpc.RPCError)(0x140004970e0)({
 Code: (int) -32002,
 Message: (string) (len=99) "Transaction simulation failed: Error processing Instruction 1: invalid account data for instruction",
 Data: (map[string]interface {}) (len=4) {
  (string) (len=8) "accounts": (interface {}) <nil>,
  (string) (len=3) "err": (map[string]interface {}) (len=1) {
   (string) (len=16) "InstructionError": ([]interface {}) (len=2 cap=2) {
    (json.Number) (len=1) "1",
    (string) (len=18) "InvalidAccountData"
   }
  },
  (string) (len=4) "logs": ([]interface {}) (len=7 cap=8) {
   (string) (len=51) "Program 11111111111111111111111111111111 invoke [1]",
   (string) (len=48) "Program 11111111111111111111111111111111 success",
   (string) (len=62) "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]",
   (string) (len=44) "Program log: Instruction: InitializeAccount3",
   (string) (len=38) "Program log: Error: InvalidAccountData",
   (string) (len=89) "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 1281 of 400000 compute units",
   (string) (len=96) "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA failed: invalid account data for instruction"
  },
  (string) (len=13) "unitsConsumed": (json.Number) (len=1) "0"
 }
})