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

Claim Rewards in buckets #644

Merged
merged 4 commits into from
May 8, 2024
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
20 changes: 10 additions & 10 deletions packages/spl-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
export * from './extendBorsh';
export * from './transaction';
export * from './anchorError';
export * from './executeRemoteTxn';
export * from './utils';
export * from './token';
export * from './constants';
export * from "./extendBorsh";
export * from "./transaction";
export * from "./anchorError";
export * from "./executeRemoteTxn";
export * from "./utils";
export * from "./token";
export * from "./constants";
export * from "./draft";

export type {
AssetProof,
Asset,
AssetsByOwnerOpts,
SearchAssetsOpts,
} from './mplAssetAPI';
} from "./mplAssetAPI";
export {
getAsset,
getAssets,
Expand All @@ -25,5 +25,5 @@ export {
} from "./mplAssetAPI";
export { estimatePrioritizationFee, withPriorityFees } from "./priorityFees";

export { proofArgsAndAccounts } from './proofArgsAndAccounts';
export type { ProofArgsAndAccountsArgs } from './proofArgsAndAccounts';
export { proofArgsAndAccounts } from "./proofArgsAndAccounts";
export type { ProofArgsAndAccountsArgs } from "./proofArgsAndAccounts";
30 changes: 30 additions & 0 deletions packages/spl-utils/src/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,36 @@ export async function batchParallelInstructions({
);
}

export async function batchSequentialParallelInstructions({
provider,
instructions,
onProgress,
triesRemaining = 10,
extraSigners = [],
maxSignatureBatch = TX_BATCH_SIZE,
addressLookupTableAddresses = [],
}: {
provider: AnchorProvider;
instructions: TransactionInstruction[][];
onProgress?: (status: Status) => void;
triesRemaining?: number; // Number of blockhashes to try resending txs with before giving up
extraSigners?: Keypair[];
maxSignatureBatch?: number;
addressLookupTableAddresses?: PublicKey[];
}): Promise<void> {
for (const instruction of instructions) {
await batchParallelInstructions({
provider,
instructions: instruction,
onProgress,
triesRemaining,
extraSigners,
maxSignatureBatch,
addressLookupTableAddresses,
});
}
}

export async function batchInstructionsToTxsWithPriorityFee(
provider: AnchorProvider,
// If passing an array of arrays, that indicates the instructions need to be run in the same tx,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { BN, Program } from "@coral-xyz/anchor";
import {
PROGRAM_ID as CIRCUIT_BREAKER_PROGRAM_ID,
accountWindowedBreakerKey,
} from "@helium/circuit-breaker-sdk";
import {
EPOCH_LENGTH,
PROGRAM_ID,
Expand All @@ -8,28 +12,32 @@ import {
subDaoEpochInfoKey,
} from "@helium/helium-sub-daos-sdk";
import {
PROGRAM_ID as CIRCUIT_BREAKER_PROGRAM_ID,
accountWindowedBreakerKey,
} from "@helium/circuit-breaker-sdk";
import { batchParallelInstructions, HNT_MINT, Status } from "@helium/spl-utils";
HNT_MINT,
Status,
batchSequentialParallelInstructions,
chunks,
} from "@helium/spl-utils";
import {
PROGRAM_ID as VSR_PROGRAM_ID,
isClaimed,
} from "@helium/voter-stake-registry-sdk";
import {
getAssociatedTokenAddressSync,
TOKEN_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
getAssociatedTokenAddressSync,
} from "@solana/spl-token";
import {
PublicKey,
SYSVAR_CLOCK_PUBKEY,
SystemProgram,
TransactionInstruction,
} from "@solana/web3.js";
import { useAsyncCallback } from "react-async-hook";
import { MAX_TRANSACTIONS_PER_SIGNATURE_BATCH } from "../constants";
import { useHeliumVsrState } from "../contexts/heliumVsrContext";
import { PositionWithMeta, SubDao } from "../sdk/types";
import { MAX_TRANSACTIONS_PER_SIGNATURE_BATCH } from "../constants";
import { PROGRAM_ID as VSR_PROGRAM_ID, isClaimed } from "@helium/voter-stake-registry-sdk";

const DAO = daoKey(HNT_MINT)[0];

export const useClaimAllPositionsRewards = () => {
const { provider, unixNow } = useHeliumVsrState();
const { error, loading, execute } = useAsyncCallback(
Expand Down Expand Up @@ -61,7 +69,10 @@ export const useClaimAllPositionsRewards = () => {
throw new Error("Unable to Claim All Rewards, Invalid params");
} else {
const currentEpoch = new BN(unixNow).div(new BN(EPOCH_LENGTH));
const multiDemArray: TransactionInstruction[][] = [];
const bucketedEpochsByPosition: Record<
string,
TransactionInstruction[][]
> = {};
const delegatedPositions = await Promise.all(
positions.map(async (p) => {
const key = delegatedPositionKey(p.pubkey)[0];
Expand All @@ -88,7 +99,8 @@ export const useClaimAllPositionsRewards = () => {

for (const [idx, position] of positions.entries()) {
const delegatedPosition = delegatedPositions[idx];
multiDemArray[idx] = multiDemArray[idx] || [];
bucketedEpochsByPosition[position.pubkey.toBase58()] =
bucketedEpochsByPosition[position.pubkey.toBase58()] || [];
const { lastClaimedEpoch, claimedEpochsBitmap } =
delegatedPosition.account;
const epoch = lastClaimedEpoch.add(new BN(1));
Expand All @@ -107,57 +119,76 @@ export const useClaimAllPositionsRewards = () => {
const subDaoStr = subDao.toBase58();
const subDaoAcc = subDaos[subDaoStr];

multiDemArray[idx].push(
...(await Promise.all(
epochsToClaim.map((epoch) =>
hsdProgram.methods
.claimRewardsV0({
epoch,
})
.accountsStrict({
position: position.pubkey,
mint: position.mint,
positionTokenAccount: getAssociatedTokenAddressSync(
position.mint,
provider.wallet.publicKey
),
positionAuthority: provider.wallet.publicKey,
registrar: position.registrar,
dao: DAO,
subDao: delegatedPosition.account.subDao,
delegatedPosition: delegatedPosition.key,
dntMint: subDaoAcc.dntMint,
subDaoEpochInfo: subDaoEpochInfoKey(subDao, epoch.mul(new BN(EPOCH_LENGTH)))[0],
delegatorPool: subDaoAcc.delegatorPool,
delegatorAta: getAssociatedTokenAddressSync(
subDaoAcc.dntMint,
provider.wallet.publicKey
),
delegatorPoolCircuitBreaker: accountWindowedBreakerKey(
subDaoAcc.delegatorPool
)[0],
vsrProgram: VSR_PROGRAM_ID,
systemProgram: SystemProgram.programId,
circuitBreakerProgram: CIRCUIT_BREAKER_PROGRAM_ID,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
tokenProgram: TOKEN_PROGRAM_ID,
})
.instruction()
// Chunk size is 128 because we want each chunk to correspond to the 128 bits in bitmap
for (const chunk of chunks(epochsToClaim, 128)) {
bucketedEpochsByPosition[position.pubkey.toBase58()].push(
await Promise.all(
chunk.map((epoch) =>
hsdProgram.methods
.claimRewardsV0({
epoch,
})
.accountsStrict({
position: position.pubkey,
mint: position.mint,
positionTokenAccount: getAssociatedTokenAddressSync(
position.mint,
provider.wallet.publicKey
),
positionAuthority: provider.wallet.publicKey,
registrar: position.registrar,
dao: DAO,
subDao: delegatedPosition.account.subDao,
delegatedPosition: delegatedPosition.key,
dntMint: subDaoAcc.dntMint,
subDaoEpochInfo: subDaoEpochInfoKey(
subDao,
epoch.mul(new BN(EPOCH_LENGTH))
)[0],
delegatorPool: subDaoAcc.delegatorPool,
delegatorAta: getAssociatedTokenAddressSync(
subDaoAcc.dntMint,
provider.wallet.publicKey
),
delegatorPoolCircuitBreaker: accountWindowedBreakerKey(
subDaoAcc.delegatorPool
)[0],
vsrProgram: VSR_PROGRAM_ID,
systemProgram: SystemProgram.programId,
circuitBreakerProgram: CIRCUIT_BREAKER_PROGRAM_ID,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
tokenProgram: TOKEN_PROGRAM_ID,
})
.instruction()
)
)
))
);
);
}
}

const multiDemArray = Object.entries(bucketedEpochsByPosition).reduce(
(acc, [_, instructions]) => {
instructions.map((ixs, idx) => {
acc[idx] = acc[idx] || [];
acc[idx].push(...ixs);
});
return acc;
},
[] as TransactionInstruction[][]
);

if (onInstructions) {
await onInstructions(multiDemArray.flat());
for (const ixs of multiDemArray) {
await onInstructions(ixs);
}
} else {
await batchParallelInstructions({
await batchSequentialParallelInstructions({
provider,
instructions: multiDemArray.flat(),
instructions: multiDemArray,
onProgress,
triesRemaining: 10,
extraSigners: [],
maxSignatureBatch
maxSignatureBatch,
});
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import {
delegatedPositionKey,
init,
} from "@helium/helium-sub-daos-sdk";
import { Status, batchParallelInstructions } from "@helium/spl-utils";
import {
Status,
batchSequentialParallelInstructions,
chunks,
} from "@helium/spl-utils";
import { isClaimed } from "@helium/voter-stake-registry-sdk";
import { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { useAsyncCallback } from "react-async-hook";
Expand Down Expand Up @@ -61,31 +65,40 @@ export const useClaimPositionRewards = () => {
})
);

const instructions: TransactionInstruction[] = await Promise.all(
epochsToClaim.map(
async (epoch) =>
await hsdProgram.methods
.claimRewardsV0({
epoch,
})
.accounts({
position: position.pubkey,
subDao: delegatedPosAcc.subDao,
})
.instruction()
)
);
const instructions: TransactionInstruction[][] = [];

// Chunk size is 128 because we want each chunk to correspond to the 128 bits in bitmap
for (const chunk of chunks(epochsToClaim, 128)) {
instructions.push(
await Promise.all(
chunk.map(
async (epoch) =>
await hsdProgram.methods
.claimRewardsV0({
epoch,
})
.accounts({
position: position.pubkey,
subDao: delegatedPosAcc.subDao,
})
.instruction()
)
)
);
}

if (onInstructions) {
await onInstructions(instructions);
for (const ixs of instructions) {
await onInstructions(ixs);
}
} else {
await batchParallelInstructions({
await batchSequentialParallelInstructions({
provider,
instructions,
onProgress,
triesRemaining: 10,
extraSigners: [],
maxSignatureBatch
maxSignatureBatch,
});
}
}
Expand Down
Loading