Skip to content

Conversation

Davien21
Copy link
Contributor

@Davien21 Davien21 commented Sep 7, 2025

What I did

Corrected BN (Big Number) usage in memcmp filters to ensure proper 8-byte little-endian encoding for u64 values


Problem

The current documentation shows:

bytes: bs58.encode(new BN(0, "le").toArray()),

This is problematic for two reasons:

  1. Incorrect use of BN constructor: The second argument to BN is the numeric base, not the endianness. Passing "le" is misleading and may behave inconsistently across bn.js versions.
  2. Variable-length encoding: .toArray() without an explicit length produces a variable number of bytes. For example, new BN(5).toArray("le") yields [5], but Solana accounts store u64 values in 8-byte little-endian format. Using shorter arrays may still match as a prefix in memcmp filters, but it’s unsafe and can produce false positives or fail unexpectedly.

Fixes

Updated example to:

bytes: bs58.encode(new BN(0).toArray("le", 8)),

Ensures numbers are serialized as fixed-length 8-byte little-endian arrays, consistent with Solana’s on-chain u64 layout. This makes memcmp filters deterministic and avoids misleading or unsafe BN usage.


Example Failure

Suppose an on-chain account has a u64 field set to 65536.

On-chain bytes (u64 LE):

[0, 0, 1, 0, 0, 0, 0, 0]

Current doc version (new BN(65536, "le").toArray()):

[1] // only 1 byte

→ Encodes incorrectly, does not match the on-chain value.

Correct version (new BN(65536).toArray("le", 8)):

[0, 0, 1, 0, 0, 0, 0, 0]

→ Matches exactly as expected.

The documentation previously showed `new BN(value, "le").toArray()` when demonstrating
memcmp filters. This is misleading because the second argument to `BN` is the base, not
endianness, and the resulting array is variable length.

Updated example here now uses:
  new BN(value).toArray("le", 8)

This ensures the number is serialized as an 8-byte little-endian value, consistent with
Rust’s u64 layout on Solana. Without the explicit length, filters may fail when values
require fewer bytes (e.g. 5 → [5] instead of [5, 0, 0, 0, 0, 0, 0, 0]).
Copy link

vercel bot commented Sep 7, 2025

@Davien21 is attempting to deploy a commit to the Solana Foundation Team on Vercel.

A member of the Team first needs to authorize it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant