Search code examples
blockchainsolanasolana-web3js

solana@web3.js / program transfer


I'm trying to have a simple program written in Solana that, on user approval, runs and transfers a given amount of SOL into the program's owner account.

From JS side I've this based on the HelloWorld example from Solana repo

        ...
        const secretKeyString = await fs.readFile(filePath, {encoding: 'utf8'});
        const secretKey = Uint8Array.from(JSON.parse(secretKeyString))
        const keypair = Keypair.fromSecretKey(secretKey)

        const instruction = new TransactionInstruction({
            keys: [
              {pubkey: publicKey, isSigner: false, isWritable: true}, // from wallet
              {pubkey: keypair.publicKey, isSigner: false, isWritable: true} // from json file, program owner
            ],
            programId,
            data: Buffer.alloc(0)
          });

        const transaction = new Transaction().add(instruction);
        signature = await sendTransaction(transaction, connection);
        //toast('Transaction Sent');

On the program side I've simple used an example in a C example from Solana repo (no edit) - therefore assume all is good

/**
 * @brief A program demonstrating the transfer of lamports
 */
#include <solana_sdk.h>

extern uint64_t transfer(SolParameters *params) {
  // As part of the program specification the first account is the source
  // account and the second is the destination account
  if (params->ka_num != 2) {
    return ERROR_NOT_ENOUGH_ACCOUNT_KEYS;
  }
  SolAccountInfo *source_info = &params->ka[0];
  SolAccountInfo *destination_info = &params->ka[1];

  // Withdraw five lamports from the source
  *source_info->lamports -= 100000000;
  // Deposit five lamports into the destination
  *destination_info->lamports += 100000000;

  return SUCCESS;
}

extern uint64_t entrypoint(const uint8_t *input) {
  SolAccountInfo accounts[2];
  SolParameters params = (SolParameters){.ka = accounts};

  if (!sol_deserialize(input, &params, SOL_ARRAY_SIZE(accounts))) {
    return ERROR_INVALID_ARGUMENT;
  }

  return transfer(&params);
}

However this keeps failing with error ´-32003 Transaction creation failed.`


Solution

  • The system level SOL transfer has a constraint that the from PublicKey must be a system owned account. This means accounts owned by programs or PDA will fail as they are owned by your program. https://solanacookbook.com/references/accounts.html#transfer

    The transfer of lamports that your code shows can only happen if the from PublicKey is a program owned account. https://solanacookbook.com/references/programs.html#transferring-lamports