Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created January 14, 2022 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save topherPedersen/e5e73043d3001b20155a6a3a88a6210d to your computer and use it in GitHub Desktop.
Save topherPedersen/e5e73043d3001b20155a6a3a88a6210d to your computer and use it in GitHub Desktop.
Solana 101: Transfering Funds (From Figment.io's Solana 101 Course)
import type {NextApiRequest, NextApiResponse} from 'next';
import {getNodeURL} from '@figment-solana/lib';
import {
Connection,
PublicKey,
SystemProgram,
Transaction,
sendAndConfirmTransaction,
} from '@solana/web3.js';
export default async function transfer(
req: NextApiRequest,
res: NextApiResponse<string>,
) {
try {
const {address, secret, recipient, lamports, network} = req.body;
const url = getNodeURL(network);
const connection = new Connection(url, 'confirmed');
const fromPubkey = new PublicKey(address);
const toPubkey = new PublicKey(recipient);
// The secret key is stored in our state as a stringified array
const secretKey = Uint8Array.from(JSON.parse(secret as string));
//... let's skip the beginning as it should be familiar for you by now!
// Find the parameter to pass
const instructions = SystemProgram.transfer({
fromPubkey,
toPubkey,
lamports,
});
// How could you construct a signer array's
const signers = [
{
publicKey: fromPubkey,
secretKey,
},
];
// Maybe adding something to a Transaction could be interesting ?
const transaction = new Transaction().add(instructions);
// We can send and confirm a transaction in one row.
const hash = await sendAndConfirmTransaction(connection, transaction, signers);
res.status(200).json(hash);
} catch (error) {
let errorMessage = error instanceof Error ? error.message : 'Unknown Error';
res.status(500).json(errorMessage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment