
| Audited | solana-foundation/solana-web3.js at commit 8837d96f7ce5b446c5f95f1a6dd58647b1eb02b1 |
|---|---|
| Date | 11 October 2026 (audited again; first audit 11 October 2026) |
| How it ran | local run on our workstation, full audit, Standard review |
| Verdict after review | Pass with notes (Fail if a High finding remains after review, otherwise Pass with notes) |
Compared with the first audit
Same commit as the first audit: the project's default branch has no later commits (checked 11 October 2026), so nothing could have been fixed upstream in between. Each finding of the first audit (11 October 2026) was checked again against the code audited now. 25 findings in the first audit; 23 still open (15 found again, 8 not reported again but still present); 2 not in the code, so the first audit was wrong there. This audit has 65 findings after review, 49 of them new.
| First audit | Finding | Reviewed rating then | Now | In this audit |
|---|---|---|---|---|
| #1 | Example sign-in no nonce | Info | Still open | #1, #2 |
| #2 | No secure-context check | Info | Still open | #6 |
| #3 | WS reconnect with no backoff | Medium | Still open | #59 |
| #4 | Failed disconnect leaves selection cleared | Low | Still open | #25 |
| #5 | Nonce confirmation polls | Info | Still open | #11 |
| #6 | Cached blockhash ignores commitment/slot | Not in the code: the first audit was wrong here | not reported again | |
| #7 | Abort listeners never removed | Low | Still open | #8 |
| #8 | ConnectionProvider never closes connections | Low | Still open | not reported again |
| #9 | useLocalStorage not synced | Low | Still open | #23 |
| #10 | Lockup.default shared mutable | Info | Still open | #21 |
| #11 | Loader.chunkSize mutable mid-upload | Not in the code: the first audit was wrong here | not reported again | |
| #12 | Dead commitment branches, contradicting comment | Low | Still open | not reported again |
| #13 | Wire parser: no size cap, quadratic populate | Medium | Still open | #31 |
| #14 | connection.ts about 6,600 lines | Low | Still open | #26 |
| #15 | stake.ts combines five classes | Low | Still open | #33 |
| #16 | legacy.ts mixes four jobs | Low | Still open | #34 |
| #17 | Blockhash flag + sleep loop | Low | Still open | #28 |
| #18 | Repeated connect() not joined | Info | Still open | not reported again |
| #19 | Example send flow repeated 4x | Low | Still open | #38 |
| #20 | console.error scattered | Info | Still open | not reported again |
| #21 | Release does not test exact tarballs | Low | Still open | not reported again |
| #22 | Release gate unit tests only | Low | Still open | not reported again |
| #23 | Same callback twice: removing one cancels other | Medium | Still open | #9 |
| #24 | gh-pages action by mutable tag | Medium | Still open | not reported again |
| #25 | CI pipes unverified installer to sh | Low | Still open | not reported again |
Each finding keeps the number it has in the audit report. The rating shown first is the one after review; the first automated rating is listed with it. 16 findings were first rated Medium or High; 9 of them are Medium or High after review. Text marked "From the report" is quoted from the audit report; fixes are suggestions and were not tested. Code locations link to the file and line at the audited commit.
Medium after review (9)
From the report
(subscription.callbacks as Set<SubscriptionConfig['callback']>).delete(
callback,
);
registering the same callback twice for the same subscription gives two client ids but only one entry in the Set. Removing either id deletes the shared entry, and the other registration stops receiving notifications without any error.
store one entry per client subscription id (a Map keyed by client id), or reference-count the callbacks per hash. Delete only the entry that belongs to the id being removed.
packages/web3.js/src/connection.ts:2327From the report
return await Promise.all(
signatures.map(signature => fetcher(signature, config)),
);
getTransactions and getParsedTransactions are often called with hundreds of signatures (up to 1000 from getSignaturesForAddress). Every request starts at once, which triggers rate limiting (HTTP 429) and socket exhaustion. The retries then add more load on top.
send through a bounded worker pool (5 to 10 requests in flight), or use a single JSON-RPC batch request.
From the report
isSigner:
transaction.signatures.some(
keyObj => keyObj.publicKey.toString() === pubkey.toString(),
every key comparison base58-encodes both keys, inside a nested loop, and the input size is never checked first.
reject buffers larger than the packet size before decoding, and look keys up in a Set of signer addresses built once.
packages/web3.js/src/connection.ts:3771From the report
if (value?.err) {
reject(value.err);
} else if (
when the websocket notification arrives first, a failed transaction resolves with {value: {err}}, and sendAndConfirmTransaction turns that into a SendTransactionError. When the initial status poll arrives first, the promise rejects with the raw error object, which has no message and no stack. Callers get different failure types for the same event.
resolve this path with {context, value} too, exactly as the subscription callback does.
From the report
} catch (e) {
throw new Error(
'failed to get info about account ' + publicKey.toBase58() + ': ' + String(e),
callers can no longer branch on RPC error codes such as "minimum context slot not reached" or "node unhealthy". The "and context" variant of the same method keeps those codes.
use throwSolanaRpcErrorIfNeeded, or wrap the error with {cause}.
From the report
this._disconnectChannel(
SUBSCRIPTION_CHANNEL_CLOSE_CODE_UNEXPECTED,
error instanceof Error ? error : new Error(String(error)),
a failed connect is reported as an unexpected close. The controller marks every subscription pending and calls ensureConnected again with no delay (controller.ts:162-179). An unreachable endpoint produces a tight connect-and-fail loop and a flood of log lines.
add capped exponential backoff with jitter, plus a maximum attempt count or a failed state, before reconnecting. Reset the delay after a successful connect.
packages/web3.js/src/loader.ts:206From the report
transactions.push(
sendAndConfirmTransaction(connection, transaction, [payer, program], {
on the throttled endpoints the loop awaits a sleep while earlier chunk promises have no rejection handler yet. A chunk that fails during that wait is an unhandled rejection, which ends a Node 15+ process before the caller's try/catch can run.
attach a handler to each promise as it is created (for example, collect results with Promise.allSettled), or send the chunks through a bounded queue that awaits each one.
From the report
const options = useMemo(
() => ({autoConnect, chain, filter, storage, storageKey}),
[chain, autoConnect, storage, storageKey, filter],
the layout effect disposes the wallet controller and creates a new one whenever options changes. Toggling auto-connect, as the example's checkbox does, therefore disconnects a connected user. The README and release notes do not list auto-connect as an option that rebuilds the controller.
remove autoConnect from the options that rebuild the controller and pass it to the live controller instead, or document it as a rebuild trigger.
packages/wallet-adapter/README.md:31From the report
<ConnectionProvider endpoint="https://api.mainnet-beta.solana.com">
<WalletProvider chain="solana:mainnet">
the repository's own example app warns that this endpoint rejects browser requests and that sends will fail. Developers who copy the quick start get an app that does not work.
use a placeholder RPC URL, or the devnet endpoint, and note the limits of the public mainnet endpoint.
Low after review (41)
docs/web3js-spl-token-migration.md:336From the report
const mintRaw = await connection.getAccountInfo(mint);
const tokenRaw = await connection.getAccountInfo(tokenAccount);
const mintData = getMintDecoder().decode(mintRaw.data);
an account owned by a different program is accepted as a classic token account, and so is a Token-2022 account. Payment checks built from this sample can be fooled by a substituted account.
before decoding, compare mintRaw.owner and tokenRaw.owner with the expected token program (classic or Token-2022). Use the Token-2022 decoder for Token-2022 accounts.
From the report
| `getMint(connection, address)` | `connection.getAccountInfo(pubkey)` + `getMintDecoder().decode(data)` |
an AI agent that follows this table will generate the decode from finding 4, with no owner check.
state in the table that the account owner must match the expected token program before the decoded values are trusted.
From the report
await mockRpcResponse({ method: 'getBalance', params: [accountPayer.publicKey.toBase58(), ...], value: LAMPORTS_PER_SOL - 1, ...});
expect(balance <= BigInt(LAMPORTS_PER_SOL)).to.eq(true);
in mock mode the test compares canned answers with themselves. A bug that swaps the payer and the sender would still pass.
in mock mode, assert on the transaction itself: the fee payer and the first signer are accountPayer, and the transfer source is accountFrom. Keep the balance checks for live runs only.
packages/web3.js/src/connection.ts:3650From the report
signal.addEventListener('abort', () => {
reject(signal.reason);
});
apps often pass one long-lived AbortSignal to many confirmTransaction calls. Each call adds a listener and a promise that never settles, and neither is released, so memory grows and Node prints MaxListeners warnings.
register the listener with {once: true} and remove it when the confirmation settles. Alternatively, return a {promise, dispose} pair and call dispose in a finally block.
From the report
setBlockDispatchConfig(hash, dispatchConfig): void {
this._blockDispatchConfigByHash.set(hash, dispatchConfig);
}
the copy keyed by server id is refreshed only when a subscription changes state. A later registration for a subscription that is already active is dispatched with the old settings.
when the hash already has a server subscription id, update both maps in one place. Alternatively, resolve the settings through the hash at dispatch time and drop the second map.
packages/web3.js/src/connection.ts:4008From the report
if (status.context.slot < (outcome.slotInWhichNonceDidAdvance ?? nonceMinContextSlot ?? 0n)) {
await Promise.race([sleep(400), cancellationPromise]);
continue;
if the serving node lags and the caller passed no abort signal, an expensive full-history status query repeats every 400 ms with no end.
add a deadline or a maximum attempt count with backoff, and throw a clear timeout error when it is reached.
packages/web3.js/src/loader.ts:260From the report
while (true) {
try {
const currentSlot = await connection.getSlot({
every getSlot error is swallowed and there is no deadline. If the RPC node becomes unreachable after the program is finalized, Loader.load never returns and never reports an error.
add a deadline or a retry cap, and rethrow the last error when it is exceeded. A slot-change subscription is a cheaper signal than polling.
packages/web3.js/src/loader.ts:213From the report
if (connection._rpcEndpoint.includes('solana.com')) {
const REQUESTS_PER_SECOND = 4;
await sleep(1000 / REQUESTS_PER_SECOND);
throttling applies only when the URL happens to contain solana.com. On any other provider, all chunk transactions for a large program are sent at once.
use a bounded-concurrency queue for every endpoint and make the rate configurable. Do not decide behaviour from a substring of the URL.
From the report
publicKey: message.accountKeys[index],
Transaction.from pairs signatures with keys by position and never checks that the counts match. Malformed input fails later with a raw TypeError on an undefined key instead of a clear validation error.
assert signatures.length === message.header.numRequiredSignatures before building the pairs, as the versioned transaction already does.
From the report
this.instructions.forEach(ix =>
this.indexToProgramIds.set(ix.programIdIndex, this.accountKeys[ix.programIdIndex]),
an out-of-range program index is stored silently as an undefined key, and the consistency of the header counts is never checked.
validate the header, key and index invariants in one function that the constructor calls, so every construction path goes through it.
packages/web3.js/src/message/v0.ts:72From the report
this.header = Object.freeze({...args.header});
signer and writable status is calculated from the header. A header whose read-only counts exceed the key counts makes isAccountWritable and isAccountSigner return wrong answers without any error. The same applies at message/v1.ts:175.
write one shared header validator and call it from the legacy, v0 and v1 constructors and from every fromCompiledMessage.
From the report
private indexToProgramIds: Map<number, PublicKey> = new Map<number, PublicKey>();
instructions and accountKeys are public and mutable, but this map is filled only once. After a direct mutation, isProgramId, programIds and nonProgramIds give stale answers.
derive the program ids from the fields when they are read, or make the fields read-only.
From the report
const [network, setNetwork] = useLocalStorage<Cluster>('network', 'devnet');
whatever is in localStorage is cast to a cluster name without a check. A stale or edited value makes clusterApiUrl throw while the root provider renders (providers.tsx:26). The whole app fails on every load, and because the network selector is inside the crashed tree, users cannot fix it without clearing site data.
validate the stored value against the supported networks and fall back to devnet. Let useLocalStorage take an optional validator.
From the report
const stored = globalThis.localStorage?.getItem(key);
return stored ? (JSON.parse(stored) as T) : defaultState;
generic keys such as network can collide with other code on the same origin. A second tab never sees the first tab's change and can overwrite it with stale state.
namespace the keys, validate the parsed value, and listen to the storage event.
From the report
const target = active()?.wallet;
select(null);
try { await namespace.disconnect();
if disconnect rejects, the wallet is still connected but no wallet is selected, so a later connect() throws "wallet not selected".
clear the selection only after disconnect resolves.
packages/web3.js/src/connection.ts:2728From the report
export class Connection {
/** @internal */ _blockhashInfo: {
/** @internal */ private readonly _subscriptionRegistry =
one class of about 3,900 lines holds the blockhash cache, three confirmation strategies, the transport and all RPC methods. Changes are slow to make and risky.
extract the blockhash cache, the confirmation strategies and the HTTP transport into their own modules, and keep Connection as a thin facade over them.
packages/web3.js/src/connection.ts:2740From the report
/** @internal */ _disableBlockhashCaching: boolean = false;
/** @internal */ _pollingBlockhash: boolean = false;
the cache state and the methods that use it are spread through the facade class.
move them into a dedicated blockhash-cache class that Connection holds.
packages/web3.js/src/connection.ts:5636From the report
while (this._pollingBlockhash) {
await sleep(100);
}
callers wait by polling a flag every 100 ms. Two callers that arrive together when the cache is empty both start a refresh, and a caller that bypasses the cache clears the shared flag early.
keep one in-flight refresh promise, return it to every concurrent caller, and clear it when it settles.
From the report
return new Lockup(
Number(lockup.unixTimestamp),
Number(lockup.epoch),
these on-chain fields are 64-bit integers. Values above 2^53, such as the maximum value used to lock an account forever, are rounded when an instruction is decoded. The decoded instruction then shows a wrong value and does not encode back to the same bytes.
keep these fields as bigint (as the stake-account lockup type already does), or throw when a value is not a safe integer.
From the report
export class StakeInstruction {
...
export class StakeProgram {
a file of about 1,600 lines holds three separable concerns.
split it into account, instruction-decoder and program modules, and re-export them from an index file.
From the report
export class Transaction {
...
async getEstimatedFee(connection: Connection)
wire encoding and decoding, signing and RPC calls are all in one class, so a change to one concern risks the others.
extract the wire encode/decode and the signing helpers into separate modules.
packages/web3.js/src/message/v1.ts:209From the report
const instructions = expandInstructionPlans(args.instructions).map(
instruction =>
isKitInstruction(instruction)
the legacy, v0 and v1 message classes each carry a copy of the instruction conversion, the signer test and the codec setup, so a fix to one copy can miss the others.
move the shared logic into one message helper module and call it from all three classes.
From the report
const VOTE_PROGRAM_ID = new PublicKey(
'Vote111111111111111111111111111111111111111',
);
the same id and the same u64 and public-key codecs are also defined in vote-account.ts, so there are two sources of truth.
import them from one module.
From the report
export function createWalletController({
onError,
...config
one 427-line closure holds selection, the connect and disconnect lifecycle, sign-in, message and transaction signing, a long send pipeline and snapshot assembly.
move the send pipeline and the snapshot builder into their own modules.
From the report
const {
context: {slot: minContextSlot},
value: {blockhash, lastValidBlockHeight},
four components repeat the blockhash fetch, send, confirm and notify steps. Only the transaction builder differs, so every fix has to be made four times.
extract one shared hook or helper that takes the transaction builder as its input.
From the report
function isRecord(value: unknown): value is Record<string, unknown> {
return value != null && typeof value === 'object';
}
the same guard is also in connection.ts, kit-adapters/block-notifications.ts and validator-info.ts.
define it once in utils and import it everywhere.
From the report
const BASE58_ENCODER = getBase58Encoder();
const BASE64_CODEC = getBase64Codec();
the same pair is also created in connection.ts, account-notifications.ts, response.ts and message/legacy.ts.
export one shared pair from codecs.ts.
From the report
const sendOptions = options && {
skipPreflight: options.skipPreflight,
preflightCommitment: options.preflightCommitment || options.commitment,
the same block is in send-and-confirm-transaction.ts, so the two helpers can drift apart.
extract one shared mapping helper.
From the report
type RawBlockReward = Readonly<{
commission?: number | null;
identical types are also declared in response.ts.
export them from one module.
From the report
function checkProgramId(programId: PublicKey) {
if (!programId.equals(ComputeBudgetProgram.programId)) {
five program modules each carry their own decode and program-id-check helpers, and the copies already differ. For example, the system program checks the program id in each caller and has no guard for an unknown instruction type.
write one generic decode helper that takes the program id, the parser and the expected type, and use it from all five modules.
From the report
signatures.length * 64 + signData.length;
the literal 64 appears in several files, and in others it is re-declared locally, next to an imported constant for the same value.
use the existing signature-length and public-key-length constants everywhere.
From the report
if (error.name !== 'AbortError') setError(error.message);
the same check is in WalletModal.tsx and WalletMultiButton.tsx, so a change in how superseded requests are recognised can miss one copy.
use one shared helper or hook.
From the report
const PUBLIC_MAINNET_HOSTS = new Set(['api.mainnet-beta.solana.com','api.mainnet.solana.com']);
the wallet controller keeps its own list of the official endpoints, and both lists must change together.
export the list from the package and derive the warning from it.
From the report
export const mockServer = process.env.TEST_LIVE === undefined ? new MockHttpServer() : undefined;
when TEST_LIVE is set to an empty string, some files treat the run as live and others as mocked. Tests then call a port that nothing listens on.
export one boolean from test/url.ts and use it everywhere.
From the report
function isPromise<T>(value: PromiseLike<T> | T): value is PromiseLike<T> {
an identical copy is in mocks/rpc-http.ts.
move it to a shared test utility.
From the report
function getSubscriptionRegistry(connection: Connection): { hasServerSubscription(serverSubscriptionId: number): boolean; }
the same accessor and its constant are also in connection-subscriptions.test.ts.
move both into the shared test utilities.
From the report
function createTestKeys(count: number): Array<PublicKey> {
return Array.from({length: count}, () => getUniqueAddress());
createTestKeys is copied into six files and createTestLookupTable into three.
put both next to getUniqueAddress in test/utils/address.ts.
packages/web3.js/src/connection.ts:4910 (also 4976)From the report
} catch (e) {
throw new SolanaJSONRPCError(
e as JsonRpcErrorLike,
in getBlock and getParsedBlock, network failures, aborts and mapping errors all become JSON-RPC errors with an undefined code, and the original error and its stack are lost. Every other method rethrows non-RPC errors unchanged.
use the existing throwSolanaRpcErrorIfNeeded helper here, as the sibling methods do.
From the report
const info = parseInfo(JSON.parse(rawInfo));
return new ValidatorInfo(configKeys[1].publicKey, info);
the method is documented to return null when no info is found, but it throws on malformed JSON. Any validator can publish such text, and one bad account aborts every consumer that enumerates all validator-info accounts.
wrap the parse and the validation, and return null (or a typed error) for malformed content.
examples/wallet-adapter/.env.example:1From the report
# Private mainnet RPC. The public mainnet endpoint returns 403 to browsers.
NEXT_PUBLIC_MAINNET_RPC_URL=
Next.js copies every NEXT_PUBLIC_ value into the shipped JavaScript, and this app is a static export. A provider URL that carries an API key becomes readable by every visitor, who can then use up its quota.
say in the template that this value is public. Recommend an origin-restricted browser key, or put a server-side RPC proxy in front of private endpoints.
From the report
npm publish "$TARBALL" --access public --tag "$NPM_TAG"
PUBLISHED=$((PUBLISHED + 1))
the packages are published in a loop. If the first package publishes and the second fails, no tag or GitHub release is created. A re-run then fails at the pre-flight "already published" check (line 300), so the only way out is to bump the version of both packages.
make the publish step skip a package already on the registry at that version (after confirming the content matches), and fail only when a package is missing. Create the tag and release in a step that records what was published, even after a partial failure.
Info after review (15)
From the report
const message = new TextEncoder().encode(
`${window.location.host} wants you to sign in with your Solana account:\n${publicKey.toBase58()}\n\nPlease sign in.`,
the text has no nonce and no expiry, so one signature stays valid for every later use of the same text. Readers who copy this demo into a login flow get a replayable sign-in.
have the server issue a random nonce with an issue time and an expiry. Include them in the signed text and verify them, and the domain, on the server. Label the fixed text as demo-only.
From the report
const input: SolanaSignInInput = {
address: address ?? undefined,
domain: window.location.host,
there is no replay protection, and a check that runs only in the browser proves nothing to a backend.
add a server-supplied nonce, issuedAt and expirationTime. Add a comment that verifySignIn must run on the server against the nonce the server issued.
From the report
const {signature, signedOffchainMessage} = await signOffchainMessage(
`${window.location.host} wants you to sign an offchain message.`,
);
the demo checks the signature over whatever bytes the wallet returned, not over the content it asked for. Code copied from it would accept a signature over different content.
decode signedOffchainMessage and compare its content and required signers with the request before you treat the signature as proof.
From the report
target = selectedWallet();
if (active()?.wallet.name === target.name) return;
await namespace.connect(target);
browser wallets refuse to work on plain-HTTP origins other than localhost. The library never checks the origin, so integrators see an unexplained failure.
before connecting, check window.isSecureContext. When the origin is insecure and not localhost, raise a configuration error that says to serve the app over HTTPS.
packages/web3.js/src/connection.ts:3966From the report
sleep(2000),
...
const nextNonceValue = await Promise.race<
an RPC request every 2 seconds, while the same Connection already offers an account-change subscription for the nonce account.
use the account-change subscription as the main signal, and keep a slow poll only as a fallback when the subscription is not active.
packages/web3.js/src/programs/stake.ts:1069 (also programs/vote.ts:371)From the report
export const StakeAuthorizationLayout = Object.freeze({
Staker: {
index: 0,
the nested Staker, Withdrawer and Voter objects can still be changed at runtime. Their index goes straight into instruction data, so one stray write changes which authority later instructions set.
freeze the nested objects as well, or export plain numeric constants.
From the report
static default: Lockup = new Lockup(0, 0, PublicKey.default);
every stake account initialized without an explicit lockup uses this one object, so mutating it changes the lockup of all later accounts.
return a fresh or frozen instance from a getter, and mark constant statics read-only.
From the report
setTimeout(() => setCopied(false), 400);
the timer can fire after the component has unmounted. The same pattern is in the example's Notifications.tsx:41.
keep the timer id in a ref and clear it in an effect cleanup.
packages/web3.js/src/connection.ts:1825From the report
const rawResponse = await response.text();
return (
rawResponse.length === 0 ? null : parseJsonWithBigInts(rawResponse)
a misbehaving or hostile endpoint can make the client buffer and parse an unbounded body.
add a configurable maximum response size and a default request timeout.
packages/web3.js/src/timing.ts:7From the report
// TODO: These constants should be removed in favor of reading them out of a
// Syscall account
export const NUM_TICKS_PER_SECOND = 160;
poll intervals are derived from these values, so they are mis-tuned on clusters with a different slot time.
derive the slot time from cluster data, or make the poll intervals configurable.
From the report
export function supportsTransactionVersion(
wallet: Wallet,
version: SolanaTransactionVersion,
components/transactionVersion.ts has a helper with the same name and a different input. A wrong import can compile and quietly answer a different question.
rename one of them, for example to walletAdvertisesTransactionVersion.
From the report
onClick={onClick}
disabled={!publicKey}
the button stays enabled while the wallet prompt and the send are pending, so a double click starts two sends.
disable the button, or reuse the in-flight promise, until the action settles.
From the report
? 'Connect a wallet on Solana to continue'
: "You'll need a wallet on Solana to continue"
the buttons accept a labels map, but the modal hard-codes its strings, so integrators who work in other languages have to fork it.
add a labels prop to the modal, with the current English strings as defaults.
From the report
import type {
BlockSubscriptionAccountsModeBlockResponse,
} from '../connection';
connection.ts imports the adapters and the adapters import types back from it, which makes the module graph cyclic.
move the shared response and config types into a neutral types module that both sides import.
From the report
const noSubscription = () => () => {};
the helper is repeated in the example's PublicEndpointWarning.tsx and Settings.tsx.
export it once, together with a small "is mounted" hook.