basic smart contract in rust

To create a basic smart contract in Rust, you can use the ink! framework which is specifically designed for building smart contracts on the Substrate blockchain. Here's a step-by-step guide on creating a simple smart contract using ink!.

  1. Create a new Rust project by running cargo new <project-name>
  2. Add the following dependencies to your Cargo.toml:
[dependencies]
ink_lang = { version = "3.0.0", default-features = false }

[dev-dependencies]
ink-as-dependency = { version = "1.0", package = "ink-as-dependency" }
165 chars
6 lines
  1. Create a new file in your project's src directory called lib.rs
  2. Define your smart contract by adding the following code to lib.rs:
main.rs
use ink_lang::contract;

#[contract]
mod my_contract {
    // Define your smart contract's storage here using the `ink_storage` macro

    #[ink(constructor)]
    pub fn new() -> Self {
        // Code executed when creating a new instance of the contract
    }

    #[ink(message)]
    pub fn my_function(&self) {
        // Code executed when calling the `my_function` function on the contract
    }
}
404 chars
17 lines
  1. Implement the storage for your smart contract by adding the following code inside the mod my_contract declaration:
main.rs
use ink_storage::traits::*;

#[ink(storage)]
struct MyContract {
    value: i32,
}

impl MyContract {
    // Add any other functions you need for your smart contract implementation here
}

impl Default for MyContract {
    fn default() -> Self {
        Self { value: 0 }
    }
}
280 chars
17 lines
  1. Build your smart contract by running cargo contract build
  2. Run tests to ensure everything is working as expected by running cargo contract test
  3. Deploy your smart contract by running cargo contract deploy -p my_contract --network dev --account $ACCOUNT_ID, replacing $ACCOUNT_ID with your account ID on the Substrate blockchain.

This is just a basic example, but ink! provides a lot of additional features for building more complex smart contracts. Check out the ink! documentation for more information.

gistlibby LogSnag