paint-brush
Blockchain ❤️'s WASM: Chapter Arbitrumby@glaze
1,298 reads
1,298 reads

Blockchain ❤️'s WASM: Chapter Arbitrum

by GlazeNovember 6th, 2023
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

Arbitrum recently launched Stylus, its WebAssembly (WASM)-based smart contract VM. This brings several benefits like expanded language support, lower costs, customizable precompilers, and interoperability with EVM. WASM is gaining popularity for its performance, compact size, portability, and language support. Other chains like Polkadot and Cosmos also use it. However, Stylus has some limitations currently. It only supports C++ and Rust, lacking JavaScript/Python support. The SDKs are still nascent. There's no local testnet or contract verification yet. Choosing the right language is crucial - a JavaScript/Python eDSL could attract more developers. Performance benchmarks show WASM can be 4-8x faster than EVM. But there's a 128KB contract size limit. EVM-WASM interoperability is quite comprehensive. Custom precompiles aren't implemented yet. Reentrancy is optional but disabled by default. Overall, WASM provides a performance boost for Arbitrum against zk-rollups. But EVM remains foundational, with WASM as an "EVM+" supplement for now.
featured image - Blockchain ❤️'s WASM: Chapter Arbitrum
Glaze HackerNoon profile picture

The recent update to Arbitrum features the Stylus VM upgrade, boasting several enhancements:


  • Expanded language support
  • Reduced costs and memory usage
  • Customizable pre-compilers
  • EVM compatibility


These improvements stem from integrating WASM, renowned for its numerous benefits within cloud-native environments. Further details on WASM's role will be covered in subsequent sections.

Pioneers

Arbitrum has introduced WASM to its chain, but it's not the inaugural platform to do so. Polkadot previously allowed the creation of WASM smart contracts. It offers two languages for this: an assembly script similar to an embedded DSL and a Rust-inspired language called ink!


Similarly, Cosmos utilizes CosmWasm for its smart contract execution. Developers can craft smart contracts using Rust here.


Before exploring the affinity blockchain has for WASM, let's review Cosmos and Polkadot's rationale for choosing WASM.


Cosmos touts WASM for these advantages:

  • Rust library compatibility
  • A broad developer community
  • Enhanced security, including reentrancy attack prevention
  • Simplified testing procedures
  • Superior performance


Polkadot's WASM runtime showcases features like:

  • Exceptional performance
  • EVM interoperability
  • Hardware and software platform independence
  • Compact size
  • Support for Rust and Assembly Script, akin to Typescript


Polkadot, Cosmos, and Arbitrum share several WASM-induced benefits. However, Arbitrum has distinctive offerings we'll discuss later, along with Cosmos specifics.

WASM

Let's delve into what WASM is and the motivations behind it.

What is WASM?

WebAssembly (WASM) is a binary instruction format. It enables code to execute at speeds comparable to native applications, specifically within web browsers. As a compilation target for languages such as C and Rust, it's optimized for speed, efficiency, and security. WASM significantly improves web performance and expands web functionalities.


WASM is closely tied to the web, as it operates within JavaScript environments like browsers. Within these environments, developers have full access to WASM APIs as well as complete Web API support. This control allows developers to fine-tune web interactions.

The Evolution of WASM

The concept of WASM revolves around the ideal of writing code once to run it anywhere.


In 2016, programs frequently introduced new features via Domain Specific Languages (DSLs). Creating a DSL involved balancing maintenance, efficiency, and safety. The industry sought a method to deploy functions across numerous servers without compromising on these aspects.


Various solutions were scrutinized, each with its own set of challenges:

  • System Virtual Machines struggled with overhead, lack of code visibility for safety, and were too abstract for high performance.
  • Containers also lacked code visibility and were similarly abstract, with significant overhead.
  • Language-level Virtual Machines necessitated frequent modifications for safety, incurred overhead from embedded VMs like V8, and were slow in adopting new languages to fit security models.
  • Instruction Set Architectures (ISAs) were tough to modify for efficient sandboxing and lacked mature implementations.


WASM emerged as a solution. Development of WASM compilers began, and by 2018, the concept of universal code compatibility across various architectures and devices was expanded. Unlike Java, the goal was not to compromise on safety.


In 2019, the component model was introduced, elevating WASM modules for cross-language interoperability. This innovation enabled, for instance, the creation of a universal HTTP library applicable across different languages, addressing complex issues innovatively.

WASM Today

WASM boasts an array of impressive features:


  • High Performance: WASM code runs efficiently and swiftly.
  • Compact Size: The binary format of WASM ensures a small footprint.
  • Portability: It allows the same bytecode to operate on any WASM-compatible runtime.
  • Language Support: WASM supports a wide range of languages, from C/C++ and Rust to Go and Swift, among others.
  • JavaScript Engine Compatibility: WASM works seamlessly within JS engines.
  • Sandboxing: A robust default sandbox restricts memory and CPU access to prevent external interference.
  • Rapid Startup: WASM modules typically boot in milliseconds.


The WASM community is actively enhancing integration and performance across different programming languages.

Stylus

Exploring the potential of WASM and its use in blockchains leads us back to the limitations of Arbitrum Stylus.

Functioning of Stylus

Here's a simplified breakdown of how Stylus operates:


  1. Developers use standard WASM compilers, like Clang or Rustc, to compile their smart contracts to WASM.
  2. The resulting WASM bytecode is then uploaded to the Arbitrum chain in a compressed state.
  3. Through the ArbWasm precompile's compileProgram method, the bytecode undergoes instrumentation for security, gas metering, and is compiled into native code tailored for the validator’s hardware. This step is crucial for enhancing performance and security.
  4. Upon invocation, the contract runs on a WASM runtime, such as Wasmer, which is significantly faster and more gas-efficient than the EVM.


The seemingly additional third step is, in fact, vital. Converting WASM code to native machine code accelerates execution speeds. Moreover, this added compilation phase helps to prevent "compile bombs."


A "compile bomb" is malicious code designed to exhaust system resources during compilation, potentially crashing or stalling the compiler. This acts as a denial-of-service attack aimed at hindering the software development process.

Concerns About Stylus

Language Support

Stylus has widened Arbitrum's developer community to include C++ and Rust. However, it has yet to encompass the most prevalent developer communities of today. It facilitates smart contract execution in browsers but does not support JavaScript and Python yet.


Programming Language Users


There are projects in the early stages attempting to bridge Python and JavaScript to WASM. But, these are not ready for widespread adoption due to the complexities with garbage collection and performance concerns.

Language Compatibility

Stylus currently supports C/C++ and Rust through its SDKs. These SDKs are compatible with the tools of the respective languages. They also allow the integration of third-party libraries, such as native cryptography. The main constraint is the gas cost associated with these libraries.


The Rust SDK is in its nascent phase, lacking some functionalities. The C SDK does not support exporting functions with ABI. Additionally, neither SDK supports the use of modifiers.


As of now, Stylus does not have a local test environment. Developers are encouraged to conduct tests within the SDKs. The testnet is the sole option for running smart contracts on Stylus. However, the testnet has not yet implemented smart contract verification.


There is ongoing work to port various ERC tokens and platforms like Uniswap V2 to Stylus.

Language Choice

Choosing between a Domain-Specific Language (DSL), an embedded DSL (eDSL), or a general programming language is challenging. Developers must weigh the benefits of working "close to the metal" for control against the ease of use offered by higher-level abstractions, which may limit flexibility.


Creating a new DSL requires time to develop its toolchains and ecosystem. An eDSL, as a subset of a general programming language, maintains the same semantics and syntax. It allows developers to use existing languages and tools, which can simplify the learning process. An eDSL also offers better interoperability with general-purpose code. For example, an eDSL for JavaScript or Python would be strategic to engage the largest developer communities.


General programming languages necessitate the use of an SDK for development. This adds layers of tooling, increases verbosity, and reduces expressiveness. It can also result in lengthy API calls and complex object operations.


Choosing the right language and crafting an eDSL could be an ideal compromise. It could draw developers from popular communities and offer user-friendly tools. Current data shows that the Ethereum community remains the largest among crypto developers. However, ecosystems like Polkadot, Cosmos, and Solana, which use Rust for smart contracts, are also attracting a significant number of developers and are experiencing rapid growth. Full-Time Developers



Total Developers


Performance

WASM has the potential to significantly enhance execution speed and reduce bundle size. Although Stylus hasn't been deployed to the mainnet, benchmarks from other networks serve as a useful reference.


These benchmarks indicate that execution times can be reduced by 4 to 8 times, and the compiled size may be halved.

WASM Execution Time


WASM contract Size


Stylus imposes a limit on contract sizes, which is about 128KB uncompressed. This constraint makes it challenging to migrate very large smart contracts from languages like Solidity to Stylus. This limitation is evident within the Stylus codebase:



// arbos/programs/programs.go

const MaxWasmSize = 128 * 1024 // Maximum WASM size allowed
const initialFreePages = 2 // Number of initial free pages
const initialPageGas = 1000 // Gas cost for an initial page
const initialPageRamp = 620674314 // Adjusts for a target size cost
const initialPageLimit = 128 // Maximum number of pages allowed
const initialInkPrice = 10000 // Ink price per EVM gas
const initialCallScalar = 8 // Scalar for call cost


It's important to note that WASM incurs some overhead for starting up and shutting down. For very lightweight operations, EVM might be more cost-effective than WASM.

EVM-WASM Interoperability

EVM and WASM use the same storage slots and state tree. Stylus achieves interoperability with EVM by implementing EVM APIs within WASM. This integration utilizes the widely-adopted Host I/O mode in WASM. Below is the complete list of EVM APIs supported in WASM, indicating comprehensive interoperability support.


read_args
write_result
storage_load_bytes32
storage_store_bytes32
call_contract
delegate_call_contract
static_call_contract
do_call
create1
create2
do_create
read_return_data
return_data_size
emit_log
account_balance
account_codehash
evm_gas_left
evm_ink_left
block_basefee
block_coinbase
block_gas_limit
block_number
block_timestamp
chainid
contract_address
msg_reentrant
msg_sender
msg_value
native_keccak256
tx_gas_price
tx_ink_price
tx_prigin
memoery_grow
console_log_text
console_log
console_tee

Custom Precompiles

Custom precompiles are an innovative concept. They have the potential to integrate advanced crypto primitives on-chain at reduced execution costs. For instance, tensor computations could be precompiled to decrease costs for on-chain machine learning. However, there is no evidence of custom precompile functionality in the current codebase. While precompiles exist for the EVM, they are not designed to be swappable.


It's likely that these features are still being developed, leveraging WASM's capabilities. This would enable EVM to call WASM-written functions, which are then compiled to machine code.

Reentrancy

In contrast to CosmWasm's actor model, which doesn't support reentrancy, Stylus’s Rust SDK includes reentrancy as an optional feature. By default, this feature is turned off. Developers have the choice to enable reentrancy in their contracts.


Activating reentrancy affects the API since developers must ensure they clear the storage cache during calls and consider other safety measures. This precaution is essential to prevent potential vulnerabilities associated with reentrant calls.


Reentrancy

Conclusion

WASM is gaining popularity in the cloud-native domain, with many blockchains adopting it for smart contract execution. Although Arbitrum isn't the pioneer in this integration, its implementation could be highly impactful. WASM isn't positioned to completely overhaul the blockchain landscape or replace EVM. However, it could boost Arbitrum's edge against the emerging zk-rollups. Arbitrum's term "EVM+" aptly describes this scenario. EVM sets the foundation for smart contract platforms, and WASM could provide an additional performance boost for Arbitrum.