-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathindex.ts
104 lines (89 loc) · 2.71 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import {
Connection,
Transaction,
TransactionInstruction,
PublicKey,
ComputeBudgetProgram,
} from '@solana/web3.js';
// Add priority fee according to 50th percentile of recent fees paid
const DEFAULT_FEE_PERCENTILE = 0.5;
export async function addComputeBudget(
connection: Connection,
transaction: Transaction,
lockedWritableAccounts: PublicKey[] = [],
): Promise<void> {
const ixs = await determineComputeBudget(
connection,
transaction,
lockedWritableAccounts,
);
transaction.add(...ixs);
}
export async function determineComputeBudget(
connection: Connection,
transaction: Transaction,
lockedWritableAccounts: PublicKey[] = [],
feePercentile: number = DEFAULT_FEE_PERCENTILE,
): Promise<TransactionInstruction[]> {
let computeBudget = 250_000;
let priorityFee = 1;
try {
const simulateResponse = await connection.simulateTransaction(transaction);
if (simulateResponse.value.err) {
console.error(
`Error simulating Solana transaction: ${simulateResponse.value.err}`,
);
}
if (simulateResponse?.value?.unitsConsumed) {
// Set compute budget to 120% of the units used in the simulated transaction
computeBudget = Math.round(simulateResponse.value.unitsConsumed * 1.2);
}
priorityFee = await determinePriorityFee(
connection,
lockedWritableAccounts,
feePercentile,
);
} catch (e) {
console.error(`Failed to get compute budget for Solana transaction: ${e}`);
}
console.info(`Setting Solana compute unit budget to ${computeBudget} units`);
console.info(
`Setting Solana compute unit price to ${priorityFee} microLamports`,
);
return [
ComputeBudgetProgram.setComputeUnitLimit({
units: computeBudget,
}),
ComputeBudgetProgram.setComputeUnitPrice({
microLamports: priorityFee,
}),
];
}
async function determinePriorityFee(
connection: Connection,
lockedWritableAccounts: PublicKey[] = [],
percentile: number,
): Promise<number> {
// https://twitter.com/0xMert_/status/1768669928825962706
let fee = 1; // Set fee to 1 microlamport by default
try {
const recentFeesResponse = await connection.getRecentPrioritizationFees({
lockedWritableAccounts,
});
if (recentFeesResponse) {
// Get 75th percentile fee paid in recent slots
const recentFees = recentFeesResponse
.map((dp) => dp.prioritizationFee)
.filter((dp) => dp > 0)
.sort((a, b) => a - b);
if (recentFees.length > 0) {
const medianFee =
recentFees[Math.floor(recentFees.length * percentile)];
fee = Math.max(fee, medianFee);
}
}
} catch (e) {
console.error('Error fetching Solana recent fees', e);
}
return fee;
}