SOL transfer

import { WalletContextState } from '@solana/wallet-adapter-react';
import {
  clusterApiUrl,
  Connection,
  PublicKey,
  SystemProgram,
  Transaction,
  TransactionInstruction,
} from '@solana/web3.js';

const transferNativeSol = async ({
  toPubkey,
  amount,
  payerPublicKey,
  connection,
  wallet,
}: {
  toPubkey: PublicKey;
  amount: number; payerPublicKey? : PublicKey; connection: Connection; wallet: WalletContextState; = > {})if(! payerPublicKey) {return console.error('error not connect wallet');
  }

  const instructions: TransactionInstruction[] = [];
  instructions.push(
    SystemProgram.transfer({
      fromPubkey: payerPublicKey,
      lamports: amount,
      toPubkey,
    }),
  );
  const transaction = new Transaction();

  instructions.forEach(instruction= > {
    transaction.add(instruction);
  });
  transaction.recentBlockhash = (
    await connection.getRecentBlockhash('max')
  ).blockhash;
  transaction.feePayer = payerPublicKey;
  const signedTransaction = await wallet.signTransaction(transaction);
  const tx = await connection.sendRawTransaction(
    signedTransaction.serialize(),
  );
  return tx
};
Copy the code

Test run example (wallet connection need their own connection oh)

const a = () = > {
  const solana = (window as any).solana;
  const connection = new Connection(clusterApiUrl('devnet'), 'recent');

  const toPubkey = new PublicKey(
    'FdU6FwgcDhqQGcpYtHwXg4T98YBT1SSiGinhzrPdEBr6',);const amount = 2;

  (window as any).test = async () => {
    transferNativeSol({
      payerPublicKey: solana.publicKey,
      toPubkey,
      amount: amount * 1e9,
      connection,
      wallet: solana as any}); }; };Copy the code

Scrip account transfer

Official Token source code

The official tutorial

This is a little more complicated, as only transfer is required above. Here, we need to judge whether the other party has the address of corresponding token. If there is an address with the most amount selected, if no corresponding account is created for him, the transfer will be made to him after completion.

In order to test, we need to have some tokens first, so we mint the tokens and give ourselves the permission to transfer some money to ourselves.

// TODO