Skip to content

feat: M013 CosmWasm fee-router contract scaffold with unit tests#65

Open
brawlaphant wants to merge 3 commits intoregen-network:mainfrom
brawlaphant:pr/m013-cosmwasm-contract-scaffold
Open

feat: M013 CosmWasm fee-router contract scaffold with unit tests#65
brawlaphant wants to merge 3 commits intoregen-network:mainfrom
brawlaphant:pr/m013-cosmwasm-contract-scaffold

Conversation

@brawlaphant
Copy link
Copy Markdown
Contributor

Summary

  • Adds a complete CosmWasm contract scaffold for M013 Value-Based Fee Routing in contracts/fee-router/
  • Implements fee calculation (fee = max(value * rate, min_fee)) and 4-pool distribution matching the JS reference implementation's integer rounding strategy (floor for burn/community/agent, remainder to validator)
  • Includes 13 unit tests validated against the M013 test vectors (vector_v0_sample), covering all tx types, fee conservation invariant, share sum unity, rate caps, and authorization

Files

File Purpose
Cargo.toml CosmWasm 2.2+ dependencies (cosmwasm-std, cw-storage-plus, schemars, serde, thiserror)
src/msg.rs InstantiateMsg, ExecuteMsg (CollectFee, UpdateFeeRate, UpdateDistribution), QueryMsg (FeeConfig, PoolBalances, CalculateFee)
src/state.rs FeeConfig (Decimal rates, distribution shares, min_fee), PoolBalances (4 Uint128 pools)
src/error.rs InvalidFeeRate, ShareSumNotUnity, Unauthorized, ZeroValue, RateExceedsCap
src/contract.rs Entry points: instantiate (validate shares=1.0, rates<=10%), execute (collect/update), query (config/pools/simulate)
src/tests.rs 13 unit tests matching M013 SPEC acceptance tests and reference impl test vectors
.cargo/config.toml cargo wasm alias for wasm32 builds

Test vectors validated

TX Type Value (uregen) Rate Fee (uregen) Min fee?
CreditIssuance 5,000,000,000 2% 100,000,000 No
CreditTransfer 100,000,000 0.1% 1,000,000 Yes (clamped)
CreditRetirement 1,000,000,000 0.5% 5,000,000 No
MarketplaceTrade 2,500,000,000 1% 25,000,000 No
CreditTransfer 500,000 0.1% 1,000,000 Yes (clamped)

Fee conservation: total 132,000,000 uregen = burn 39,600,000 + validator 52,800,000 + community 33,000,000 + agent 6,600,000

Spec references

  • mechanisms/m013-value-based-fee-routing/SPEC.md (sections 4-5, 9, 13)
  • phase-3/m013-contract-architecture.md
  • mechanisms/m013-value-based-fee-routing/reference-impl/m013_fee.js

Test plan

  • cargo test passes (13/13 tests)
  • No compiler warnings
  • Review: Decimal precision matches JS Math.floor for all test vectors
  • Review: Fee Conservation invariant holds for edge cases (very small fees, max uint values)
  • Future: cargo wasm build + schema generation for integration testing

🤖 Generated with Claude Code

Implement the CosmWasm contract scaffold for M013 Value-Based Fee Routing,
translating the mechanism spec and JS reference implementation into Rust.

Contract structure:
- msg.rs: InstantiateMsg, ExecuteMsg (CollectFee, UpdateFeeRate, UpdateDistribution),
  QueryMsg (FeeConfig, PoolBalances, CalculateFee) with typed responses
- state.rs: FeeConfig (rates as Decimal, distribution shares, min_fee) and
  PoolBalances (burn_pool, validator_fund, community_pool, agent_infra)
- error.rs: InvalidFeeRate, ShareSumNotUnity, Unauthorized, ZeroValue, RateExceedsCap
- contract.rs: Entry points with fee calculation matching the JS reference impl
  integer rounding strategy (floor for 3 pools, remainder to validator)

Fee calculation: fee = max(value * rate, min_fee)
Distribution: burn/community/agent use floor(), validator gets remainder
  (Fee Conservation invariant: sum of pools == fee collected)

13 unit tests covering:
- Valid/invalid instantiation (share sum unity)
- All 4 tx type fee calculations matching test vectors
- Fee distribution (100M -> 30M burn, 40M validator, 25M community, 5M agent)
- Fee conservation across all 5 test vector transactions (total 132M uregen)
- Rate cap enforcement (max 10%)
- Share update validation
- Unauthorized access rejection
- Zero value rejection

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces the foundational CosmWasm smart contract for implementing value-based fee routing within the Regen Network. It establishes a robust mechanism for calculating and distributing fees across various ecological credit transaction types, ensuring adherence to specified economic models and providing a solid, tested base for future integration.

Highlights

  • CosmWasm Contract Scaffold: A complete CosmWasm contract scaffold for M013 Value-Based Fee Routing was added in contracts/fee-router/.
  • Fee Calculation and Distribution: Implemented fee calculation (fee = max(value * rate, min_fee)) and a 4-pool distribution strategy, matching the JS reference implementation's integer rounding.
  • Comprehensive Unit Tests: Thirteen unit tests were included, validated against M013 test vectors, covering all transaction types, fee conservation, share sum unity, rate caps, and authorization.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new CosmWasm fee-router contract designed to manage transaction fees for ecological credit operations. The contract allows for the configuration of fee rates for various transaction types (credit issuance, transfer, retirement, and marketplace trade) and defines how collected fees are distributed among burn, validator, community, and agent infrastructure pools. It includes functions for contract instantiation, fee collection, and administrative updates to fee rates and distribution shares, with robust validation for rates and share sums. Comprehensive unit tests are also added to ensure correct functionality. Review feedback suggests refactoring a duplicated max_rate constant into a module-level constant for improved maintainability and removing an unused InvalidFeeRate error variant to enhance code clarity.

msg: InstantiateMsg,
) -> Result<Response, ContractError> {
// Validate all rates are within [0, 0.10]
let max_rate = Decimal::raw(100_000_000_000_000_000); // 0.1
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The value for max_rate (0.1) is a magic number that is also hardcoded in execute_update_fee_rate on line 147. To improve maintainability and prevent potential inconsistencies, this value should be defined as a module-level constant.

For example, you could add this at the top of the file:

const MAX_RATE: Decimal = Decimal::raw(100_000_000_000_000_000); // 0.1

Then, you can use this MAX_RATE constant in both places.

Comment on lines +9 to +11
#[error("Invalid fee rate: rate {rate} exceeds cap of 0.10 (10%)")]
InvalidFeeRate { rate: String },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The InvalidFeeRate error variant is defined but never used within the contract. The RateExceedsCap variant is used instead to handle the same validation logic. To improve code clarity and remove unused code, you should remove the InvalidFeeRate variant.

brawlaphant and others added 2 commits March 25, 2026 11:52
…mantics

- Remove dead `InvalidFeeRate` error variant (only `RateExceedsCap` is used)
- Add doc comment on PoolBalances explaining write-only pool design and
  how downstream mechanisms (M012/M014/M015) handle distribution

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The 0.1 (10%) max rate was defined as a local variable in both
instantiate() and execute_update_fee_rate(). Extracted to a
module-level constant for single-source-of-truth and clarity.

Addresses gemini-code-assist review feedback on PR regen-network#65.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant