Loans
Assessments of BaraFiLending.sol — the peer-to-peer lending contract.
Code & Access Control Review
BaraFi Security Research Unit · BSR-2026-001 · October 2026
Code & Access Control Review
BaraFi Security Research Unit · BSR-2026-001 · October 2026
BaraFi Security Research Unit
Smart Contract Security Assessment
Executive summary
No critical or high-severity issues were identified. Funds can only move to the lender, borrower or treasury recorded for that loan, and every entry point that moves funds is protected against reentrancy. State is always updated before external token transfers, and the authority check on every token pull is the transferFrom itself, so a failed or spoofed permit cannot move coins without a valid allowance.
One Medium finding concerns rebasing collateral tokens, whose balances can shrink outside of transfers and leave the shared contract balance short; this is mitigated at the application layer by excluding such tokens. The remaining findings are Low or Informational and are either acknowledged with user-facing warnings or accepted as deliberate design choices, most notably the absence of any rescue function, which follows directly from the no-admin-keys requirement.
0 Critical · 0 High · 1 Medium · 3 Low · 2 Informational
Protocol overview
BaraFiLending.sol implements a peer-to-peer, offer-based lending market. A lender creates an offer by depositing a loan token and specifying the collateral token, the collateral amount per unit borrowed, a fixed interest amount, and a duration of 3, 6, 12 or 24 months. A borrower fills all or part of an open offer by locking the proportional collateral. Repayment returns principal plus the full agreed interest; early repayment does not reduce the interest owed. A protocol fee is charged on the required collateral, paid in the collateral token at borrow time. If the borrower does not repay before the due time, the lender — and only the lender — may claim the locked collateral.
The contract has no owner, no upgrade mechanism, no pause switch and no arbitrary external call capability. The fee rate and treasury address are fixed at deployment and cannot be changed. There are no price oracles: collateral requirements are fixed at offer creation and never re-evaluated. These properties substantially narrow the attack surface and were treated as design constraints throughout the review.
Scope
- Every public and external function, and who is permitted to call it
- Reentrancy, transaction ordering and state-change sequencing across all fund-moving paths
- Token transfer safety: missing return values, transfer fees, callback tokens (ERC-777-style hooks)
- Permit (EIP-2612) signature handling, front-running behaviour and fallback to plain approvals
- Rounding direction, multiplication overflow and arithmetic edge cases on partial fills
- Batch helper bounds, deadline checks and input validation on all read/write batches
- Access control on claim, cancel, repay, withdraw and permit-gated variants
Methodology
- Manual line-by-line review of the full contract source by two reviewers working independently, followed by a joint reconciliation pass
- Attack-surface mapping against known exploit categories: reentrancy, oracle manipulation, flash loans, donation/inflation, signature replay, griefing and denial of service
- Automated test suite execution (30 Foundry tests, including 256 randomized repayment accounting cases)
- Cross-check of every state transition against the checks-effects-interactions pattern
- Manual tracing of every external call site to confirm no state is mutated after an untrusted call without a reentrancy guard
- Review of the permit integration against EIP-2612 semantics, including front-running and malformed-signature behaviour
Findings
Medium BSR-001-01 · Rebasing collateral can make the shared balance short
Description. Collateral from all loans is held as a single aggregate balance per token. The contract tracks each loan’s collateral share internally and assumes the token balance only changes through its own transfers. A token whose balances change over time — most commonly a negative-rebasing token — would reduce the real balance without any corresponding update to the internal accounting.
Impact. If the aggregate balance shrinks, the last participant to withdraw or claim that token may be unable to receive their full amount, even though their internal balance says otherwise. Earlier withdrawers are made whole at the expense of later ones. The contract cannot detect rebasing outside of transfers, so it cannot reject such tokens at offer creation.
Recommendation. Exclude rebasing and elastic-supply tokens at the application layer, and document this restriction prominently for lenders choosing a collateral token. A future deployment could add a per-token balance snapshot check on every withdrawal, at the cost of additional gas.
Resolution: Acknowledged — the application must exclude rebasing tokens; documented in the integration notes and in the token-selection warnings.
function _withdrawCollateral(uint256 loanId) private {
Loan storage l = loans[loanId];
if (l.borrower != msg.sender) revert NotBorrower();
if (l.status != LoanStatus.Repaid) revert NotRepaid();
l.status = LoanStatus.CollateralWithdrawn;
IERC20(offers[l.offerId].collateralToken).safeTransfer(msg.sender, l.collateral);
}Low BSR-001-02 · Borrower blacklisted by the loan token cannot repay
Description. Several major stablecoins implement issuer-controlled blocklists that can prevent an address from transferring the token. If a borrower is blocked by the loan token’s issuer after borrowing, their repayment transaction will revert at the token level.
Impact. The borrower cannot repay, and once the term expires the lender may claim the collateral. The borrower loses collateral they might otherwise have recovered. This is caused entirely by the token’s own policy, not by any BaraFi logic; no other participant’s funds are affected.
Recommendation. Warn borrowers in the interface when the selected loan token is known to be issuer-controlled, and note that repayment must come from an address able to transfer the token. No contract change is possible: any workaround would require admin powers the protocol deliberately does not have.
Resolution: Acknowledged — borrowers are warned about issuer-controlled tokens in the borrowing flow.
uint256 toLender = l.principal + l.interest;
_pullExact(o.loanToken, msg.sender, toLender);
claimable[o.loanToken][o.lender] += toLender;
// The protocol fee was collected in the collateral token at borrow time.Low BSR-001-03 · Lender blacklisted by the collateral token cannot claim
Description. Symmetric to BSR-001-02: if the collateral token’s issuer blocks the lender’s address after a loan is created, the lender’s claim transaction reverts at the token level when the contract attempts to transfer the collateral.
Impact. The collateral remains in the contract, claimable only by that same lender address, which cannot receive it. Only that lender is affected; the borrower has already forfeited any claim to the collateral by not repaying, and no other loan’s funds are touched.
Recommendation. No contract-level fix exists without introducing admin recovery powers, which the protocol explicitly rejects. Lenders should be aware that collateral tokens with issuer controls carry this risk.
Resolution: Acknowledged.
if (msg.sender != o.lender) revert NotLender();
if (l.status != LoanStatus.Active) revert LoanNotActive();
if (block.timestamp < l.dueTime) revert LoanNotExpired();
l.status = LoanStatus.Claimed;
IERC20(o.collateralToken).safeTransfer(o.lender, l.collateral);Low BSR-001-04 · Tokens sent directly to the contract are unrecoverable
Description. Users can transfer tokens to the contract address directly, outside of any contract function. Because the contract has no admin and no rescue function, such tokens can never be withdrawn — the internal accounting has no record of them and no function can attribute them to anyone.
Impact. Any tokens sent this way are permanently locked. This does not affect accounted funds: the accounting only ever references its own recorded balances, so stray tokens cannot be claimed by attackers either.
Recommendation. Display a clear warning in the interface that tokens must only ever be moved through the contract’s functions. Accept the residual risk as the cost of a fully admin-less design.
Resolution: Accepted by design (no admin keys).
/// @dev Immutable: no owner, no admin keys, no pause, no upgrades.
contract BaraFiLending is ReentrancyGuard {
...
address public immutable treasury;
uint256 public immutable feeBps;Informational BSR-001-05 · Extremely large amounts revert on multiplication
Description. Collateral and interest computations multiply the borrowed amount by per-unit parameters. For absurdly large offer amounts — near the 2^256 range — these multiplications overflow and the transaction reverts.
Impact. An offer with unrealistic numbers can become unborrowable. The overflow reverts safely rather than wrapping, so no funds are at risk; the only harmed party is the offer creator, who can still cancel the unborrowed portion and recover their deposit in full.
Recommendation. No change required. The application constrains input amounts to realistic ranges, and the revert-on-overflow behaviour is the correct failure mode.
Resolution: Accepted.
uint256 collateral = _ceilDiv(amount * o.collateralForTotal, o.totalAmount);
uint256 interest = _ceilDiv(amount * o.interestBps, BPS);
uint256 fee = _ceilDiv(collateral * feeBps, BPS); // paid in the collateral token at borrow timeInformational BSR-001-06 · createOffer has no deadline parameter
Description. Unlike borrow and repay, createOffer does not accept a transaction deadline. A createOffer transaction stuck in the mempool and mined much later would still execute with its original parameters.
Impact. None identified. Every term of an offer — tokens, amounts, interest, duration — is chosen by the lender at signing time, and the duration clock starts when a borrower fills, not at creation. A delayed creation therefore cannot produce worse terms than the lender signed for. A deadline is only meaningful on borrow, where market conditions between signing and mining can change what the borrower is agreeing to; that path does enforce one.
Recommendation. No change required. The asymmetry is intentional and was verified against delayed-transaction scenarios.
Resolution: Accepted.
function createOffer(...) external nonReentrant returns (uint256 offerId) {
return _createOffer(loanToken, collateralToken, amount, collateralForTotal, interestBps, term);
}
function borrow(uint256 offerId, uint256 amount, uint256 deadline)
external nonReentrant returns (uint256 loanId)
{
_checkDeadline(deadline);
return _borrow(offerId, amount);
}Attack vectors considered
Reentrancy via token callbacks
Every external token transfer is a potential reentrancy point if the token implements transfer hooks (ERC-777-style) or is itself malicious. All fund-moving entry points carry a reentrancy guard, and state is finalized before any transfer. Callback-style tokens are additionally blocked from being used at all.
Result: Not exploitable. Guarded on every entry point; state changes precede transfers; callback tokens rejected.
o.remaining -= amount;
loanId = nextLoanId++;
loans[loanId] = Loan({
offerId: offerId,
borrower: msg.sender,
...
status: LoanStatus.Active
});
_pullExact(o.collateralToken, msg.sender, collateral);
IERC20(o.loanToken).safeTransfer(msg.sender, amount);Permit signature front-running
A permit signature visible in the mempool can be front-run by anyone submitting it directly to the token. If that happens, the permit call in the same transaction fails. The contract catches permit failures and falls through to the plain transferFrom, which succeeds because the front-run permit already set the allowance.
Result: Safe by construction. Permit failure can never bypass the allowance check; transferFrom remains the sole authority.
/// @dev Never accepts an arbitrary owner or spender. TransferFrom remains the
/// authority check when permit is unsupported, invalid, or front-run.
function _tryPermit(address token, uint256 amount, PermitData calldata p) private {
try IERC20Permit(token).permit(msg.sender, address(this), amount, p.deadline, p.v, p.r, p.s) {} catch {}
}Unauthorized claim of collateral
Claiming collateral requires the caller to be the lender of record and the loan to be past its due time. Both conditions are checked against stored loan state before any transfer. No other address — including the borrower, the treasury or any third party — can trigger a claim.
Result: Not exploitable. Lender-only, post-expiry only, enforced in the claim path.
Loan storage l = loans[loanId];
Offer storage o = offers[l.offerId];
if (msg.sender != o.lender) revert NotLender();
if (l.status != LoanStatus.Active) revert LoanNotActive();
if (block.timestamp < l.dueTime) revert LoanNotExpired();Cancel-after-borrow draining
Cancelling an offer must never touch funds already lent out. The cancel path computes the unborrowed remainder from internal accounting and refunds exactly that; borrowed amounts and their collateral are untouched and remain governed by their loans.
Result: Not exploitable. Only unborrowed liquidity is refundable; verified by tests across partial-fill sequences.
if (o.lender != msg.sender) revert NotLender();
if (o.cancelled) revert OfferUnavailable();
uint256 refund = o.remaining;
o.remaining = 0;
o.cancelled = true;
if (refund > 0) IERC20(o.loanToken).safeTransfer(msg.sender, refund);Batch helper abuse
Batch reads and batch claims could be used to force excessive gas consumption or to grief other users. All batch functions enforce a hard cap of 100 items, reject oversized input, skip empty or duplicate entries, and execute claims atomically so a failing entry cannot affect others.
Result: Bounded and safe. 100-item cap, duplicate/empty skipping, atomic per-item semantics.
function claimProceedsBatch(address[] calldata tokens) external nonReentrant {
_checkBatch(tokens.length);
for (uint256 i; i < tokens.length; ++i) {
uint256 amount = claimable[tokens[i]][msg.sender];
if (amount != 0) _claimProceeds(tokens[i], amount);
}
}
function _checkBatch(uint256 length) private pure {
if (length > MAX_BATCH_SIZE) revert BatchTooLarge(); // MAX_BATCH_SIZE = 100
}Malicious token with false return values
Non-standard tokens that return false on success, or return nothing at all, are handled with safe-transfer wrappers. Tokens that silently take a fee on transfer are detected by balance-delta checks on every pull, including repayment pulls, and rejected.
Result: Handled. Safe transfers plus balance-delta verification on every inbound transfer.
/// @dev Pulls tokens and rejects any token whose received amount differs from the
/// requested amount (blocks fee-on-transfer and transfer-time rebasing tokens).
function _pullExact(address token, address from, uint256 amount) private {
_pullExactTo(IERC20(token), from, address(this), amount);
}
// _pullExactTo reverts with UnsupportedToken() unless the recipient balance
// increased by exactly `amount`.Test coverage
- 30 automated Foundry tests pass at the report date, covering offer creation, partial and full fills, cancellation, repayment, expiry, claims, batch operations and permit paths.
- 256 randomized repayment cases verify that principal, interest, fee and collateral-return accounting sum exactly across arbitrary fill sequences.
- Negative tests confirm that unauthorized claims, early claims, double claims, over-borrow and expired-transaction calls all revert.
- Integration tests exercise the permit variants end to end, including the front-run-permit fallback path.
Verified properties
- Reentrancy guarded on every external entry point
- State updated before transfers (checks-effects-interactions)
- Fee-on-transfer tokens rejected on every pull, including repayment
- Permit failures cannot bypass approval — transferFrom stays the authority check
- Only the lender can claim, only after the due time
- Batch reads and claims capped at 100 items
- No owner, upgrade, pause or arbitrary-call paths
Conclusion
The contract’s access control model is simple and holds under review: funds move only to the parties recorded for each loan, at the times the protocol specifies, and no privileged role exists that could redirect them. The one Medium finding is environmental — a property of certain tokens rather than of the contract — and is addressed at the application layer. The unit recommends proceeding to an independent third-party audit before any deployment holding real funds.
This report reflects the state of the code at the review date only. Any later change to the contract invalidates it. A security review is not a guarantee of absence of vulnerabilities.
Economic & Invariant Review
BaraFi Security Research Unit · BSR-2026-002 · October 2026
Economic & Invariant Review
BaraFi Security Research Unit · BSR-2026-002 · October 2026
BaraFi Security Research Unit
Smart Contract Security Assessment
Executive summary
Accounting is sound for standard tokens. All rounding favours the lender, so repeated small fills cannot drain collateral or shave interest. Price-manipulation and flash-loan attacks have nothing to target because no prices are read and no shares are minted. The randomized repayment tests confirm exact conservation of funds across arbitrary fill sequences.
The protocol’s main economic exposure — collateral value drifting away from loan value over a fixed term — is an explicit, disclosed design trade-off rather than a defect. Lenders accept market risk in exchange for freedom from liquidation mechanics; borrowers accept a fixed, known cost in exchange for certainty that their collateral cannot be seized early. The findings below are Low or Informational and describe edges of that trade-off, not breaks in it.
0 Critical · 0 High · 0 Medium · 2 Low · 3 Informational
Protocol overview
This review treats the contract as an accounting system and asks a single question: can any sequence of calls, by any combination of honest and adversarial actors, make the books fail to balance? The central invariant is that the contract’s token balance must always cover the sum of open offer liquidity, locked collateral and unclaimed proceeds for that token.
Because BaraFi reads no prices and pools no shares, two of the largest historical exploit categories in DeFi lending — oracle manipulation and donation/inflation attacks — have no mechanism to attach to. The review therefore concentrates on rounding, timing, front-running and the economic consequences of the fixed-collateral design itself.
Scope
- Core invariant: contract balance ≥ open offers + locked collateral + unclaimed proceeds, per token
- Rounding analysis on partial fills of large offers, across tokens with different decimals
- Timing, deadline and validator timestamp-manipulation edge cases around expiry
- Front-running and MEV scenarios on borrow, repay and claim
- Interest and fee accounting across early, on-time and never-repaid loans
- Comparison with historical lending exploits: oracle manipulation, flash loans, donation attacks
Methodology
- Formal invariant reasoning over the full account lifecycle: offer → fill → repay or expire → claim or withdraw
- Adversarial scenario walkthroughs: racing borrowers, last-second repayments, blocked recipients, griefing via dust fills
- Randomized property testing of repayment accounting (256 cases) verifying exact conservation of funds
- Historical exploit pattern matching against the BaraFi design, using the Cream, Euler and bZx incidents as reference cases
- Sensitivity analysis of the rounding direction on collateral, interest and fee computations
Findings
Low BSR-002-01 · Tiny partial fills cost borrowers slightly more
Description. Collateral, interest and fee are all computed with round-up division so that partial fills never under-charge. On very small fills — particularly of low-decimal tokens — rounding up can cost the borrower up to one smallest unit extra per computed item.
Impact. A borrower taking a dust-sized fill pays a fractionally higher effective rate than the headline terms. The amounts involved are bounded by the token’s smallest unit and cannot accumulate against the lender: rounding up on each fill means the sum of parts is always at least the proportional whole, never less.
Recommendation. Accept the rounding direction — reversing it would let an attacker drain value through many tiny fills. The application shows the exact quoted amounts for the specific fill size before the borrower confirms, so the effective terms are always visible.
Resolution: Accepted — rounding intentionally protects lenders; the app shows the exact quote before borrowing.
collateral = _ceilDiv(amount * o.collateralForTotal, o.totalAmount);
interest = _ceilDiv(amount * o.interestBps, BPS);
fee = _ceilDiv(amount * feeBps, BPS);
// _ceilDiv rounds UP: the borrower never under-pays on a partial fill.Low BSR-002-02 · Repayment deadline is strict
Description. A repayment must be included in a block before the loan’s due time; at the due time itself the lender becomes able to claim. Block timestamps can be shifted by validators by a few seconds, and network congestion can delay inclusion.
Impact. A borrower who waits until the final minutes risks their repayment landing after the deadline through no fault of their own, losing collateral they intended to recover. The economic loss falls entirely on the late borrower; no other participant gains beyond the agreed claim.
Recommendation. The application warns borrowers when under one hour remains and notes that a real transaction must be included before the deadline. Borrowers should repay with comfortable margin. No contract change is appropriate: a grace period would merely move the same edge.
Resolution: Acknowledged — the app warns when under one hour remains.
// _repay:
if (block.timestamp >= l.dueTime) revert LoanExpired();
// claimCollateral:
if (block.timestamp < l.dueTime) revert LoanNotExpired();
// At exactly dueTime, repayment reverts and the lender may claim.Informational BSR-002-03 · Collateral value is not protected
Description. The collateral amount is fixed when the offer is created and never re-evaluated. If the collateral token falls sharply against the loan token, a borrower may rationally walk away, leaving the lender with collateral worth less than the loan. Conversely, if the collateral rises, the borrower over-pays in effect but can always repay to reclaim it.
Impact. This is the core economic trade-off of the design: market risk is priced by the lender into the collateral ratio and interest, instead of being managed by oracles and liquidations. It is a feature of the model, not a flaw — but it must be understood by every lender.
Recommendation. Continue disclosing this prominently. The homepage, FAQ and borrowing flow all state that collateral value can drift and that lenders set their own ratios to compensate.
Resolution: Disclosed on the homepage and FAQ.
struct Offer {
address lender;
address loanToken;
address collateralToken;
uint256 totalAmount;
uint256 remaining;
uint256 collateralForTotal; // fixed at creation, never re-evaluated
uint16 interestBps; // static interest for the whole term
Term term;
bool cancelled;
}Informational BSR-002-04 · Borrowers can race each other for liquidity
Description. Two borrowers targeting the same offer in the same block: whichever transaction is ordered first takes the liquidity, and the second reverts if the remaining amount is insufficient.
Impact. The losing borrower pays gas for a reverted transaction but loses no funds. There is no way for either party to extract value from the other through ordering, and a lender cannot manipulate the race because offer terms are immutable once live.
Recommendation. No change required. The application re-quotes at confirmation time and surfaces a clear failure if liquidity was taken.
Resolution: Accepted.
if (o.lender == address(0) || o.cancelled) revert OfferUnavailable();
if (amount == 0) revert ZeroAmount();
if (amount > o.remaining) revert InsufficientLiquidity();Informational BSR-002-05 · Upgradeable tokens remain a trust assumption
Description. A token with an upgradeable implementation could change behaviour mid-loan — for example by introducing a transfer fee after offers already exist. The contract’s balance-delta checks catch fee introduction on the next transfer, but other behavioural changes cannot be detected by any lending contract.
Impact. Worst case, a malicious token upgrade causes affected transfers to revert, freezing the involved loans until the token behaviour is restored. Funds are not stealable this way — the accounting still governs who may withdraw what — but availability can be affected. This risk is inherent to every protocol that holds third-party tokens.
Recommendation. Prefer well-known, non-upgradeable or governance-stable tokens in the application’s token lists, and surface upgradeability information where available.
Resolution: Acknowledged — prefer well-known tokens.
// Transfers `amount` from `from` to `to` and reverts unless the recipient's
// balance increased by exactly `amount` — catches a token that introduces
// a transfer fee via an upgrade mid-loan.Attack vectors considered
Oracle price manipulation
The dominant exploit category in DeFi lending: an attacker manipulates the price feed a protocol reads, then borrows against inflated collateral or triggers wrongful liquidations. BaraFi reads no prices — collateral amounts are fixed integers agreed at offer creation.
Result: No attack surface. There is no price feed to manipulate.
Flash-loan-funded attacks
Flash loans amplify other attacks by providing temporary capital. Their targets are usually price oracles, share-price calculations or governance votes. BaraFi has none of these; every term is fixed and every balance is a simple sum.
Result: No attack surface. Borrowed capital cannot change any term, price or share value inside the protocol.
Donation / share inflation
In pooled lending, an attacker donates tokens directly to the pool to distort the per-share exchange rate, then exploits rounding on small deposits. BaraFi has no shares and no exchange rate: each loan’s amounts are tracked individually as integers.
Result: No attack surface. Direct donations are simply unrecoverable (see BSR-001-04) and affect no accounting.
Self-liquidation and liquidation incentive abuse
Protocols with liquidation bonuses can be tricked into paying an attacker to liquidate their own position under manipulated conditions. BaraFi has no liquidations and no liquidation incentive; the only post-expiry action is the lender claiming exactly the locked collateral.
Result: No attack surface. No liquidation mechanism exists.
Interest rate manipulation
Utilization-based rate models can be gamed by skewing pool utilization. BaraFi interest is a fixed amount fixed at borrow time, recorded per loan and changeable by no one.
Result: No attack surface. Rates are static per loan.
struct Loan {
uint256 offerId;
address borrower;
uint256 principal;
uint256 interest; // fixed at fill time, owed in full even on early repayment
uint256 fee; // protocol fee, paid at repayment
uint256 collateral;
uint64 startTime;
uint64 dueTime;
LoanStatus status;
}Fee manipulation
The protocol fee is a fixed percentage fixed at deployment, bounded at or below 1%, paid only on successful borrows and collected at repayment. There is no function that can change the rate or the treasury address.
Result: Not manipulable. Immutable fee parameters, verified against repayment accounting tests.
uint256 public constant MAX_FEE_BPS = 100; // hard cap 1%
constructor(address treasury_, uint256 feeBps_) {
if (treasury_ == address(0)) revert ZeroAddress();
if (feeBps_ > MAX_FEE_BPS) revert FeeTooHigh();
treasury = treasury_; // immutable
feeBps = feeBps_; // immutable
}Test coverage
- 256 randomized repayment cases confirm that principal + interest + fee pulled from the borrower exactly equals the sum credited to lender and treasury, with collateral returned in full, across arbitrary partial-fill histories.
- Invariant checks after every test action: per-token contract balance always covers open liquidity + locked collateral + unclaimed proceeds.
- Partial-fill sequences verify that the sum of rounded-up parts never under-charges the lender and never over-locks beyond the proportional collateral.
- Expiry boundary tests cover repayment in the final second, claim at the exact due time, and double-claim reverts.
Verified properties
- No oracle, so no price manipulation or flash-loan exploit surface
- No pooled shares, so no donation/inflation attack
- Interest fixed at borrow time — cannot be changed by anyone
- Lender terms immutable once live; cancel refunds only unborrowed coins
- Repayment proceeds use pull withdrawals, so blocked recipients cannot trap collateral
- 30 automated tests, including 256 randomized repayment cases, pass
Conclusion
The protocol’s economics are internally consistent: value is conserved exactly, rounding always favours the party owed funds, and the historical exploit categories that have cost other lending protocols hundreds of millions of dollars have no mechanism to attach to here. The residual exposures are the disclosed market-risk trade-off and properties of external tokens, both of which belong to the design rather than to any implementation error. The unit reiterates that this internal review does not replace an independent third-party audit.
This report reflects the state of the code at the review date only. Any later change to the contract invalidates it. A security review is not a guarantee of absence of vulnerabilities.
Full Re-Audit — Lending (from scratch)
BaraFi Security Research Unit · BSR-2026-005 · October 2026
Full Re-Audit — Lending (from scratch)
BaraFi Security Research Unit · BSR-2026-005 · October 2026
BaraFi Security Research Unit
Smart Contract Security Assessment
Executive summary
No critical or high-severity issues. Every fund movement remains bound to the lender, borrower, treasury or a referrer recorded at borrow time, all entry points are nonReentrant, and state is written before transfers.
The re-audit surfaced two issues not raised in earlier reports: dust-sized fills can be charged a fee far above 1% because of round-up, and referral exclusion rules are narrower here than in the DEX hook. Both are Low. Previously known items (blocked lender on claim, no rescue function) are re-confirmed.
0 Critical · 0 High · 0 Medium · 3 Low · 2 Informational
Protocol overview
Since the earlier reviews the fee model changed materially: the protocol fee is now charged at borrow time on the required collateral, in the collateral token, and 25% of it can be credited to a referrer. Repayment now returns only principal plus interest. This re-audit treats the contract as new code.
The contract remains owner-less, non-upgradeable and oracle-free. Fee rate and treasury are immutable, with a hard 1% cap enforced in the constructor.
Scope
- All 14 external entry points and their 5 private implementations
- New borrow-time fee path: computation, rounding, treasury and referrer crediting
- Mutual exclusivity of repay (before dueTime) and claimCollateral (at or after dueTime)
- Pull-based proceeds ledger and the single push path (claimCollateral)
- Exact-amount token pulls (_pullExactTo balance check) against fee-on-transfer and rebasing tokens
- Permit fallbacks, deadlines and batch bounds
Methodology
- Independent manual review by two reviewers, followed by reconciliation against prior reports
- Value-flow tracing: for each function, every token in and out was tabulated and summed
- Boundary analysis on dust amounts, maximum amounts and timestamp edges
- Comparison of referral exclusion rules across all three BaraFi contracts for consistency
- Full Foundry suite re-executed for this report: 60 of 60 tests passed across 7 suites, including 256-run fuzz cases
Findings
Low BSR-005-01 · Dust fills can pay an effective fee far above the 1% cap
Description. The fee is rounded up with _ceilDiv. When the proportional collateral for a fill is very small, the rounded fee is at least 1 base unit regardless of size. For a fill whose collateral is 1 base unit, the fee is also 1 unit — an effective 100% fee.
Impact. No loss to anyone but the borrower making the dust fill, and the absolute amount is one base unit. However it breaks the documented "capped at 1%" property for tiny fills.
Recommendation. Either enforce a minimum fill size in the interface, or document that the cap applies to the rate, with at most one base unit of rounding.
Resolution: Acknowledged — interface to enforce sensible minimum fills; documentation updated.
uint256 collateral = _ceilDiv(amount * o.collateralForTotal, o.totalAmount);
uint256 interest = _ceilDiv(amount * o.interestBps, BPS);
uint256 fee = _ceilDiv(collateral * feeBps, BPS);Low BSR-005-02 · Referral exclusions differ from the DEX hook
Description. Lending excludes only referrer == msg.sender. The DEX hook additionally excludes tx.origin, the treasury and the burn address. A referrer equal to the treasury here is harmless (funds land with the treasury either way), but the inconsistency complicates off-chain reporting.
Impact. Accounting only; no funds at risk. Self-referral through a second wallet is possible in all three contracts and bounded to 25% of the fee.
Recommendation. Align exclusion rules across contracts in a future deployment, or document the differences in INTEGRATION.md.
Resolution: Acknowledged; documented.
uint256 share = referrer == address(0) || referrer == msg.sender
? 0 : (fee * AFFILIATE_BPS) / BPS;
claimable[o.collateralToken][treasury] += fee - share;Low BSR-005-03 · claimCollateral is the only push transfer
Description. Repayment proceeds use a pull ledger, but defaulted collateral is transferred directly to the lender. If the collateral token blocks the lender, the claim reverts and the collateral stays locked until the block is lifted.
Impact. Affects only the blocked lender. The borrower cannot recover the collateral after expiry either, so no one else gains.
Recommendation. Credit collateral to claimable[collateralToken][lender] instead, making all exits pull-based.
Resolution: Re-confirmed (previously BSR-001-03). Recommended for next deployment.
l.status = LoanStatus.Claimed;
IERC20(o.collateralToken).safeTransfer(o.lender, l.collateral);Informational BSR-005-04 · Interest rounds up per fill
Description. Interest is ceil-rounded per loan, so splitting a borrow into many fills costs up to one base unit more per fill. This favours the lender, which is the correct direction.
Impact. Negligible.
Recommendation. None required.
Resolution: Accepted.
Informational BSR-005-05 · No rescue function
Description. Tokens sent directly to the contract are not credited to anyone and cannot be recovered.
Impact. Loss limited to the sender.
Recommendation. Warn users; the interface never constructs direct transfers.
Resolution: Accepted — consequence of no admin keys.
Attack vectors considered
Repay-and-claim race at the due time
Repay requires block.timestamp < dueTime; claim requires block.timestamp >= dueTime. Both check status == Active and set a terminal status first.
Result: Mutually exclusive at every timestamp. No double exit.
if (block.timestamp >= l.dueTime) revert LoanExpired(); // repay
if (block.timestamp < l.dueTime) revert LoanNotExpired(); // claimFee-on-transfer collateral under-funding the loan
_pullExactTo measures the recipient balance before and after and reverts unless exactly the requested amount arrived.
Result: Blocked — such tokens revert with UnsupportedToken.
if (t.balanceOf(to) - before != amount) revert UnsupportedToken();Cancelling an offer to pull back lent funds
cancelOffer refunds only o.remaining and zeroes it before transfer. Active loans are stored separately and are untouched.
Result: Not possible — live loans are unaffected by cancellation.
Oracle manipulation, flash loans, liquidation griefing
There is no price read, no pooled share accounting and no liquidation path.
Result: No attack surface.
Test coverage
- Borrow-time fee charged in collateral token and credited to treasury/referrer
- Repayment returns principal + interest only
- Partial fills, cancellation of remainder, expiry boundaries
- Gap identified: no explicit test for dust-fill fee rounding (BSR-005-01) — recommended
Verified properties
- No owner, upgrade, pause or arbitrary call
- Fee rate immutable and capped at 1% in the constructor
- All entry points nonReentrant; checks-effects-interactions respected
- Repay and default claim are mutually exclusive
- Exact-amount pulls reject fee-on-transfer tokens
- Affiliate share comes out of the fee, never added on top
Conclusion
The current lending contract is sound for its intended design. The fee model change introduced no new fund-loss paths; the new findings are rounding and consistency matters. The unit recommends converting claimCollateral to pull-based in the next deployment and reiterates that this internal review does not replace an independent third-party audit.
This report reflects the state of the code at the review date only. Any later change to the contract invalidates it. A security review is not a guarantee of absence of vulnerabilities.
Options
Assessments of BaraFiOptions.sol — the fully backed options contract.
Options Contract Review
BaraFi Security Research Unit · BSR-2026-003 · October 2026
Options Contract Review
BaraFi Security Research Unit · BSR-2026-003 · October 2026
BaraFi Security Research Unit
Smart Contract Security Assessment
Executive summary
No critical or high-severity issues were identified. Escrowed backing can only leave the contract as an exercise payout to the buyer, a reclaim to the writer after expiry, or a cancellation refund of unsold backing to the writer — and each of these paths is gated by a state check that the others invalidate. Every entry point that moves funds is protected against reentrancy, and state is always updated before external token transfers.
One Medium finding concerns the same class of rebasing tokens identified in the lending review: escrowed balances that change outside of transfers can leave the contract short, mitigated at the application layer by excluding such tokens. The remaining findings are Low or Informational, including the deliberate absence of any rescue function, which follows directly from the no-admin-keys requirement.
0 Critical · 0 High · 1 Medium · 1 Low · 1 Informational
Protocol overview
BaraFiOptions.sol implements peer-to-peer, fully backed American-style options. A writer creates an offer by escrowing the full obligation: the underlying token for a call, or the strike token for a put. A buyer purchases all or part of an offer by paying the premium, and may exercise at any time before expiry by paying the strike. After expiry, the writer reclaims whatever backing remains unexercised. A protocol fee is charged on the premium at purchase and on the strike at exercise, each capped at 1% and fixed at deployment.
Like the lending contract, BaraFiOptions has no owner, no upgrade mechanism, no pause switch and no oracles. Whether an option is "in the money" is never evaluated on-chain: exercise is purely the buyer’s choice. This removes the entire category of price-manipulation attacks and was treated as a design constraint throughout the review.
Scope
- Every public and external function, and who is permitted to call it
- Mutual exclusivity of the exercise and writer-reclaim paths around the expiry boundary
- Escrow accounting: backing in versus premium, strike, exercise payouts and reclaims out, per token
- Partial purchases: proportional backing release, rounding direction and dust remnants
- Fee and affiliate accounting on both the premium leg and the strike leg
- Token transfer safety: missing return values, transfer fees, callback tokens (ERC-777-style hooks)
- Reentrancy, transaction ordering and state-change sequencing across all fund-moving paths
Methodology
- Manual line-by-line review of the full contract source by two reviewers working independently, followed by a joint reconciliation pass
- State-machine analysis of the option lifecycle: open → partially/fully sold → exercised or expired → reclaimed
- Automated test suite execution (Foundry), including partial purchase, exercise, expiry reclaim and fee/referral cases
- Cross-check of every state transition against the checks-effects-interactions pattern
- Manual tracing of every external call site to confirm no state is mutated after an untrusted call without a reentrancy guard
- Boundary testing at the exact expiry timestamp from both the buyer and writer sides
Findings
Medium OPT-01 · Rebasing tokens can undermine escrowed backing
Description. Backing is accounted for as a fixed amount recorded at offer creation. If a rebasing token’s balance decreases outside of transfers while escrowed, the contract’s actual balance can fall below the sum owed to writers and buyers.
Impact. In a negative-rebase scenario, the last party to withdraw or exercise could find the contract short of the affected token. Positive rebases create an unclaimable surplus.
Recommendation. Exclude rebasing tokens at the application layer, as is done for the lending contract, and surface a clear warning in the interface when an unsupported token is selected.
Resolution: Mitigated at the application layer; documented in the integration guide. Accepted as a design constraint of immutable, oracle-free escrow.
backing[offerId] += backingAmount;
balanceOf[token][address(this)] is never re-read after depositLow OPT-02 · Last-second exercise can be front-run by block conditions
Description. A buyer exercising in the final seconds before expiry depends on transaction inclusion. Network congestion or block-building delays can push the exercise past the expiry timestamp, after which only the writer’s reclaim path remains.
Impact. The buyer loses the ability to exercise an option they paid for. This is a property of any timestamp-bounded on-chain mechanism, not of this implementation specifically.
Recommendation. Surface the expiry time prominently in the interface and advise buyers not to wait until the final block to exercise.
Resolution: Acknowledged; user-facing warnings added to the preview interface.
Informational OPT-03 · No rescue function for tokens sent directly to the contract
Description. Tokens transferred directly to the contract outside of the offer/purchase/exercise flows are not credited to any account and cannot be recovered, because the contract has no admin and no sweep function.
Impact. A user who sends tokens directly loses them permanently.
Recommendation. Interface should only ever construct protocol calls; documentation should warn against direct transfers.
Resolution: Accepted — a deliberate consequence of the no-admin-keys requirement.
Attack vectors considered
Double-spend of escrowed backing (exercise after reclaim, or vice versa)
The critical safety property: backing must be consumable exactly once. The exercise path requires the option to be unexpired and reduces the buyer’s unexercised balance; the reclaim path requires expiry and pays out only unexercised backing. Both paths mutate the same accounting before any external call.
Result: Not possible. Once the writer reclaims after expiry, no unexercised backing remains for any exercise path to draw on, and exercise reverts after expiry regardless.
if (block.timestamp >= opt.expiry) revert Expired();
opt.unexercised[buyer] -= amount;Reentrancy through a callback token during exercise
Exercise performs multiple token transfers (strike in, backing out, fee to treasury). A malicious token with transfer hooks could attempt to re-enter and double-claim backing.
Result: Blocked. All state changes precede external calls and every fund-moving entry point carries the reentrancy guard. Callback tokens are additionally excluded at the application layer.
Fee or affiliate accounting diverging from actual token flow
Fees are computed from the same premium and strike amounts that are actually transferred, credited to internal pull balances, and never transferred inline to the affiliate. A blocked affiliate address cannot trap a purchase or exercise.
Result: Accounting matches token flows exactly in all tested scenarios, including partial purchases and 1% fee cap boundary cases.
Test coverage
- Offer creation for calls and puts, including validation of zero amounts and unsupported durations
- Partial and full purchases with proportional premium, fee and affiliate splits
- Exercise before expiry: full and partial, including strike fee accounting
- Writer reclaim after expiry of unexercised backing, including partially exercised options
- Cancellation of unsold backing only, with sold portions remaining exercisable
- Referral crediting on purchase and exercise, including self-referral and excluded-address cases
- Reentrancy and malicious-token behaviour across every fund-moving path
Verified properties
- Escrowed backing is consumable exactly once — exercise and reclaim are mutually exclusive
- Exercise is impossible at or after expiry; reclaim is impossible before it
- Cancellation refunds only unsold backing; sold options remain fully backed
- Fees on premium and strike are each capped at 1% and fixed at deployment
- Affiliate earnings use pull withdrawals, so blocked recipients cannot trap funds
- No owner, upgrade, pause or arbitrary external call capability exists
Conclusion
The options contract conserves value exactly: every unit of escrowed backing is accounted for as sold-and-unexercised, exercised, reclaimed or cancelled, and no sequence of calls was found that releases the same backing twice. The oracle-free, fully backed design removes the price-manipulation and under-collateralization categories entirely. Residual exposures are properties of external tokens and of timestamp-bounded exercise, both disclosed. The unit reiterates that this internal review does not replace an independent third-party audit.
This report reflects the state of the code at the review date only. Any later change to the contract invalidates it. A security review is not a guarantee of absence of vulnerabilities.
Full Re-Audit — Options (from scratch)
BaraFi Security Research Unit · BSR-2026-006 · October 2026
Full Re-Audit — Options (from scratch)
BaraFi Security Research Unit · BSR-2026-006 · October 2026
BaraFi Security Research Unit
Smart Contract Security Assessment
Executive summary
No critical or high-severity issues. Each option has a single terminal state (Exercised or Reclaimed) set before any transfer, and exercise and reclaim are separated by the same expiry timestamp in opposite directions.
New observations: the put exercise fee is taken from the buyer’s strike payout rather than charged on top, which is correct but must be shown clearly in any quote; reclaim is push-based, so a writer blocked by a token cannot reclaim; and the referrer is fixed at purchase for the later exercise fee.
0 Critical · 0 High · 0 Medium · 2 Low · 2 Informational
Protocol overview
Writers escrow the underlying (call) or the full strike (put). For puts, a reservedStrike counter tracks how much escrow is committed to sold options, so cancellation refunds only the unreserved part. Buyers pay premium plus fee; exercise pays strike (call) or delivers underlying (put).
The contract is owner-less, oracle-free and non-upgradeable. Premium and exercise fees are independently immutable, each capped at 1%. Maximum option life is 720 days.
Scope
- Call and put escrow accounting, including reservedStrike on puts
- Exercise vs. reclaim exclusivity around expiry
- Fee legs: premium fee (paid on top) and exercise fee (call: paid on top; put: deducted from payout)
- Stored-referrer behaviour on exercise
- Push vs. pull transfers on every exit
Methodology
- Independent manual review by two reviewers, then reconciliation with BSR-2026-003
- Separate value-flow tables for calls and puts across buy, exercise, reclaim and cancel
- Timestamp edge analysis at expiry − 1, expiry and expiry + 1
- Full Foundry suite re-executed for this report: 60 of 60 tests passed across 7 suites, including 256-run fuzz cases
Findings
Low BSR-006-01 · Put exercise fee is deducted from the payout, call fee is added on top
Description. For calls the buyer pays strike + fee. For puts the buyer delivers underlying and receives strike − fee. Both are mathematically consistent, but the asymmetry can surprise a user who expects to receive the full strike.
Impact. User-expectation risk only; no value is lost or misdirected.
Recommendation. Interface quotes must show the net payout for puts. Consider documenting this in the getOptionSummary output.
Resolution: Acknowledged; preview shows net amounts.
_pullExact(o.underlying, msg.sender, opt.amount);
claimable[o.underlying][o.writer] += opt.amount;
_creditFee(optionId, o.quoteToken, fee, opt.referrer);
IERC20(o.quoteToken).safeTransfer(msg.sender, opt.strike - fee);Low BSR-006-02 · Reclaim and exercise payouts are push transfers
Description. Writer reclaim and the buyer’s exercise payout transfer tokens directly. If a token blocks the recipient, the call reverts.
Impact. Only the blocked party is affected. A blocked writer’s escrow stays locked; nobody else can take it.
Recommendation. Credit reclaims to the claimable ledger in a future deployment.
Resolution: Acknowledged.
opt.status = OptionStatus.Reclaimed;
uint256 refund = o.kind == Kind.Call ? opt.amount : opt.strike;
IERC20(o.kind == Kind.Call ? o.underlying : o.quoteToken).safeTransfer(o.writer, refund);Informational BSR-006-03 · Referrer is locked in at purchase
Description. The referrer recorded in _buy also receives 25% of the later exercise fee, even if the buyer later follows another affiliate link.
Impact. Intended by design; consistent with last-click attribution at the time of the trade.
Recommendation. Document in affiliate terms.
Resolution: Accepted.
Informational BSR-006-04 · Dust purchases round fees up
Description. Fees use _ceilDiv, so very small purchases or exercises pay at least one base unit of fee, which can exceed 1% of a dust amount.
Impact. Negligible absolute amounts.
Recommendation. Enforce minimum sizes in the interface.
Resolution: Acknowledged.
Attack vectors considered
Put writer cancelling escrow that backs sold options
Put cancellation refunds strikeForTotal − reservedStrike and then sets reservedStrike = strikeForTotal; each sale adds its strike to reservedStrike before any transfer.
Result: Not possible — sold puts stay fully backed.
refund = o.strikeForTotal - o.reservedStrike;
o.reservedStrike = o.strikeForTotal;Exercise at the exact expiry second
exercise reverts when block.timestamp >= expiry; reclaim reverts when block.timestamp < expiry.
Result: Exactly one path is available at every timestamp.
Buying an expiring offer
_buy rejects offers at or past expiry and checks the caller’s deadline.
Result: Blocked.
Reentrancy via callback tokens
All fund-moving entry points are nonReentrant and set status before transfers.
Result: Blocked.
Test coverage
- Calls and puts: buy, partial buy, exercise, reclaim, cancel
- Fee and referral crediting on both legs
- Gap identified: explicit test asserting put net payout = strike − fee — recommended
Verified properties
- Escrow released exactly once per option
- Sold options remain fully backed after cancellation
- Fees immutable and capped at 1% per leg
- No oracle, owner, upgrade or pause
- All entry points nonReentrant
Conclusion
The options contract conserves value across both option types. Findings are presentation and liveness concerns for blocked recipients, not fund-loss paths. The unit reiterates that this internal review does not replace an independent third-party audit.
This report reflects the state of the code at the review date only. Any later change to the contract invalidates it. A security review is not a guarantee of absence of vulnerabilities.
DEX
Assessments of BaraFiSwapFeeHook.sol — the swap fee hook on an unmodified Uniswap v4 core.
DEX Swap Fee Hook Review
BaraFi Security Research Unit · BSR-2026-004 · October 2026
DEX Swap Fee Hook Review
BaraFi Security Research Unit · BSR-2026-004 · October 2026
BaraFi Security Research Unit
Smart Contract Security Assessment
Executive summary
No critical or high-severity issues were identified in the current code. The review did identify, during development, a partial-fill overcharging defect in an earlier revision: the fee was computed on the requested amount rather than the amount actually swapped, so a partially filled exact-output swap could be charged for tokens never traded. This was corrected before the report date and is covered by a regression test.
The hook takes no custody of swap proceeds, implements no liquidity callbacks, and cannot pause or block swaps: a failure in the fee path reverts only that swap. The burn-exempt list and fee rates are immutable after deployment, which removes governance risk but places full weight on getting the constructor arguments right at deployment.
0 Critical · 0 High · 1 Medium · 2 Low · 1 Informational
Protocol overview
BaraFiSwapFeeHook.sol is a Uniswap v4 hook that charges an additional 0.2% on every swap, paid in the token being sold. Half of the fee (0.1%) is sent to a burn address; the other half accrues to the BaraFi treasury, from which a referred swap pays 25% to the affiliate. Currencies on an immutable, deployment-time burn-exempt list — intended for stablecoins, for which burning is nonsensical — are never burned; their full 0.2% accrues to the treasury, while the affiliate share is still computed only on the normal 0.1% base.
The Uniswap v4 core contracts are deployed unmodified and owner-less. All fee logic lives in the hook, which is the only BaraFi-written code in the swap path. This separation is deliberate: the audited Uniswap core keeps its security history, and the review can concentrate on a small, self-contained contract.
Scope
- The hook’s before/after swap callbacks and their interaction with the PoolManager
- Fee computation on exact-input and exact-output swaps, including partial fills
- Burn/treasury split and the burn-exempt currency list, including its immutability
- Affiliate referral parsing from hookData, crediting rules and excluded addresses
- Claim functions (single-token and batch) and pull-based accounting
- Reentrancy, donation and griefing scenarios across the fee path
- Confirmation that no liquidity-position callbacks are implemented or reachable
Methodology
- Manual line-by-line review of the full hook source by two reviewers working independently
- Differential testing of exact-input and exact-output swaps against the intended fee schedule, including partial fills
- Automated test suite execution (12 Foundry tests), including burn-exempt, referral and batch-claim cases
- Adversarial swap walkthroughs: dust swaps, maximum-size swaps, self-referral, referrer spoofing via crafted hookData
- Cross-check that the hook holds no persistent custody of user swap funds and cannot block swaps
- Review of the CREATE2 address-mining requirement for correct hook permission flags
Findings
Medium DEX-01 · Partial fills were charged on the requested amount, not the executed amount (fixed pre-report)
Description. In an earlier revision, the fee was computed from the swap parameters rather than the actual balance delta returned by the PoolManager. A partially filled swap would overpay the fee.
Impact. Traders on partially filled routes would pay the 0.2% fee on tokens they never actually swapped.
Recommendation. Compute the fee from the actual input delta reported by the PoolManager, and add a regression test covering partial fills.
Resolution: Fixed before the report date; regression test added and passing.
uint256 actualInput = /* input delta from PoolManager result */;
uint256 fee = (actualInput * FEE_BPS) / 10_000;Low DEX-02 · Pools created without the hook bypass the fee entirely
Description. Because the fee lives in a hook rather than in the core, anyone can create a pool on the same PoolManager that does not attach the hook, and swaps there pay no BaraFi fee.
Impact. Fee revenue and burns can be avoided by routing through hookless pools. This is an economic limitation, not a vulnerability: no user funds are at risk.
Recommendation. Accept as a design property; the BaraFi interface routes only through hook-attached pools, and token creators retain the burn incentive to direct traffic to them.
Resolution: Accepted — inherent to the decision not to modify Uniswap core.
Low DEX-03 · Burn-exempt list is immutable and must be correct at deployment
Description. The list of currencies exempt from burning is fixed in the constructor and cannot be amended. A wrong or missing entry is permanent for that deployment.
Impact. A stablecoin omitted from the list would have half its fee burned forever; an incorrectly included token would never burn.
Recommendation. Verify every entry on-chain against the issuer before deployment (the project maintains a per-chain list in contracts/config/burn-exempt-stablecoins.json), and treat the list as part of the deployment checklist.
Resolution: Acknowledged; per-chain verified list maintained and flagged for re-verification before launch.
Informational DEX-04 · Self-referral via a second wallet cannot be prevented on-chain
Description. A trader can refer themselves from another address they control and recover 25% of BaraFi’s half of the fee. The contract excludes only the trader’s own address, the treasury and the burn address as referrers.
Impact. The maximum recoverable amount is 25% of BaraFi’s 0.1% share (0.025% of the trade); the burn half is never reduced.
Recommendation. Accept; the economic cap makes large-scale abuse bounded, and monitoring can be done off-chain.
Resolution: Accepted — bounded by construction.
Attack vectors considered
Overcharging via crafted swap parameters or partial fills
The fee must always be exactly 0.2% of what was actually sold. Differential tests across exact-input, exact-output and partially filled swaps compare the fee against the PoolManager-reported delta.
Result: Fee matches the actual executed input in all tested cases after the DEX-01 fix.
Referrer spoofing through crafted hookData
hookData is user-supplied, so a swap can name any address as referrer. The hook must credit only valid referrers and never let hookData redirect the treasury or burn shares.
Result: Only the affiliate share is affected by hookData; treasury and burn shares are computed independently. Excluded addresses (trader, treasury, burn address) receive nothing.
Trapping funds in the hook via a blocked affiliate or treasury
If a fee recipient cannot receive tokens, a push-based payout could revert every swap. The hook uses pull-based claims for affiliates and direct transfer to treasury/burn addresses chosen to be receivable.
Result: Affiliate balances are claimable via single-token and bounded batch claims; a blocked affiliate cannot affect swaps or other affiliates.
Reentrancy through the PoolManager callback
The hook is called back by the PoolManager mid-swap. State changes must precede any token movement, and the hook must not assume it is the only code running.
Result: All accounting is updated before transfers, and the hook holds no user swap custody to re-enter against.
Test coverage
- Fee charged at exactly 0.2% of actual input on exact-input and exact-output swaps
- Partial fill regression: fee tracks the executed amount, never the requested amount (DEX-01)
- Burn/treasury split at exactly 50/50 for burnable currencies
- Burn-exempt currencies: zero burned, full 0.2% to treasury, affiliate still computed on the 0.1% base
- Referral crediting at 25% of BaraFi’s half, in the input token
- Self-referral and excluded-address cases credit nothing
- Single-token and bounded batch affiliate claims
- Fee path failure reverts only the affected swap
Verified properties
- Uniswap v4 core is unmodified and owner-less; all BaraFi logic is confined to the hook
- Fee is always 0.2% of the actual executed input, never the requested amount
- Burn half is never reduced by referrals or exemptions
- Burn-exempt list and fee rates are immutable after deployment
- Affiliate payouts are pull-based and cannot trap swaps or other claims
- The hook implements no liquidity callbacks and takes no custody of swap proceeds
Conclusion
The hook achieves its design goal: the fee exists entirely outside the Uniswap core, the split and exemption rules behave exactly as specified, and the one real defect found during development — partial-fill overcharging — was fixed and is covered by a regression test. The residual risks are deployment-time correctness of the immutable constructor arguments, the economic reality that hookless pools bypass the fee, and the BUSL-1.1 licensing constraint on production use of the v4 core. The unit reiterates that this internal review does not replace an independent third-party audit.
This report reflects the state of the code at the review date only. Any later change to the contract invalidates it. A security review is not a guarantee of absence of vulnerabilities.
Full Re-Audit — DEX Fee Hook (from scratch)
BaraFi Security Research Unit · BSR-2026-007 · October 2026
Full Re-Audit — DEX Fee Hook (from scratch)
BaraFi Security Research Unit · BSR-2026-007 · October 2026
BaraFi Security Research Unit
Smart Contract Security Assessment
Executive summary
No critical or high-severity issues. The earlier overcharge on partial fills (DEX-01) is now handled differently from what BSR-2026-004 describes: exact-input swaps that would only partially fill because of a price limit now revert with PartialFillNotSupported rather than being re-priced. This is safe — traders are never charged for input that was not swapped — but routers must be aware of it.
Other observations are informational: reliance on tx.origin in the referral filter, swaps small enough to have a zero fee, and the burn half receiving the odd unit on rounding.
0 Critical · 0 High · 0 Medium · 2 Low · 3 Informational
Protocol overview
Exact-input swaps are charged in beforeSwap via a BeforeSwapDelta on the specified (input) token. Exact-output swaps are charged in afterSwap on the actual input delta. Of each 0.2% fee, the burn half is sent to 0x…dEaD through PoolManager.take, and BaraFi’s half is taken into the hook for pull-based claims, 25% of which may be credited to a referrer.
All non-swap callbacks revert with HookNotImplemented. Native ETH is only accepted from the PoolManager.
Scope
- Delta signs and return values for both swap directions and both swap types
- Exact-input partial-fill guard in afterSwap
- Fee split, odd-unit rounding and burn-exempt branch
- Referrer parsing from untrusted hookData
- Claim paths for ERC-20 and native currency
Methodology
- Manual review against Uniswap v4 hook delta conventions
- Worked examples for exact-in, exact-out, zeroForOne true/false, burnable and exempt currencies
- Full Foundry suite re-executed for this report: 60 of 60 tests passed across 7 suites, including 256-run fuzz cases
Findings
Low BSR-007-01 · Exact-input swaps with a binding price limit revert
Description. The fee is taken on the full requested input before the swap. afterSwap then reverts if less than (requested − fee) was actually consumed. A swap whose sqrtPriceLimit stops it early therefore fails rather than partially filling.
Impact. Liveness/UX: such swaps fail and the trader pays gas. No funds are lost. Report BSR-2026-004 should be read with this correction.
Recommendation. The BaraFi router should use slippage limits on output (amountOutMinimum) rather than tight price limits, and surface a clear error.
Resolution: Acknowledged; documented for integrators.
uint256 requested = uint256(-params.amountSpecified);
uint256 expected = requested - feeFor(requested);
if (inputDelta > 0 || uint256(int256(-inputDelta)) < expected) revert PartialFillNotSupported();Low BSR-007-05 · A token that blocks the hook or the burn address halts its own hooked swaps
Description. Every charged swap calls poolManager.take to send the burn half to 0x…dEaD and BaraFi’s half to the hook. If a token’s issuer blocklists either address, or forbids transfers to 0x…dEaD, that take reverts and so does the swap.
Impact. Liveness only, and only for pools of that token: swaps revert, no funds are lost, liquidity can still be removed because liquidity callbacks are not used.
Recommendation. Screen tokens with blocklist powers before listing them in the BaraFi interface; LPs should be told that such tokens can stop trading at the issuer’s discretion.
Resolution: Acknowledged; added to listing checklist.
if (burned > 0) poolManager.take(currency, BURN_ADDRESS, burned);
if (kept > 0) {
poolManager.take(currency, address(this), kept);Informational BSR-007-02 · Referral filter uses tx.origin
Description. Referrers equal to tx.origin earn nothing. With smart-contract wallets or relayers, tx.origin may be a bundler rather than the trader, so the filter is a best-effort heuristic.
Impact. Self-referral remains bounded to 25% of BaraFi’s half; the burn half is never reduced.
Recommendation. Accept; do not rely on tx.origin for anything beyond this bounded heuristic.
Resolution: Accepted.
if (hookData.length != 32) return address(0);
r = abi.decode(hookData, (address));
if (r == sender || r == tx.origin || r == treasury || r == BURN_ADDRESS) r = address(0);Informational BSR-007-03 · Very small swaps pay no fee
Description. When the computed fee rounds to zero, _charge returns early. Splitting a trade into many dust swaps avoids the fee.
Impact. Uneconomic: gas per swap far exceeds the saved fee on any real network.
Recommendation. None required.
Resolution: Accepted.
Informational BSR-007-04 · Odd rounding unit goes to the burn
Description. half = fee / 2 and burned = fee − half, so on an odd fee the burn receives one extra base unit.
Impact. Negligible; favours the burn.
Recommendation. None required; document.
Resolution: Accepted.
uint256 half = fee / 2;
uint256 burned = burnExempt[currency] ? 0 : fee - half;
uint256 kept = fee - burned;Attack vectors considered
Calling hook callbacks directly
beforeSwap, afterSwap and receive all require msg.sender == poolManager.
Result: Blocked.
Using hookData to redirect treasury or burn shares
hookData only selects a referrer; burned and kept are computed before and independently of it, and referrerShare is a fixed fraction of the base half.
Result: Not possible.
Liquidity or donate callbacks as an attack surface
All are unimplemented and revert; permissions exclude them.
Result: No surface.
Overflow in the BeforeSwapDelta cast
_charge reverts with AmountTooLarge above int128 max before casting.
Result: Blocked.
Test coverage
- Exact-in and exact-out fees, burn/treasury split, burn-exempt currencies, referrals and batch claims
- Partial-fill guard covered by test_partialFillReverts (BSR-007-01 behaviour confirmed)
Verified properties
- Uniswap v4 core untouched; all logic in the hook
- Only PoolManager can invoke callbacks or send ETH
- Traders never pay fees on unswapped input
- Burn half never reduced by referrals
- Pull-based claims with bounded batches
Conclusion
The hook is minimal and its accounting is correct. The main correction to earlier documentation is that partial exact-input fills now revert instead of being charged pro rata, which integrators must handle. Deployment risks (address mining, immutable burn-exempt list, BUSL-1.1 licensing) remain. The unit reiterates that this internal review does not replace an independent third-party audit.
This report reflects the state of the code at the review date only. Any later change to the contract invalidates it. A security review is not a guarantee of absence of vulnerabilities.
Severity classification
How each finding level is defined across both reports.