I want to use my pda as a vault.
Deposit function works fine, but withdraw doesn't
pub fn withdraw(ctx: Context<DepositWithdrawVault>, amount: u64) -> Result<()> {
let config = &mut ctx.accounts.config;
let recipient = &mut ctx.accounts.user;
if transfer_amount > config.balance {
return Err(errors::InsufficientBalance.into())
}
let transfer_sol = transfer( &config.key(), &recipient.key(), amount);
let required_accounts_for_transfer = [
config.to_account_info().clone(),
recipient.to_account_info().clone(),
ctx.accounts.system_program.to_account_info().clone()
];
invoke(
&transfer_sol,
&required_accounts_for_transfer,
)?;
config.balance -= transfer_amount;
Ok(())
// another solution is:
// // Debit from_account and credit to_account
// **from_account.try_borrow_mut_lamports()? -= amount_of_lamports;
// **to_account.try_borrow_mut_lamports()? += amount_of_lamports;
// but how to modify it?
}
and the test
initialize seed, bump and all that stuff
await program.methods.withdraw(1)
.accounts({
user: provider.wallet.publicKey,
config: config,
systemProgram: SystemProgram.programId,
}).rpc();
essentially, the error:
Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: Cross-program invocation with unauthorized signer or writable account
at Connection.sendEncodedTransaction (node_modules/@solana/web3.js/src/connection.ts:4480:13)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at Connection.sendRawTransaction (node_modules/@solana/web3.js/src/connection.ts:4439:20)
at sendAndConfirmRawTransaction (node_modules/@project-serum/anchor/src/provider.ts:288:21)
at AnchorProvider.sendAndConfirm (node_modules/@project-serum/anchor/src/provider.ts:148:14)
at MethodsBuilder.rpc [as _rpcFn] (node_modules/@project-serum/anchor/src/program/namespace/rpc.ts:29:16)