Search code examples
nearprotocol

How to build and deploy multiple contracts in NEAR protocol


Currently the cargo build produces one WASM file like contract/target/wasm32-unknown-unknown/release/hello.wasm. How can I produce multiple wasm binaries if my contract source tree contains multiple contracts, one per named Rust module?

My Cargo.toml

[package]
name = "hello"
version = "0.1.0"
authors = ["Why so difficult <argh@example.com>"]
edition = "2018"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
near-sdk = "2.0.0"

[profile.release]
codegen-units = 1
# Tell `rustc` to optimize for small code size.
opt-level = "z"
lto = true
debug = false
panic = "abort"

[workspace]
members = []


Solution

  • Although each contract still needs to go to its own crate, there is a cargo feature called workspaces that remove at least some of the repetitive boilerplate out of your contracts and you will have only one Cargo.lock file.

    Split contract folder to multiple folders - let's call them 'token' and 'pool'.

    On the the top contract folder have one workspaced Cargo.toml:

    [profile.release]
    codegen-units = 1
    # Tell `rustc` to optimize for small code size.
    opt-level = "z"
    lto = true
    debug = false
    panic = "abort"
    
    # Important security flag for the compiler,
    # otherwise not present in optimised builds
    # https://stackoverflow.com/q/64129432/315168
    overflow-checks = true
    
    
    [workspace]
    members = [
        "token",
        "pool"
    ]
    
    

    Then on each folder you have its own Cargo.toml that can have dependencies to other crates in the same workspace:

    [package]
    name = "nep9000_pool"
    version = "0.0.0"
    
    # https://stackoverflow.com/a/53985748/315168
    edition = "2018"
    
    [dependencies]
    near-sdk = "2.0.0"
    nep9000_token = { path = "../token" }
    
    
    [lib]
    crate-type = ["cdylib", "rlib"]
    
    

    One cargo build in the root will build them all.

    Full example.