Repository navigation
Add helpers and a generic rejection error for custom message packers - #2073
Conversation
🦋 Changeset detectedLatest commit: aa1cfe5 The changes in this PR will be included in the next version bump. This PR includes changesets to release 48 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
This stack of pull requests is managed by Graphite. Learn more about stacking. |
BundleMonFiles updated (10)
Unchanged files (140)
Total files change +618B +0.11% Final result: ✅ View report in BundleMon website ➡️ |
trevor-cortex
left a comment
There was a problem hiding this comment.
Verdict: LGTM — approving in spirit (this account can't formally approve on the repo). Nits below are all non-blocking.
Summary
Extracts the instruction-count / size validation that the built-in packers relied on into a public message-packer-errors.ts module (resolveMaxInstructionsPerTransaction, assertMaxInstructionsPerTransaction, assertMessageCanAccommodateSize), adds a new SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_REJECTED_BY_PACKER error with a free-text reason, and replaces the planner's inline six-code isSolanaError chain with an exported isMessagePackerErrorThatRequiresNewCandidate guard that also covers the new code. max-instructions.ts is folded into the new module.
I traced the refactors and they're behaviour-preserving:
resolveMaxInstructionsPerTransaction= oldassertValid…+resolveMaxInstructionsfused. The planner now resolves once up front andTraverseContext.maxInstructionsPerTransactionbecomes a plainnumber, which removes the repeatedresolveMaxInstructions(...)calls at every assertion site. Same semantics, less noise.- In
getMessagePackerInstructionPlanFromInstructions, the restructuredif (index === instructionIndex) assert… else if (nextSize > sizeLimit) …is equivalent to the old nested check, andnumBytesRequired/numFreeBytescompute to the same values (nextSize - originalMessageSize,sizeLimit - originalMessageSize). max-instructions.tswas never re-exported fromindex.ts, so droppingDEFAULT_MAX_INSTRUCTIONS_PER_TRANSACTION'sexportisn't a public break.- Rejection semantics in the planner check out:
selectAndMutateCandidateswallowsMESSAGE_REJECTED_BY_PACKERand moves on (covering both thetraverseMessagePackerpredicate and thefitEntirePlanInsideMessagepath for non-divisible / parallel-nested packers), whilecreateNewMessagedoesn't catch, so a fresh-message rejection propagates. Both planner tests exercise exactly those two outcomes.
Nits (non-blocking)
MessagePackerInstructionPlandocblock example is now inconsistent. TheMessagePackertype's example was updated to add theif (!isMessagePackerErrorThatRequiresNewCandidate(error)) throw error;guard, but the near-identical "Using a message packer plan" example in theMessagePackerInstructionPlandocblock (instruction-plan.ts~L205–215, unchanged) still has a barecatchwith just comments. Worth mirroring the guard there too so the two examples don't teach different things.- Consider exporting
MessagePackerErrorThatRequiresNewCandidate. See inline. - Error message wording. See inline on
messages.ts. - Test gap (optional): the planner tests cover
traverseMessagePacker, but not thefitEntirePlanInsideMessageroute where a rejection is swallowed and the plan falls back to normal traversal. Something likesequentialInstructionPlan([A, nonDivisibleSequentialInstructionPlan([rejectingPacker([B])])])→ expectsequential([Tx: A], [Tx: B])would pin that down, since it's the path most likely to regress if someone later narrows the catch inselectAndMutateCandidate.
Notes for subsequent reviewers
- No README change needed here — the package README just links to solanakit.com docs, and per
CLAUDE.mddocs can't reference unpublished types, so the docs follow-up has to land post-release. - The changeset bumps
@solana/errorsand@solana/instruction-plansasminor, which matches new-feature precedent. - The linear packer only adopted the max-instructions helpers, not
assertMessageCanAccommodateSize— that's correct, its size math has the+1/-1shortU16 leeway adjustments that don't map onto the generic helper.
This PR makes it practical to write a custom `MessagePacker` without reimplementing the built-in packers' internals. Today a packer that wants to refuse a candidate message for a reason other than byte size (for example a per-transaction realloc budget) has to throw `MESSAGE_CANNOT_ACCOMMODATE_PLAN` with fabricated byte counts, and has to copy the instruction-count validation and the size arithmetic by hand.
Three helpers are now exported from `@solana/instruction-plans`: `resolveMaxInstructionsPerTransaction` validates and defaults the `maxInstructions` option, `assertMaxInstructionsPerTransaction` throws `MAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDED` when a message would hold too many instructions, and `assertMessageCanAccommodateSize` throws `MESSAGE_CANNOT_ACCOMMODATE_PLAN` with correctly computed byte counts from sizes the caller already has. The two built-in packers use them.
A new `SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_REJECTED_BY_PACKER` error with a free-text `reason` lets a packer refuse a message for any other constraint. The planner treats it like the existing capacity errors, so rejecting a candidate opens a new transaction message while rejecting a fresh message still propagates. The set of errors that mean "use a new candidate" is now exposed as `isMessagePackerErrorThatRequiresNewCandidate`, which the planner uses in place of its inline six-code chain.
```ts
packMessageToCapacity: (message, config) => {
const maxInstructions = resolveMaxInstructionsPerTransaction(config?.maxInstructions);
assertMaxInstructionsPerTransaction(message.instructions.length + 1, maxInstructions);
if (budgetLeft(message) <= 0) {
throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_REJECTED_BY_PACKER, {
reason: 'the account cannot grow any further in this transaction',
});
}
const nextMessage = appendTransactionMessageInstruction(nextInstruction, message);
assertMessageCanAccommodateSize({
currentSize: getTransactionMessageSize(message),
nextSize: getTransactionMessageSize(nextMessage),
sizeLimit: getTransactionMessageSizeLimit(nextMessage),
});
return nextMessage;
};
```
c3defa8 to
aa1cfe5
Compare
trevor-cortex
left a comment
There was a problem hiding this comment.
Re-review: LGTM, nothing further — approving in spirit (this account can't formally approve on the repo).
All four points from the previous pass are addressed in the current head:
- Error message trimmed to
'The message packer rejected the provided transaction message: $reason.'— no more misleading "pack into a new message" advice at the point where a fresh message was already rejected. MessagePackerErrorThatRequiresNewCandidateis now exported with a docblock that enumerates each code in the union and what it means. The guard's return type narrows to it.MessagePackerInstructionPlandocblock example now carries the sameif (!isMessagePackerErrorThatRequiresNewCandidate(error)) throw error;guard as theMessagePackerone, and theMessagePackertype docblock gained a paragraph pointing custom packers at the three helpers and the new error.fitEntirePlanInsideMessagepath is now covered by the new "falls back to a new transaction message when a message packer rejects the parent candidate of a non-divisible plan" test (sequential([A, nonDivSeq([rejectingPacker([B])])])→sequential([Tx: A], [Tx: B])). That pins down theselectAndMutateCandidatecatch for the nested route, which was the one most likely to regress silently.
Re-checked the rest of the diff (transaction-planner.ts, __setup__.ts, codes.ts, context.ts, changeset) — unchanged from the prior pass, no regressions. Planner tests now cover all three outcomes: reject-candidate-via-traverseMessagePacker, reject-candidate-via-fitEntirePlanInsideMessage, and reject-fresh-message propagates.
Good to merge from my side.
mcintyre94
left a comment
There was a problem hiding this comment.
LGTM! I found these helpers a little odd because they're just comparing two numbers and throwing an error, but I think they make it much more straightforward to write a packer and it wouldn't make sense to pass any other input (like the transaction message or something). So I think this makes sense!
|
🔎💬 Inkeep AI search and chat service is syncing content for source 'Solana Kit Docs' |
|
Because there has been no activity on this PR for 14 days since it was merged, it has been automatically locked. Please open a new issue if it requires a follow up. |

This PR makes it practical to write a custom
MessagePackerwithout reimplementing the built-in packers' internals. Today a packer that wants to refuse a candidate message for a reason other than byte size (for example a per-transaction realloc budget) has to throwMESSAGE_CANNOT_ACCOMMODATE_PLANwith fabricated byte counts, and has to copy the instruction-count validation and the size arithmetic by hand.Three helpers are now exported from
@solana/instruction-plans:resolveMaxInstructionsPerTransactionvalidates and defaults themaxInstructionsoption,assertMaxInstructionsPerTransactionthrowsMAX_INSTRUCTIONS_PER_TRANSACTION_EXCEEDEDwhen a message would hold too many instructions, andassertMessageCanAccommodateSizethrowsMESSAGE_CANNOT_ACCOMMODATE_PLANwith correctly computed byte counts from sizes the caller already has. The two built-in packers use them.A new
SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_REJECTED_BY_PACKERerror with a free-textreasonlets a packer refuse a message for any other constraint. The planner treats it like the existing capacity errors, so rejecting a candidate opens a new transaction message while rejecting a fresh message still propagates. The set of errors that mean "use a new candidate" is now exposed asisMessagePackerErrorThatRequiresNewCandidate, which the planner uses in place of its inline six-code chain.