UNPKG

test-raydium-sdk-v2

Version:

An SDK for building applications on top of Raydium.

1 lines 400 kB
{"version":3,"sources":["../../../src/raydium/farm/instruction.ts","../../../src/marshmallow/index.ts","../../../src/marshmallow/buffer-layout.ts","../../../src/common/pda.ts","../../../src/common/txTool/txUtils.ts","../../../src/common/logger.ts","../../../src/common/txTool/txType.ts","../../../src/common/bignumber.ts","../../../node_modules/decimal.js/decimal.mjs","../../../src/module/token.ts","../../../src/common/pubKey.ts","../../../src/raydium/token/constant.ts","../../../src/module/fraction.ts","../../../src/module/formatter.ts","../../../src/module/price.ts","../../../src/module/currency.ts","../../../src/module/amount.ts","../../../src/module/percent.ts","../../../src/common/utility.ts","../../../src/raydium/farm/config.ts","../../../src/common/programId.ts","../../../src/raydium/farm/layout.ts","../../../src/raydium/farm/pda.ts","../../../src/raydium/farm/util.ts","../../../src/common/accountInfo.ts","../../../src/common/txTool/txTool.ts","../../../src/common/txTool/lookupTable.ts","../../../src/common/transfer.ts","../../../src/raydium/account/layout.ts"],"sourcesContent":["import {\n PublicKey,\n SystemProgram,\n SYSVAR_RENT_PUBKEY,\n SYSVAR_CLOCK_PUBKEY,\n TransactionInstruction,\n Connection,\n} from \"@solana/web3.js\";\nimport {\n createAssociatedTokenAccountInstruction,\n TOKEN_PROGRAM_ID,\n ASSOCIATED_TOKEN_PROGRAM_ID,\n} from \"@solana/spl-token\";\nimport BN from \"bn.js\";\n\nimport { struct, u8, u64, u32, bool } from \"@/marshmallow\";\nimport { FormatFarmKeyOut } from \"@/api/type\";\nimport { getATAAddress } from \"@/common/pda\";\nimport { createLogger } from \"@/common/logger\";\nimport { parseBigNumberish } from \"@/common/bignumber\";\nimport {\n accountMeta,\n commonSystemAccountMeta,\n SOLMint,\n RENT_PROGRAM_ID,\n INSTRUCTION_PROGRAM_ID,\n} from \"@/common/pubKey\";\nimport { InstructionType } from \"@/common/txTool/txType\";\nimport { InstructionReturn } from \"../type\";\nimport {\n associatedLedgerAccountLayout,\n farmRewardLayout,\n withdrawRewardLayout,\n farmLedgerLayoutV3_2,\n farmAddRewardLayout,\n} from \"./layout\";\nimport { FarmRewardInfoConfig, RewardInfoKey, RewardType } from \"./type\";\nimport {\n getRegistrarAddress,\n getVotingTokenMint,\n getVotingMintAuthority,\n getVoterAddress,\n getVoterWeightRecordAddress,\n getTokenOwnerRecordAddress,\n} from \"./pda\";\nimport { dwLayout, farmRewardRestartLayout } from \"./layout\";\nimport { getAssociatedLedgerAccount, getDepositEntryIndex } from \"./util\";\nimport { poolTypeV6 } from \"./config\";\n\nconst logger = createLogger(\"Raydium_farm_instruction\");\n\nconst anchorDataBuf = {\n voterStakeRegistryCreateVoter: Buffer.from([6, 24, 245, 52, 243, 255, 148, 25]), // CreateVoter\n voterStakeRegistryCreateDepositEntry: Buffer.from([185, 131, 167, 186, 159, 125, 19, 67]), // CreateDepositEntry\n voterStakeRegistryDeposit: Buffer.from([242, 35, 198, 137, 82, 225, 242, 182]), // Deposit\n voterStakeRegistryWithdraw: Buffer.from([183, 18, 70, 156, 148, 109, 161, 34]), // Withdraw\n voterStakeRegistryUpdateVoterWeightRecord: Buffer.from([45, 185, 3, 36, 109, 190, 115, 169]), // UpdateVoterWeightRecord\n};\n\nexport function createAssociatedLedgerAccountInstruction(params: {\n version: number;\n id: PublicKey;\n programId: PublicKey;\n ledger: PublicKey;\n owner: PublicKey;\n}): InstructionReturn {\n const { version, id, ledger, programId, owner } = params;\n const instruction = { 3: 9, 5: 10 }[version];\n if (!instruction) logger.logWithError(`invalid farm pool version: ${version}`);\n\n const data = Buffer.alloc(associatedLedgerAccountLayout.span);\n associatedLedgerAccountLayout.encode(\n {\n instruction: instruction!,\n },\n data,\n );\n\n const keys = [\n accountMeta({ pubkey: id }),\n accountMeta({ pubkey: ledger }),\n accountMeta({ pubkey: owner, isWritable: false }),\n accountMeta({ pubkey: SystemProgram.programId, isWritable: false }),\n accountMeta({ pubkey: SYSVAR_RENT_PUBKEY, isWritable: false }),\n ];\n\n return {\n instruction: new TransactionInstruction({\n programId,\n keys,\n data,\n }),\n instructionType: InstructionType.FarmV3CreateLedger,\n };\n}\n\ninterface CreateFarmInstruction {\n farmId: PublicKey;\n farmAuthority: PublicKey;\n lpVault: PublicKey;\n lpMint: PublicKey;\n lockVault: PublicKey;\n lockMint: PublicKey;\n lockUserAccount?: PublicKey;\n programId: PublicKey;\n owner: PublicKey;\n rewardInfo: RewardInfoKey[];\n rewardInfoConfig: FarmRewardInfoConfig[];\n nonce: number;\n}\nexport function makeCreateFarmInstruction(params: CreateFarmInstruction): InstructionReturn {\n const data = Buffer.alloc(farmRewardLayout.span);\n farmRewardLayout.encode(\n {\n instruction: 0,\n nonce: new BN(params.nonce),\n rewardTimeInfo: params.rewardInfoConfig,\n },\n data,\n );\n\n const keys = [\n ...commonSystemAccountMeta,\n accountMeta({ pubkey: params.farmId }),\n accountMeta({ pubkey: params.farmAuthority, isWritable: false }),\n accountMeta({ pubkey: params.lpVault }),\n accountMeta({ pubkey: params.lpMint, isWritable: false }),\n accountMeta({ pubkey: params.lockVault }),\n accountMeta({ pubkey: params.lockMint, isWritable: false }),\n accountMeta({ pubkey: params.lockUserAccount ?? SOLMint }),\n accountMeta({ pubkey: params.owner, isWritable: false, isSigner: true }),\n ];\n\n for (const item of params.rewardInfo) {\n keys.push(\n ...[\n accountMeta({ pubkey: item.rewardMint, isWritable: false }),\n accountMeta({ pubkey: item.rewardVault }),\n accountMeta({ pubkey: item.userRewardToken }),\n ],\n );\n }\n\n return {\n instruction: new TransactionInstruction({ programId: params.programId, keys, data }),\n instructionType: InstructionType.FarmV6Create,\n };\n}\n\ninterface CreatorWithdrawFarmRewardInstruction {\n id: PublicKey;\n programId: PublicKey;\n authority: PublicKey;\n lpVault: PublicKey;\n rewardVault: PublicKey;\n userRewardToken: PublicKey;\n owner: PublicKey;\n}\n\nexport function makeCreatorWithdrawFarmRewardInstruction(\n params: CreatorWithdrawFarmRewardInstruction,\n): InstructionReturn {\n const data = Buffer.alloc(withdrawRewardLayout.span);\n withdrawRewardLayout.encode({ instruction: 5 }, data);\n\n const keys = [\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n accountMeta({ pubkey: params.id }),\n accountMeta({ pubkey: params.authority, isWritable: false }),\n accountMeta({ pubkey: params.lpVault, isWritable: false }),\n accountMeta({ pubkey: params.rewardVault }),\n accountMeta({ pubkey: params.userRewardToken }),\n accountMeta({ pubkey: params.owner, isWritable: false, isSigner: true }),\n ];\n\n return {\n instruction: new TransactionInstruction({ programId: params.programId, keys, data }),\n instructionType: InstructionType.FarmV6CreatorWithdraw,\n };\n}\n\nexport function voterStakeRegistryDeposit(\n programId: PublicKey,\n registrar: PublicKey,\n voter: PublicKey,\n voterVault: PublicKey,\n depositToken: PublicKey,\n depositAuthority: PublicKey,\n\n userStakerInfoV2: PublicKey,\n pool: PublicKey,\n votingMint: PublicKey,\n votingMintAuthority: PublicKey,\n stakeProgramId: PublicKey,\n\n depositEntryIndex: number,\n amount: BN,\n): TransactionInstruction {\n const dataLayout = struct([u8(\"depositEntryIndex\"), u64(\"amount\")]);\n\n const keys = [\n { pubkey: registrar, isSigner: false, isWritable: false },\n { pubkey: voter, isSigner: false, isWritable: true },\n { pubkey: voterVault, isSigner: false, isWritable: true },\n { pubkey: depositToken, isSigner: false, isWritable: true },\n { pubkey: depositAuthority, isSigner: false, isWritable: false },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n\n { pubkey: userStakerInfoV2, isSigner: false, isWritable: true },\n { pubkey: pool, isSigner: false, isWritable: false },\n { pubkey: votingMint, isSigner: false, isWritable: true },\n\n { pubkey: votingMintAuthority, isSigner: false, isWritable: false },\n { pubkey: stakeProgramId, isSigner: false, isWritable: false },\n { pubkey: INSTRUCTION_PROGRAM_ID, isSigner: false, isWritable: false },\n ];\n\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode(\n {\n depositEntryIndex,\n amount,\n },\n data,\n );\n const aData = Buffer.from([...anchorDataBuf.voterStakeRegistryDeposit, ...data]);\n\n return new TransactionInstruction({\n keys,\n programId,\n data: aData,\n });\n}\n\nexport function voterStakeRegistryUpdateVoterWeightRecord(\n programId: PublicKey,\n registrar: PublicKey,\n voter: PublicKey,\n voterWeightRecord: PublicKey,\n): TransactionInstruction {\n const dataLayout = struct([]);\n\n const keys = [\n { pubkey: registrar, isSigner: false, isWritable: false },\n { pubkey: voter, isSigner: false, isWritable: false },\n { pubkey: voterWeightRecord, isSigner: false, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ];\n\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode({}, data);\n const aData = Buffer.from([...anchorDataBuf.voterStakeRegistryUpdateVoterWeightRecord, ...data]);\n\n return new TransactionInstruction({\n keys,\n programId,\n data: aData,\n });\n}\n\nexport function voterStakeRegistryWithdraw(\n programId: PublicKey,\n registrar: PublicKey,\n voter: PublicKey,\n voterAuthority: PublicKey,\n tokenOwnerRecord: PublicKey,\n voterWeightRecord: PublicKey,\n vault: PublicKey,\n destination: PublicKey,\n\n userStakerInfoV2: PublicKey,\n pool: PublicKey,\n votingMint: PublicKey,\n votingMintAuthority: PublicKey,\n stakeProgramId: PublicKey,\n\n depositEntryIndex: number,\n amount: BN,\n): TransactionInstruction {\n const dataLayout = struct([u8(\"depositEntryIndex\"), u64(\"amount\")]);\n\n const keys = [\n { pubkey: registrar, isSigner: false, isWritable: false },\n { pubkey: voter, isSigner: false, isWritable: true },\n { pubkey: voterAuthority, isSigner: true, isWritable: false },\n { pubkey: tokenOwnerRecord, isSigner: false, isWritable: false },\n\n { pubkey: voterWeightRecord, isSigner: false, isWritable: true },\n { pubkey: vault, isSigner: false, isWritable: true },\n { pubkey: destination, isSigner: false, isWritable: true },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n\n { pubkey: userStakerInfoV2, isSigner: false, isWritable: true },\n { pubkey: pool, isSigner: false, isWritable: false },\n { pubkey: votingMint, isSigner: false, isWritable: true },\n\n { pubkey: votingMintAuthority, isSigner: false, isWritable: false },\n { pubkey: stakeProgramId, isSigner: false, isWritable: false },\n { pubkey: INSTRUCTION_PROGRAM_ID, isSigner: false, isWritable: false },\n ];\n\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode(\n {\n depositEntryIndex,\n amount,\n },\n data,\n );\n const aData = Buffer.from([...anchorDataBuf.voterStakeRegistryWithdraw, ...data]);\n\n return new TransactionInstruction({\n keys,\n programId,\n data: aData,\n });\n}\n\nexport function governanceCreateTokenOwnerRecord(\n programId: PublicKey,\n realm: PublicKey,\n governingTokenOwner: PublicKey,\n governingTokenMint: PublicKey,\n payer: PublicKey,\n tokenOwnerRecordAddress: PublicKey,\n): TransactionInstruction {\n const dataLayout = struct([u8(\"ins\")]);\n\n const keys = [\n { pubkey: realm, isSigner: false, isWritable: false },\n { pubkey: governingTokenOwner, isSigner: false, isWritable: false },\n\n { pubkey: tokenOwnerRecordAddress, isSigner: false, isWritable: true },\n\n { pubkey: governingTokenMint, isSigner: false, isWritable: false },\n\n { pubkey: payer, isSigner: true, isWritable: true },\n\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ];\n\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode({ ins: 23 }, data);\n\n return new TransactionInstruction({\n keys,\n programId,\n data,\n });\n}\n\nexport function voterStakeRegistryCreateVoter(\n programId: PublicKey,\n registrar: PublicKey,\n voter: PublicKey,\n voterWeightRecord: PublicKey,\n voterAuthority: PublicKey,\n payer: PublicKey,\n\n voterBump: number,\n voterWeightRecordBump: number,\n): TransactionInstruction {\n const dataLayout = struct([u8(\"voterBump\"), u8(\"voterWeightRecordBump\")]);\n\n const keys = [\n { pubkey: registrar, isSigner: false, isWritable: false },\n { pubkey: voter, isSigner: false, isWritable: true },\n { pubkey: voterAuthority, isSigner: true, isWritable: false },\n { pubkey: voterWeightRecord, isSigner: false, isWritable: true },\n { pubkey: payer, isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: INSTRUCTION_PROGRAM_ID, isSigner: false, isWritable: false },\n ];\n\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode({ voterBump, voterWeightRecordBump }, data);\n const aData = Buffer.from([...anchorDataBuf.voterStakeRegistryCreateVoter, ...data]);\n\n return new TransactionInstruction({\n keys,\n programId,\n data: aData,\n });\n}\n\nexport function voterStakeRegistryCreateDepositEntry(\n programId: PublicKey,\n registrar: PublicKey,\n voter: PublicKey,\n voterVault: PublicKey,\n voterAuthority: PublicKey,\n payer: PublicKey,\n depositMint: PublicKey,\n\n depositEntryIndex: number,\n kind: number,\n startTs: BN | undefined,\n periods: number,\n allowClawback: boolean,\n): TransactionInstruction {\n const dataLayout = struct([\n u8(\"depositEntryIndex\"),\n u8(\"kind\"),\n u8(\"option\"),\n u64(\"startTs\"),\n u32(\"periods\"),\n bool(\"allowClawback\"),\n ]);\n\n const keys = [\n { pubkey: registrar, isSigner: false, isWritable: false },\n { pubkey: voter, isSigner: false, isWritable: true },\n { pubkey: voterVault, isSigner: false, isWritable: true },\n { pubkey: voterAuthority, isSigner: true, isWritable: false },\n { pubkey: payer, isSigner: true, isWritable: true },\n { pubkey: depositMint, isSigner: false, isWritable: false },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n ];\n\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode(\n {\n depositEntryIndex,\n kind,\n option: startTs === undefined ? 0 : 1,\n startTs: startTs!,\n periods,\n allowClawback,\n },\n data,\n );\n const aData = Buffer.from([...anchorDataBuf.voterStakeRegistryCreateDepositEntry, ...data]);\n\n return new TransactionInstruction({\n keys,\n programId,\n data: aData,\n });\n}\n\nexport async function makeDepositTokenInstruction({\n connection,\n programId,\n governanceProgramId,\n voteWeightAddinProgramId,\n realm,\n communityTokenMint,\n owner,\n poolId,\n tokenProgram,\n}: {\n connection: Connection;\n programId: PublicKey;\n governanceProgramId: PublicKey;\n voteWeightAddinProgramId: PublicKey;\n realm: PublicKey;\n communityTokenMint: PublicKey;\n owner: PublicKey;\n poolId: PublicKey;\n tokenProgram?: PublicKey;\n}): Promise<TransactionInstruction[]> {\n const registrar = getRegistrarAddress(voteWeightAddinProgramId, realm, communityTokenMint).publicKey;\n const ownerPda = getAssociatedLedgerAccount({ programId, poolId, owner, version: 3 });\n const ownerAccountInfo = await connection.getAccountInfo(ownerPda);\n if (ownerAccountInfo === null) {\n throw Error(\"user is not staker\");\n }\n const ownerInfo = farmLedgerLayoutV3_2.decode(ownerAccountInfo.data);\n const mintAmount = ownerInfo.deposited.sub(ownerInfo.voteLockedBalance);\n console.log(\"amount\", mintAmount.toString());\n if (mintAmount.eq(new BN(0))) {\n throw Error(\"user do not has new stake amount\");\n }\n\n const votingMint = getVotingTokenMint(programId, poolId).publicKey;\n const votingMintAuthority = getVotingMintAuthority(programId, poolId).publicKey;\n const { publicKey: voter, nonce: voterBump } = getVoterAddress(voteWeightAddinProgramId, registrar, owner);\n const voterVault = getATAAddress(voter, votingMint, tokenProgram).publicKey;\n\n const { publicKey: voterWeightRecord, nonce: voterWeightRecordBump } = getVoterWeightRecordAddress(\n voteWeightAddinProgramId,\n registrar,\n owner,\n );\n\n const tokenOwnerRecordAddress = getTokenOwnerRecordAddress(\n governanceProgramId,\n realm,\n communityTokenMint,\n owner,\n ).publicKey;\n\n const instructions: TransactionInstruction[] = [];\n\n const depositToken = getATAAddress(owner, votingMint, tokenProgram).publicKey;\n const depositTokenAccountInfo = await connection.getAccountInfo(depositToken);\n if (depositTokenAccountInfo === null) {\n instructions.push(createAssociatedTokenAccountInstruction(owner, depositToken, owner, votingMint));\n }\n const voterAccountInfo = await connection.getAccountInfo(voter);\n if (voterAccountInfo === null) {\n const createTokenOwnerRecodeIns = governanceCreateTokenOwnerRecord(\n governanceProgramId,\n realm,\n owner,\n communityTokenMint,\n owner,\n tokenOwnerRecordAddress,\n );\n\n instructions.push(\n createTokenOwnerRecodeIns,\n voterStakeRegistryCreateVoter(\n voteWeightAddinProgramId,\n registrar,\n voter,\n voterWeightRecord,\n owner,\n owner,\n voterBump,\n voterWeightRecordBump,\n ),\n );\n }\n\n const { index: depositEntryIndex, isInit: depositEntryInit } = await getDepositEntryIndex(\n connection,\n registrar,\n voter,\n votingMint,\n );\n if (!depositEntryInit) {\n instructions.push(\n voterStakeRegistryCreateDepositEntry(\n voteWeightAddinProgramId,\n registrar,\n voter,\n voterVault,\n owner,\n owner,\n votingMint,\n\n depositEntryIndex,\n 0,\n undefined,\n 0,\n false,\n ),\n );\n }\n\n instructions.push(\n voterStakeRegistryDeposit(\n voteWeightAddinProgramId,\n registrar,\n voter,\n voterVault,\n depositToken,\n owner,\n\n ownerPda,\n poolId,\n votingMint,\n votingMintAuthority,\n programId,\n\n depositEntryIndex,\n mintAmount,\n ),\n voterStakeRegistryUpdateVoterWeightRecord(voteWeightAddinProgramId, registrar, voter, voterWeightRecord),\n );\n\n return instructions;\n}\n\nexport async function makeWithdrawTokenInstruction({\n connection,\n programId,\n governanceProgramId,\n voteWeightAddinProgramId,\n realm,\n communityTokenMint,\n owner,\n poolId,\n tokenProgram,\n}: {\n connection: Connection;\n programId: PublicKey;\n\n governanceProgramId: PublicKey;\n voteWeightAddinProgramId: PublicKey;\n realm: PublicKey;\n communityTokenMint: PublicKey;\n owner: PublicKey;\n poolId: PublicKey;\n tokenProgram?: PublicKey;\n}): Promise<TransactionInstruction[]> {\n const registrar = getRegistrarAddress(voteWeightAddinProgramId, realm, communityTokenMint).publicKey;\n const ownerPda = getAssociatedLedgerAccount({ programId, poolId, owner, version: 3 });\n const ownerAccountInfo = await connection.getAccountInfo(ownerPda);\n if (ownerAccountInfo === null) {\n throw Error(\"user is not staker\");\n }\n const ownerInfo = farmLedgerLayoutV3_2.decode(ownerAccountInfo.data);\n if (ownerInfo.voteLockedBalance.eq(new BN(0))) {\n throw Error(\"user has vote locked balance = 0\");\n }\n\n const votingMint = getVotingTokenMint(programId, poolId).publicKey;\n const votingMintAuthority = getVotingMintAuthority(programId, poolId).publicKey;\n const { publicKey: voter } = getVoterAddress(voteWeightAddinProgramId, registrar, owner);\n const voterVault = getATAAddress(voter, votingMint, tokenProgram).publicKey;\n const { publicKey: voterWeightRecord } = getVoterWeightRecordAddress(voteWeightAddinProgramId, registrar, owner);\n\n const tokenOwnerRecordAddress = getTokenOwnerRecordAddress(\n governanceProgramId,\n realm,\n communityTokenMint,\n owner,\n ).publicKey;\n\n const instructions: TransactionInstruction[] = [];\n\n const { index: depositEntryIndex, isInit: depositEntryInit } = await getDepositEntryIndex(\n connection,\n registrar,\n voter,\n votingMint,\n );\n if (!depositEntryInit) throw Error(\"deposit entry index check error\");\n\n instructions.push(\n voterStakeRegistryWithdraw(\n voteWeightAddinProgramId,\n registrar,\n voter,\n owner,\n tokenOwnerRecordAddress,\n voterWeightRecord,\n voterVault,\n getATAAddress(owner, votingMint, tokenProgram).publicKey,\n ownerPda,\n poolId,\n votingMint,\n votingMintAuthority,\n programId,\n\n depositEntryIndex,\n ownerInfo.voteLockedBalance,\n ),\n );\n\n return instructions;\n}\n\nexport function makeRestartRewardInstruction({\n payer,\n rewardVault,\n userRewardTokenPub,\n farmKeys,\n rewardInfo,\n}: {\n payer: PublicKey;\n rewardVault: PublicKey;\n userRewardTokenPub: PublicKey;\n farmKeys: {\n id: PublicKey;\n programId: PublicKey;\n lpVault: PublicKey;\n };\n rewardInfo: {\n openTime: number;\n endTime: number;\n perSecond: string;\n };\n}): TransactionInstruction {\n const data = Buffer.alloc(farmRewardRestartLayout.span);\n farmRewardRestartLayout.encode(\n {\n instruction: 3,\n rewardReopenTime: parseBigNumberish(rewardInfo.openTime),\n rewardEndTime: parseBigNumberish(rewardInfo.endTime),\n rewardPerSecond: parseBigNumberish(rewardInfo.perSecond),\n },\n data,\n );\n\n const keys = [\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n accountMeta({ pubkey: farmKeys.id }),\n accountMeta({ pubkey: farmKeys.lpVault, isWritable: false }),\n accountMeta({ pubkey: rewardVault }),\n accountMeta({ pubkey: userRewardTokenPub! }),\n accountMeta({ pubkey: payer, isWritable: false, isSigner: true }),\n ];\n\n return new TransactionInstruction({ programId: farmKeys.programId, keys, data });\n}\n\nexport function makeAddNewRewardInstruction({\n payer,\n userRewardTokenPub,\n farmKeys,\n rewardVault,\n rewardInfo,\n}: {\n payer: PublicKey;\n userRewardTokenPub: PublicKey;\n rewardVault: PublicKey;\n farmKeys: {\n id: PublicKey;\n programId: PublicKey;\n authority: PublicKey;\n };\n rewardInfo: {\n mint: PublicKey;\n openTime: number;\n endTime: number;\n perSecond: string;\n rewardType: RewardType;\n };\n}): TransactionInstruction {\n const data = Buffer.alloc(farmAddRewardLayout.span);\n farmAddRewardLayout.encode(\n {\n instruction: 4,\n isSet: new BN(1),\n rewardPerSecond: parseBigNumberish(rewardInfo.perSecond),\n rewardOpenTime: parseBigNumberish(rewardInfo.openTime),\n rewardEndTime: parseBigNumberish(rewardInfo.endTime),\n rewardType: parseBigNumberish(poolTypeV6[rewardInfo.rewardType]),\n },\n data,\n );\n\n const keys = [\n ...commonSystemAccountMeta,\n accountMeta({ pubkey: farmKeys.id }),\n accountMeta({ pubkey: farmKeys.authority, isWritable: false }),\n accountMeta({ pubkey: rewardInfo.mint, isWritable: false }),\n accountMeta({ pubkey: rewardVault }),\n accountMeta({ pubkey: userRewardTokenPub! }),\n accountMeta({ pubkey: payer, isWritable: false, isSigner: true }),\n ];\n\n return new TransactionInstruction({ programId: farmKeys.programId, keys, data });\n}\n\nexport function makeDepositWithdrawInstruction(params: {\n instruction: number;\n amount: BN;\n farmInfo: { id: string; programId: string };\n farmKeys: FormatFarmKeyOut;\n lpAccount: PublicKey;\n owner: PublicKey;\n rewardAccounts: PublicKey[];\n deposit?: boolean;\n version: 3 | 5 | 6;\n}): TransactionInstruction {\n const { farmInfo, farmKeys, version, lpAccount, rewardAccounts, owner, instruction, amount, deposit } = params;\n\n const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n const ledgerAddress = getAssociatedLedgerAccount({\n programId,\n poolId: id,\n owner,\n version,\n });\n\n const data = Buffer.alloc(dwLayout.span);\n dwLayout.encode(\n {\n instruction,\n amount,\n },\n data,\n );\n\n const keys =\n version === 6\n ? [\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n ...(deposit ? [accountMeta({ pubkey: SystemProgram.programId, isWritable: false })] : []),\n accountMeta({ pubkey: id }),\n accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n accountMeta({ pubkey: ledgerAddress }),\n accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n accountMeta({ pubkey: lpAccount }),\n ]\n : [\n accountMeta({ pubkey: id }),\n accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n accountMeta({ pubkey: ledgerAddress }),\n accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n accountMeta({ pubkey: lpAccount }),\n accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n accountMeta({ pubkey: rewardAccounts[0] }),\n accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[0].vault) }),\n // system\n accountMeta({ pubkey: SYSVAR_CLOCK_PUBKEY, isWritable: false }),\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n ];\n\n if (version === 5) {\n for (let index = 1; index < farmKeys.rewardInfos.length; index++) {\n keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n }\n }\n\n if (version === 6) {\n for (let index = 0; index < farmKeys.rewardInfos.length; index++) {\n keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n }\n }\n\n return new TransactionInstruction({ programId, keys, data });\n}\n\ninterface DepositWithdrawParams {\n amount: BN;\n farmInfo: { id: string; programId: string };\n farmKeys: FormatFarmKeyOut;\n lpAccount: PublicKey;\n owner: PublicKey;\n rewardAccounts: PublicKey[];\n userAuxiliaryLedgers?: PublicKey[];\n}\n\nexport function makeWithdrawInstructionV6(params: DepositWithdrawParams): TransactionInstruction {\n const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount } = params;\n const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n const ledgerAddress = getAssociatedLedgerAccount({\n programId,\n poolId: id,\n owner,\n version: 6,\n });\n\n const data = Buffer.alloc(dwLayout.span);\n dwLayout.encode(\n {\n instruction: 2,\n amount: parseBigNumberish(amount),\n },\n data,\n );\n\n const keys = [\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n\n accountMeta({ pubkey: id }),\n\n accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n accountMeta({ pubkey: ledgerAddress }),\n accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n accountMeta({ pubkey: lpAccount }),\n ];\n\n for (let index = 0; index < farmKeys.rewardInfos.length; index++) {\n keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n }\n\n return new TransactionInstruction({ programId, keys, data });\n}\n\nexport function makeWithdrawInstructionV5(params: DepositWithdrawParams): TransactionInstruction {\n const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount, userAuxiliaryLedgers } = params;\n const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n const ledgerAddress = getAssociatedLedgerAccount({\n programId,\n poolId: id,\n owner,\n version: 5,\n });\n\n const data = Buffer.alloc(dwLayout.span);\n dwLayout.encode(\n {\n instruction: 12,\n amount: parseBigNumberish(amount),\n },\n data,\n );\n\n const keys = [\n accountMeta({ pubkey: id }),\n accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n accountMeta({ pubkey: ledgerAddress }),\n accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n accountMeta({ pubkey: lpAccount }),\n accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n accountMeta({ pubkey: rewardAccounts[0] }),\n accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[0].vault) }),\n // system\n accountMeta({ pubkey: SYSVAR_CLOCK_PUBKEY, isWritable: false }),\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n ];\n\n for (let index = 1; index < farmKeys.rewardInfos.length; index++) {\n keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n }\n\n if (userAuxiliaryLedgers) {\n for (const auxiliaryLedger of userAuxiliaryLedgers) {\n keys.push(accountMeta({ pubkey: auxiliaryLedger }));\n }\n }\n\n return new TransactionInstruction({ programId, keys, data });\n}\n\nexport function makeWithdrawInstructionV3(params: DepositWithdrawParams): TransactionInstruction {\n const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount, userAuxiliaryLedgers } = params;\n const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n const ledgerAddress = getAssociatedLedgerAccount({\n programId,\n poolId: id,\n owner,\n version: 3,\n });\n\n const data = Buffer.alloc(dwLayout.span);\n dwLayout.encode(\n {\n instruction: 11,\n amount: parseBigNumberish(amount),\n },\n data,\n );\n\n const keys = [\n accountMeta({ pubkey: id }),\n accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n accountMeta({ pubkey: ledgerAddress }),\n accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n accountMeta({ pubkey: lpAccount }),\n accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n accountMeta({ pubkey: rewardAccounts[0] }),\n accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[0].vault) }),\n // system\n accountMeta({ pubkey: SYSVAR_CLOCK_PUBKEY, isWritable: false }),\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n ];\n\n if (userAuxiliaryLedgers) {\n for (const auxiliaryLedger of userAuxiliaryLedgers) {\n keys.push(accountMeta({ pubkey: auxiliaryLedger }));\n }\n }\n\n return new TransactionInstruction({ programId, keys, data });\n}\n\nexport function makeDepositInstructionV3(params: DepositWithdrawParams): TransactionInstruction {\n const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount, userAuxiliaryLedgers } = params;\n const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n const ledgerAddress = getAssociatedLedgerAccount({\n programId,\n poolId: id,\n owner,\n version: 3,\n });\n\n const data = Buffer.alloc(dwLayout.span);\n dwLayout.encode(\n {\n instruction: 10,\n amount: parseBigNumberish(amount),\n },\n data,\n );\n\n const keys = [\n accountMeta({ pubkey: id }),\n accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n accountMeta({ pubkey: ledgerAddress }),\n accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n accountMeta({ pubkey: lpAccount }),\n accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n accountMeta({ pubkey: rewardAccounts[0] }),\n accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[0].vault) }),\n // system\n accountMeta({ pubkey: SYSVAR_CLOCK_PUBKEY, isWritable: false }),\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n ];\n\n if (userAuxiliaryLedgers) {\n for (const auxiliaryLedger of userAuxiliaryLedgers) {\n keys.push(accountMeta({ pubkey: auxiliaryLedger }));\n }\n }\n\n return new TransactionInstruction({ programId, keys, data });\n}\n\nexport function makeDepositInstructionV5(params: DepositWithdrawParams): TransactionInstruction {\n const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount, userAuxiliaryLedgers } = params;\n const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n const ledgerAddress = getAssociatedLedgerAccount({\n programId,\n poolId: id,\n owner,\n version: 5,\n });\n\n const data = Buffer.alloc(dwLayout.span);\n dwLayout.encode(\n {\n instruction: 11,\n amount: parseBigNumberish(amount),\n },\n data,\n );\n\n const keys = [\n accountMeta({ pubkey: id }),\n accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n accountMeta({ pubkey: ledgerAddress }),\n accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n accountMeta({ pubkey: lpAccount }),\n accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n accountMeta({ pubkey: rewardAccounts[0] }),\n accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[0].vault) }),\n // system\n accountMeta({ pubkey: SYSVAR_CLOCK_PUBKEY, isWritable: false }),\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n ];\n\n for (let index = 1; index < farmKeys.rewardInfos.length; index++) {\n keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n }\n\n if (userAuxiliaryLedgers) {\n for (const auxiliaryLedger of userAuxiliaryLedgers) {\n keys.push(accountMeta({ pubkey: auxiliaryLedger }));\n }\n }\n\n return new TransactionInstruction({ programId, keys, data });\n}\n\nexport function makeDepositInstructionV6(params: DepositWithdrawParams): TransactionInstruction {\n const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount } = params;\n const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n const ledgerAddress = getAssociatedLedgerAccount({\n programId,\n poolId: id,\n owner,\n version: 6,\n });\n\n const data = Buffer.alloc(dwLayout.span);\n dwLayout.encode(\n {\n instruction: 1,\n amount: parseBigNumberish(amount),\n },\n data,\n );\n\n const keys = [\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n accountMeta({ pubkey: SystemProgram.programId, isWritable: false }),\n accountMeta({ pubkey: id }),\n accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n accountMeta({ pubkey: ledgerAddress }),\n accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n accountMeta({ pubkey: lpAccount }),\n ];\n\n for (let index = 0; index < farmKeys.rewardInfos.length; index++) {\n keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n }\n\n return new TransactionInstruction({ programId, keys, data });\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport BN, { isBN } from \"bn.js\";\n\nimport {\n bits,\n blob,\n Blob,\n Layout,\n offset as _offset,\n seq as _seq,\n Structure as _Structure,\n u32 as _u32,\n u8 as _u8,\n UInt,\n union as _union,\n Union as _Union,\n} from \"./buffer-layout\";\n\nexport * from \"./buffer-layout\";\nexport { blob };\n\nexport class BNLayout<P extends string = \"\"> extends Layout<BN, P> {\n blob: Layout<Buffer>;\n signed: boolean;\n\n constructor(span: number, signed: boolean, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends, but it desn't matter\n super(span, property);\n this.blob = blob(span);\n this.signed = signed;\n }\n\n /** @override */\n decode(b: Buffer, offset = 0): BN {\n const num = new BN(this.blob.decode(b, offset), 10, \"le\");\n if (this.signed) {\n return num.fromTwos(this.span * 8).clone();\n }\n return num;\n }\n\n /** @override */\n encode(src: BN, b: Buffer, offset = 0): number {\n if (typeof src === \"number\") src = new BN(src); // src will pass a number accidently in union\n if (this.signed) {\n src = src.toTwos(this.span * 8);\n }\n return this.blob.encode(src.toArrayLike(Buffer, \"le\", this.span), b, offset);\n }\n}\n\nexport class WideBits<P extends string = \"\"> extends Layout<Record<string, boolean>, P> {\n _lower: any;\n _upper: any;\n // TODO: unknown\n constructor(property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(8, property);\n this._lower = bits(_u32(), false);\n this._upper = bits(_u32(), false);\n }\n\n addBoolean(property: string): void {\n if (this._lower.fields.length < 32) {\n this._lower.addBoolean(property);\n } else {\n this._upper.addBoolean(property);\n }\n }\n\n decode(b: Buffer, offset = 0): Record<string, boolean> {\n const lowerDecoded = this._lower.decode(b, offset);\n const upperDecoded = this._upper.decode(b, offset + this._lower.span);\n return { ...lowerDecoded, ...upperDecoded };\n }\n\n encode(src: any /* TEMP */, b: Buffer, offset = 0): any {\n return this._lower.encode(src, b, offset) + this._upper.encode(src, b, offset + this._lower.span);\n }\n}\n\nexport function u8<P extends string = \"\">(property?: P): UInt<number, P> {\n return new UInt(1, property);\n}\n\nexport function u32<P extends string = \"\">(property?: P): UInt<number, P> {\n return new UInt(4, property);\n}\n\nexport function u64<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(8, false, property);\n}\n\nexport function u128<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(16, false, property);\n}\n\nexport function i8<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(1, true, property);\n}\n\nexport function i64<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(8, true, property);\n}\n\nexport function i128<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(16, true, property);\n}\n\nexport class WrappedLayout<T, U, P extends string = \"\"> extends Layout<U, P> {\n layout: Layout<T>;\n decoder: (data: T) => U;\n encoder: (src: U) => T;\n\n constructor(layout: Layout<T>, decoder: (data: T) => U, encoder: (src: U) => T, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(layout.span, property);\n this.layout = layout;\n this.decoder = decoder;\n this.encoder = encoder;\n }\n\n decode(b: Buffer, offset?: number): U {\n return this.decoder(this.layout.decode(b, offset));\n }\n\n encode(src: U, b: Buffer, offset?: number): number {\n return this.layout.encode(this.encoder(src), b, offset);\n }\n\n getSpan(b: Buffer, offset?: number): number {\n return this.layout.getSpan(b, offset);\n }\n}\n\nexport function publicKey<P extends string = \"\">(property?: P): Layout<PublicKey, P> {\n return new WrappedLayout(\n blob(32),\n (b: Buffer) => new PublicKey(b),\n (key: PublicKey) => key.toBuffer(),\n property,\n );\n}\n\nexport class OptionLayout<T, P> extends Layout<T | null, P> {\n layout: Layout<T>;\n discriminator: Layout<number>;\n\n constructor(layout: Layout<T>, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(-1, property);\n this.layout = layout;\n this.discriminator = _u8();\n }\n\n encode(src: T | null, b: Buffer, offset = 0): number {\n if (src === null || src === undefined) {\n return this.discriminator.encode(0, b, offset);\n }\n this.discriminator.encode(1, b, offset);\n return this.layout.encode(src, b, offset + 1) + 1;\n }\n\n decode(b: Buffer, offset = 0): T | null {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return null;\n } else if (discriminator === 1) {\n return this.layout.decode(b, offset + 1);\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n\n getSpan(b: Buffer, offset = 0): number {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return 1;\n } else if (discriminator === 1) {\n return this.layout.getSpan(b, offset + 1) + 1;\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n}\n\nexport function option<T, P extends string = \"\">(layout: Layout<T>, property?: P): Layout<T | null, P> {\n return new OptionLayout<T, P>(layout, property);\n}\n\nexport function bool<P extends string = \"\">(property?: P): Layout<boolean, P> {\n return new WrappedLayout(_u8(), decodeBool, encodeBool, property);\n}\n\nexport function decodeBool(value: number): boolean {\n if (value === 0) {\n return false;\n } else if (value === 1) {\n return true;\n }\n throw new Error(\"Invalid bool: \" + value);\n}\n\nexport function encodeBool(value: boolean): number {\n return value ? 1 : 0;\n}\n\nexport function vec<T, P extends string = \"\">(elementLayout: Layout<T>, property?: P): Layout<T[], P> {\n const length = _u32(\"length\");\n const layout: Layout<{ values: T[] }> = struct([\n length,\n seq(elementLayout, _offset(length, -length.span), \"values\"),\n ]) as any; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ values }) => values,\n (values) => ({ values }),\n property,\n );\n}\n\nexport function tagged<T, P extends string = \"\">(tag: BN, layout: Layout<T>, property?: P): Layout<T, P> {\n const wrappedLayout: Layout<{ tag: BN; data: T }> = struct([u64(\"tag\"), layout.replicate(\"data\")]) as any; // Something I don't know\n\n function decodeTag({ tag: receivedTag, data }: { tag: BN; data: T }): T {\n if (!receivedTag.eq(tag)) {\n throw new Error(\"Invalid tag, expected: \" + tag.toString(\"hex\") + \", got: \" + receivedTag.toString(\"hex\"));\n }\n return data;\n }\n\n return new WrappedLayout(wrappedLayout, decodeTag, (data) => ({ tag, data }), property);\n}\n\nexport function vecU8<P extends string = \"\">(property?: P): Layout<Buffer, P> {\n const length = _u32(\"length\");\n const layout: Layout<{ data: Buffer }> = struct([length, blob(_offset(length, -length.span), \"data\")]) as any; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ data }) => data,\n (data) => ({ data }),\n property,\n );\n}\n\nexport function str<P extends string = \"\">(property?: P): Layout<string, P> {\n return new WrappedLayout(\n vecU8(),\n (data) => data.toString(\"utf-8\"),\n (s) => Buffer.from(s, \"utf-8\"),\n property,\n );\n}\n\nexport interface EnumLayout<T, P extends string = \"\"> extends Layout<T, P> {\n registry: Record<string, Layout<any>>;\n}\n\nexport function rustEnum<T, P extends string = \"\">(variants: Layout<any>[], property?: P): EnumLayout<T, P> {\n const unionLayout = _union(_u8(), property);\n variants.forEach((variant, index) => unionLayout.addVariant(index, variant, variant.property));\n return unionLayout as any; // ?why use UnionLayout? This must be a fault\n}\n\nexport function array<T, P extends string = \"\">(\n elementLayout: Layout<T>,\n length: number,\n property?: P,\n): Layout<T[], P> {\n const layout = struct([seq(elementLayout, length, \"values\")]) as any as Layout<{ values: T[] }>; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ values }) => values,\n (values) => ({ values }),\n property,\n );\n}\n\nexport class Structure<T, P, D> extends _Structure<T, P, D> {\n /** @override */\n decode(b: Buffer, offset?: number): D {\n return super.decode(b, offset);\n }\n}\n\nexport function struct<T, P extends string = \"\">(\n fields: T,\n property?: P,\n decodePrefixes?: boolean,\n): T extends Layout<infer Value, infer Property>[]\n ? Structure<\n Value,\n P,\n {\n [K in Exclude<Extract<Property, string>, \"\">]: Extract<T[number], Layout<any, K>> extends Layout<infer V, any>\n ? V\n : any;\n }\n >\n : any {\n //@ts-expect-error this type is not quite satisfied the define, but, never no need to worry about.\n return new Structure(fields, property, decodePrefixes);\n}\n\nexport type GetLayoutSchemaFromStructure<T extends Structure<any, any, any>> = T extends Structure<any, any, infer S>\n ? S\n : any;\nexport type GetStructureFromLayoutSchema<S> = Structure<any, any, S>;\n\nexport class Union<Schema> extends _Union<Schema> {\n encodeInstruction(instruction: any): Buffer {\n const instructionMaxSpan = Math.max(...Object.values(this.registry).map((r) => r.span));\n const b = Buffer.alloc(instructionMaxSpan);\n return b.slice(0, this.encode(instruction, b));\n }\n\n decodeInstruction(instruction: any): Partial<Schema> {\n return this.decode(instruction);\n }\n}\nexport function union<UnionSchema extends { [key: string]: any } = any>(\n discr: any,\n defaultLayout?: any,\n property?: string,\n): Union<UnionSchema> {\n return new Union(discr, defaultLayout, property);\n}\n\nclass Zeros extends Blob {\n decode(b: Buffer, offset: number): Buffer {\n const slice = super.decode(b, offset);\n if (!slice.every((v) => v === 0)) {\n throw new Error(\"nonzero padding bytes\");\n }\n return slice;\n }\n}\n\nexport function zeros(length: number): Zeros {\n return new Zeros(length);\n}\n\nexport function seq<T, P extends string = \"\", AnotherP extends string = \"\">(\n elementLayout: Layout<T, P>,\n count: number | BN | Layout<BN | number, P>,\n property?: AnotherP,\n): Layout<T[], AnotherP> {\n let parsedCount: number;\n const superCount =\n typeof count === \"number\"\n ? count\n : isBN(count)\n ? count.toNumber()\n : new Proxy(count as unknown as Layout<number> /* pretend to be Layout<number> */, {\n get(target, property): any {\n if (!parsedCount) {\n // get count in targetLayout. note that count may be BN\n const countProperty = Reflect.get(target, \"count\");\n\n // let targetLayout's property:count be a number\n parsedCount = isBN(countProperty) ? countProperty.toNumber() : countProperty;\n\n // record the count\n Reflect.set(target, \"count\", parsedCount);\n }\n return Reflect.get(target, property);\n },\n set(target, property, value): any {\n if (property === \"count\") {\n parsedCount = value;\n }\n return Reflect.set(target, property, value);\n },\n });\n\n // @ts-expect-error force type\n return _seq(elementLayout, superCount, property);\n}\n","import {\n bits as _bits,\n BitStructure as _BitStructure,\n blob as _blob,\n Blob as _Blob,\n cstr as _cstr,\n f32 as _f32,\n f32be as _f32be,\n f64 as _f64,\n f64be as _f64be,\n greedy as _greedy,\n Layout as _Layout,\n ns64 as _ns64,\n ns64be as _ns64be,\n nu64 as _nu64,\n nu64be as _nu64be,\n offset as _offset,\n s16 as _s16,\n s16be as _s16be,\n s24 as _s24,\n s24be as _s24be,\n s32 as _s32,\n s32be as _s32be,\n s40 as _s40,\n s40be as _s40be,\n s48 as _s48,\n s48be as _s48be,\n s8 as _s8,\n seq as _seq,\n struct as _struct,\n Structure as _Structure,\n u16 as _u16,\n u16be as _u16be,\n u24 as _u24,\n u24be as _u24be,\n u32 as _u32,\n u32be as _u32be,\n u40 as _u40,\n u40be as _u40be,\n u48 as _u48,\n u48be as _u48be,\n u8 as _u8,\n UInt as _UInt,\n union as _union,\n Union as _Union,\n unionLayoutDiscriminator as _unionLayoutDiscriminator,\n utf8 as _utf8,\n} from \"@solana/buffer-layout\";\n\n//#region ------------------- Layout -------------------\nexport interface Layout<T = any, P = \"\"> {\n span: number;\n property?: P;\n decode(b: Buffer, offset?: number): T;\n encode(src: T, b: Buffer, offset?: number): number;\n getSpan(b: Buffer, offset?: number): number;\n replicate<AP extends string>(name: AP): Layout<T, AP>;\n}\nexport interface LayoutConstructor {\n new <T, P>(): Layout<T, P>; // for class extends syntex\n new <T, P>(span?: T, property?: P): Layout<T, P>;\n readonly prototype: Layout;\n}\nexport const Layout = _Layout as unknown as LayoutConstructor;\n//#endregion\n\n//#region ------------------- Structure -------------------\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface Structure<T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>\n extends Layout<DecodeSchema, P> {\n span: number;\n decode(b: Buffer, offset?: number): DecodeSchema;\n layoutFor<AP extends string>(property: AP): Layout<DecodeSchema[AP]>;\n offsetOf<AP extends string>(property: AP): number;\n}\ninterface StructureConstruc