Skip to content
This repository was archived by the owner on Jan 22, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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