coral-xyz / anchor

⚓ Solana Sealevel Framework
https://anchor-lang.com
Apache License 2.0
3.36k stars 1.25k forks source link

[Proposal]: Modularization of `#[program]` Attribute Macro for Improved Maintainability #3011

Closed wiseaidev closed 3 days ago

wiseaidev commented 3 weeks ago

Hello!

I've been using Anchor for quite a while now and found an area of improvement regarding the #[program] attribute macro. Currently, all smart contract functions must be defined in a single module, which can become cumbersome for enterprise level programs.

I propose enhancing the #[program] attribute macro to allow splitting smart contract functions into multiple modules. This would improve maintainability and modularity, making the codebase easier to manage, especially for large projects.

Let's consider the example from the readme file:

#[program]
mod counter {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>, start: u64) -> Result<()> {
        let counter = &mut ctx.accounts.counter;
        counter.authority = *ctx.accounts.authority.key;
        counter.count = start;
        Ok(())
    }

    pub fn increment(ctx: Context<Increment>) -> Result<()> {
        let counter = &mut ctx.accounts.counter;
        counter.count += 1;
        Ok(())
    }
}

Instead, we can split these functions into separate modules:

Module 1: init.rs

pub fn initialize(ctx: Context<Initialize>, start: u64) -> Result<()> {
    let counter = &mut ctx.accounts.counter;
    counter.authority = *ctx.accounts.authority.key;
    counter.count = start;
    Ok(())
}

Module 2: funcs.rs

pub fn increment(ctx: Context<Increment>) -> Result<()> {
    let counter = &mut ctx.accounts.counter;
    counter.count += 1;
    Ok(())
}

Combined Modules:

#[program]
pub mod init;
#[program]
pub mod funcs;

This is just a toy example to easily explain this feature request.

The benefits of such a feature, including but not limited to:

  1. Improved Code Organization: Splitting functions into different modules allows for better organization of code.
  2. Enhanced Maintainability: Modularizing the codebase makes it easier to manage and maintain, especially for large smart contracts.
  3. Scalability: Facilitates the addition of new functionalities by simply adding new modules.

What do you think about this feature? I believe it will be particularly useful for large smart contracts, making them more modular and easier to maintain. Your feedback and thoughts on this proposal would be greatly appreciated.

Best!

acheroncrypto commented 3 weeks ago

You don't need to implement all your program logic in one file. You can easily modularize it if you use the multiple files template, which is quite popular among larger programs.

Also, a similar issue exists, and I'm not sure if this is necessary https://github.com/coral-xyz/anchor/issues/454#issuecomment-979116091