Repository navigation
fix(js): resume interrupted creates when the metadata PDA holds a pre-allocated buffer - #129
Conversation
trevor-cortex
left a comment
There was a problem hiding this comment.
Summary
getWriteMetadataInstructionPlan now dispatches on the account discriminator instead of mere existence. A Buffer-discriminated account at the metadata PDA (a create interrupted before initialize) is routed to a new getResumeMetadataInstructionPlan, which emits a lone initialize when the buffer already holds the desired bytes, or grows + rewrites first when it doesn't. Smaller data is rejected with close-buffer guidance; unknown discriminators throw. Four LiteSVM tests build the stuck PDA by hand and cover the identical / same-length / larger / smaller cases.
I checked the approach against the program and it holds up:
BufferandMetadataheaders are both 96 bytes (the RustBufferstruct carries explicit padding for exactly this), so decoding the stuck PDA with the metadata decoder gives a correctdataslice.initializeon aBuffer-discriminated PDA derivesdata_lengthfromdata_len() - Header::LEN, andtrimon a buffer only reclaims excess lamports without resizing, so the "cannot shrink, close it" rejection is accurate.allocatestores the signer as the bufferauthority, soclose-buffer <pda>succeeds through the explicit-authority path even for canonical buffers (the CLI command doesn't passprogram/programData).
Things to look at
- Self-referential
bufferfootgun (inline at L125). If a caller passes the stuck PDA itself asinput.buffer— plausible after seeing it inlist-buffers—dataEqualsis trivially true, the plan emitsinitialize, thencloseon the just-initialized metadata account. For non-canonical metadata the close succeeds (authority is stored on the header), destroying the account; for canonical it fails withIncorrectAuthority. A one-line guard fixes it. - Rent top-up over-funds by the 128-byte header (inline at L144).
getMinimumBalance(growth)adds the account header by default;getExtraRentinupdateMetadata.tspasses{ withoutHeader: true }for the same situation. Not a correctness issue, just ~0.0009 SOL stranded per extend. - Source precedence differs from create/update (inline at L125). Those flows prefer
bufferoverdata; this one prefersdata.
Notes for other reviewers
- The
writeMetadatadocblock (unchanged, ~L36–44 ofwriteMetadata.ts) still says "if so, the operation is an update, otherwise it is a create" — worth a one-liner about the resume path since that's where a reader would look first. - Tests only exercise the canonical PDA with
dataas the source. A non-canonical case and a--buffer-as-source case would be cheap additions, though I don't think they're blocking. - No
.changeset/in this repo, so nothing needed on that front despite the new public export.
|
Thank you for the review. Commit
Guard when Rent for the extend transfer — The transfer now uses Precedence of Close and re-create for small data — We keep the error. We do not know that the runtime accepts a close and a re-create of one account in the same transaction. The error tells you how to correct this: close the buffer with Other changes — The Tool output: |
|
Hey 👋 Thanks for the fix! I pushed a commit on top to save us some back and forth. Instead of a separate resume helper, the create factories now check the metadata PDA's state and skip whatever an interrupted create already did. That means create gets fixed as well as write. I also made update fail early on a pre-allocated buffer, and switched to fetching the metadata and buffer accounts in a single getMultipleAccounts call. The buried error.cause.cause was a Kit bug, fixed in anza-xyz/kit#2165. Lmk what you think 🙂 |
trevor-cortex
left a comment
There was a problem hiding this comment.
Re-review
Significant rework since my first pass. The resume logic no longer lives in a separate getResumeMetadataInstructionPlan; instead the create flow itself became resumable: getCreateMetadataInstructionPlan accepts the fetched PDA account (CreateMetadataTarget), getMetadataPdaState reduces it to { address, allocated, data, lamports }, and the new shared getCreateMetadataInstructionPlanUsingPdaBuffer skips whichever steps already landed (rent, allocate, extend, write). writeMetadata just routes on isInitializedMetadata, updateMetadata refuses buffers up front, and the CLI commands batch the PDA + source-buffer fetch into one getMultipleAccounts call and warn when resuming.
All points from my previous review are addressed:
- self-referential
buffernow throws (buffer must not be the metadata account itself), with a test; - rent top-up is now
requiredRent - pda.lamports, which is strictly better than mywithoutHeadersuggestion — verified with the "only transfers the missing rent" test; buffertakes precedence overdata, matching create/update, with a test;writeMetadatadocblock updated;- non-canonical and
--buffer-as-source cases covered.
I re-checked the on-chain assumptions against the new shape: both generated decoders read data as the remainder after the 96-byte header (getBytesDecoder(), not sliced by dataLength), so pda.data is correct whether the PDA was decoded via decodeBuffer or decodeMetadata; write resizes to max(len, offset + data.len) so it grows but never shrinks; extend accepts a Buffer-discriminated account through validate_authority. The growth computation reproduces the old needsExtend semantics for the fresh-allocate path and only counts the remaining bytes once allocated, so the singleExtendPerTransaction / CPI budget remains right.
Two non-blocking nits inline (funded-but-unallocated PDA re-transfers the full rent; the existing-buffer path could skip the write when the PDA already holds the source bytes), plus one consistency note on updateMetadata. None of these need to hold the merge.
Notes for other reviewers
getDecodedAccountDiscriminatorduck-types ondata+lamports+data.discriminator. That's fine for the inputsCreateMetadataTargetadmits today (addresses,HasAddress, signers, decoded accounts), but it's the kind of helper that silently misroutes if someone later passes a custom object with those keys. Worth keeping in mind if the input union grows.getMetadataPdaStateis called twice on theinput.bufferpath (once ingetCreateMetadataInstructionPlan, once in…UsingExistingBuffer). Pure and cheap, so not an issue, just noting it's intentional rather than a leftover.- The CLI still does its own
fetchEncodedAccountingetCanonicalPdaDetailsUnchecked, so the "single RPC request" guarantee in the test applies to the library entry points, not the CLI end-to-end.
trevor-cortex
left a comment
There was a problem hiding this comment.
Re-review (3rd pass)
Only updateMetadata.ts, internals.ts and updateMetadata.test.ts moved since my last review; createMetadata.ts is unchanged. The delta addresses the consistency note I left last time: updateMetadata now goes through the same fetchMetadataAndBuffer + decodeMaybeMetadataOrBuffer path as create/write, so foreign-owned accounts and unknown discriminators are rejected before any planning, and a funded-but-empty PDA is reported as missing (surfacing as SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND, same as before via fetchMetadata). The three new tests cover exactly those branches — pre-allocated buffer (with the payer balance check proving nothing was sent), foreign owner, and missing account.
Nothing new to flag. The two remaining nits from my previous review (full-rent re-transfer on a funded-but-unallocated PDA, and skipping the write on the existing-buffer path when bytes already match) are still open but were explicitly non-blocking. Still approved.
|
@lorisleiva Thank you for the rework! We read it in full and we like it. One create flow that resumes itself is the correct design. The @trevor-cortex Both of your open points are now addressed in
Two new tests cover both cases. The full suite passes: 148 tests. @mcintyre94 Your |
mcintyre94
left a comment
There was a problem hiding this comment.
LGTM! Let me take a look at the audit CI job and then we can get this merged, thankyou!
|
@xeroc would you mind rebasing this PR to make CI pass? Then let's get this merged. 🚀 |
…-allocated buffer The write flow decided between create and update solely on whether an account exists at the metadata PDA. A create that is interrupted between the buffer writes and the initialize instruction leaves a pre-allocated buffer (discriminator: Buffer) at that PDA, which decoded as an existing metadata account and routed every subsequent write into the update flow. The update flow then planned a fresh keypair buffer, a full set of chunk writes and a final set_data that fails on-chain with 'instruction requires an initialized account' — after the buffer transactions had already been sent, leaking rent-exempt buffers on every retry. Route on the account discriminator instead: - absent account -> create (unchanged) - initialized metadata account -> update (unchanged) - pre-allocated buffer -> resume: initialize the account in place, rewriting the data (and growing the buffer) when it differs, and rejecting data smaller than the buffer since buffer accounts cannot shrink
- Reject `buffer` == metadata PDA with an explicit error instead of initializing the account only to close it right after - Prefer `buffer` over `data`, matching the create and update flows - Fund extends with `withoutHeader: true` so the existing account header is not paid for twice (~0.0009 SOL stranded per extend) - Use Kit's `bytesEqual` instead of the local `dataEquals` helper - Document the resume path in `writeMetadata`'s docblock New tests: buffer==PDA guard throws, source buffer preferred over conflicting inline data, non-canonical PDA resume. Suite: 131 passed; oxlint, oxffmt and tsc clean.
Fold the resume logic into the buffer-based create factories, which now inspect the state of the metadata PDA and skip the steps an interrupted create already completed (rent, allocate, extend, write). Callers pass the fetched account straight through, so `createMetadata`, `writeMetadata` and the CLI no longer duplicate the "already exists" check. Reject updates on a pre-allocated buffer before sending any transaction, and fetch the metadata and source buffer accounts using a single `getMultipleAccounts` request.
…rites - Carry the lamports of a funded, empty metadata PDA through `decodeMaybeMetadataOrBuffer` so the create flow transfers only the rent that is missing - Accept `existingLamports` in the instruction-data plan, which had the same full-rent transfer - Skip the source-buffer `write` when the PDA already holds its bytes, mirroring the data path's `bytesEqual` short-circuit Optional polish from the review round; plan shapes stay compatible. Tests: pre-funded PDA keeps its exact balance, buffer-source resume plans a single `initialize`. Suite: 148 passed.
cd2c642 to
0dd5326
Compare
|
The rebase on |
|
Thanks! Just gonna trigger one last AI review to make sure nothing got lost on the rebase whilst we wait for CI. |
trevor-cortex
left a comment
There was a problem hiding this comment.
Re-review (4th pass)
Changes since my last approval are confined to createMetadata.ts, createMetadata.test.ts, a new extendInstructionPlan.test.ts, and a one-line tweak in internals.ts. From the diff these address the two non-blocking nits I had left open plus xeroc's comments:
- Funded-but-unallocated PDA no longer re-transfers the full rent.
decodeMaybeMetadataOrBuffernow carrieslamportsthrough on its synthetic missing account, andgetMetadataPdaStatereads it on theexists: falsebranch, somissingRentis correct for a PDA that only got the system transfer before the create was interrupted. The docblock claim I flagged as overclaiming is now accurate. - Existing-buffer path short-circuits the
writewhen the PDA already holds the source bytes.getCreateMetadataInstructionPlanUsingExistingBuffernow applies the samebytesEqualcheck as the inline-data path, so a--bufferretry on a fully-written PDA emits onlyinitialize(+ optionalclose). Symmetric with thedatapath, and covered by the new test. extendInstructionPlancovers theallocated+ partially extended case. The new test pins down that growth is computed from the remaining bytes, not the full target, so the single-extend-per-transaction CPI budget isn't blown by a resume. Good to have this isolated rather than only implicitly exercised throughwriteMetadata.
I re-read the final createMetadata.ts end to end against the program's allocate / extend / write / initialize processors; the resume branches still line up (grow-never-shrink on write, extend accepted on Buffer-discriminated PDAs, initialize sizing from account length). No new issues.
All my earlier points are now resolved. Approving; nothing from me is holding the merge once Callum's audit CI check clears.
|
Small correction to my review above: the new test in |
Fixes #128
Problem
getWriteMetadataInstructionPlanchose between the create and update flows solely on whether an account exists at the metadata PDA. A create interrupted between the buffer writes and theinitializeinstruction leaves a pre-allocated buffer (discriminatorBuffer) at that PDA; the generated metadata decoder accepts it as an existing metadata account, so every subsequentwritetook the update flow. The update flow plans a fresh keypair buffer, a full set of chunk writes and a finalset_data— which fails on-chain withInstruction requires an initialized accountafter the buffer transactions have already been sent, leaking a rent-exempt buffer on every retry.Change
getWriteMetadataInstructionPlannow routes on the account discriminator:getResumeMetadataInstructionPlan:initializeinstruction resumes the create,initialize,close-bufferguidance, since buffer accounts cannot shrink andinitializederivesdata_lengthfrom the account size,Testing
Four new integration tests in
clients/js/test/writeMetadata.test.tsconstruct the stuck PDA in LiteSVM (pre-allocated buffer + chunk writes, noinitialize) and cover: resume with identical data, rewrite of same-length stale data, extend for larger data, and the rejection of smaller data. The identical-data scenario reproduced the exact production failure (Instruction requires an initialized account) before the fix. Full suite: 128 passed; oxlint, oxfmt and tsc clean.Also verified against the mainnet incident that motivated this: the resume path's single-
initializetransaction was executed manually to complete a stuck 13 KB IDL upload, after which the standardwritecommand succeeded again.