Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[solana] Fix bug dropping first checkpoint in castVote #227

Merged
merged 5 commits into from
Jan 10, 2025
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
2 changes: 1 addition & 1 deletion solana/app/StakeConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export class StakeConnection {
);
}

async sendAndConfirmAsVersionedTransaction(
public async sendAndConfirmAsVersionedTransaction(
instructions: TransactionInstruction[],
) {
const addressLookupTableAccount = this.addressLookupTable
Expand Down
8 changes: 3 additions & 5 deletions solana/programs/staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -524,18 +524,14 @@ pub mod staking {
);

let mut total_weight = window_start_checkpoint.value;

let mut checkpoint_index = window_start_checkpoint_index;

let mut checkpoint_index = window_start_checkpoint_index + 1;
let mut reading_from_next_account = false;

// The loop below is guaranteed to exit because:
// 1. It breaks when there are no more checkpoints in the current or next account.
// 2. It breaks when a checkpoint's timestamp exceeds the `vote_start` timestamp.
// This ensures that the loop will not run indefinitely
loop {
checkpoint_index += 1;

if !reading_from_next_account
&& (checkpoint_index as u32) == config.max_checkpoints_account_limit
{
Expand Down Expand Up @@ -604,6 +600,8 @@ pub mod staking {
if checkpoint.value < total_weight {
total_weight = checkpoint.value;
}

checkpoint_index += 1;
}
}

Expand Down
166 changes: 164 additions & 2 deletions solana/tests/api_test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import {
Keypair,
LAMPORTS_PER_SOL,
PublicKey,
SystemProgram,
Transaction,
TransactionInstruction,
} from "@solana/web3.js";
import assert from "assert";
import {
Expand Down Expand Up @@ -35,7 +37,10 @@ import {
QueryProxyMock,
signaturesToSolanaArray,
} from "@wormhole-foundation/wormhole-query-sdk";
import { AnchorError } from "@coral-xyz/anchor";
import { AnchorError, utils } from "@coral-xyz/anchor";
import * as importedWasm from "@wormhole/staking-wasm";
let wasm = importedWasm;
export { wasm };

const portNumber = getPortNumber(path.basename(__filename));

Expand Down Expand Up @@ -80,6 +85,7 @@ describe("api", async () => {
let user6StakeConnection: StakeConnection;
let user7StakeConnection: StakeConnection;
let user8StakeConnection: StakeConnection;
let user9StakeConnection: StakeConnection;

let controller;
let owner;
Expand All @@ -89,6 +95,7 @@ describe("api", async () => {
let user6;
let user7;
let user8;
let user9;
let delegate;

const confirm = async (signature: string): Promise<string> => {
Expand Down Expand Up @@ -186,7 +193,17 @@ describe("api", async () => {
whMintAuthority,
WHTokenBalance.fromString("1000"),
);
user8 = user7StakeConnection.provider.wallet.publicKey;
user8 = user8StakeConnection.provider.wallet.publicKey;

user9StakeConnection = await newUserStakeConnection(
stakeConnection,
Keypair.generate(),
config,
whMintAccount,
whMintAuthority,
WHTokenBalance.fromString("1000"),
);
user9 = user9StakeConnection.provider.wallet.publicKey;
});

it("postSignatures", async () => {
Expand Down Expand Up @@ -1279,6 +1296,151 @@ describe("api", async () => {
assert.equal(abstainVotes.toString(), "12");
});

it("should fail to castVote with zeroing out the first checkpoint in new checkpoint account", async () => {
// filling the checkpoint account to the limit
for (let i = 0; i < TEST_CHECKPOINTS_ACCOUNT_LIMIT - 1; i++) {
await sleep(1000);
await user9StakeConnection.delegate(
user9StakeConnection.userPublicKey(),
WHTokenBalance.fromString("5"),
);
}

let user9StakeAccountMetadataAddress =
await user9StakeConnection.getStakeMetadataAddress(
user9StakeConnection.userPublicKey(),
);
let previousUser9StakeAccountCheckpointsAddress =
await user9StakeConnection.getStakeAccountCheckpointsAddressByMetadata(
user9StakeAccountMetadataAddress,
false,
);
let user9StakeAccountCheckpointsAddress =
PublicKey.findProgramAddressSync(
[
utils.bytes.utf8.encode(wasm.Constants.CHECKPOINT_DATA_SEED()),
user9StakeConnection.userPublicKey().toBuffer(),
Buffer.from([1]),
],
user9StakeConnection.program.programId,
)[0];

let user6StakeAccountMetadataAddress =
await user6StakeConnection.getStakeMetadataAddress(
user6StakeConnection.userPublicKey(),
);
let user6StakeAccountCheckpointsAddress =
await user6StakeConnection.getStakeAccountCheckpointsAddressByMetadata(
user6StakeAccountMetadataAddress,
false,
);

await sleep(2000);
const instructions: TransactionInstruction[] = [];
instructions.push(
await user9StakeConnection.buildTransferInstruction(
user9StakeConnection.userPublicKey(),
WHTokenBalance.fromString("5").toBN(),
),
);
instructions.push(
await user9StakeConnection.program.methods
.delegate(
user9StakeConnection.userPublicKey(),
user9StakeConnection.userPublicKey(),
)
.accountsPartial({
currentDelegateStakeAccountCheckpoints:
previousUser9StakeAccountCheckpointsAddress,
delegateeStakeAccountCheckpoints:
previousUser9StakeAccountCheckpointsAddress,
vestingConfig: null,
vestingBalance: null,
mint: user9StakeConnection.config.votingTokenMint,
})
.instruction(),
);
instructions.push(
await user9StakeConnection.program.methods
.createCheckpoints()
.accounts({
payer: user9StakeConnection.userPublicKey(),
stakeAccountCheckpoints:
previousUser9StakeAccountCheckpointsAddress,
newStakeAccountCheckpoints: user9StakeAccountCheckpointsAddress,
stakeAccountMetadata: user9StakeAccountMetadataAddress,
})
.instruction(),
);
instructions.push(
await user9StakeConnection.program.methods
.delegate(
user6StakeConnection.userPublicKey(),
user9StakeConnection.userPublicKey(),
)
.accountsPartial({
currentDelegateStakeAccountCheckpoints:
user9StakeAccountCheckpointsAddress,
delegateeStakeAccountCheckpoints:
user6StakeAccountCheckpointsAddress,
vestingConfig: null,
vestingBalance: null,
mint: user9StakeConnection.config.votingTokenMint,
})
.instruction(),
);
await user9StakeConnection.sendAndConfirmAsVersionedTransaction(
instructions,
);

await sleep(2000);
await user9StakeConnection.delegate(
user9StakeConnection.userPublicKey(),
WHTokenBalance.fromString("150"),
);

let user9StakeAccountCheckpoints: CheckpointAccount =
await user9StakeConnection.fetchCheckpointAccount(
user9StakeAccountCheckpointsAddress,
);
assert.equal(
user9StakeAccountCheckpoints.checkpoints[0].value.toString(),
"0",
);
assert.equal(
user9StakeAccountCheckpoints.checkpoints[1].value.toString(),
"225000000",
);

let proposalIdInput = await addTestProposal(
user9StakeConnection,
Math.floor(Date.now() / 1000),
);
const { proposalAccount } =
await user9StakeConnection.fetchProposalAccount(proposalIdInput);

try {
await user9StakeConnection.program.methods
.castVote(
Array.from(proposalIdInput),
new BN(10),
new BN(20),
new BN(12),
0,
)
.accountsPartial({
proposal: proposalAccount,
voterCheckpoints: previousUser9StakeAccountCheckpointsAddress,
voterCheckpointsNext: user9StakeAccountCheckpointsAddress,
})
.rpc();

assert.fail("Expected an error but none was thrown");
} catch (e) {
assert((e as AnchorError).error?.errorCode?.code === "NoWeight");
}
});

it("should fail when castVote with an invalid voter checkpoints", async () => {
let proposalId = await addTestProposal(
user2StakeConnection,
Expand Down
Loading