Skip to content

Commit 6a74b53

Browse files
committed
A utility to estimate the compute unit consumption of a transaction message
1 parent 4852d1d commit 6a74b53

File tree

9 files changed

+530
-1
lines changed

9 files changed

+530
-1
lines changed

.changeset/two-cougars-try.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solana/web3.js-experimental": patch
3+
---
4+
5+
Created a utility function to estimate the compute unit consumption of a transaction message

packages/errors/src/codes.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ export const SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCT
202202
export const SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015 as const;
203203
export const SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016 as const;
204204
export const SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH = 5663017 as const;
205+
export const SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT = 5663018 as const;
205206

206207
// Transaction errors.
207208
// Reserve error codes starting with [7050000-7050999] for the Rust enum `TransactionError`.
@@ -484,6 +485,7 @@ export type SolanaErrorCode =
484485
| typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE
485486
| typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING
486487
| typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND
488+
| typeof SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT
487489
| typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING
488490
| typeof SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING
489491
| typeof SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE

packages/errors/src/messages.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ import {
171171
SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,
172172
SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,
173173
SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,
174+
SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,
174175
SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING,
175176
SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,
176177
SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE,
@@ -570,6 +571,10 @@ export const SolanaErrorMessages: Readonly<{
570571
[SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING]: 'No fee payer set in CompiledTransaction',
571572
[SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]:
572573
'Could not find program address at index $index',
574+
[SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT]:
575+
'Failed to estimate the compute unit consumption for this transaction message. This is ' +
576+
'likely because simulating the transaction failed. Inspect the `cause` property of this ' +
577+
'error to learn more',
573578
[SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING]: 'Transaction is missing a fee payer.',
574579
[SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING]:
575580
"Could not determine this transaction's signature. Make sure that the transaction has " +

packages/library/README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -878,6 +878,46 @@ const signedTransaction = await signTransaction([signer], transactionMessageWith
878878
// => "Property 'lifetimeConstraint' is missing in type"
879879
```
880880

881+
### Calibrating A Transaction Message's Compute Unit Budget
882+
883+
Correctly budgeting a compute unit limit for your transaction message can increase the probabilty that your transaction will be accepted for processing. If you don't declare a compute unit limit on your transaction, validators will assume an upper limit of 200K compute units (CU) per instruction.
884+
885+
Since validators have an incentive to pack as many transactions into each block as possible, they may choose to include transactions that they know will fit into the remaining compute budget for the current block over transactions that might not. For this reason, you should set a compute unit limit on each of your transaction messages, whenever possible.
886+
887+
Use this utility to estimate the actual compute unit cost of a given transaction message.
888+
889+
```ts
890+
import { getSetComputeLimitInstruction } from '@solana-program/compute-budget';
891+
import { createSolanaRpc, getComputeUnitEstimateForTransactionMessageFactory, pipe } from '@solana/web3.js';
892+
893+
// Create an estimator function.
894+
const rpc = createSolanaRpc('http://127.0.0.1:8899');
895+
const getComputeUnitEstimateForTransactionMessage = getComputeUnitEstimateForTransactionMessageFactory({
896+
rpc,
897+
});
898+
899+
// Create your transaction message.
900+
const transactionMessage = pipe(
901+
createTransactionMessage({ version: 'legacy' }),
902+
/* ... */
903+
);
904+
905+
// Request an estimate of the actual compute units this message will consume.
906+
const computeUnitsEstimate = await getComputeUnitEstimateForTransactionMessage(transactionMessage);
907+
908+
// Set the transaction message's compute unit budget.
909+
const transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(
910+
getSetComputeLimitInstruction({ units: computeUnitsEstimate }),
911+
transactionMessage,
912+
);
913+
```
914+
915+
> [!WARNING]
916+
> The compute unit estimate is just that &ndash; an estimate. The compute unit consumption of the actual transaction might be higher or lower than what was observed in simulation. Unless you are confident that your particular transaction message will consume the same or fewer compute units as was estimated, you might like to augment the estimate by either a fixed number of CUs or a multiplier.
917+
918+
> [!NOTE]
919+
> If you are preparing an _unsigned_ transaction, destined to be signed and submitted to the network by a wallet, you might like to leave it up to the wallet to determine the compute unit limit. Consider that the wallet might have a more global view of how many compute units certain types of transactions consume, and might be able to make better estimates of an appropriate compute unit budget.
920+
881921
### Helpers For Building Transaction Messages
882922

883923
Building transaction messages in this manner might feel different from what you’re used to. Also, we certainly wouldn’t want you to have to bind transformed transaction messages to a new variable at each step, so we have released a functional programming library dubbed `@solana/functional` that lets you build transaction messages in **pipelines**. Here’s how it can be used:
Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
import { Address } from '@solana/addresses';
2+
import {
3+
SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,
4+
SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,
5+
SolanaError,
6+
} from '@solana/errors';
7+
import { AccountRole } from '@solana/instructions';
8+
import { Rpc, SimulateTransactionApi } from '@solana/rpc';
9+
import { Blockhash } from '@solana/rpc-types';
10+
import { ITransactionMessageWithFeePayer, Nonce, TransactionMessage } from '@solana/transaction-messages';
11+
12+
import { getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT } from '../compute-limit-internal';
13+
14+
const FOREVER_PROMISE = new Promise(() => {
15+
/* never resolve */
16+
});
17+
18+
const MOCK_BLOCKHASH_LIFETIME_CONSTRAINT = {
19+
blockhash: 'GNtuHnNyW68wviopST3ki37Afv7LPphxfSwiHAkX5Q9H' as Blockhash,
20+
lastValidBlockHeight: 0n,
21+
} as const;
22+
23+
describe('getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT', () => {
24+
let sendSimulateTransactionRequest: jest.Mock;
25+
let mockTransactionMessage: ITransactionMessageWithFeePayer & TransactionMessage;
26+
let rpc: Rpc<SimulateTransactionApi>;
27+
let simulateTransaction: jest.Mock;
28+
beforeEach(() => {
29+
mockTransactionMessage = {
30+
feePayer: '7U8VWgTUucttJPt5Bbkt48WknWqRGBfstBt8qqLHnfPT' as Address,
31+
instructions: [],
32+
version: 0,
33+
};
34+
sendSimulateTransactionRequest = jest.fn().mockReturnValue(FOREVER_PROMISE);
35+
simulateTransaction = jest.fn().mockReturnValue({ send: sendSimulateTransactionRequest });
36+
rpc = {
37+
simulateTransaction,
38+
};
39+
});
40+
it('aborts the `simulateTransaction` request when aborted', () => {
41+
const abortController = new AbortController();
42+
getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT({
43+
abortSignal: abortController.signal,
44+
rpc,
45+
transactionMessage: {
46+
...mockTransactionMessage,
47+
lifetimeConstraint: MOCK_BLOCKHASH_LIFETIME_CONSTRAINT,
48+
},
49+
});
50+
expect(sendSimulateTransactionRequest).toHaveBeenCalledWith({
51+
abortSignal: expect.objectContaining({ aborted: false }),
52+
});
53+
abortController.abort();
54+
expect(sendSimulateTransactionRequest).toHaveBeenCalledWith({
55+
abortSignal: expect.objectContaining({ aborted: true }),
56+
});
57+
});
58+
it('passes the expected basic input to the simulation request', () => {
59+
const transactionMessage = {
60+
...mockTransactionMessage,
61+
lifetimeConstraint: MOCK_BLOCKHASH_LIFETIME_CONSTRAINT,
62+
};
63+
getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT({
64+
commitment: 'finalized',
65+
minContextSlot: 42n,
66+
rpc,
67+
transactionMessage,
68+
});
69+
expect(simulateTransaction).toHaveBeenCalledWith(
70+
expect.any(String),
71+
expect.objectContaining({
72+
commitment: 'finalized',
73+
encoding: 'base64',
74+
minContextSlot: 42n,
75+
sigVerify: false,
76+
}),
77+
);
78+
});
79+
it('appends a set compute unit limit instruction when one does not exist', async () => {
80+
expect.assertions(1);
81+
await jest.isolateModulesAsync(async () => {
82+
jest.mock('@solana/transactions');
83+
const [
84+
{ compileTransaction },
85+
{ getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT },
86+
] = await Promise.all([
87+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
88+
// @ts-ignore
89+
import('@solana/transactions'),
90+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
91+
// @ts-ignore
92+
import('../compute-limit-internal'),
93+
]);
94+
const transactionMessage = {
95+
...mockTransactionMessage, // No `SetComputeUnitLimit` instruction
96+
lifetimeConstraint: MOCK_BLOCKHASH_LIFETIME_CONSTRAINT,
97+
};
98+
getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT({
99+
rpc,
100+
transactionMessage,
101+
});
102+
expect(compileTransaction).toHaveBeenCalledWith({
103+
...transactionMessage,
104+
instructions: [
105+
...transactionMessage.instructions,
106+
{
107+
data:
108+
// prettier-ignore
109+
new Uint8Array([
110+
0x02, // SetComputeUnitLimit instruction inde
111+
0xff, 0xff, 0xff, 0xff, // U32::MAX
112+
]),
113+
programAddress: 'ComputeBudget111111111111111111111111111111',
114+
},
115+
],
116+
});
117+
});
118+
});
119+
it('replaces the existing set compute unit limit instruction when one exists', async () => {
120+
expect.assertions(1);
121+
await jest.isolateModulesAsync(async () => {
122+
jest.mock('@solana/transactions');
123+
const [
124+
{ compileTransaction },
125+
{ getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT },
126+
] = await Promise.all([
127+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
128+
// @ts-ignore
129+
import('@solana/transactions'),
130+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
131+
// @ts-ignore
132+
import('../compute-limit-internal'),
133+
]);
134+
const transactionMessage = {
135+
...mockTransactionMessage,
136+
instructions: [
137+
{ programAddress: '4Kk4nA3F2nWHCcuyT8nR6oF7HQUQHmmzAVD5k8FQPKB2' as Address },
138+
{
139+
data:
140+
// prettier-ignore
141+
new Uint8Array([
142+
0x02, // SetComputeUnitLimit instruction inde
143+
0x01, 0x02, 0x03, 0x04, // ComputeUnits(u32)
144+
]),
145+
programAddress: 'ComputeBudget111111111111111111111111111111' as Address,
146+
},
147+
{ programAddress: '4Kk4nA3F2nWHCcuyT8nR6oF7HQUQHmmzAVD5k8FQPKB2' as Address },
148+
],
149+
lifetimeConstraint: MOCK_BLOCKHASH_LIFETIME_CONSTRAINT,
150+
};
151+
getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT({
152+
rpc,
153+
transactionMessage,
154+
});
155+
expect(compileTransaction).toHaveBeenCalledWith(
156+
expect.objectContaining({
157+
instructions: [
158+
transactionMessage.instructions[0],
159+
{
160+
...transactionMessage.instructions[1],
161+
data: new Uint8Array([0x02, 0xff, 0xff, 0xff, 0xff]), // Replaced with U32::MAX
162+
},
163+
transactionMessage.instructions[2],
164+
],
165+
}),
166+
);
167+
});
168+
});
169+
it('does not ask for a replacement blockhash when the transaction message is a durable nonce transaction', () => {
170+
getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT({
171+
rpc,
172+
transactionMessage: {
173+
...mockTransactionMessage,
174+
instructions: [
175+
{
176+
accounts: [
177+
{
178+
address: '7wJFRFuAE9x5Ptnz2VoBWsfecTCfuuM2sQCpECGypnTU' as Address,
179+
role: AccountRole.WRITABLE,
180+
},
181+
{
182+
address: 'SysvarRecentB1ockHashes11111111111111111111' as Address,
183+
role: AccountRole.READONLY,
184+
},
185+
{
186+
address: 'HzMoc78z1VNNf9nwD4Czt6CDYEb9LVD8KsVGP46FEmyJ' as Address,
187+
role: AccountRole.READONLY_SIGNER,
188+
},
189+
],
190+
data: new Uint8Array([4, 0, 0, 0]),
191+
programAddress: '11111111111111111111111111111111' as Address,
192+
},
193+
],
194+
lifetimeConstraint: {
195+
nonce: 'BzAqD6382v5r1pcELoi8HWrBDV4dSL9NGemMn2JYAhxc' as Nonce,
196+
},
197+
},
198+
});
199+
expect(simulateTransaction).toHaveBeenCalledWith(
200+
expect.anything(),
201+
expect.objectContaining({ replaceRecentBlockhash: false }),
202+
);
203+
});
204+
it('asks for a replacement blockhash even when the transaction message has a blockhash lifetime', () => {
205+
getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT({
206+
rpc,
207+
transactionMessage: {
208+
...mockTransactionMessage,
209+
lifetimeConstraint: MOCK_BLOCKHASH_LIFETIME_CONSTRAINT,
210+
},
211+
});
212+
expect(simulateTransaction).toHaveBeenCalledWith(
213+
expect.anything(),
214+
expect.objectContaining({ replaceRecentBlockhash: true }),
215+
);
216+
});
217+
it('asks for a replacement blockhash when the transaction message has no lifetime', () => {
218+
getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT({
219+
rpc,
220+
transactionMessage: mockTransactionMessage,
221+
});
222+
expect(simulateTransaction).toHaveBeenCalledWith(
223+
expect.anything(),
224+
expect.objectContaining({ replaceRecentBlockhash: true }),
225+
);
226+
});
227+
it('returns the estimated compute units on success', async () => {
228+
expect.assertions(1);
229+
sendSimulateTransactionRequest.mockResolvedValue({ value: { unitsConsumed: 42n } });
230+
const estimatePromise = getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT({
231+
rpc,
232+
transactionMessage: mockTransactionMessage,
233+
});
234+
await expect(estimatePromise).resolves.toBe(42);
235+
});
236+
it('caps the estimated compute units to U32::MAX', async () => {
237+
expect.assertions(1);
238+
sendSimulateTransactionRequest.mockResolvedValue({ value: { unitsConsumed: 4294967295n /* U32::MAX + 1 */ } });
239+
const estimatePromise = getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT({
240+
rpc,
241+
transactionMessage: mockTransactionMessage,
242+
});
243+
await expect(estimatePromise).resolves.toBe(4294967295 /* U32::MAX */);
244+
});
245+
it('throws with the cause when simulation fails', async () => {
246+
expect.assertions(1);
247+
const simulationError = new SolanaError(SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS, {
248+
index: 42,
249+
});
250+
sendSimulateTransactionRequest.mockRejectedValue(simulationError);
251+
const estimatePromise = getComputeUnitEstimateForTransactionMessage_INTERNAL_ONLY_DO_NOT_EXPORT({
252+
rpc,
253+
transactionMessage: mockTransactionMessage,
254+
});
255+
await expect(estimatePromise).rejects.toThrow(
256+
new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT, {
257+
cause: simulationError,
258+
}),
259+
);
260+
});
261+
});

0 commit comments

Comments
 (0)