How to send solana via my app in vanilla js?

354 Views Asked by At

Trying to do a simple send and receive function in Solana with vanilla JS.

Below is my send function that works fine, and now I want a receive function. Where the provider would get Solana transferred from my treasury wallet.

I'm not sure what approach I should have, just starting out. Is there a way to just move things around in this function? Or do I have to have a totally different approach?

Thanks!

async function transferSOL() {
  // Detecing and storing the phantom wallet of the user (creator in this case)
  var provider = phantom;

  // Establishing connection
  var connection = new web3.Connection(
    web3.clusterApiUrl('devnet'),
  );

  var transaction = new web3.Transaction().add(
    web3.SystemProgram.transfer({
      fromPubkey: provider.publicKey,
      toPubkey: treasuryWallet.publicKey,
      lamports: 0.1 * web3.LAMPORTS_PER_SOL - 100  
    }),
  );
  // Setting the variables for the transaction
  transaction.feePayer = await provider.publicKey;
  let blockhashObj = await connection.getRecentBlockhash();
  transaction.recentBlockhash = await blockhashObj.blockhash;

  // Request creator to sign the transaction (allow the transaction)
  let signed = await provider.signTransaction(transaction);
  let signature = await connection.sendRawTransaction(signed.serialize());
  await connection.confirmTransaction(signature);
}
1

There are 1 best solutions below

6
On

If you want to transfer from your treasury to the user, then you must sign for treasuryWallet somehow. In your case, it looks like you already have the keypair available to you in your app, so you can simply do:

var transaction = new web3.Transaction().add(
    web3.SystemProgram.transfer({
      toPubkey: provider.publicKey,
      fromPubkey: treasuryWallet.publicKey,
      lamports: 0.1 * web3.LAMPORTS_PER_SOL - 100  
    }),
  );
  // Setting the variables for the transaction
  transaction.feePayer = treasuryWallet.publicKey;
  let blockhashObj = await connection.getRecentBlockhash();
  transaction.recentBlockhash = await blockhashObj.blockhash;

  // Request creator to sign the transaction (allow the transaction)
  transaction.sign(treasuryWallet);
  let signature = await connection.sendRawTransaction(transaction.serialize());
  await connection.confirmTransaction(signature);

Note that this is very unsafe! Everyone who uses your web app has full access to the treasury funds if the keypair is exposed, since they can just sign all the transactions that they want with it.