feat: enforce actual receive floors for direct native wrappers #62

Merged
PlasticDigits merged 1 commit from fix/dex-1459-wrapper-floors into master 2026-10-17 05:22:55 +00:00
Owner

Direct native wrapping previously exposed only floorless WrapDeposit {} and Unwrap { recipient } messages. This adds an explicit protected protocol for DEX #1459: treasury WrapDepositWithMinimum forwards a positive minimum_receive through an authenticated mapper callback, and mapper UnwrapWithMinimum checks actual recipient balance delta after mint or native withdrawal. Legacy message shapes remain compatible; unsupported contracts reject the distinct protected variants.

Mapper settlement holds an execution lock across callbacks and measures actual received output, including bank deductions. A failed floor reverts deposit/send/mint/burn/withdraw, supply and rate usage atomically. Both contracts expose execution_capabilities.direct_wrapper_floor_version:1; DEX observes these independently before enabling direct signing. Source versions become treasury 0.3.0 / wrap-mapper 0.4.0. This PR does not migrate production contracts.

Validation:

  • Locked treasury + mapper unit/integration corpus: 146 + 113 PASS, including corrected retry, fee drift, inventory exclusion, capability, exact serialization, legacy ABI rejection, missing/zero floors, callback authentication, unknown replies and reentry guards.
  • Corrected and retested Rust 1.83 release library wasm build for compatible LocalTerra deployment.
  • Isolated LocalTerra fixtures with upstream-token and DEX-token artifacts: protected wrap/unwrap, explicit floor-failure rollback snapshots, actual taxed recipient delta and exact-net retry PASS.
  • Measured protected wrap 459,434 / 459,431 gas; unwrap 500,257 / 500,258; exact-net DEX-token retry 500,607. Nominal 497,500 native delivered 495,013 after actual bank deduction. Public receipts include code hashes, heights, tx hashes, gas, driver/helper fingerprints and build scope.
  • Normal commit hooks: frontend TypeScript check PASS; lint-staged found no changed frontend files.
  • Production migration/capability readback, optimized release artifact attestation and deployed DEX/browser acceptance remain separate unchecked rollout work.

Protocol and agent checklist, invariants, DEX checklist, and reproducible isolated driver describe how another agent completes review. An unavailable check may be explicit SKIP with overall PASS WITH SKIPS when all executed checks pass; failed assertions remain FAIL, skipped acceptance remains unchecked, and source/local-chain evidence does not establish production deployment.

Direct native wrapping previously exposed only floorless `WrapDeposit {}` and `Unwrap { recipient }` messages. This adds an explicit protected protocol for [DEX #1459](https://git.cl8y.com/code/cl8y-dex-terraclassic/issues/1459): treasury `WrapDepositWithMinimum` forwards a positive `minimum_receive` through an authenticated mapper callback, and mapper `UnwrapWithMinimum` checks actual recipient balance delta after mint or native withdrawal. Legacy message shapes remain compatible; unsupported contracts reject the distinct protected variants. Mapper settlement holds an execution lock across callbacks and measures actual received output, including bank deductions. A failed floor reverts deposit/send/mint/burn/withdraw, supply and rate usage atomically. Both contracts expose `execution_capabilities.direct_wrapper_floor_version:1`; DEX observes these independently before enabling direct signing. Source versions become treasury 0.3.0 / wrap-mapper 0.4.0. This PR does not migrate production contracts. Validation: - [x] Locked treasury + mapper unit/integration corpus: 146 + 113 PASS, including corrected retry, fee drift, inventory exclusion, capability, exact serialization, legacy ABI rejection, missing/zero floors, callback authentication, unknown replies and reentry guards. - [x] Corrected and retested Rust 1.83 release library wasm build for compatible LocalTerra deployment. - [x] Isolated LocalTerra fixtures with upstream-token and DEX-token artifacts: protected wrap/unwrap, explicit floor-failure rollback snapshots, actual taxed recipient delta and exact-net retry PASS. - [x] Measured protected wrap 459,434 / 459,431 gas; unwrap 500,257 / 500,258; exact-net DEX-token retry 500,607. Nominal 497,500 native delivered 495,013 after actual bank deduction. Public receipts include code hashes, heights, tx hashes, gas, driver/helper fingerprints and build scope. - [x] Normal commit hooks: frontend TypeScript check PASS; lint-staged found no changed frontend files. - [ ] Production migration/capability readback, optimized release artifact attestation and deployed DEX/browser acceptance remain separate unchecked rollout work. [Protocol and agent checklist](docs/qa/dex-1459/README.md), [invariants](skills/direct-wrapper-floors/SKILL.md), [DEX checklist](https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/fix/issue-1459-quote-semantics/docs/qa/issue-1459/README.md), and [reproducible isolated driver](https://git.cl8y.com/code/cl8y-dex-terraclassic/src/branch/fix/issue-1459-quote-semantics/scripts/qa/localterra-wrapper-floors-1459.py) describe how another agent completes review. An unavailable check may be explicit SKIP with overall PASS WITH SKIPS when all executed checks pass; failed assertions remain FAIL, skipped acceptance remains unchecked, and source/local-chain evidence does not establish production deployment.
feat: enforce receive floors for direct native wrappers
All checks were successful
ci/woodpecker/pr/woodpecker Pipeline was successful
519c2766e5
Add protected wrap and unwrap messages, actual recipient balance-delta settlement, capability queries, atomic rollback tests and measured LocalTerra receipts.
Author
Owner

This is a complex change that covers a wide variety of likely unecssary changes that greatly increases the security overhead for minimal benefit. Postponed until multiple rounds of internal audits by uncensored models can be completed

This is a complex change that covers a wide variety of likely unecssary changes that greatly increases the security overhead for minimal benefit. Postponed until multiple rounds of internal audits by uncensored models can be completed
Author
Owner

Security review — direct wrapper receive floors (DEX #1459)

Review artifact: 519c2766e5be0a3788a4c920ad879b641a50aa74 vs be0f048
Scope: wrap-mapper 0.4.0 and treasury 0.3.0 source changes; the DEX consumer is referenced only where it affects the on-chain guarantee.
Method: full diff review, adversarial threat model of the settlement window (snapshot timing, message ordering, reentry, lock lifetime, delta manipulation), and an independent local run of the contract suites.

Independent verification

cargo test --locked --manifest-path contracts/Cargo.toml -p treasury -p wrap-mapper --no-default-features

Result: treasury 146 passed / 0 failed; wrap-mapper 113 passed / 0 failed — matches the PR's claimed 146 + 113. I also confirmed by inspection that the protected variants are wire-distinct, zero floors are rejected at every layer, protect saves the pending item before dispatch, and evidence rollback covers deposit/mint/supply/rate and burn/withdraw/recipient.

No high-severity, directly exploitable defect was found in the settlement logic. The core invariant — snapshot the recipient, hold a lock across the callback, measure the actual post-action balance delta, revert atomically on shortfall — is correctly implemented for the two current call sites. The findings below are risk-reduction and durability items.

Findings

F1 — Medium (capability durability / governance). Self-reported capability is not bound to code identity.
execution_capabilities.direct_wrapper_floor_version = 1 is a hardcoded constant. It proves the variant exists, not that the reviewed enforcement code is running. Both contracts are migratable and the DEX caches scheduled observations, so a later mapper upgrade that accepts NotifyDepositWithMinimum but drops the delta check would keep direct signing admitted while silently removing the floor. Recommendation: bind consumer admission to the observed code id / checksum, and/or include the contract version (env!("CARGO_PKG_VERSION")) in ExecutionCapabilitiesResponse so admission can be pinned to the reviewed artifact. Treat mapper/treasury upgrades as security events that invalidate cached capability.

F2 — Low (latent correctness in a financial contract). protect clobbers the final submessage.
settlement::protect replaces response.messages.last_mut() with SubMsg::reply_on_success(final_message.msg.clone(), 1459). I confirmed in cosmwasm-std 1.5.11 that this constructor resets gas_limit: None and drops the original id/reply_on. It also does not verify that the last message is the intended mint/withdraw. Today every protected response ends with exactly the action built by add_message, so this is not exploitable. But any future message appended after the action (or a message that intentionally carries a reply id or gas limit) would silently move the measured window and could settle the floor on the wrong transfer. Recommendation: construct the settlement SubMsg explicitly for the known action and fail closed on unexpected trailing messages.

F3 — Low (document/test the assumption). The delta is net of any recipient balance movement in the whole window.
The guarantee is balance_after − balance_before ≥ minimum, not "this transfer delivered ≥ minimum". The current windows are safe because the only system messages between snapshot and settle are the CW20 mint (wrap) or the CW20 burn plus the treasury bank send (unwrap), and mapped tokens are the project's standard cw20-mintable. It would weaken if a governance-mapped CW20 ever gained a recipient-side hook or native side effects. Recommendation: state this assumption in the invariant/skill text and add a regression test that a mapped token cannot credit the recipient between snapshot and settle.

F4 — Low. The settlement lock is contract-global, so ensure_idle blocks every execute, including governance setters, while a settlement is in flight. It is atomic (the pending item is removed on success, otherwise the transaction reverts), so there is no cross-transaction DoS; noting it because the lock is broader than the two entry points that use it.

F5 — Informational. Floorless legacy paths remain callable. WrapDeposit / NotifyDeposit / Unwrap are unchanged and not gated by capability. Intentional for compatibility, but any production consumer must be verified never to fall back to them, because a legacy call silently loses the floor.

F6 — Informational. migrate does not clear the pending item. A pending item cannot survive an atomic failed transaction, so this is defensive only. Consider clearing it on migrate (or documenting why it cannot exist) so the "no stuck lock" property does not depend on migration history.

F7 — Informational (attack surface / TCB). The change adds a reply entry point, new persisted state and roughly 600 lines to a live financial contract. This is a legitimate security-overhead concern; the wrap floor is essentially deterministic (amount − fee_wrap), so much of the value sits in the unwrap after-tax path. If the scope is revisited, consider enforcing the delta only on unwrap or moving it to the consumer to shrink the trusted base. The PR's own outstanding items (production migration, capability readback, deployed DEX acceptance) must remain release gates — source and local-chain evidence do not establish deployment.

Controls verified as sound

  • Treasury-only mapper callback (info.sender == config.treasury); pause, denom-mapping and rate-limit checks preserved on the protected path.
  • Positive-floor enforcement at the treasury, the wrapper's protected entry, and inside protect.
  • Atomic rollback of deposit/mint/supply/rate and burn/withdraw/recipient on shortfall (unit/integration tests plus LocalTerra receipts).
  • Reentry blocked: ensure_idle runs before dispatch and the pending item is persisted before the action submessage is queued.
  • The reply is delivered after the treasury's nested bank send completes, so the native delta includes the actual chain deduction (confirmed by the passing after-tax LocalTerra receipt and the source-level ordering).

Overall: no blocking security defect in the source change. Recommend addressing F1 and F2 (or explicitly accepting them) before enabling direct signing in production, and keeping rollout gated on the unchecked production/deployed checks.

## Security review — direct wrapper receive floors (DEX #1459) **Review artifact:** `519c2766e5be0a3788a4c920ad879b641a50aa74` vs `be0f048` **Scope:** `wrap-mapper` 0.4.0 and `treasury` 0.3.0 source changes; the DEX consumer is referenced only where it affects the on-chain guarantee. **Method:** full diff review, adversarial threat model of the settlement window (snapshot timing, message ordering, reentry, lock lifetime, delta manipulation), and an independent local run of the contract suites. ### Independent verification ``` cargo test --locked --manifest-path contracts/Cargo.toml -p treasury -p wrap-mapper --no-default-features ``` Result: **treasury 146 passed / 0 failed; wrap-mapper 113 passed / 0 failed** — matches the PR's claimed 146 + 113. I also confirmed by inspection that the protected variants are wire-distinct, zero floors are rejected at every layer, `protect` saves the pending item before dispatch, and `evidence` rollback covers deposit/mint/supply/rate and burn/withdraw/recipient. **No high-severity, directly exploitable defect was found in the settlement logic.** The core invariant — snapshot the recipient, hold a lock across the callback, measure the actual post-action balance delta, revert atomically on shortfall — is correctly implemented for the two current call sites. The findings below are risk-reduction and durability items. ### Findings **F1 — Medium (capability durability / governance). Self-reported capability is not bound to code identity.** `execution_capabilities.direct_wrapper_floor_version = 1` is a hardcoded constant. It proves the variant exists, not that the reviewed enforcement code is running. Both contracts are migratable and the DEX caches scheduled observations, so a later mapper upgrade that accepts `NotifyDepositWithMinimum` but drops the delta check would keep direct signing admitted while silently removing the floor. Recommendation: bind consumer admission to the observed **code id / checksum**, and/or include the contract version (`env!("CARGO_PKG_VERSION")`) in `ExecutionCapabilitiesResponse` so admission can be pinned to the reviewed artifact. Treat mapper/treasury upgrades as security events that invalidate cached capability. **F2 — Low (latent correctness in a financial contract). `protect` clobbers the final submessage.** `settlement::protect` replaces `response.messages.last_mut()` with `SubMsg::reply_on_success(final_message.msg.clone(), 1459)`. I confirmed in cosmwasm-std 1.5.11 that this constructor resets `gas_limit: None` and drops the original `id`/`reply_on`. It also does not verify that the last message is the intended mint/withdraw. Today every protected response ends with exactly the action built by `add_message`, so this is not exploitable. But any future message appended after the action (or a message that intentionally carries a reply id or gas limit) would silently move the measured window and could settle the floor on the wrong transfer. Recommendation: construct the settlement `SubMsg` explicitly for the known action and fail closed on unexpected trailing messages. **F3 — Low (document/test the assumption). The delta is net of any recipient balance movement in the whole window.** The guarantee is `balance_after − balance_before ≥ minimum`, not "this transfer delivered ≥ minimum". The current windows are safe because the only system messages between snapshot and settle are the CW20 mint (wrap) or the CW20 burn plus the treasury bank send (unwrap), and mapped tokens are the project's standard `cw20-mintable`. It would weaken if a governance-mapped CW20 ever gained a recipient-side hook or native side effects. Recommendation: state this assumption in the invariant/skill text and add a regression test that a mapped token cannot credit the recipient between snapshot and settle. **F4 — Low.** The settlement lock is contract-global, so `ensure_idle` blocks every `execute`, including governance setters, while a settlement is in flight. It is atomic (the pending item is removed on success, otherwise the transaction reverts), so there is no cross-transaction DoS; noting it because the lock is broader than the two entry points that use it. **F5 — Informational. Floorless legacy paths remain callable.** `WrapDeposit` / `NotifyDeposit` / `Unwrap` are unchanged and not gated by capability. Intentional for compatibility, but any production consumer must be verified never to fall back to them, because a legacy call silently loses the floor. **F6 — Informational. `migrate` does not clear the pending item.** A pending item cannot survive an atomic failed transaction, so this is defensive only. Consider clearing it on migrate (or documenting why it cannot exist) so the "no stuck lock" property does not depend on migration history. **F7 — Informational (attack surface / TCB).** The change adds a reply entry point, new persisted state and roughly 600 lines to a live financial contract. This is a legitimate security-overhead concern; the wrap floor is essentially deterministic (`amount − fee_wrap`), so much of the value sits in the unwrap after-tax path. If the scope is revisited, consider enforcing the delta only on unwrap or moving it to the consumer to shrink the trusted base. The PR's own outstanding items (production migration, capability readback, deployed DEX acceptance) must remain release gates — source and local-chain evidence do not establish deployment. ### Controls verified as sound - Treasury-only mapper callback (`info.sender == config.treasury`); pause, denom-mapping and rate-limit checks preserved on the protected path. - Positive-floor enforcement at the treasury, the wrapper's protected entry, and inside `protect`. - Atomic rollback of deposit/mint/supply/rate and burn/withdraw/recipient on shortfall (unit/integration tests plus LocalTerra receipts). - Reentry blocked: `ensure_idle` runs before dispatch and the pending item is persisted before the action submessage is queued. - The reply is delivered after the treasury's nested bank send completes, so the native delta includes the actual chain deduction (confirmed by the passing after-tax LocalTerra receipt and the source-level ordering). **Overall: no blocking security defect in the source change. Recommend addressing F1 and F2 (or explicitly accepting them) before enabling direct signing in production, and keeping rollout gated on the unchecked production/deployed checks.**
Author
Owner

Risk acceptance — F1 and F2 accepted for source merge

Following the security review above, F1 and F2 are explicitly accepted for this source-only merge into master. This PR is scoped not to migrate production contracts, so acceptance here does not authorize a production rollout.

F1 (capability not bound to code identity) — accepted with conditions.

  • Enforcement does not depend on the capability flag: the mapper's settle still measures the recipient delta on every protected execution. A stale or overstated capability causes a failed or unprotected hop, not an incorrect settlement.
  • Direct signing is a consumer-side admission decision and remains disabled until the deployed capability readback in the unchecked rollout list passes.
  • Condition before any production direct signing / mapper upgrade: bind DEX admission to the observed code id/checksum (or add the contract version to ExecutionCapabilitiesResponse), and treat mapper/treasury upgrades as security events that invalidate cached capability. Until then the accepted residual risk is a silent floor drop only in the scenario of a future regressed upgrade — a governance-controlled action.

F2 (protect replaces the last submessage) — accepted.

  • The two current protected call sites end with exactly the intended action (mint for wrap, withdraw for unwrap) and both are covered by the rollback and after-tax delta tests; no trailing message exists today.
  • Hardening before the next change to protected responses: construct the settlement SubMsg explicitly and fail closed on unexpected trailing messages, with a regression test. Any PR that appends a message after the protected action must add this guard.

Compensating controls that remain in force: treasury-authenticated callback, positive-floor rejection at all three layers, contract-wide reentry lock persisted before dispatch, and atomic rollback of deposit/mint/supply/rate and burn/withdraw/recipient on shortfall.

Release gates unchanged: production migration, capability readback, optimized release artifact attestation, and deployed DEX/browser acceptance remain unchecked and must pass separately. Merge is not deployment evidence.

CI status on the head is already green; no additional checks are added or substituted by this merge. Test evidence for the reviewed head is the independently reproduced treasury 146 / wrap-mapper 113 pass.

## Risk acceptance — F1 and F2 accepted for source merge Following the security review above, F1 and F2 are explicitly accepted for this **source-only** merge into `master`. This PR is scoped not to migrate production contracts, so acceptance here does not authorize a production rollout. **F1 (capability not bound to code identity) — accepted with conditions.** - Enforcement does not depend on the capability flag: the mapper's `settle` still measures the recipient delta on every protected execution. A stale or overstated capability causes a failed or unprotected hop, not an incorrect settlement. - Direct signing is a consumer-side admission decision and remains disabled until the deployed capability readback in the unchecked rollout list passes. - **Condition before any production direct signing / mapper upgrade:** bind DEX admission to the observed code id/checksum (or add the contract version to `ExecutionCapabilitiesResponse`), and treat mapper/treasury upgrades as security events that invalidate cached capability. Until then the accepted residual risk is a silent floor drop only in the scenario of a future regressed upgrade — a governance-controlled action. **F2 (`protect` replaces the last submessage) — accepted.** - The two current protected call sites end with exactly the intended action (`mint` for wrap, `withdraw` for unwrap) and both are covered by the rollback and after-tax delta tests; no trailing message exists today. - **Hardening before the next change to protected responses:** construct the settlement `SubMsg` explicitly and fail closed on unexpected trailing messages, with a regression test. Any PR that appends a message after the protected action must add this guard. **Compensating controls that remain in force:** treasury-authenticated callback, positive-floor rejection at all three layers, contract-wide reentry lock persisted before dispatch, and atomic rollback of deposit/mint/supply/rate and burn/withdraw/recipient on shortfall. **Release gates unchanged:** production migration, capability readback, optimized release artifact attestation, and deployed DEX/browser acceptance remain unchecked and must pass separately. Merge is not deployment evidence. CI status on the head is already green; no additional checks are added or substituted by this merge. Test evidence for the reviewed head is the independently reproduced treasury 146 / wrap-mapper 113 pass.
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
code/ustr-cmm!62
No description provided.