Skip to content

fix(abi): encode and decode static arrays with dynamic elements - #2334

Open
Saurav1375 wants to merge 2 commits into
LFDT-web3j:mainfrom
Saurav1375:fix/abi-static-array-dynamic-elements
Open

Saurav1375 wants to merge 2 commits into
LFDT-web3j:mainfrom
Saurav1375:fix/abi-static-array-dynamic-elements

Conversation

@Saurav1375

@Saurav1375 Saurav1375 commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

required

It fixes ABI encoding and decoding of static arrays whose elements are dynamic (bytes[2], string[2], uint256[][2], bytes[2][2], bytes[2][]) and of nested static arrays (uint256[2][2], uint256[][2][2]). Under the ABI spec, T[k] is dynamic whenever T is dynamic. It then takes a single offset word in the head of a tuple. web3j only applied this rule partly, so it produced the following bugs.

1. Decoding silently returns wrong values for every field after a bytes[2] (and similar)

  • Symptom:
    • (bytes[2], uint256) decodes the uint256 as 64 instead of 1965.
    • A real contract returning (bytes[2], uint256, string[2], uint256) gives [[lol1,omg2], 320, [,], 64] instead of [[lol1,omg2], 1965, [wat3,yes4], 42], with no exception.
    • (bytes[2], bytes, uint256) throws StringIndexOutOfBoundsException.
    • Event decoding is affected the same way, because it uses the same decoder.
  • Root cause: DefaultFunctionReturnDecoder.build advances the head by length * 32 bytes for a static array, even when the array is dynamic and only occupies one offset word: DefaultFunctionReturnDecoder.java#L109 and #L143. Only string[k] had a special case, and only for class-based TypeReferences. Type references built with TypeReference.makeTypeReference("string[2]") were still wrong.
  • Fix: new helpers Utils.isDynamic(TypeReference) and Utils.staticSizeInWords(TypeReference). Both recurse through any nesting depth. Both static-array branches now advance by one word if the array is dynamic, and by its full in-place size otherwise. getDataOffset uses the same recursive check.

2. Nested static arrays cannot be decoded at all

  • Symptom:
    • uint256[][2] → UnsupportedOperationException: Unsupported type encountered: uint256[]
    • uint256[2][2] → Unsupported type encountered: uint256[2]
    • bytes[2][2] → StringIndexOutOfBoundsException
    • uint256[][2][2] → IndexOutOfBoundsException
  • Root cause:
    • TypeDecoder.instantiateStaticArray uses the deprecated StaticArray(List) constructor. That constructor resolves the component class from the element's type string, and AbiTypes cannot resolve array type strings: TypeDecoder.java#L867.
    • In decodeArrayElements, the position after an inner static array is computed by reading the array's first value as if it were a length: TypeDecoder.java#L1014. This only works by accident when that value is small.
  • Fix:
    • Nested arrays are built with the (Class, List) constructor, using the element's class.
    • Inner static arrays are followed through their offset when dynamic (bytes[2][2]). Otherwise they are read in place and the position advances by their static size (uint256[2][2]).

3. Static arrays with dynamic elements cannot be passed as function inputs (the call reverts)

  • Symptom:
    • take(bytes[2], uint256) and sum(uint256[][2], uint256) revert on-chain.
    • The calldata differs from cast calldata in the first head word: 0x60 instead of 0x40.
  • Root cause:
  • Fix:
    • TypeEncoder.isDynamic(Type) checks nested elements.
    • getLength counts any dynamic parameter as one slot.
    • Dynamic arrays of dynamic static arrays get element offsets.

4. Struct fields that are static arrays cannot be decoded, and their events never match

This is the second commit.

  • Symptom:
    • Decoding a struct with a bytes[2], string[2], uint256[][2] or uint256[2][2] field throws UnsupportedOperationException: Array types must be wrapped in a TypeReference.
    • Utils.getStructType returns (staticarray2,uint256) instead of (bytes[2],uint256). Event topics computed from it are wrong, so get...Events(receipt) silently returns an empty list.
  • Root cause:
    • Struct decoding and getStructType take each field's type from the raw constructor parameter class: TypeDecoder.java#L465, #L682, Utils.java#L67. For StaticArray2<DynamicBytes> that loses the element type.
    • Static structs are sized as one word per field, so a uint256[2][2] field counted as 1 word instead of 4.
  • Fix:
    • Static-array fields are read from the constructor's generic parameter types (Utils.staticArrayParameterType). Static ones are decoded in place, dynamic ones through their offset.
    • Utils.staticStructSizeInWords counts static-array fields at full size. It is used everywhere a static struct's size was computed from its field count. Structs without static-array fields keep the existing count.

Where should the reviewer start?

required

  1. abi/src/main/java/org/web3j/abi/Utils.java: isDynamic(TypeReference) and staticSizeInWords(TypeReference). These are the single source of truth for "does this take one offset word, or N words in place". For structs, see staticStructSizeInWords and staticArrayParameterType (second commit).
  2. DefaultFunctionReturnDecoder.build / staticArrayHeadLength: the top-level offset fix.
  3. TypeDecoder.decodeArrayElements (nested StaticArray branch) and instantiateStaticArray.
  4. TypeEncoder.isDynamic / encode, and DefaultFunctionEncoder.getLength: the encoder side.
  5. abi/src/test/java/org/web3j/abi/StaticArrayDynamicElementsTest.java. Every expected encoding is generated by Foundry's cast abi-encode (the command is in a comment above each vector). This makes the reference an independent ABI implementation rather than web3j itself. Each tuple ends in a uint256, so a wrong head size shows up as a wrong trailing value.
  6. abi/src/test/java/org/web3j/abi/StructStaticArrayFieldsTest.java: structs shaped like the ones web3j codegen generates. It covers struct type strings, decoding, and encoding, against cast abi-encode vectors.

Why is it needed?

required

These types are common in real contracts, for example bytes[2] proofs, string[2] pairs and fixed-size batches of dynamic arrays. On main:

  • Return values and events can be silently wrong. No exception is thrown, so applications act on corrupted data.
  • Contract calls that take these types as inputs revert.
  • Nested static arrays (uint256[2][2], uint256[][2]) cannot be decoded at all.

Relation to existing PRs

This supersedes #2282 by @snuderl ("fix(abi): StaticArray offset incorrect for DynamicBytes/DynamicArray elements"). That PR has had no activity since April 2026. It correctly identified the top-level offset bug, and this PR keeps its approach and test case. It also addresses the open feedback on #2282:

Before / after

A small sample project (not part of this PR) depends on the local web3j checkout through a Gradle composite build (includeBuild '../web3j'). Its abiChecks task does two things:

  • It decodes and re-encodes 10 tuples, comparing against cast abi-encode.
  • It deploys two contracts to a local anvil chain with web3j, then checks return values, events and inputs.

The task is run once with main checked out and once with this branch:

upstream/main this branch
Offline decode/encode checks 4 / 30 pass 30 / 30 pass
On-chain checks 0 / 6 pass 6 / 6 pass

Before (main): wrong values with no exception, crashes on nested arrays, and reverted calls.

B1-abi-main

After (this branch):

B2-abi-branch

StaticArrayDynamicElementsTest: 22 of 24 tests fail when the new test class is run against main's code. All 24 pass on this branch. The init script only prints one line per test result.

Before (main code, new test class copied in):

B3-tests-main >

After (this branch, with spotlessCheck):

B4-tests-branch

StructStaticArrayFieldsTest (struct fields, second commit): 4 of 5 tests fail against main's code. Encoding already works once the first commit is in. All 5 pass on this branch.

B5-structs-main B6-structs-branch

End to end, with generated wrappers for contracts whose structs have bytes[2], string[2], uint256[][2] and uint256[2][2] fields: see #2335. Code generation for these structs is fixed there, and the last screenshot in #2335 shows both PRs merged locally passing 10 / 10 on anvil.

Test results

  • ./gradlew :abi:spotlessCheck :abi:test: 216 tests, 0 failures (29 new); spotless clean
  • ./gradlew check (all modules, without integration tests): 1211 tests, 0 failures, 3 skipped
  • ./gradlew -Pintegration-tests=true :integration-tests:test: 87 tests, 0 failures, 18 skipped (run locally with JAVA_TOOL_OPTIONS=-Dapi.version=1.44 before the Docker 29 fix in build: run integration tests on Docker 29 and fix -Pintegration-tests=false #2327 was merged; CI now runs them without it)
  • About 61k leaf-type decodes give identical results on main and this branch (values and exception messages), so non-array decoding is unchanged.

Related PRs

Generated wrappers had separate problems with these types. They are fixed in #2335 (core / codegen), which is independent of this PR:

  • nested arrays were not converted to native Java types;
  • structs with bytes[2] fields were generated as StaticStruct;
  • wrappers for structs with uint256[][2] fields did not compile.

Checklist

  • I've read the contribution guidelines.
  • I've added tests (if applicable).
  • I've added a changelog entry if necessary.

Static arrays whose elements are dynamic (bytes[2], string[2],
uint256[][2], bytes[2][2], ...) are themselves dynamic: they take one
offset word in the head of a tuple. Nested static arrays of static
elements (uint256[2][2]) are encoded in place.

- Decoder: advance the head by one word for dynamic static arrays and by
  the full static size otherwise, decided recursively (previously
  length * 32 bytes, which silently returned wrong values for every
  following field, e.g. (bytes[2], uint256)).
- Decoder: fix the inner-array offset for nested static arrays, and build
  nested StaticArray instances with an explicit component class instead
  of resolving "uint256[]"/"uint256[2]" through AbiTypes (which threw).
- Encoder: treat static arrays as dynamic when any nested element is, so
  the head offset is correct and bytes[2][2] / bytes[2][] get offsets.

Supersedes LFDT-web3j#2282.

Signed-off-by: Saurav1375 <sauravgupta1375@gmail.com>
Struct decoding picked each field's type from the raw constructor
parameter class. For a field declared as StaticArray2<DynamicBytes>
(bytes[2]) or StaticArray2<StaticArray2<Uint256>> (uint256[2][2]) the
element type was lost, so decoding threw "Array types must be wrapped in
a TypeReference", and the struct type string used in event signatures
was "(staticarray2,uint256)" instead of "(bytes[2],uint256)", so events
with such structs were never matched.

- Read static-array fields from the constructor's generic parameter
  types, decode them in place when static and through their offset when
  dynamic (bytes[2], string[2], uint256[][2]).
- Size static structs by their real word count: a uint256[2][2] field is
  4 words, not 1. Structs without static-array fields keep the existing
  flattened field count.
- Build struct type strings from the generic parameter types.

Signed-off-by: Saurav1375 <sauravgupta1375@gmail.com>

This branch has not been deployed

No deployments
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