Skip to content

fix: tips in balance checks, salt width, fee bounds, gas estimate (7 community contributions) - #972

Merged
ryanio merged 8 commits into
mainfrom
community/seaport-fixes-stack
Aug 22, 2026
Merged

ryanio merged 8 commits into
mainfrom
community/seaport-fixes-stack

Conversation

@ryanio

@ryanio ryanio commented Aug 22, 2026

Copy link
Copy Markdown
Collaborator

Stacks seven open community contributions onto one branch. Each contributor's commit is preserved with their authorship. The individual PRs are superseded and closed pointing here.

Four of them collided in src/utils/order.ts and test/utils/order.spec.ts, so reviewing and merging them as one series is cheaper than seven rebases.

Source Author What it does
#962 @Dusk1e Include tips in the fulfiller's balance and approval set. Tipping in a token the order does not carry throws today.
#964 @Ruzzgar estimateGas was estimating untagged arguments while transact sends tagged calldata.
#971 @chalomdev Resolve a zero totalSize before scaling tips. Hardening, not a live fix, see below.
#963 @Xowiek Keep domain-tagged salts a full 32 bytes. An unwidthed toBeHex drops a leading zero byte.
#961 @wodesiku Bound individual fee basisPoints, not just the total.
#970 @devorun Unit coverage for mapInputItemToOfferItem.
#969 @vhtgzzl Buffer half only. The salt half duplicated #963, and its test asserted a wrong tag value.

Verification

Every source fix was checked by reverting only its source hunk and confirming its test fails on the assertion it is named for:

On #971

scaleOrderStatusToMaxUnits already rewrites a zero totalSize at both call sites (src/seaport.ts:870 and :1060) before totalSize reaches fulfillStandardOrder or fulfillAvailableOrders, so the divide-by-zero is not reachable through the public API. Taken because the invariant is currently protected only by a caller two files away.

Semver

#961 adds a throw on input that previously returned, and changes an existing error message. Minor, not a patch.

Follow-up, not in this PR

An audit of the remaining Node-only APIs found that src/utils/merkletree.ts also requires the Buffer global, on a path every criteria order goes through, and that merkletreejs does require("buffer") in the module graph of every Seaport consumer. That work touches the merkle path and belongs in its own PR rather than here.

npm run build, npm run lint (tsc and Biome), and npm test all clean. 192 passing.

Dusk1e and others added 8 commits August 21, 2026 16:51
fulfillOrder and fulfillOrders collect the fulfiller's balances and
approvals from the order's offer and consideration items only, but the
checks that consume them sum tips in alongside the consideration. When a
tip names a token or identifier the order does not already carry, there
is no entry to look up and findBalanceAndApproval throws

  Checking for balance and approvals for token 0x... id 0 failed

before a transaction is ever built. That rules out ordinary tips: a
native ETH tip on an ERC20-denominated listing, a tip in a second ERC20,
or an NFT tip.

Include the mapped tip items in the fulfiller's lookup set so the tips
are actually checked rather than crashing the lookup. Tips are appended
after the order's items, so the criteria mapping the existing items rely
on is unchanged. This also means a tip in a token the fulfiller has not
approved now surfaces its own approval action, which the fulfillment
would otherwise revert without.
When a domain is passed, getTransactionMethods appends its four byte tag to
the calldata inside buildTransaction, and transact sends exactly that. But
estimateGas called the contract method with the encoded arguments only, so
the tag was missing from what it measured.

Calldata is charged per byte, so the returned estimate lands below what the
transaction actually consumes. On a validate() call:

  estimateGas() -> 65562
  gasUsed       -> 65626

A caller passing the estimate straight through as a gas limit, which is the
normal reason to ask for one, runs out of gas.

Estimate the transaction buildTransaction produces whenever a domain is set,
so the measured calldata is the calldata that gets sent. Calls without a
domain keep going through the contract method unchanged.

staticCall has the same gap but no visible symptom, since Seaport ignores
the trailing bytes and returns the same result either way, so it is left
alone.
mapOrderAmountsFromUnitsToFill resolves a totalSize of 0 (an order that
hasn't been partially filled yet, a common on-chain state) to the
order's own maximum size internally. That resolution is local to the
function and never reaches the sibling mapTipAmountsFromUnitsToFill
call in fulfillAdvancedOrder/fulfillAvailableAdvancedOrders, which
receives the raw, still-zero totalSize and passes it straight into
multiplyDivision as a division denominator - BigInt division by zero
throws a RangeError in JS.

Fulfilling an order with tips and an explicit unitsToFill on an order
that hasn't been filled yet (totalSize === 0n from the contract) would
throw, uncaught, instead of computing tip amounts.

Fix resolves totalSize once via getMaximumSizeForOrder and passes the
same resolved value to both the order and tip scaling calls, at both
call sites (fulfillAdvancedOrder and fulfillAvailableAdvancedOrders).
The mapTipAmountsFromFilledStatus / mapOrderAmountsFromFilledStatus
pair is untouched: both already treat totalSize === 0n as "leave
unscaled" consistently, so no fix is needed there.
generateRandomSalt builds a domain-tagged salt by concatenating the first
four bytes of keccak256(domain), twenty zero bytes and eight random bytes,
then passes the result through toBeHex. concat already yields 32 bytes, but
toBeHex without a width re-encodes the value as a number, so any leading
zero byte is dropped.

A domain whose hash starts with 0x00 -- about one in 256 -- therefore gets a
31-byte salt with every byte shifted one to the left. Reading the tag back
off the salt returns the wrong four bytes, so the order can no longer be
attributed to the domain that created it:

  domain "d362", tag 00b508f2
  salt   0xb508f200000000000000000000000000000000000000005... (31 bytes)
  salt.slice(2, 10) -> b508f200, not 00b508f2

test/create-order.spec.ts already asserts this invariant with
`expect(order.parameters.salt.slice(0, 10)).eq(openseaMagicValue)`; it only
holds today because keccak256("opensea.io") happens to start with 0x36.

Pass the 32-byte width to toBeHex. The order itself is unaffected either
way, since salt is a uint256 and both forms carry the same value -- the
order hash and signature already matched. What changes is that the tag
survives in the serialized salt for every domain, and the generated salt is
now padded the same way a caller-supplied one already is in _formatOrder.
Add unit tests for mapInputItemToOfferItem, the normalizer every
createOrder input item passes through on its way to a Seaport OfferItem.
It was previously only exercised indirectly through the hardhat-backed
create-order specs, so these fast, isolated units pin its per-variant
behavior: basic ERC721/ERC1155 items, criteria items (explicit root and
identifiers-derived merkle root), the amount defaults each variant
applies, and native vs ERC20 currency items.
The no-domain branch built its salt with `Buffer.from(...).toString("hex")`.
`Buffer` is a Node global that browser bundlers do not polyfill by default, so
the call threw "Buffer is not defined" in a browser build. opensea-sdk reaches
this exact branch: `constructPrivateListingCounterOrder` calls
`generateRandomSalt()` with no argument. Build the same 32 bytes (24 zero bytes
plus 8 random) from the ethers primitives already imported here.

Byte-for-byte equivalent to the old output, so the salt format is unchanged.

Taken from #969. The domain-branch half of that PR
duplicated #963 and is dropped, as is its null-coalescing in
findBalanceAndApproval, which guards non-nullable typed parameters and does not
address the missing-entry case that #962 fixes.

Co-authored-by: vhtgzzl <317591381+vhtgzzl@users.noreply.github.com>
The Buffer removal it guards had no coverage at all: reverting the source
change left all 191 tests passing, because Node always defines Buffer and
nothing in the suite runs without it. Delete the global for the duration of
one test so the assertion actually fails ("ReferenceError: Buffer is not
defined") if the Node dependency comes back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@ryanio
ryanio merged commit 73886ee into main Aug 22, 2026
8 checks passed
@ryanio
ryanio deleted the community/seaport-fixes-stack branch August 22, 2026 00:32
ryanio added a commit that referenced this pull request Aug 22, 2026
…rder (#973)

`considerationCriteriaItems` is computed from the tip-appended consideration,
so a criteria-based tip counts toward the "you must supply the appropriate
criterias" check and sets `hasCriteriaItems`. But `generateCriteriaResolvers`
is passed the order alone, so the tip never gets a resolver. The SDK therefore
returns a use case whose exchange action Seaport reverts with
`UnresolvedConsiderationCriteria`. Worse, if the caller listed the tip's
criteria first, the order's own criteria item resolves against the tip's
identifier on the way to that revert.

This was previously masked: the fulfiller's balance lookup had no entry for a
tip token, so `findBalanceAndApproval` threw first. #972 fixed that lookup,
which removes the earlier wall and exposes this path, so a criteria tip now
costs gas to discover instead of failing for free.

Reject it in the SDK. `TipInputItem` is `CreateInputItem & { recipient }`, so
a criteria tip type-checks today, but nothing can fulfil one, and emitting
resolvers for tips would be adding a feature rather than fixing a regression.

Verified as a tripwire: with both call sites removed the test fails with
"expected promise to be rejected ... but it was fulfilled with { actions: [...] }",
which is the doomed transaction being handed back.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
ryanio added a commit that referenced this pull request Aug 22, 2026
#972 removed the `Buffer` global from `generateRandomSalt`, but that was one of
several sites. Two more sit on paths reachable from the public `Seaport` class:

- `merkletree.ts` `hashIdentifier` bufferified the padded identifier before
  hashing. `mapInputItemToOfferItem` calls it for every criteria-based item, so
  every collection and trait offer hit it.
- `eip712/Eip712MerkleTree.ts` `getTree` mapped its leaves through
  `hexToBuffer` and hashed with `bufferKeccak`. That is `signBulkOrder` and
  `createBulkOrders`.

`Buffer` is a Node global that bundlers do not define, so both threw
"ReferenceError: Buffer is not defined" in a browser while passing every test
in Node. merkletreejs accepts hex strings for leaves, for the fill hash, and as
the hash function's return, and bufferifies them itself, so handing it hex
produces an identical tree.

Verified value-preserving rather than merely working: roots and proofs were
compared before and after for identifiers ["1","2","3","0","255", 2**256-1],
covering an odd leaf count and both boundary identifiers, plus the bulk-order
root, proof, and encoded signature for 1, 2, 3 and 5 components. Byte-identical
throughout. Those goldens are now pinned as tests, which is why they pass on
both sides of each tripwire below.

`hashIdentifier` deliberately keeps the `padStart` form rather than the tidier
`toBeHex(identifier, 32)`: the latter throws above 2**256-1 where the old code
silently hashed a 33-byte preimage, so padStart keeps every input, valid or not,
byte-identical.

This does NOT make the library isomorphic. merkletreejs does `require("buffer")`
and it is in the module graph of every Seaport consumer, so an esbuild browser
build still fails outright without a `buffer` alias, and the five exported
helpers in `eip712/utils.ts` remain Node-only. What changes is that seaport-js's
own code no longer needs the global on any live path.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
ryanio added a commit that referenced this pull request Aug 22, 2026
…ces, zero fees, conduit case, and exports (8 community contributions) (#985)

* test: pin the zero-totalSize tip-scaling resolution from #972

Adds a focused unit test against mapTipAmountsFromUnitsToFill covering
both halves of the #971/#972 hardening: the function throws given a
raw totalSize of 0 (why the resolution exists), and correctly scales
a tip once totalSize is resolved to the order's maximum size via
getMaximumSizeForOrder, matching what fulfillStandardOrder does
before calling it.

* fix: export the symbols the docs tell people to use

The entry point exports Seaport and nothing else, so that is the whole
surface a consumer gets without a deep import:

  require("@opensea/seaport-js")  ->  [ 'Seaport' ]

Both order examples in the README are written with ItemType.ERC721, and no
example imports it because there is nowhere to import it from. Copying
either one leaves ItemType undefined. fulfillOrder's doc comment has the
same problem: "We expose a helper to get this: getMaximumSizeForOrder", and
that helper is not exported either.

Export the two the documentation already promises, and add the import line
the README examples were missing. Adding to the entry point breaks nothing;
Seaport keeps resolving exactly as it did.

The second example also reached for a bare parseEther while the first uses
ethers.parseEther, so it now matches its neighbour.

Left alone deliberately: the rest of the constants and the input types are
still deep-import only. Widening the public surface further is a call worth
making on purpose rather than as a side effect of a docs fix.

* fix: leave out a fee item that rounds down to zero

multiplyBasisPoints floors, so on a small enough price the fee comes out as
0 and _formatOrder appends a zero-amount consideration item anyway. Seaport
rejects zero-amount items with MissingItemAmount, so the order is signed,
published and impossible to fill.

  price 100 at 50 bp   -> consideration [100, 0]  -> MissingItemAmount
  price 10  at 250 bp  -> consideration [10, 0]   -> MissingItemAmount
  price 1000 at 250 bp -> consideration [975, 25] -> fills

Nothing surfaces at creation time. The seller finds out when a buyer cannot
take the listing.

The item is worth nothing anyway -- deductFees floors the same way, so the
consideration was never reduced for it -- and dropping it leaves an order
that behaves exactly as the arithmetic says. That is better than refusing to
build the order, which would block low priced listings outright.

Only drop it when both ends are zero. A fee can floor to zero at the start
of an ascending range and still pay across the rest of it; Seaport looks at
the amount current at fill time, and an order like that settles today.

* fix: resolve a conduit key regardless of its hex case

conduitKeyToConduit is indexed with the conduit key exactly as it arrives.
A conduit key is a bytes32, so the same value can be written in any hex
case, and a key that differs only in case misses the lookup. The operator
comes back undefined and the failure surfaces from ethers as

  unsupported addressable value (argument="target", value=null)

which mentions neither the conduit nor the key.

Five call sites read that map: the operator approvals are granted to at
order creation, the offerer and fulfiller operators on fulfillOrder, and the
same two on fulfillOrders. All five are affected, so an order carrying a
re-cased key cannot be created or filled.

Everywhere else the SDK compares hex it already lowercases both sides --
tokens in findBalanceAndApproval and getSummedTokenAndIdentifierAmounts,
operators in getApprovalDedupKey, owners in balanceOf, the recipient in
shouldUseBasicFulfill, currencies in areAllCurrenciesSame. The conduit key
is the one hex comparison left keyed on the raw string.

Lower case the map when it is built and lower case the key on the way in,
behind a small helper so all five sites go through the same path. A key that
already matches the configured case resolves exactly as before.

* fix: type executeAllActions as the transaction it actually sends

On an exchange use case executeAllActions returns
finalAction.transactionMethods.transact(), which resolves to a
TransactionResponse. OrderUseCase declares ContractTransaction for that
branch, and the three fulfill helpers cast to it on the way out.

Those are different things in ethers v6. ContractTransaction is a prepared
request; TransactionResponse is a transaction that has been sent. The
response carries hash, wait() and confirmations(), and the request carries
none of them, so the natural thing to write after a fulfillment does not
compile:

  const transaction = await useCase.executeAllActions()
  await transaction.wait()
    Property 'wait' does not exist on type 'ContractTransaction'

The code runs fine, it is only the annotation that is wrong. Callers are
left casting through any to get at the receipt.

Point the branch and the three casts at TransactionResponse, which is
already what transact() is declared to return.

* fix: drop unfillable orders from a batch instead of failing the batch

fulfillOrders is documented as best effort: "Orders that fail will not
revert the whole transaction". fulfillAvailableAdvancedOrders behaves that
way on chain, skipping what it cannot fill and settling the rest.

The SDK never gets that far. fulfillAvailableOrders maps every order
through validateAndSanitizeFromOrderStatus, which throws on the first
cancelled or fully filled one, so a single stale order takes down the whole
call before any transaction is built. Cancel one of two listings and the
contract reports availableOrders [false, true] for the pair, while the SDK
throws "The order you are trying to fulfill is cancelled" and the caller
gets nothing.

That is the normal case for an aggregator: orders go stale between reading
them and filling them, which is the reason to use this method at all.

Filter those orders out of the batch and build the call from what is left.
Everything downstream is indexed by position in that list, so the
fulfillments and criteria resolvers now come from the filtered list too --
they were reading the unfiltered one, which only matched while nothing was
ever dropped. If no order survives, throw, since there is nothing to send.

Single order fulfillOrder still throws as before. There is no batch to fall
back on there, and a silent no-op would be worse than a clear error.

* fix: cap unitsToFill at what is left of a partially filled order

The comment over this code already describes the intended behaviour -- the
order is adjusted by "the minimum of the amount to fill and the remaining
order left to be fulfilled" -- but no minimum is ever taken. unitsToFill
goes into mapOrderAmountsFromUnitsToFill and
getAdvancedOrderNumeratorDenominator exactly as passed.

Seaport caps the fill itself. On an order with 4 of 10 units left, asking
for 8 transfers 4 and closes the order. The SDK instead sizes the offer
side for 8 units the offerer no longer holds, so its own balance check
rejects the fill:

  The offerer does not have the amount needed to create or fulfill.

The message points at the offerer, who is fine; the request simply ran past
the remainder. The same call placed directly against the contract settles.

Take the minimum the comment calls for, in both the single and batch paths.
Amounts, tips and numerator/denominator are then derived from a fill that
will actually happen, and the value attached to the transaction covers the
units that really transfer.

Only applies once an order is partially filled. Asking for more units than
the order was ever divisible into is a caller error rather than a race, and
getAdvancedOrderNumeratorDenominator still rejects that with its own
message.

* fix: stop crediting the fulfiller with offer items sent to someone else

validateStandardFulfillBalancesAndApprovals adds the offered items to the
fulfiller's balances before checking consideration, per requirement 2 in its
own doc comment: the fulfiller "does not need to own the ERC20 item as it
will first be received from the offerer".

That only holds when the offer actually reaches the fulfiller.
recipientAddress forwards it somewhere else, and the check never sees that
value -- fulfillStandardOrder and fulfillAvailableOrders both take
recipientAddress but never pass it down. The credit is applied either way.

Accepting a bid is where it shows. The offerer bids 10 ERC20 with a 2.5%
fee, so the fulfiller receives 10 and settles 0.25 out of it. Hand the
proceeds to a third party with recipientAddress and the fee has to come from
the fulfiller's own balance instead. With a zero balance the SDK reports no
problem and hands back a fulfillment that reverts on transfer with panic
0x11, which says nothing about what went wrong.

Only apply the credit when the offer lands with the fulfiller. The zero
address means it stays with them, and naming the fulfiller explicitly is the
same thing, so both keep the existing behaviour -- checked on chain, that
second case really does settle.

* style: biome formatting on the conduit lookup

---------

Co-authored-by: Chalom <130509482+chalomdev@users.noreply.github.com>
Co-authored-by: Dusk1e <yusufalweshdemir@gmail.com>
Co-authored-by: Ruzzgar <ruzzgarcn@gmail.com>
Co-authored-by: Xowiek <xowiekk@gmail.com>
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.

8 participants