diff --git a/arbitrum-docs/stylus/concepts/how-it-works.md b/arbitrum-docs/stylus/concepts/how-it-works.md new file mode 100644 index 000000000..a92a3dd2e --- /dev/null +++ b/arbitrum-docs/stylus/concepts/how-it-works.md @@ -0,0 +1,70 @@ +--- +id: how-it-works +title: 'Architecture overview' +sidebar_label: 'Architecture overview' +description: 'Learn what powers Stylus' +author: srinjoyc +SME: srinjoyc +user_story: As an Ethereum developer/project owner, I need to vet the Stylus. +content_type: concept +--- + +There are four main steps for bringing a Stylus program to life: **coding, activation, execution, and proving**. + +## Coding + +Developers can now write smart contracts in any programming language that compiles to WASM. + +:::note +Some high-level languages generate far more performant WASMs than others. +::: + +Currently, there is support for Rust, C, and C++. However, the levels of support vary. Rust has rich language support from day one, with an open-source SDK that makes writing smart contracts in Rust as easy as possible. C and C++ are supported off the bat, enabling the deployment of existing contracts in those languages on-chain with minimal modifications. + +The Stylus SDK for Rust contains the smart contract development framework and language features most developers will need to use in Stylus. The SDK also makes it possible to perform all EVM-specific functionalities that smart contract developers use. Check out the [Rust SDK Guide](https://docs.arbitrum.io/stylus/rust-sdk-guide) and the [Crate Docs](https://docs.rs/stylus-sdk/latest/stylus_sdk/index.html). + +## Activation + +Starting from a high-level language (such as Rust, C, or C++), the first compilation stage happens using the CLI provided in the Stylus SDK for Rust or any other compiler, such as Clang for C and C++. Once compiled, the WASM is posted onchain. Then, in an activation process, WASM gets lowered to a node's native machine code (such as ARM or x86). + +Activating a Stylus program requires a new precompile, ArbWasm. This precompile produces efficient binary code tailored to a node's native assembly. During this step, a series of middlewares ensure that user programs execute safely and are deterministically fraud-proven. Instrumentation includes gas metering, depth-checking, memory charging, and more to guarantee all WASM programs are safe for the chain to execute. Stylus contracts can be called only after activation. + +Gas metering is essential for certifying that computational resources are paid for. In Stylus, the unit for measuring cost is called **ink**, which is similar to Ethereum's gas but thousands of times smaller. There are two reasons why a new measurement is used: First, WASM execution is so much faster than the EVM that executing thousands of WASM opcodes could be done in the same amount of time it takes the EVM to execute one. Second, the conversion rate of ink to gas can change based on future hardware or VM improvements. For a conceptual introduction to Stylus gas and ink, see [gas and ink (Stylus)](https://docs.arbitrum.io/stylus/concepts/stylus-gas). + +## Execution + +Stylus programs execute in a fork of [Wasmer](https://wasmer.io/), the leading WebAssembly runtime, with minimal changes to optimize their codebase for blockchain-specific use cases. Wasmer executes native code much faster than Geth executes EVM bytecode, contributing to the significant gas savings that Stylus provides. + +EVM contracts continue to execute the same way they were before Stylus. When calling a contract, the difference between an EVM contract and a WASM program is visible via an [EOF](https://notes.ethereum.org/@ipsilon/evm-object-format-overview)-inspired contract header. From there, the contract executes using its corresponding runtime. Contracts written in Solidity and WASM languages can make cross-contract calls to each other, meaning a developer never has to consider which language the contract is in. Everything is interoperable. + +## Proving + +Nitro operates in two modes: a "happy case" where it compiles execution history to native code, and a "sad case" during validator disputes, where it compiles execution history to WASM for interactive fraud proofs on Ethereum. Stylus builds on Nitro's fraud-proving technology, allowing it to verify both execution history and WASM programs deployed by developers. + +Stylus is made possible by Nitro’s ability to replay and verify disputes using WASM. Validators bisect disputes until an invalid step is identified and proven on-chain through a [“one-step proof.”](/how-arbitrum-works/fraud-proofs/challenge-manager.mdx#general-bisection-protocol). This deterministic fraud-proving capability ensures the correctness of any arbitrary program compiled to WASM. The combination of WASM's and Nitro's properties enables this technological leap we call Stylus. + +For more details on Nitro’s architecture, refer to the [documentation](/how-arbitrum-works/inside-arbitrum-nitro.mdx) or the [Nitro whitepaper](https://github.com/OffchainLabs/nitro/blob/master/docs/Nitro-whitepaper.pdf). + +## Why does this matter? + +Stylus innovates on many levels, with the key ones described here: + +### One chain, many languages + +There are roughly 20k Solidity developers, compared to 3 million Rust developers or 12 million C developers [[1](https://slashdatahq.medium.com/state-of-the-developer-nation-23rd-edition-the-fall-of-web-frameworks-coding-languages-711525e3df3a)]. Developers can now use their preferred programming language, which is interoperable on any Arbitrum chain with Stylus. By onboarding the next million developers, scaling to the next billion users becomes possible. + +### A better EVM + +Stylus' MultiVM brings the best of both worlds. Developers still get all of the benefits of the EVM, including the ecosystem and liquidity, while getting efficiency improvements and access to existing libraries in Rust, C, and C++, all without changing anything about how the EVM works. EVM equivalence is no longer the ceiling; it's the floor. + +### Cheaper execution + +Stylus is a more efficient execution environment than the EVM, leading directly to gas savings for complex smart contracts. Computation and memory can be significantly cheaper. Deploying cryptography libraries can be done permissionlessly as custom application layer precompiles. Use cases that are impractical in the EVM are now possible in Stylus. + +### Opt-in reentrancy + +Stylus doesn't just improve on cost and speed. WASM programs are also safer. Reentrancy is a common vulnerability developers can only attempt to mitigate in Solidity. Stylus provides cheap reentrancy detection, and using the Rust SDK, reentrancy is disabled by default unless intentionally overridden. + +### Fully interoperable + +Solidity programs and WASM programs are completely composable. If working in Solidity, a developer can call a Rust program or rely on another dependency in a different language. If working in Rust, all Solidity functionalities are accessible out of the box. diff --git a/arbitrum-docs/stylus/concepts/stylus-gas.md b/arbitrum-docs/stylus/concepts/stylus-gas.md index 6a4cbdcaf..975a87a61 100644 --- a/arbitrum-docs/stylus/concepts/stylus-gas.md +++ b/arbitrum-docs/stylus/concepts/stylus-gas.md @@ -1,5 +1,5 @@ --- -title: 'Gas and ink in Stylus' +title: 'Gas metering' description: 'A conceptual overview of gas and ink, the primitives that Stylus uses to measure the cost of WASM activation, compute, memory, and storage.' author: rachel-bousfield sme: rachel-bousfield diff --git a/arbitrum-docs/stylus/recommended-libraries.md b/arbitrum-docs/stylus/recommended-libraries.md index 3ebe933dc..11f5485db 100644 --- a/arbitrum-docs/stylus/recommended-libraries.md +++ b/arbitrum-docs/stylus/recommended-libraries.md @@ -1,7 +1,7 @@ --- id: recommended-libraries title: Recommended Libraries -sidebar_label: Recommended libraries +sidebar_label: Use Rust Crates --- # Recommended libraries diff --git a/arbitrum-docs/stylus/reference/overview.md b/arbitrum-docs/stylus/reference/overview.md index 8152031b1..39380d069 100644 --- a/arbitrum-docs/stylus/reference/overview.md +++ b/arbitrum-docs/stylus/reference/overview.md @@ -13,6 +13,6 @@ The Stylus Rust SDK is built on top of [Alloy](https://www.paradigm.xyz/2023/06/ The Stylus Rust SDK has been audited in August 2024 at [commit #62bd831](https://github.com/OffchainLabs/stylus-sdk-rs/tree/62bd8318c7f3ab5be954cbc264f85bf2ba3f4b06) by Open Zeppelin which can be viewed [on our audits page](audit-reports.mdx). -This section contains a set of pages that describe a certain aspect of the Stylus Rust SDK, like how to work with [variables](/stylus-by-example/variables.mdx), or what ways are there to [send ether](/stylus-by-example/sending_ether.mdx). Additionally, there's also a page that compiles a set of [advanced features](/stylus/reference/rust-sdk-guide.md) that the Stylus Rust SDK provides. +This section contains a set of pages that describe a certain aspect of the Stylus Rust SDK, like how to work with [variables](/stylus-by-example/basic_examples/variables.mdx), or what ways are there to [send ether](/stylus-by-example/basic_examples/sending_ether.mdx). Additionally, there's also a page that compiles a set of [advanced features](/stylus/reference/rust-sdk-guide.md) that the Stylus Rust SDK provides. Finally, there's also a [Stylus by example](https://stylus-by-example.org) portal available that provides most of the information included in this section, as well as many different example contracts. diff --git a/arbitrum-docs/stylus/reference/rust-sdk-guide.md b/arbitrum-docs/stylus/reference/rust-sdk-guide.md index 301acb4ad..b49961bef 100644 --- a/arbitrum-docs/stylus/reference/rust-sdk-guide.md +++ b/arbitrum-docs/stylus/reference/rust-sdk-guide.md @@ -19,7 +19,7 @@ Many of the affordances use macros. Though this section details what each does, ## Storage -This section provides extra information about how the Stylus Rust SDK handles storage. You can find more information and basic examples in [Variables](/stylus-by-example/variables.mdx). +This section provides extra information about how the Stylus Rust SDK handles storage. You can find more information and basic examples in [Variables](/stylus-by-example/basic_examples/variables.mdx). Rust smart contracts may use state that persists across transactions. There’s two primary ways to define storage, depending on if you want to use Rust or Solidity definitions. Both are equivalent, and are up to the developer depending on their needs. @@ -226,7 +226,7 @@ The above allows consumers of `Erc20` to choose immutable constants via speciali ## Functions -This section provides extra information about how the Stylus Rust SDK handles functions. You can find more information and basic examples in [Functions](/stylus-by-example/function.mdx), [Bytes in, bytes out programming](/stylus-by-example/bytes_in_bytes_out.mdx), [Inheritance](/stylus-by-example/inheritance.mdx) and [Sending ether](/stylus-by-example/sending_ether.mdx). +This section provides extra information about how the Stylus Rust SDK handles functions. You can find more information and basic examples in [Functions](/stylus-by-example/basic_examples/function.mdx), [Bytes in, bytes out programming](/stylus-by-example/basic_examples/bytes_in_bytes_out.mdx), [Inheritance](/stylus-by-example/basic_examples/inheritance.mdx) and [Sending ether](/stylus-by-example/basic_examples/sending_ether.mdx). ### Pure, View, and Write functions diff --git a/arbitrum-docs/stylus/stylus-gentle-introduction.md b/arbitrum-docs/stylus/stylus-gentle-introduction.md index 5801c448e..8a363290b 100644 --- a/arbitrum-docs/stylus/stylus-gentle-introduction.md +++ b/arbitrum-docs/stylus/stylus-gentle-introduction.md @@ -9,119 +9,45 @@ sidebar_position: 1 # A gentle introduction: Stylus -This introduction is for developers who want to build on Arbitrum using popular programming languages like Rust. This capability is made possible by Stylus, a new way to write EVM-compatible smart contracts using your favorite programming languages. - ### In a nutshell: -- Stylus lets you write smart contracts in programming languages that compile to WASM, such as **Rust, C, C++, and many others**. -- Rich language support already exists for Rust: you can use the Stylus SDK and CLI tool to start building today. -- Stylus smart contracts benefit from **Arbitrum's EVM equivalence** thanks to a second, coequal WASM virtual machine. -- Solidity contracts and Stylus contracts are fully interoperable. In Solidity, you can call a Rust program and vice versa. -- Stylus contracts are significantly faster and have lower gas fees due to the superior efficiency of WASM programs. -- Stylus makes it viable to consume RAM on the blockchain because it can greatly optimize memory use, enabling new use cases. +- Stylus lets you write smart contracts in programming languages that compile to WASM, such as **Rust, C, C++, and many others**, allowing you to tap into their ecosystem of libraries and tools. Rich language and tooling support already exist for Rust. You can try the SDK and CLI with the [quickstart](https://docs.arbitrum.io/stylus/stylus-quickstart). +- Solidity contracts and Stylus contracts are fully interoperable. In Solidity, you can call a Rust program and vice versa, thanks to a second, coequal WASM virtual machine. +- Stylus contracts offer significantly faster execution and lower gas fees for memory and compute-intensive operations, thanks to the superior efficiency of WASM programs. ### What's Stylus? -Stylus is an upgrade to Arbitrum Nitro, the tech stack powering Arbitrum One, Arbitrum Nova, and Arbitrum Orbit chains. This upgrade adds a second, coequal virtual machine to the EVM, where EVM contracts continue to behave exactly as they would in Ethereum. We call this paradigm **MultiVM** since **everything is entirely additive.** +Stylus is an upgrade to Arbitrum Nitro [(ArbOS 32)](https://docs.arbitrum.io/run-arbitrum-node/arbos-releases/arbos32), the tech stack powering Arbitrum One, Arbitrum Nova, and Arbitrum Orbit chains. This upgrade adds a second, coequal virtual machine to the EVM, where EVM contracts continue to behave exactly as they would in Ethereum. We call this paradigm **MultiVM** since **everything is entirely additive.** ![Stylus gives you MultiVM](./assets/stylus-multivm.jpg) This second virtual machine executes WebAssembly (WASM) rather than EVM bytecode. WASM is a modern binary format popularized by its use in major web standards, browsers, and companies to speed up computation. WASM is built to be fast, portable, and human-readable. It has sandboxed execution environments for security and simplicity. Working with WASM is nothing new for Arbitrum chains. Ever since the [Nitro upgrade](https://medium.com/offchainlabs/arbitrum-nitro-one-small-step-for-l2-one-giant-leap-for-ethereum-bc9108047450), WASM has been a fundamental component of Arbitrum's fully functioning fraud proofs. -With a WASM VM, any programming language that can compile to WASM is within Stylus's scope. While many popular programming languages can be compiled into WASM, some compilers are more suitable for smart contract development than others, like Rust, C, and C++. Other languages like Go, Sway, Move, and Cairo can also be supported. Languages that include their own runtimes, like Python and Javascript, are more complex for Stylus to support, although not impossible. Third-party contribution in the form of libraries for new and existing languages is welcomed! - -Compared to using Solidity, WASM programs are much more efficient. There are many reasons for this, including the decades of compiler development for Rust and C. WASM also has a faster runtime than the EVM, resulting in faster execution. - -### How is this possible? - -Stylus is only possible because of Arbitrum Nitro's unique fraud-proving technology. When there's a dispute on an Arbitrum network, Nitro replays the execution of the chain **in WASM.** Honest Arbitrum validators will then bisect what is being disputed until a single invalid step is identified and checked on-chain via a [“one-step proof.”](/how-arbitrum-works/fraud-proofs/challenge-manager.mdx#general-bisection-protocol) - -Nitro's fraud-proving enables it to prove **arbitrary WASM** in a deterministic way. - -Because any code logic can be proven with WASM, the correctness of **any program** compiling to WASM can also be proven. The combination of WASM's and Nitro's properties enables this technological leap we call Stylus. - -For a detailed overview of Nitro's technical architecture, see the [documentation](/how-arbitrum-works/inside-arbitrum-nitro.mdx) or the [Nitro whitepaper](https://github.com/OffchainLabs/nitro/blob/master/docs/Nitro-whitepaper.pdf). - -### Why does this matter? - -Stylus innovates on many levels, with the key ones described here: - -#### One chain, many languages - -There are estimated to be roughly 20k Solidity developers, compared to 3 million Rust developers or 12 million C developers [[1](https://www.slashdata.co/blog/state-of-the-developer-nation-23rd-edition-the-fall-of-web-frameworks-coding-languages-blockchain-and-more)]. Developers are now free to use their preferred programming language, all interoperable on any Arbitrum chain with Stylus. By onboarding the next million developers, scaling to the next billion users becomes possible. - -#### A better EVM - -Stylus' MultiVM brings the best of both worlds. Developers still get all of the benefits of the EVM, including the ecosystem and liquidity, while getting efficiency improvements and access to existing libraries in Rust, C, and C++, all without changing anything about how the EVM works. EVM equivalence is no longer the ceiling; it's the floor. - -#### Cheaper execution - -Stylus is a more efficient execution environment than the EVM, leading directly to gas savings for complex smart contracts. Computation and memory can be significantly cheaper. Cryptography libraries can be permissionlessly deployed as custom application layer precompiles. Use cases that are impractical in the EVM are now possible in Stylus. - -#### Opt-in reentrancy - -Stylus doesn't just improve on cost and speed. WASM programs are also safer. Reentrancy is a common vulnerability that developers can only attempt to mitigate in Solidity. Stylus provides cheap reentrancy detection, and using the Rust SDK, reentrancy is disabled by default unless intentionally overridden. - -#### Fully interoperable - -Solidity programs and WASM programs are completely composable. If working in Solidity, a developer can call a Rust program or rely on another dependency in a different language. If working in Rust, all Solidity functionalities are accessible out of the box. - -### How does it work? - -There are four main steps for bringing a Stylus contract to life: coding, activation, execution, and proving. - -#### Coding - -Developers can now write smart contracts in any programming language that compiles to WASM. Note that some high-level languages generate far more performant WASMs than others. - -Initially, there will be support for Rust, C, and C++. However, the levels of support will differ at first. Rust has rich language support from day one, with an open-source SDK that makes writing smart contracts in Rust as easy as possible. C and C++ are supported off the bat, too, enabling the deployment of existing contracts in those languages on-chain with minimal modifications. - -The Stylus SDK for Rust contains the smart contract development framework and language features most developers will need to use in Stylus. The SDK also makes it possible to perform all of the EVM-specific functionalities that smart contract developers are used to. Check out the [Rust SDK Guide](https://docs.arbitrum.io/stylus/rust-sdk-guide) and the [Crate Docs](https://docs.rs/stylus-sdk/latest/stylus_sdk/index.html). - -#### Activation - -Stylus contracts are compiled to WASM and then lowered to assembly. Starting from a high-level language (such as Rust, C, or C++), the first compilation stage happens either using the CLI provided in the Stylus SDK for Rust or any other compiler, such as Clang for C and C++. Once compiled, the WASM is posted onchain. Then, in a process called activation, WASM gets lowered to a node's native machine code (such as ARM or x86). - -Activating a Stylus contract requires a new precompile, ArbWasm. This precompile produces efficient binary code tailored to a node's native assembly. During this step, a series of middlewares ensure user programs can be safely executed and deterministically fraud-proven. Instrumentation includes gas metering, depth-checking, memory charging, and more to guarantee all WASM programs are safe for the chain to execute. Stylus contracts can be called only after they've been activated. - -Gas metering is essential for certifying that computational resources are paid for. In Stylus, the unit for measuring cost is called “ink,” similar to Ethereum's gas but thousands of times smaller. There are two reasons why a new measurement is used: First, WASM execution is so much faster than the EVM that thousands of WASM opcodes could be executed in the same time it takes the EVM to execute one. Second, the conversion rate of ink to gas can change based on future hardware or VM improvements. For a conceptual introduction to Stylus gas and ink, see [gas and ink (Stylus)](https://docs.arbitrum.io/stylus/concepts/stylus-gas). - -#### Execution - -Stylus contracts are executed in a fork of [Wasmer](https://wasmer.io/), the leading WebAssembly runtime, with minimal changes to optimize their codebase for blockchain-specific use cases. Wasmer executes native code much faster than Geth executes EVM bytecode, contributing to the significant gas savings that Stylus provides. - -EVM contracts continue to execute the same way they did before Stylus. When a contract is called, the difference between an EVM contract and a WASM program can be seen via an [EOF](https://notes.ethereum.org/@ipsilon/evm-object-format-overview)-inspired contract header. From there, the contract is executed using its corresponding runtime. Contracts written in Solidity and WASM languages can make cross-contract calls to each other, meaning a developer never has to consider what language the contract was written in. Everything is interoperable. - -#### Proving - -Nitro has a happy case and a sad case. Most of the time, it's in a happy case, compiling execution history to native code. In the sad case of a dispute between validators, Nitro compiles execution history to WASM to conduct interactive fraud proofs on Ethereum. Stylus is a natural extension to Nitro's fraud-proving technology, utilizing it to not only bisect execution history but also any WASM programs deployed by developers. - -### New use cases - -It's impossible to list all of the use cases Stylus enables, think about the properties of all WASM compatible languages! - -That said, here are some new features that are particularly exciting: - -- Generative art libraries that consume a bunch of RAM -- Bringing existing games written in C++ on-chain -- Compute-heavy AI models -- Projects using alternative signature schemes, such as `secp256r1`, via custom precompiles -- Optimization of Solidity-based projects for speed and cost - -We leave it up to you to ideate blockchain projects that were not technically feasible until now. +With a WASM VM, any programming language compilable to WASM is within Stylus's scope. While many popular programming languages can compile into WASM, some compilers are more suitable for smart contract development than others, like Rust, C, and C++. Other languages like Go, Sway, Move, and Cairo are also supported. Languages that include their own runtimes, like Python and Javascript, are more complex for Stylus to support, although not impossible. Compared to Solidity, WASM programs are much more efficient for memory-intensive applications. There are many reasons for this, including the decades of compiler development for Rust and C. WASM also has a faster runtime than the EVM, resulting in faster execution. Third-party [contribution](#contributing) in the form of libraries for new and existing languages is welcomed! -While many developers will be drawn to new use cases, rebuilding existing applications in Stylus will also open the door to innovation and optimization. dApps have never been faster, cheaper, or safer. +### Use Cases -Stylus is open to all. Much thought has been given to creating the best programming experience possible. However, the work continues. Feedback gained from developers will help drive Stylus to the next level, improving tooling, documentation, and language features. Becoming an early adopter of Stylus is the best way to familiarize oneself with its opportunities. +While many developers will be drawn to new use cases, rebuilding existing applications in Stylus will also open the door to innovation and optimization. dApps have never been faster, cheaper, or safer. Stylus can integrate easily into existing Solidity projects by calling a Stylus contract to optimize specific parts of your dApp or building the entire dApp with Stylus. It's impossible to list all of the use cases Stylus enables; think about the properties of all WASM-compatible languages! That said, here are some particularly exciting ideas: -If you're a developer interested in Stylus, visit the [quickstart](https://docs.arbitrum.io/stylus/stylus-quickstart), join the [Discord channel](https://discord.com/invite/arbitrum), and start building! +- Efficient On-Chain Verification with ZK-Proofs: Enable cost-effective onchain verification + using zero-knowledge proving systems for privacy, interoperability, and more (see [case + study](https://blog.arbitrum.io/renegade-stylus-case-study/)). +- Advanced DeFi Instruments: Power complex financial instruments and processes like custom + pricing curves for AMMs, synthetic assets, options, and futures with onchain computation via + extending current protocols (ie. Uniswap V4 hooks) or building your own. +- High-Performance On-Chain Logic: Support memory and compute-intensive applications like + onchain games and generative art either by writing all of the application in Stylus or enhance + performance of existing Solidity contracts by optimizing specific parts. +- **Endless Possibilities**: Enable innovative use cases such as generative art, compute-heavy + AI models, on-chain games, and projects utilizing advanced cryptography, unlocking the full potential + of resource-intensive applications on-chain. -### Wen mainnet? +### Getting Started -Stylus is now live on mainnet. +1. Utilize our [quickstart](https://docs.arbitrum.io/stylus/stylus-quickstart), [Rust SDK](https://docs.arbitrum.io/stylus/reference/overview), to help you start building. +2. Join our Stylus Developer [Telegram](https://t.me/arbitrum_stylus) group and [Arbitrum Discord](https://discord.gg/arbitrum) for support as well as the official Arbitrum ([@Arbitrum](https://twitter.com/arbitrum)) and Arbitrum Developers ([@ArbitrumDevs](https://twitter.com/ArbitrumDevs)) X accounts for announcements. +3. Check out the [Awesome Stylus](https://github.com/OffchainLabs/awesome-stylus) repository for various community contributed Stylus projects and tools. If you build something useful, we'd be happy to add it there. -To keep up with the latest announcements and updates about Stylus: +### Contributing -- Subscribe to the [Arbitrum Node Upgrade Announcement channel on Telegram](https://t.me/arbitrumnodeupgrade) -- Join both the `#dev-announcements` and `#node-runners` Discord channels in the [Arbitrum Discord server](https://discord.gg/arbitrum) -- Follow the official Arbitrum ([`@Arbitrum`](https://twitter.com/arbitrum)) and Arbitrum Developers ([`@ArbitrumDevs`](https://twitter.com/ArbitrumDevs)) X accounts, formerly Twitter. +Stylus is open to everyone, with a strong focus on delivering an exceptional programming experience. But the journey doesn't end here—developer feedback is crucial to enhancing Stylus’s tooling, documentation, and language features. By becoming an early adopter, you can explore its full potential and help shape its future. We’re actively seeking builders eager to push the limits of the EVM or develop tooling for Stylus. With over [$5M in grant funding available through the Stylus Sprint](https://blog.arbitrum.io/stylus-sprint/), now’s the time to get involved! diff --git a/arbitrum-docs/stylus/stylus-quickstart.mdx b/arbitrum-docs/stylus/stylus-quickstart.mdx index cb4605ee8..c3f103d98 100644 --- a/arbitrum-docs/stylus/stylus-quickstart.mdx +++ b/arbitrum-docs/stylus/stylus-quickstart.mdx @@ -172,7 +172,8 @@ Compressed WASM size: 3 KB Program succeeded Stylus onchain activation checks with Stylus version: 1 ``` -Note that running `cargo stylus check` may take a few minutes, especially if you're verifying a contract for the first time. +Note that running `cargo stylus check` may take a few minutes, especially if you're verifying a contract for the first time +. See `cargo stylus check --help` for more options. diff --git a/arbitrum-docs/stylus/using-stylus-cli.mdx b/arbitrum-docs/stylus/using-stylus-cli.mdx new file mode 100644 index 000000000..e7740a701 --- /dev/null +++ b/arbitrum-docs/stylus/using-stylus-cli.mdx @@ -0,0 +1,130 @@ +--- +id: using-stylus-cli +title: 'Using Stylus CLI' +description: 'Get started with Stylus CLI, a Rust toolkit for developing Stylus contracts' +author: 'anegg0' +sme: 'anegg0' +sidebar_position: 2 +target_audience: Developers writing Stylus contracts in Rust using Stylus +--- + +This guide will get you started using [cargo stylus](https://github.com/OffchainLabs/cargo-stylus), a CLI toolkit to help developers manage, compile, deploy, and optimize their Stylus contracts efficiently. + +This overview will help you discover and learn how to uses cargo stylus tools. + +### Installing cargo stylus + +Cargo stylus is a plugin to the standard cargo tool for developing Rust programs. + +#### Prerequisites + +
+Rust toolchain + +Follow the instructions on [Rust Lang's installation page](https://www.rust-lang.org/tools/install) to install a complete Rust toolchain (v1.81 or older; v1.82 is currently not supported) on your system. After installation, ensure you can access the programs `rustup`, `rustc`, and `cargo` from your preferred terminal application. + +
+ +
+Docker + +We will use the testnet, and some `cargo stylus` commands will require Docker to operate. + +You can download Docker from [Docker's website](https://www.docker.com/products/docker-desktop). + +
+ +
+Foundry's Cast + +[Foundry's Cast](https://book.getfoundry.sh/cast/) is a command-line tool for interacting with your EVM contracts. + +
+ +
+Nitro devnode + +Stylus is available on Arbitrum Sepolia, but we'll use Nitro devnode, which has a pre-funded wallet, saving us the effort of wallet provisioning or running out of tokens to send transactions. + +```shell title="Install your devnode" +git clone https://github.com/OffchainLabs/nitro-devnode.git +cd nitro-devnode +``` + +```shell title="Launch your devnode" +./run-dev-node.sh +``` + +
+ +#### Installation + +In your terminal, run: + +```shell +cargo install --force cargo-stylus +``` + +Add WASM ([WebAssembly](https://webassembly.org/)) as a build target for the specific Rust toolchain you are using. The below example sets your default Rust toolchain to 1.80 as well as adding the WASM build target: + +```shell +rustup default 1.80 +rustup target add wasm32-unknown-unknown --toolchain 1.80 +``` + +You can verify the cargo stylus installation by running `cargo stylus -V` in your terminal, returning something like:`stylus 0.5.6` + +### Using cargo stylus + +#### Cargo Stylus Commands Reference + +| Command | Description | Arguments | Options | Example Usage | +| ------------ | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `new` | Create a new Stylus project | • `name`: Project name (required) | • `--minimal`: Create a minimal contract | `cargo stylus new ` | +| `init` | Initialize a Stylus project in current directory | | • `--minimal`: Create a minimal contract | `cargo stylus init --minimal` | +| `export-abi` | Export a Solidity ABI | | • `--output`: Output file (defaults to stdout)
• `--json`: Write JSON ABI using `solc` | `cargo stylus export-abi --json` | +| `activate` | Activate an already deployed contract | • `--address`: Contract address to activate | • `--data-fee-bump-percent`: Percent to bump estimated fee (default 20%)
• `--estimate-gas`: Only estimate gas without sending transaction | `cargo stylus activate --address ` | +| `cache` | Cache contract using Stylus CacheManager | • `bid`: Place bid on contract
• `status`: Check contract status
• `suggest-bid`: Get suggested minimum bid | | `cargo stylus cache bid --address ` | +| `check` | Check a contract | | • `--wasm-file`: WASM file to check
• `--contract-address`: Deployment address | | +| `deploy` | Deploy a contract | • `--contract-address `: Where to deploy and activate the contract (defaults to a random address) | • `--estimate-gas`: Only perform estimation
• `--no-verify`: Skip reproducible container
• `--cargo-stylus-version`: Version for Docker image
• `--source-files-for-project-hash `: Path to source files to include in the project hash
• `--max-fee-per-gas-gwei `: Optional max fee per gas in gwei units
• `--wasm-file `: The WASM file to check (defaults to any found in the current directory) | `cargo stylus deploy --endpoint='http://localhost:8547' --private-key="" --estimate-gas` | +| `verify` | Verify contract deployment | • `--deployment-tx`: Hash of deployment transaction | • `--no-verify`: Skip reproducible container
• `--cargo-stylus-version`: Version for Docker image | | +| `cgen` | Generate C code bindings | • `--input`: Input file path
• `--out_dir`: Output directory path | | | +| `replay` | Replay transaction in GDB | • `-t, --tx `: Transaction to replay | • `-p, --project `: Project path (default: `.`)
• `-u, --use-native-tracer`: Use the native tracer instead of the JavaScript one (may not be available in the node)
• `-s, --stable-rust`: Use stable Rust (note that nightly is needed to expand macros) | `cargo stylus replay --tx ` | +| `trace` | Trace a transaction | • `--tx`: Transaction hash | • `--endpoint`: RPC endpoint
• `--project`: Project path
• `--use-native-tracer`: Use native tracer | | + +##### Common options + +These options are available across multiple commands: + +| Option | Description | +| ------------------------------- | ------------------------------------------------------ | +| --endpoint | Arbitrum RPC endpoint (default: http://localhost:8547) | +| --verbose | Print debug info | +| --source-files-for-project-hash | Paths to source files for project hash | +| --max-fee-per-gas-gwei | Optional max fee per gas in gwei | + +##### Authentication options + +Available for commands involving transactions: + +| Option | Description | +| ------------------------ | ---------------------------------------------------- | +| --private-key-path | Path to file containing hex-encoded private key | +| --private-key | Private key as hex string (exposes to shell history) | +| --keystore-path | Path to Ethereum wallet keystore file | +| --keystore-password-path | Keystore password file path | + +#### How-tos + +| Topic | Description | +| -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | +| [Learn how to optimize WASM binaries](https://docs.arbitrum.io/stylus/how-tos/optimizing-binaries) | The `cargo-stylus` tool allows you to optimize WebAssembly (WASM) binaries, ensuring that your contracts are as efficient as possible. | +| [Debug Stylus transactions](https://docs.arbitrum.io/stylus/how-tos/debug-stylus-transactions) | A guide to debugging transactions, helping you identify and fix issues. Gain insights into your Stylus contracts by debugging transactions. | +| [Verify contracts](https://docs.arbitrum.io/stylus/how-tos/verify-contracts) | Ensure that your Stylus contracts are correctly verified. Step-by-step instructions on how to verify your contracts using `cargo-stylus`. | +| [Run a Stylus dev node](https://docs.arbitrum.io/run-arbitrum-node/run-local-dev-node) | Learn how to run a local Arbitrum dev node to test your Stylus contracts. | + +#### Additional resources + +#### [Troubleshooting](https://docs.arbitrum.io/stylus/troubleshooting-building-stylus): solve the most common issues. + +#### [cargo-stylus repository](https://github.com/OffchainLabs/stylus): consult cargo stylus' source code. diff --git a/website/sidebars.js b/website/sidebars.js index 63255560d..2769830ac 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -1,7 +1,8 @@ // @ts-check const sdkDocsSidebar = require('../arbitrum-docs/sdk/sidebar.js'); -const stylusByExampleDocsSidebar = require('../arbitrum-docs/stylus-by-example/sidebar.js'); +const stylusByExampleDocsSidebarSDK = require('../arbitrum-docs/stylus-by-example/basic_examples/sidebar.js'); +const stylusByExampleDocsSidebarExamples = require('../arbitrum-docs/stylus-by-example/applications/sidebar.js'); /** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ const sidebars = { @@ -490,7 +491,7 @@ const sidebars = { }, { type: 'category', - label: 'Write Stylus contracts', + label: 'Write Stylus Contracts', collapsed: true, link: { type: 'doc', @@ -505,21 +506,11 @@ const sidebars = { { type: 'doc', id: 'stylus/stylus-quickstart', - label: 'Quickstart (Rust)', - }, - { - type: 'doc', - id: 'for-devs/dev-tools-and-resources/chain-info', - label: 'Chain info', - }, - { - type: 'doc', - label: 'Arbiscan contract verification', - id: 'stylus/how-tos/verifying-contracts-arbiscan', + label: 'Quickstart', }, { type: 'category', - label: 'Stylus Rust SDK', + label: 'Rust SDK', collapsed: true, items: [ { @@ -527,120 +518,127 @@ const sidebars = { id: 'stylus/reference/overview', label: 'Overview', }, - ...stylusByExampleDocsSidebar, - { - type: 'doc', - id: 'stylus/recommended-libraries', - label: 'Recommended libraries', - }, + ...stylusByExampleDocsSidebarSDK, { type: 'doc', id: 'stylus/reference/rust-sdk-guide', label: 'Advanced features', }, - { - type: 'link', - label: 'Rust crate docs', - href: 'https://docs.rs/stylus-sdk/latest/stylus_sdk/index.html', - }, - { - type: 'link', - label: 'Stylus by example', - href: 'https://stylus-by-example.org/', - }, ], }, { type: 'category', - label: 'Gas, ink and caching', + label: 'Rust CLI', collapsed: true, items: [ { type: 'doc', + id: 'stylus/using-stylus-cli', label: 'Overview', - id: 'stylus/concepts/stylus-gas', }, { type: 'doc', - id: 'stylus/reference/opcode-hostio-pricing', - label: 'Gas and ink costs', + id: 'stylus/how-tos/debugging-stylus-tx', + label: 'Debug transactions', + }, + { + type: 'doc', + id: 'stylus/how-tos/verifying-contracts', + label: 'Verify contracts', }, { type: 'doc', id: 'stylus/concepts/stylus-cache-manager', - label: 'Caching strategy', + label: 'Cache contracts', }, - ], - }, - { - type: 'category', - label: 'CLI tools (cargo-stylus)', - collapsed: true, - items: [ { type: 'doc', - label: 'Overview', - id: 'stylus/cli-tools-overview', + id: 'stylus/how-tos/verifying-contracts-arbiscan', + label: 'Verify on Arbiscan', }, { type: 'doc', - label: 'Optimize WASM binaries', id: 'stylus/how-tos/optimizing-binaries', + label: 'Optimize WASM binaries', }, + ], + }, + { + type: 'html', + value: + 'Run a local dev node', + }, + { + type: 'category', + label: 'Concepts', + collapsed: true, + items: [ { type: 'doc', - label: 'Debug Stylus transactions', - id: 'stylus/how-tos/debugging-stylus-tx', + id: 'stylus/concepts/how-it-works', + label: 'Architecture overview', }, { type: 'doc', - label: 'Verify Stylus contracts', - id: 'stylus/how-tos/verifying-contracts', + id: 'stylus/concepts/stylus-gas', + label: 'Gas metering', }, + ], + }, + { + type: 'category', + label: 'Examples', + collapsed: true, + items: [ + ...stylusByExampleDocsSidebarExamples, { type: 'link', - label: 'cargo-stylus repository', - href: 'https://github.com/OffchainLabs/cargo-stylus', + label: 'Awesome Stylus', + href: 'https://docs.rs/stylus-sdk/latest/stylus_sdk/index.html', }, ], }, - { - type: 'html', - value: - 'Run a Stylus dev node', - // q: why use an anchor html tag here?/node-running/how-tos/running-an-stylus-node - // a: see note at end of file - }, { type: 'category', - label: 'Other supported languages', + label: 'Reference', collapsed: true, - link: { - type: 'doc', - id: 'stylus/reference/other-language-frameworks', - }, items: [ + { + type: 'html', + value: + 'Chain Info', + }, { type: 'doc', - label: 'Add a new smart contract language', - id: 'stylus/how-tos/adding-support-for-new-languages', + id: 'stylus/reference/opcode-hostio-pricing', + label: 'Gas & Ink Pricing', + }, + { + type: 'link', + label: 'Cargo Stylus CLI GitHub', + href: 'https://github.com/OffchainLabs/cargo-stylus', + }, + { + type: 'link', + label: 'Rust SDK Crate', + href: 'https://docs.rs/stylus-sdk/latest/stylus_sdk/index.html', + }, + { + type: 'link', + label: 'Source Code Repository', + href: 'https://github.com/OffchainLabs/stylus', }, ], }, { type: 'doc', - label: 'Troubleshooting', - id: 'stylus/troubleshooting-building-stylus', - }, - { - type: 'link', - label: 'Source code repository', - href: 'https://github.com/OffchainLabs/stylus', + id: 'stylus/how-tos/adding-support-for-new-languages', + label: 'Using other languages', }, { type: 'doc', - label: 'Public preview', - id: 'stylus/concepts/public-preview-expectations', + id: 'stylus/troubleshooting-building-stylus', + label: 'Troubleshooting', }, ], }, diff --git a/website/src/scripts/stylusByExampleDocsHandler.ts b/website/src/scripts/stylusByExampleDocsHandler.ts index c039d46ae..eea9760a7 100644 --- a/website/src/scripts/stylusByExampleDocsHandler.ts +++ b/website/src/scripts/stylusByExampleDocsHandler.ts @@ -21,28 +21,59 @@ const allowList = [ 'bytes_in_bytes_out', ]; +const appsAllowList = ['erc20', 'erc721', 'vending_machine', 'multi_call']; + function load(app) { const outputDir = path.join(app.options.getValue('out'), '../../stylus-by-example'); - const sourceDir = path.join(outputDir, '../../stylus-by-example/src/app/basic_examples'); + const basicExamplesOutputDir = path.join(outputDir, 'basic_examples'); + const applicationsOutputDir = path.join(outputDir, 'applications'); + const sourceDirBasicExamples = path.join( + outputDir, + '../../stylus-by-example/src/app/basic_examples', + ); + const sourceDirApplications = path.join( + outputDir, + '../../stylus-by-example/src/app/applications', + ); app.renderer.on(RendererEvent.START, async () => { cleanDirectory(outputDir); }); app.renderer.on(RendererEvent.END, async () => { - copyFiles(sourceDir, outputDir); + // Copy basic examples into their directory + copyFiles(sourceDirBasicExamples, basicExamplesOutputDir, allowList); + + // Generate sidebar for basic examples + const basicExamplesSidebarItems = generateSidebar(basicExamplesOutputDir, '/basic_examples'); + const basicExamplesSidebarConfig = { items: basicExamplesSidebarItems }; + const basicExamplesSidebarPath = path.join(basicExamplesOutputDir, 'sidebar.js'); + + fs.writeFileSync( + basicExamplesSidebarPath, + `// @ts-check\n/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */\nconst sidebar = ${JSON.stringify( + basicExamplesSidebarConfig, + null, + 2, + )};\nmodule.exports = sidebar.items;`, + 'utf8', + ); + + // Copy applications into their directory + copyFiles(sourceDirApplications, applicationsOutputDir, appsAllowList); - const sidebarItems = generateSidebar(outputDir); - const sidebarConfig = { items: sidebarItems }; - const sidebarPath = path.join(outputDir, 'sidebar.js'); + // Generate sidebar for applications + const applicationsSidebarItems = generateSidebar(applicationsOutputDir, '/applications'); + const applicationsSidebarConfig = { items: applicationsSidebarItems }; + const applicationsSidebarPath = path.join(applicationsOutputDir, 'sidebar.js'); fs.writeFileSync( - sidebarPath, - `// @ts-check\n/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */\nconst typedocSidebar = ${JSON.stringify( - sidebarConfig, + applicationsSidebarPath, + `// @ts-check\n/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */\nconst sidebar = ${JSON.stringify( + applicationsSidebarConfig, null, 2, - )};\nmodule.exports = typedocSidebar.items;`, + )};\nmodule.exports = sidebar.items;`, 'utf8', ); }); @@ -62,7 +93,7 @@ function cleanDirectory(directory) { } } -function copyFiles(source, target) { +function copyFiles(source, target, allowList) { if (!fs.existsSync(source)) { console.error(`Source path does not exist: ${source}`); return; @@ -131,7 +162,7 @@ function copyFiles(source, target) { // Adjust the file path const firstCodeBlock = `\`\`\`rust`; const admonitionNotForProduction = ` -import NotForProductionBannerPartial from '../partials/_not-for-production-banner-partial.mdx'; +import NotForProductionBannerPartial from '../../partials/_not-for-production-banner-partial.mdx'; `;