Smart Contract Development on NEAR Protocol with Rust

Unpacking the gems of NEAR Protocol and Rust

M. Kuck
5 min readDec 5, 2023

NEAR Protocol emerges as a state-of-the-art, sharded, proof-of-stake blockchain, carving a niche for itself in the realm of decentralized applications (DApps). Its unique selling point is the integration with Rust, a systems programming language known for its relentless focus on memory safety and concurrency, making it an ideal candidate for the rigors of smart contract development.

Revolutionizing Smart Contract Codebases

Rust’s design principles prioritize zero-cost abstractions, move semantics, and guaranteed memory safety, setting a high standard in the domain of blockchain development. Its borrow checker system and ownership model are game-changers in preventing data races and ensuring thread safety, critical factors in the immutable and transparent world of smart contracts.

Toolchain and SDK: The Bedrock of NEAR and Rust Development

Developers embarking on this journey need to master the Rust toolchain and the intricacies of the NEAR CLI and SDK.

NEAR CLI gives you an array of options when initialized

This toolkit is not just about writing Rust code; it’s about understanding how to transpile this into WebAssembly (Wasm) — the bytecode that runs on the NEAR blockchain. This process involves leveraging the power of cargo, Rust's package manager and build system, and integrating with NEAR's blockchain-specific libraries provided in the SDK.

Setting Up the Rust and Wasm Toolchain

To begin developing smart contracts on NEAR Protocol using Rust, the initial step involves setting up the Rust environment and the WebAssembly (Wasm) toolchain. The Wasm toolchain is essential as the smart contracts you develop will be compiled to Wasm to run on the NEAR blockchain. For Linux or MacOS users, the setup process is initiated via the command line using:

curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh   
source $HOME/.cargo/env

Subsequently, the wasm32-unknown-unknown toolchain is added:

rustup target add wasm32-unknown-unknown

This setup forms the foundation for developing and deploying Rust-based smart contracts on NEAR​​.

Project Initialization: NEAR App and Rust SDK

Creating a new NEAR application with an integrated frontend can be efficiently done using the create-near-app tool. This tool streamlines the process, especially when initializing with Rust SDK. The command below demonstrates how to initiate a project with the Rust SDK and without a specific frontend framework (the default being vanilla HTML):

npx create-near-app my-project --contract rust --frontend none --tests rust

For developers focusing solely on Rust contract development and deployment, utilizing the status message example or the cargo-generate tool is highly recommended​​.

Advanced Project Setup with cargo-generate

For a more customized setup, cargo-generate is an invaluable tool. It allows for the creation of a new project template, particularly tailored for Rust-based NEAR contracts. To initialize a project with cargo-generate, the following commands are used:

cargo install cargo-generate --features vendored-openssl   
cargo generate --git https://github.com/near-examples/rust-status-message --name my-project
cd my-project

When manually generating a new crate with cargo new --lib <crate-name>, it is crucial to include specific configurations in the Cargo.toml file. These configurations ensure the proper setup for NEAR SDK compatibility, optimization for small code size, and safety checks on arithmetic operations:

[dependencies]  
near-sdk = "4.0.0"
[lib]
crate-type = ["cdylib"]
[profile.release]
codegen-units = 1
opt-level = "z"
lto = true
debug = false
panic = "abort"
overflow-checks = true

These configurations in Cargo.toml optimize the Rust code for efficient execution in the NEAR blockchain environment, ensuring not only performance but also adherence to safety and security standards​​.

Asynchronous Programming and State Management in Rust on NEAR

  • Handling Async/Await Patterns: In Rust, managing asynchronous operations involves mastering the async/await syntax, crucial for non-blocking I/O operations — a common scenario in DApp development.
  • Stateful Smart Contracts: When it comes to state management in smart contracts on NEAR, understanding Rust’s nuanced approach to memory allocation and data serialization/deserialization is key. Rust’s strict type system, combined with its powerful macro capabilities, allows developers to efficiently handle state changes and storage management in a blockchain environment.
  • Cross-Contract Calls and Callbacks: A deep dive into NEAR’s asynchronous cross-contract calls reveals a complex interplay of Rust’s futures and error handling mechanisms. This requires a sophisticated grasp of Rust’s concurrency model, particularly in how it interfaces with NEAR’s runtime environment and handles callback patterns.

Security Paradigms in Rust for Blockchain Applications

Developing in Rust for blockchain necessitates a comprehensive understanding of security best practices.

This includes being adept at leveraging Rust’s type safety and error handling to prevent common vulnerabilities like reentrancy attacks, integer overflows, and unauthorized access — all too common in less rigorous programming environments.

Advanced Rust Features for Optimized Smart Contracts

While Rust’s features don’t automatically prevent such logical vulnerabilities, they can contribute to making them less likely:

  • Ownership and Borrowing Model: Rust’s ownership system can help manage state more safely. By enforcing strict rules about how data is accessed and mutated, Rust can help ensure that the state is not unexpectedly altered during execution.
  • Type Safety and Explicitness: Rust’s type system and requirement for explicit handling of possible error conditions make it easier to write clear, understandable code where the programmer must consider edge cases and potential vulnerabilities.
  • Concurrency Management: Leverage Rust’s advanced concurrency model, including threads and channels, to create high-performance, scalable smart contracts that can handle complex computations and high throughput. Rust’s strong guarantees about concurrency might help in scenarios where contract calls are asynchronous, but this doesn’t directly translate to attack prevention.

Conclusion: Charting the Future with NEAR and Rust

This exploration underscores the formidable combination of NEAR Protocol and Rust in the blockchain ecosystem.

As a developer in this space, mastering these tools and concepts is not just about writing code. It’s about embracing a new paradigm in decentralized computing, where efficiency, security, and scalability are not just ideals but prerequisites.

The fusion of NEAR’s cutting-edge blockchain technology with Rust’s robust programming capabilities represents the bleeding edge of smart contract development, paving the way for a new generation of secure, efficient, and scalable DApps.

--

--