From fda8cdedcc1663bd719fcd9c0952dfe7d1f484c5 Mon Sep 17 00:00:00 2001 From: Paul Contreras <83374367+pol-cova@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:48:08 -0600 Subject: [PATCH] fix(realloc): handle already funded accounts Transfer rent only when the account needs more lamports. Keep the payer signature check when skipping transfers. This prevents subtraction overflow on overfunded accounts and avoids unnecessary transfers. --- .../program/src/instructions/reallocate.rs | 18 ++- basics/realloc/native/tests/realloc.test.ts | 104 ++++++++++++++- .../program/src/instructions/reallocate.rs | 11 +- .../realloc/pinocchio/tests/realloc.test.ts | 119 +++++++++++++++--- 4 files changed, 225 insertions(+), 27 deletions(-) diff --git a/basics/realloc/native/program/src/instructions/reallocate.rs b/basics/realloc/native/program/src/instructions/reallocate.rs index 84c5b35c6..91391996e 100644 --- a/basics/realloc/native/program/src/instructions/reallocate.rs +++ b/basics/realloc/native/program/src/instructions/reallocate.rs @@ -2,7 +2,7 @@ use borsh::{BorshDeserialize, BorshSerialize}; use { solana_account_info::{next_account_info, AccountInfo}, solana_cpi::invoke, - solana_program_error::ProgramResult, + solana_program_error::{ProgramError, ProgramResult}, solana_sysvar::{rent::Rent, Sysvar}, }; @@ -14,17 +14,23 @@ pub fn reallocate_without_zero_init(accounts: &[AccountInfo], args: EnhancedAddr let payer = next_account_info(accounts_iter)?; let system_program = next_account_info(accounts_iter)?; + if !payer.is_signer { + return Err(ProgramError::MissingRequiredSignature); + } + let address_info_data = AddressInfo::try_from_slice(&target_account.data.borrow())?; let enhanced_address_info_data = EnhancedAddressInfo::from_address_info(address_info_data, args.state, args.zip); let account_span = borsh::to_vec(&enhanced_address_info_data)?.len(); let lamports_required = (Rent::get()?).minimum_balance(account_span); - let diff = lamports_required - target_account.lamports(); - invoke( - &solana_system_interface::instruction::transfer(payer.key, target_account.key, diff), - &[payer.clone(), target_account.clone(), system_program.clone()], - )?; + let rent_shortfall = lamports_required.saturating_sub(target_account.lamports()); + if rent_shortfall > 0 { + invoke( + &solana_system_interface::instruction::transfer(payer.key, target_account.key, rent_shortfall), + &[payer.clone(), target_account.clone(), system_program.clone()], + )?; + } target_account.resize(account_span)?; diff --git a/basics/realloc/native/tests/realloc.test.ts b/basics/realloc/native/tests/realloc.test.ts index 4f73711fe..ef65504f6 100644 --- a/basics/realloc/native/tests/realloc.test.ts +++ b/basics/realloc/native/tests/realloc.test.ts @@ -1,4 +1,5 @@ import { + AccountRole, type Address, appendTransactionMessageInstruction, createTransactionMessage, @@ -10,6 +11,7 @@ import { setTransactionMessageFeePayerSigner, signTransactionMessageWithSigners, } from '@solana/kit'; +import { getTransferSolInstruction } from '@solana-program/system'; import { assert } from 'chai'; import { FailedTransactionMetadata, LiteSVM } from 'litesvm'; import { @@ -26,6 +28,7 @@ describe('Realloc!', () => { let programId: Address; let payer: KeyPairSigner; let testAccount: KeyPairSigner; + let feePayer: KeyPairSigner; before(async () => { programId = (await generateKeyPairSigner()).address; @@ -33,18 +36,22 @@ describe('Realloc!', () => { payer = await generateKeyPairSigner(); svm.airdrop(payer.address, lamports(1_000_000_000n)); testAccount = await generateKeyPairSigner(); + + feePayer = await generateKeyPairSigner(); + svm.airdrop(feePayer.address, lamports(1_000_000_000n)); }); async function sendTransaction(ix: Instruction) { const transactionMessage = pipe( createTransactionMessage({ version: 0 }), - m => setTransactionMessageFeePayerSigner(payer, m), + m => setTransactionMessageFeePayerSigner(feePayer, m), m => svm.setTransactionMessageLifetimeUsingLatestBlockhash(m), m => appendTransactionMessageInstruction(ix, m), ); const signedTx = await signTransactionMessageWithSigners(transactionMessage); const result = svm.sendTransaction(signedTx); assert(!(result instanceof FailedTransactionMetadata), `transaction failed: ${result.toString()}`); + return result; } it('Create the account with data', async () => { @@ -59,7 +66,25 @@ describe('Realloc!', () => { it('Reallocate WITHOUT zero init', async () => { const ix = createReallocateWithoutZeroInitInstruction(testAccount.address, payer, programId, 'Illinois', 12345); - await sendTransaction(ix); + const targetBefore = svm.getAccount(testAccount.address); + assert(targetBefore.exists); + const payerBefore = svm.getAccount(payer.address); + assert(payerBefore.exists); + const result = await sendTransaction(ix); + + const account = svm.getAccount(testAccount.address); + assert(account.exists); + assert.equal(account.lamports, svm.minimumBalanceForRentExemption(BigInt(account.data.length))); + assert.equal(svm.getBalance(payer.address), payerBefore.lamports - (account.lamports - targetBefore.lamports)); + assert.lengthOf(result.innerInstructions().flat(), 1); + assert.deepEqual(enhancedAddressInfoDecoder.decode(account.data), { + name: 'Jacob', + house_number: 123, + street: 'Main St.', + city: 'Chicago', + state: 'Illinois', + zip: 12345, + }); printEnhancedAddressInfo(testAccount.address); }); @@ -80,6 +105,81 @@ describe('Realloc!', () => { printWorkInfo(testAccount.address); }); + async function prepareFundedReallocation(excess: bigint) { + const target = await generateKeyPairSigner(); + await sendTransaction(createCreateInstruction(target, payer, programId, 'Jacob', 123, 'Main St.', 'Chicago')); + + const createdAccount = svm.getAccount(target.address); + assert(createdAccount.exists); + const reallocIx = createReallocateWithoutZeroInitInstruction( + target.address, + payer, + programId, + 'Illinois', + 12345, + ); + // the payload appends the new fields, so its first byte is the instruction tag + const newSize = createdAccount.data.length + reallocIx.data.length - 1; + const fundedBalance = svm.minimumBalanceForRentExemption(BigInt(newSize)) + excess; + await sendTransaction( + getTransferSolInstruction({ + source: payer, + destination: target.address, + amount: lamports(fundedBalance - createdAccount.lamports), + }), + ); + + return { target, reallocIx, newSize, fundedBalance }; + } + + for (const excess of [0n, 1_000_000n]) { + it(`Reallocates an account funded ${excess} lamports above its new rent minimum`, async () => { + const { target, reallocIx, newSize, fundedBalance } = await prepareFundedReallocation(excess); + const payerBefore = svm.getAccount(payer.address); + assert(payerBefore.exists); + const result = await sendTransaction(reallocIx); + + const account = svm.getAccount(target.address); + assert(account.exists); + assert.equal(account.data.length, newSize); + assert.equal(account.lamports, fundedBalance); + assert.equal(svm.getBalance(payer.address), payerBefore.lamports); + assert.deepEqual(enhancedAddressInfoDecoder.decode(account.data), { + name: 'Jacob', + house_number: 123, + street: 'Main St.', + city: 'Chicago', + state: 'Illinois', + zip: 12345, + }); + assert.isEmpty(result.innerInstructions().flat()); + }); + } + + it('Rejects an unsigned payer when rent is already funded', async () => { + const { target, reallocIx } = await prepareFundedReallocation(0n); + const targetBefore = svm.getAccount(target.address); + assert(targetBefore.exists); + const unsignedPayer = (await generateKeyPairSigner()).address; + const unsignedIx: Instruction = { + ...reallocIx, + accounts: reallocIx.accounts.map((account, index) => + index === 1 ? { address: unsignedPayer, role: AccountRole.WRITABLE } : account, + ), + }; + const message = pipe( + createTransactionMessage({ version: 0 }), + m => setTransactionMessageFeePayerSigner(feePayer, m), + m => svm.setTransactionMessageLifetimeUsingLatestBlockhash(m), + m => appendTransactionMessageInstruction(unsignedIx, m), + ); + const failedResult = svm.sendTransaction(await signTransactionMessageWithSigners(message)); + assert(failedResult instanceof FailedTransactionMetadata, 'expected the unsigned payer to be rejected'); + assert.include(failedResult.err().toString(), 'MissingRequiredSignature'); + + assert.deepEqual(svm.getAccount(target.address), targetBefore); + }); + function printAddressInfo(address: Address): void { const account = svm.getAccount(address); if (account.exists) { diff --git a/basics/realloc/pinocchio/program/src/instructions/reallocate.rs b/basics/realloc/pinocchio/program/src/instructions/reallocate.rs index 8119311cc..014f3f39c 100644 --- a/basics/realloc/pinocchio/program/src/instructions/reallocate.rs +++ b/basics/realloc/pinocchio/program/src/instructions/reallocate.rs @@ -13,12 +13,17 @@ pub fn reallocate_without_zero_init(accounts: &mut [AccountView], instruction_da return Err(ProgramError::NotEnoughAccountKeys); }; + if !payer.is_signer() { + return Err(ProgramError::MissingRequiredSignature); + } + let account_span = EnhancedAddressInfo::LEN; let lamports_required = (Rent::get()?).try_minimum_balance(account_span)?; - let diff = lamports_required - target_account.lamports(); - - Transfer { from: payer, to: target_account, lamports: diff }.invoke()?; + let rent_shortfall = lamports_required.saturating_sub(target_account.lamports()); + if rent_shortfall > 0 { + Transfer { from: payer, to: target_account, lamports: rent_shortfall }.invoke()?; + } target_account.resize(account_span)?; diff --git a/basics/realloc/pinocchio/tests/realloc.test.ts b/basics/realloc/pinocchio/tests/realloc.test.ts index a205013fe..f253d02ff 100644 --- a/basics/realloc/pinocchio/tests/realloc.test.ts +++ b/basics/realloc/pinocchio/tests/realloc.test.ts @@ -21,7 +21,7 @@ import { setTransactionMessageFeePayerSigner, signTransactionMessageWithSigners, } from '@solana/kit'; -import { SYSTEM_PROGRAM_ADDRESS } from '@solana-program/system'; +import { getTransferSolInstruction, SYSTEM_PROGRAM_ADDRESS } from '@solana-program/system'; import { assert } from 'chai'; import { FailedTransactionMetadata, LiteSVM } from 'litesvm'; @@ -78,6 +78,7 @@ describe('Realloc!', () => { let programId: Address; let payer: KeyPairSigner; let testAccount: KeyPairSigner; + let feePayer: KeyPairSigner; before(async () => { programId = (await generateKeyPairSigner()).address; @@ -87,18 +88,22 @@ describe('Realloc!', () => { svm.airdrop(payer.address, lamports(1_000_000_000n)); testAccount = await generateKeyPairSigner(); + + feePayer = await generateKeyPairSigner(); + svm.airdrop(feePayer.address, lamports(1_000_000_000n)); }); async function sendInstruction(ix: Instruction) { const transactionMessage = pipe( createTransactionMessage({ version: 0 }), - m => setTransactionMessageFeePayerSigner(payer, m), + m => setTransactionMessageFeePayerSigner(feePayer, m), m => svm.setTransactionMessageLifetimeUsingLatestBlockhash(m), m => appendTransactionMessageInstruction(ix, m), ); const signedTx = await signTransactionMessageWithSigners(transactionMessage); const result = svm.sendTransaction(signedTx); assert(!(result instanceof FailedTransactionMetadata), `transaction failed: ${result.toString()}`); + return result; } function getTestAccountData(): Uint8Array { @@ -107,11 +112,11 @@ describe('Realloc!', () => { return new Uint8Array(account.data); } - it('Create the account with data', async () => { - const ix = { + function createAccountInstruction(target: KeyPairSigner) { + return { programAddress: programId, accounts: [ - { address: testAccount.address, role: AccountRole.WRITABLE_SIGNER, signer: testAccount }, + { address: target.address, role: AccountRole.WRITABLE_SIGNER, signer: target }, { address: payer.address, role: AccountRole.WRITABLE_SIGNER, signer: payer }, { address: SYSTEM_PROGRAM_ADDRESS, role: AccountRole.READONLY }, ], @@ -123,8 +128,22 @@ describe('Realloc!', () => { city: 'Chicago', }), }; + } - await sendInstruction(ix); + function createReallocateInstruction(target: Address) { + return { + programAddress: programId, + accounts: [ + { address: target, role: AccountRole.WRITABLE }, + { address: payer.address, role: AccountRole.WRITABLE_SIGNER, signer: payer }, + { address: SYSTEM_PROGRAM_ADDRESS, role: AccountRole.READONLY }, + ], + data: reallocWithoutZeroInitEncoder.encode({ discriminator: 1, state: 'Illinois', zip: 12345 }), + }; + } + + it('Create the account with data', async () => { + await sendInstruction(createAccountInstruction(testAccount)); const data = getTestAccountData(); assert.strictEqual(data.length, 25); @@ -137,17 +156,17 @@ describe('Realloc!', () => { }); it('Reallocate WITHOUT zero init', async () => { - const ix = { - programAddress: programId, - accounts: [ - { address: testAccount.address, role: AccountRole.WRITABLE }, - { address: payer.address, role: AccountRole.WRITABLE_SIGNER, signer: payer }, - { address: SYSTEM_PROGRAM_ADDRESS, role: AccountRole.READONLY }, - ], - data: reallocWithoutZeroInitEncoder.encode({ discriminator: 1, state: 'Illinois', zip: 12345 }), - }; + const targetBefore = svm.getAccount(testAccount.address); + assert(targetBefore.exists); + const payerBefore = svm.getAccount(payer.address); + assert(payerBefore.exists); + const result = await sendInstruction(createReallocateInstruction(testAccount.address)); - await sendInstruction(ix); + const rentMinimum = svm.minimumBalanceForRentExemption(BigInt(enhancedAddressInfoDecoder.fixedSize)); + const rentShortfall = rentMinimum - targetBefore.lamports; + assert.equal(svm.getBalance(testAccount.address), rentMinimum); + assert.equal(svm.getBalance(payer.address), payerBefore.lamports - rentShortfall); + assert.lengthOf(result.innerInstructions().flat(), 1); const data = getTestAccountData(); assert.strictEqual(data.length, 37); @@ -182,4 +201,72 @@ describe('Realloc!', () => { assert.strictEqual(workInfo.company, 'Anza'); assert.strictEqual(workInfo.yearsEmployed, 2); }); + + async function prepareFundedReallocation(excess: bigint) { + const target = await generateKeyPairSigner(); + await sendInstruction(createAccountInstruction(target)); + + const createdAccount = svm.getAccount(target.address); + assert(createdAccount.exists); + const newSize = enhancedAddressInfoDecoder.fixedSize; + const fundedBalance = svm.minimumBalanceForRentExemption(BigInt(newSize)) + excess; + await sendInstruction( + getTransferSolInstruction({ + source: payer, + destination: target.address, + amount: lamports(fundedBalance - createdAccount.lamports), + }), + ); + + const reallocIx = createReallocateInstruction(target.address); + return { target, reallocIx, newSize, fundedBalance }; + } + + for (const excess of [0n, 1_000_000n]) { + it(`Reallocates an account funded ${excess} lamports above its new rent minimum`, async () => { + const { target, reallocIx, newSize, fundedBalance } = await prepareFundedReallocation(excess); + const payerBefore = svm.getAccount(payer.address); + assert(payerBefore.exists); + const result = await sendInstruction(reallocIx); + + const account = svm.getAccount(target.address); + assert(account.exists); + assert.equal(account.data.length, newSize); + assert.equal(account.lamports, fundedBalance); + assert.equal(svm.getBalance(payer.address), payerBefore.lamports); + assert.deepEqual(enhancedAddressInfoDecoder.decode(account.data), { + name: 'Jacob', + houseNumber: 123, + street: 'Main St.', + city: 'Chicago', + state: 'Illinois', + zip: 12345, + }); + assert.isEmpty(result.innerInstructions().flat()); + }); + } + + it('Rejects an unsigned payer when rent is already funded', async () => { + const { target, reallocIx } = await prepareFundedReallocation(0n); + const targetBefore = svm.getAccount(target.address); + assert(targetBefore.exists); + const unsignedPayer = (await generateKeyPairSigner()).address; + const unsignedIx: Instruction = { + ...reallocIx, + accounts: reallocIx.accounts.map((account, index) => + index === 1 ? { address: unsignedPayer, role: AccountRole.WRITABLE } : account, + ), + }; + const message = pipe( + createTransactionMessage({ version: 0 }), + m => setTransactionMessageFeePayerSigner(feePayer, m), + m => svm.setTransactionMessageLifetimeUsingLatestBlockhash(m), + m => appendTransactionMessageInstruction(unsignedIx, m), + ); + const failedResult = svm.sendTransaction(await signTransactionMessageWithSigners(message)); + assert(failedResult instanceof FailedTransactionMetadata, 'expected the unsigned payer to be rejected'); + assert.include(failedResult.err().toString(), 'MissingRequiredSignature'); + + assert.deepEqual(svm.getAccount(target.address), targetBefore); + }); });