DeFi Security AllianceRequest an audit
Menu

EVM patterns

SafeERC20: Verify Token Receipts Before Crediting Deposits

Use SafeERC20 to normalize ERC20 call failures, then decide how actual receipts become application credit. Our local tests show why a successful wrapper call can still leave nominal deposit credit larger than the tokens received.

Blue tokens pass through a transparent conduit while one diverts from a receiving tray beneath a row of empty outlines.

Key facts

Measured population
144 local EVM cases across 3 routes, 6 token behaviors, 4 amounts and 2 reserves.
Nominal credit
8 of 48 SafeERC20 cases credited more than the pool received.
Receipt credit
0 of 48 delta cases overcredited. Zero receipt could still succeed.
Executed dependency
OpenZeppelin Contracts v5.4.0 with Solidity 0.8.36 and Cancun rules.
Scope boundary
Synthetic tokens. No callbacks, dishonest balance reporting or withdrawals tested.

What SafeERC20 checks before returning

Request 10 token units and credit 10 only if the application has evidence supporting that credit. A successful transfer call is part of that evidence. It does not establish the quantity received. In our fee fixture, the receiver gained 9 units while the SafeERC20 call returned normally. The error arose when the deposit application assigned the requested quantity to its internal ledger.

SafeERC20 is OpenZeppelin's wrapper for ERC20 operations with inconsistent return signaling. The ERC20 specification requires callers to handle a false result. Simply invoking IERC20.transferFrom and ignoring its boolean leaves the application free to continue after a token reports failure. Requiring a boolean also creates a compatibility question when a token returns no data.

The experiment pins OpenZeppelin Contracts v5.4.0. Its safeTransferFrom uses a low-level call through _callOptionalReturn. A token revert propagates. A nonempty response is checked against the expected success word. An empty response can pass when the target has code. This supports an empty-return token without treating every successful low-level call as a valid token operation.

Keep the remaining obligation explicit. Neither the function name nor the using SafeERC20 for IERC20 declaration authenticates the asset or calculates a deposit entitlement. The wrapper's transfer path does not compare recipient balances. An arbitrary token can acknowledge the call without implementing the intended movement. A transfer fee can also make an honestly reported receipt smaller than the request.

Our ERC20 listing audit packet examines the token's privilege surface and listing evidence. This integration review asks a narrower execution question: after a particular call, which units may the receiving application credit? Authorization granted through ERC20 permit is another prerequisite, with its own signer and beneficiary checks.

What 144 local transfer tests revealed

Identical success totals concealed different acceptance behavior. Each route completed 32 of 48 cases, yet the unchecked typed call accepted false returns and rejected empty returns. The SafeERC20 routes reversed those outcomes. Crediting the nominal request still produced 8 overcredits in the helper route. Measuring receipt produced none within this grid.

Method

Execution date
.
Population
144 cases: 3 application routes, 6 token behaviors, 4 requested amounts and 2 reserve balances. No rows excluded.
Requested amounts
0, 1, 9 and 10 token base units. No decimal conversion.
Initial state
A fresh token and deposit fixture per row. The actor starts with 1000 units and approves the pool for 1000. Uncredited pool reserves are 0 or 100 units. Initial application credit is zero.
Token behaviors
Ordinary true return, empty return after movement, false return without movement, phantom true return without movement, transfer fee and explicit revert. These are synthetic fixtures, not named live assets or complete standard implementations.
Fee rule
The fee fixture burns floor(amount / 10). The actor loses the requested amount. The receiver obtains the remainder.
Runtime
Foundry 1.5.1, Solidity 0.8.36 and Cancun EVM rules, with optimizer and via IR enabled. The retained OpenZeppelin v5.4.0 helper and its imports are compiled into the fixture.
Reproduction
Run measurement.py in seo/research/safeerc20-transfer-accounting-2026-11-20/. It compiles TransferMatrix.t.sol, retains raw ABI observations and writes measurement.json. Run again with --verify for exact row replay. independent-check.py separately checks branches, balances, allowances and supply conservation.

Results

Complete local transfer grid by application route
RouteCasesSuccessRevertOvercreditReserve masked
Unchecked typed call, nominal credit483216147
SafeERC20, nominal credit48321684
SafeERC20, receipt credit48321600

An overcredit means final application credit exceeds the pool's balance increase. Reserve masked means the pool's final total balance still covers that incorrect credit. The reserve is uncredited fixture funding, not a reconstruction of a live pool's liabilities. Total-balance coverage therefore answers a different question from whether this deposit received the credit it earned.

Successful cases by token behavior, out of 8 per cell
Fixture behaviorUnchecked typedSafe nominalSafe receipt
True with movement888
Empty after movement088
False without movement800
Phantom true888
Fee with true return888
Explicit revert000

The unchecked empty-return call rolled back the token movement when typed return decoding failed. Final actor balance and allowance remained 1000, with no credited receipt. In the helper routes, false returns reverted with SafeERC20FailedOperation. Explicit token reverts retained their own error selector. Distinguish these paths before interpreting a reverted transaction as evidence of one particular failure.

Selected executed rows, with a request of 10 base units
RouteBehaviorReserveSuccessReceivedCreditFinal pool
Safe nominalFee0Yes9109
Safe nominalFee100Yes910109
Safe receiptFee100Yes99109
Safe nominalPhantom100Yes010100
Safe receiptPhantom100Yes00100
Unchecked typedEmpty100No00100

The 8 nominal-helper overcredits split into 6 phantom rows and 2 fee rows. Each positive phantom request appeared with both reserve settings. Only the request of 10 produced a nonzero fee, again under both reserve settings. Ordinary true and empty-return movements created no excess nominal credit in these fixtures. That decomposition lets a reviewer identify which control disappeared if a later run produces a different total.

For the fee request with a reserve of 100, the actor finished with 990 units and the pool with 109. Their combined balance was 1099, equal to the remaining fixture supply after burning 1 unit. Allowance was 990. These observations separate a transfer fee from an unexplained disappearance: the asset movement reconciled, while the nominal application's 10-unit credit still exceeded its 9-unit receipt. The measured receipt route assigned 9 without changing the token's fee behavior.

The smaller positive requests incurred no fee because of integer rounding in this fixture. Testing only those amounts would miss the fee-induced discrepancy. Zero requests also matter: the false-return fixture rejects them through the wrapper while the phantom fixture can complete without receipt. Success is an execution outcome, not a promise that a positive deposit occurred.

Limits

  • The complete fixture exposes unsafe routes and is not deployable application code. Comparing a route does not certify the contract containing it.
  • No live chain, deployed-token prevalence, realized loss or gas benchmark was measured.
  • Dishonest balance reporting, rebasing, callbacks and outgoing transfers were not executed. The delta result assumes the fixture's truthful balance mapping.
  • Only the retained library pin and listed inputs were run. Malformed return lengths, other compiler versions and arbitrary token implementations remain outside this matrix.

Choose a receipt policy before assigning credit

Separate transfer compatibility from the application's economic promise. An exact-amount settlement may reject a taxed receipt. A deposit account may support such assets by crediting what it received. These policies require different assertions even when they share the same transfer wrapper. OpenZeppelin's token integration workshop describes the before-and-after balance approach. The acceptance rule remains application specific.

Receipt policies and the assumptions that remain
Application policyAcceptance conditionCredit basisRemaining assumption
Exact settlementReceipt equals requestAccepted exact receiptThe balance report is trustworthy
Fee-aware depositReceipt meets agreed minimumAccepted balance increaseAsset behavior fits the accounting model
Measured delta fixtureWrapper returns normallyBalance increaseZero receipt is permitted
Unsupported assetReject before transferNoneThe support list is enforced consistently

The executed receipt branch contains the following operations. This is an excerpt from the deliberately incomplete fixture, not a production deposit implementation. Minimum receipt, asset admission and callback protection were not implemented by this branch.

uint256 beforeBalance = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 received = token.balanceOf(address(this)) - beforeBalance;
credit[msg.sender] += received;
The tested branch credits a measured balance increase after a successful helper call. Asset trust and deposit acceptance remain separate obligations.

Define the credited account as carefully as the credited quantity. Our fixture assigns credit to the actor that calls the pool and uses that actor as the transfer source. It does not accept an independently supplied beneficiary. A router, forwarded request or signed instruction needs its own binding between funding authority and beneficiary. Measuring the right amount cannot repair credit assigned to the wrong account.

For a fee-aware product, define who accepts the fee and which unit the minimum uses. A human-readable decimal amount needs a deliberate conversion into token base units. Rejecting an insufficient receipt should revert the enclosing operation so that its transfer and credit changes do not survive independently. This exact-minimum policy is proposed acceptance logic. It was not another executed route in our grid.

Separate call acceptance from receipt creditThe wrapper checks call behavior, a balance comparison measures receipt under asset assumptions and the application decides whether that receipt qualifies for credit.Call acceptedby the wrapperReceipt measuredunder asset assumptionsCredit acceptedby product policy
A successful call reaches another decision boundary before an application can assign an entitlement.
  1. Check the transfer outcome under the installed wrapper's rules.
  2. Measure receipt with an asset model that makes the balance comparison meaningful.
  3. Apply the acceptance condition before recording an entitlement. Preserve a minimum-receipt failure as a distinct regression case.

Diagnose a failed token operation

Start with the actual caller, token address and library revision. For transferFrom, the allowance must authorize the contract that calls the token. A user's approval of another address does not establish this pool's spending permission. Check the owner's balance as well as the spender allowance at the relevant execution state. Our fixtures deliberately supplied enough of both, so they do not measure insufficient-funding failures.

Helper rejection
The false-return fixture produced selector 0x5274afe7, matching SafeERC20FailedOperation(address) in the tested helper. Decode with the actual deployed ABI.
Token revert
The explicit revert fixture produced 0x08c379a0, the selector of its encoded error string. The wrapper bubbled that data rather than replacing it with a receipt diagnosis.
Empty return
Empty data was accepted from our deployed token fixture through the helper. The pinned source separately rejects an empty response from a no-code target. An externally owned token address was not executed here.
Optional failure handling
trySafeTransferFrom returns a boolean under the pinned library's rules. A caller choosing that API must handle false before recording success. This variant was inspected, not executed in the matrix.

Error messages found in an older tutorial should not become assertions about a different installed dependency. This pin exposes forceApprove and has no safeApprove declaration. Its approval fallback can reset a standard allowance before retrying. Temporary allowances are separate: the source warns that they can remain active in addition to the standard allowance. Neither changing the import nor resetting approval proves that receipt accounting is correct.

Do not fix an allowance failure by granting a larger allowance before establishing why the operation failed. The tested phantom token already had adequate spending permission and still moved nothing. Conversely, the empty-return token moved funds correctly through the helper without requiring a larger approval. Authorization and receipt are separate observations, so changing one should not substitute for checking the other.

Retain the exact failing calldata and final state. If a simulation reports failure but an interface shows a completed deposit, compare the chain, transaction and state being observed before changing the transfer code. The approval race analysis covers pending authority changes. A generic transfer error alone does not identify that race.

Where balance deltas stop being sufficient

A balance delta is a measurement reported by the asset contract. It is not an independent proof of economic backing. An arbitrary balanceOf implementation can supply misleading values, and a rebase or reflection mechanism can change the relationship between balances and transfers. The weird ERC20 repository treats balance modifications and reentrant calls as distinct integration behaviors. Its catalog is a fixture resource, not a current inventory of every token's deployed settings.

Do not map every balance increase to the current depositor automatically. If supported asset behavior can introduce unrelated changes during the observation interval, specify how they are attributed or reject that behavior. Donations already present before the first balance read should not be credited by a simple delta calculation. Our reserve contrast tests that initial-state distinction, without executing a donation callback or a rebase.

Token calls also cross a control boundary. Solidity's security considerations explain how interaction with another contract can permit callbacks. Reading before a transfer and updating afterward does not by itself prevent reentry. Review locks, observable intermediate state and all entrypoints that share accounting. The reentrancy test matrix addresses that separate property. No callback ran in this experiment.

The fixture holds one token per case and its credit mapping has no asset dimension. It cannot model a production account that accepts several assets. Such an account needs a defined relationship between each supported token and its liabilities, including any conversion between units. Preserve that distinction when adapting the test: a correct receipt measured for one asset must not silently fund an entitlement denominated in another.

Finally, prove the exit path separately. Crediting 9 received units says nothing about how many units a user receives when those units leave a fee-charging token account. A later fee change or token implementation change can invalidate a previously accepted model. Vault share conversion adds another ledger with its own rounding and donation questions, covered in ERC4626 integration checks. Deposit correctness is one boundary in that system.

Require release evidence for each supported asset

Write the credit invariant before selecting the test token. For a fixed-unit deposit model, newly assigned credit should equal the qualifying receipt measured for that operation. If the product promises a conversion, state that conversion separately. Use an existing reserve in the negative controls so that a total-balance check cannot conceal incorrect deposit attribution.

  1. Freeze the application revision, compiler settings and exact dependency pin.
  2. Record supported asset behavior and the expected receipt policy. Identify upgrade authority or settings that could change those assumptions.
  3. Run true, empty, false and phantom responses alongside fee boundaries and explicit reverts. Compare acceptance sets as well as aggregate success counts.
  4. Assert final credit, actor balance, receiver balance and allowance after each operation. Add callback and withdrawal cases separately before claiming those properties.
  5. Link each remediation to its failing fixture and rerun the unchanged control set. Preserve raw observations with the release evidence.

Pharos Production describes manual review, specification testing and remediation guidance in its smart contract logic review and specification testing service. For a token integration, define the asset behavior, receipt invariant and negative controls in the review scope. Ask for finding-linked reproduction and remediation evidence. This local experiment does not establish that Pharos reviewed any particular deployment.

The DeFiSec Pharos profile supplies directory context, while the security tools hub helps separate test execution from source scanning. Accept the release only when the observed credit matches the chosen policy at the shipped revision, including the negative case that previously passed incorrectly.

Frequently asked questions

Can ERC721 or ERC1155 safeTransferFrom calls use SafeERC20?

No. The shared name does not make these token APIs interchangeable. SafeERC20 wraps IERC20 operations; ERC721 and ERC1155 define their own transfer arguments and receiver checks. Use the correct standard and test its callback behavior separately.

Does SafeERC20 make a receiving contract acknowledge an ERC20 transfer?

No. The tested safeTransferFrom path calls the token and checks its return behavior. It does not invoke a separate ERC20 recipient acceptance callback. A successful call does not prove that a recipient application can recover or account for the tokens.

Can an indexer credit a deposit from a Transfer event alone?

Treat the application credit state as a separate fact to reconcile. An asset event describes what its contract reported and does not establish the receiving application's acceptance policy. Check the finalized application outcome and retain block identity so a reorganization can be handled. This experiment did not execute an indexer.

Comments

0

    Leave a comment

    Share a question or observation about this article.

    10 to 3,000 characters.