VoteProgram.safeWithdraw function to safeguard against accidental vote account closures (#26586)

feat: safe withdraw function

Co-authored-by: aschonfeld <andrew@proofofalpha.io>
This commit is contained in:
Andrew Schonfeld 2022-08-16 18:22:38 -04:00 committed by GitHub
parent 74f487c828
commit 4b8ab4e65d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 0 deletions

View File

@ -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);
}
}

View File

@ -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,