Skip to content

Commit

Permalink
VoteProgram.safeWithdraw function to safeguard against accidental vot…
Browse files Browse the repository at this point in the history
…e account closures (solana-labs#26586)

feat: safe withdraw function

Co-authored-by: aschonfeld <[email protected]>
  • Loading branch information
2 people authored and xiangzhu70 committed Aug 17, 2022
1 parent 44c7637 commit 7ad782f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
21 changes: 21 additions & 0 deletions web3.js/src/programs/vote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,4 +410,25 @@ export class VoteProgram {
data,
});
}

/**
* Generate a transaction to withdraw safely from a Vote account.
*
* This function was created as a safeguard for vote accounts running validators, `safeWithdraw`
* checks that the withdraw amount will not exceed the specified balance while leaving enough left
* to cover rent. If you wish to close the vote account by withdrawing the full amount, call the
* `withdraw` method directly.
*/
static safeWithdraw(
params: WithdrawFromVoteAccountParams,
currentVoteAccountBalance: number,
rentExemptMinimum: number,
): Transaction {
if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) {
throw new Error(
'Withdraw will leave vote account with insuffcient funds.',
);
}
return VoteProgram.withdraw(params);
}
}
15 changes: 15 additions & 0 deletions web3.js/test/program-tests/vote.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,21 @@ describe('VoteProgram', () => {

// Withdraw from Vote account
let recipient = Keypair.generate();
const voteBalance = await connection.getBalance(newVoteAccount.publicKey);

expect(() =>
VoteProgram.safeWithdraw(
{
votePubkey: newVoteAccount.publicKey,
authorizedWithdrawerPubkey: authorized.publicKey,
lamports: voteBalance - minimumAmount + 1,
toPubkey: recipient.publicKey,
},
voteBalance,
minimumAmount,
),
).to.throw('Withdraw will leave vote account with insuffcient funds.');

let withdraw = VoteProgram.withdraw({
votePubkey: newVoteAccount.publicKey,
authorizedWithdrawerPubkey: authorized.publicKey,
Expand Down

0 comments on commit 7ad782f

Please sign in to comment.