# Directory Structure ``` docs/ background/ contracts-vs-parachains.md ink-vs-cosmwasm.md ink-vs-solidity.md migrate-to-parachain.md polkadot-sdk.md precompiles.md why-riscv.md why-rust.md basics/ abi/ all.md ink.md overview.md solidity.md metadata/ ink-format.md overview.md solidity-format.md contract-template.md contract-verification.md cross-contract-calling.md env-functions.md environment.md events.md gas.md mutating-values.md precompiles.md reading-values.md selectors.md storing-values.md trait-definitions.md upgradeability.md xcm.md datastructures/ custom.md mapping.md overview.md storage-in-metadata.md storage-layout.md storagevec.md debugging/ decoding.md events.md overview.md precompiles.md replays.md return_value.md sandbox.md tracing.md faq/ faq.md migrating-from-ink-3-to-4.md migrating-from-ink-4-to-5.md migrating-from-ink-5-to-6.md getting-started/ assets/ canvas-connect-to-local.png flipper-false.png flipper-instantiate-01.png flipper-instantiate-02.png flipper-instantiate-03.png flipper-instantiate-04.png flipper-true.png send-as-transaction.png start-substrate-node.png calling.md compiling.md creating.md deploying.md setup.md integrations-and-sdks/ javascript-typescript/ core-libraries.md react.md ethereum-compatibility.md other-languages.md overview.md intro/ intro.mdx overview.md sub0-hackathon.mdx tutorials-examples.md where-to-deploy.md linter/ rules/ no_main.md non_fallible_api.md primitive_topic.md storage_never_freed.md strict_balance_equality.md overview.md macros-attributes/ anonymous.md constructor.md contract_ref.md contract.md default.md error.md event.md implementation.md message.md name.md namespace.md overview.md payable.md selector.md storage.md topic.md trait_definition.md testing/ testnet/ faucet.md Faucet.tsx overview.md e2e.md overview.md sandbox.md testing-with-live-state.md unit-integration.md ``` # Files ## File: docs/background/contracts-vs-parachains.md ````markdown --- title: Smart Contracts vs. Parachains hide_title: true slug: /background/smart-contracts-vs-parachains ---
 # Smart Contracts vs. Polkadot Parachains One of the first questions we typically get when somebody learns about the Polkadot SDK is when to develop a parachain vs. when to develop a smart contract. ## The Difference The distinction here is that in the context of Polkadot and Kusama a parachain leases a slot for a couple of months for up to two years. The deal with a lease is that the parachain gets a fixed slot for executing its business logic (typically referred to as its _state transition function_) and can persist its modified state in a block. In Polkadot SDK terminology this state transition function is called the chain's _runtime_. The distinction to other ecosystems here is that, in the context of Polkadot, parachains and smart contracts exist at different layers of the stack: _smart contracts sit on top of parachains_. Parachains would usually be described as layer-1 blockchains — except for that they don't have to build their own security, are upgradable, and interoperable. ## Polkadot Parachains It's noteworthy that a parachain's state transition function doesn't get further validated — it's up to the parachain how it utilizes its slot time. The parachain already pre-paid for its slot when it won the slot auction on Polkadot or Kusama. This means the parachain can build its own (blockchain) world! For example, it can decide on how transaction fees are charged ‒ or even if transaction fees are charged at all. These options are crucial when building new or more user-friendly business models. Other distinguishing factors between parachains that we observe in the wild are differences in how governance works or the crypto-economics. There are some constraints on how the parachain can build its world though. Like physics in the real world it has to adhere to certain ground rules. For Polkadot and Kusama that's for example the consensus algorithm for the Relay Chain to communicate with the parachain. From those ground rules the advantages of Polkadot and Kusama emerge. Advantages like the aforementioned shared security, cross-chain communication, or guaranteed execution slot time. ## Smart Contracts For smart contracts, on the other hand, an existing parachain has to include the `pallet-revive` for users to deploy smart contracts. The deployed smart contract is always untrusted code. Anyone (or any program) that has tokens of the chain can upload a smart contract without requiring permission. Smart contracts allow _permissionless_ deployment of _untrusted_ programs on a blockchain. The `pallet-revive` has to assume that these programs are adversarial, it has to put a number of safety pillars in place to ensure that the contract can not e.g. stall the chain or cause state corruption of other contracts. For `pallet-revive` those safety pillars include mechanisms like gas metering or deposits for storing data on-chain. _To restate this important distinction: developing a parachain runtime is different from developing a smart contract — a smart contract sits on top of a parachain_. ## The Trade-off  The trade-off is that with a parachain one has the freedom to decide on (nearly) all the rules that make up the parachain. With a smart contract one is constrained by what the chain allows and the safety pillars that necessarily have to be in place. A smart contract can never be as fast as a native pallet built in the parachain runtime ‒ there is too much logic in between. A smart contract on the other hand has less friction for developing and deploying it. Developers don't have to take care of governance, crypto-economics, etc. One just needs a few tokens and can go on its merry way deploying a smart contract. It's as simple as that. ```` ## File: docs/background/ink-vs-cosmwasm.md ````markdown --- title: ink! vs. CosmWasm slug: /background/ink-vs-cosmwasm hide_title: true ---  # ink! vs. CosmWasm This is a short comparison between [ink!](https://github.com/use-ink/ink/) and [CosmWasm](https://github.com/CosmWasm/cosmwasm) meant to onboard developers coming from the Cosmos ecosystem. ## Architecture CosmWasm is modular, meaning that any blockchain using the Cosmos SDK can add smart contract support to their chain. That is similar to the [Polkadot SDK](https://polkadot.com/platform/sdk) approach, where chains have the option to add `pallet-revive` to their runtime. Aside from that, the architecture philosophy is likely the point where CosmWasm and ink! differ the most. CosmWasm follows the actor model design pattern, while ink! follows a synchronous execution model. That means some fundamental differences in how the source code is structured. The main entry point functions of CosmWasm contracts are: - `instantiate` which bootstraps the initial contract state (assuming it's already been deployed). - `execute` which has the actor perform operations to its internal state. - `query` which retrieves data from the actor’s internal state. An ink! contract can have as many public dispatchables as the developer desires, and differently from CosmWasm, it doesn’t rely on JSON schemas for defining how the messages are structured. Instead, ink! makes heavy usage of Rust macros. The main ink! macros are: - `#[ink(constructor)]` which is called when the contract is deployed, and is responsible for bootstrapping the initial contract state into the storage. It is analogous to the CosmWasm `instantiate` function. - `#[ink(storage)]` which annotates a struct that represents the contract's internal state. - `#[ink(message)]` which marks a function as a public dispatchable, meaning that it is exposed in the contract interface to the outside world. This macro can make a function behave analogously to CosmWasm’s `execute` and `query` functions. This depends on how it affects the internal contract state and what the return types. - `#[ink(event)]` and `#[ink(topic)]` which annotates a struct and its members as the events and topics that the contract might emit. There are other ink! macros, for which details can be found at [Macros & Attributes](../macros-attributes/overview.md). ## Unit Testing Unit testing in CosmWasm is quite similar to ink!. Both use the conventional Rust `#[cfg(test)]` macro and set up a mock on-chain environment. While CosmWasm unit tests have different modules for each of the three main entry-point functions, ink! allows for a more generalised approach, where the `#[ink(test)]` macro is used for each unit test. You can read more about ink! unit tests [here](../testing/unit-integration.md). ## Compiler CosmWasm uses [cargo-wasm](https://docs.rs/crate/cargo-wasm/latest) as its main compiler, while ink! uses [cargo-contract](https://github.com/use-ink/cargo-contract). `cargo-contract` is developed specifically for building, testing, and deploying ink! contracts. # Local Development Network In terms of local development networks, the [cosmos/gaia](https://github.com/cosmos/gaia) repository acts as the basic template for a generic Cosmos node. With the addition of the `x/wasm` module and some clean-up, this template repository becomes [wasmd](https://github.com/CosmWasm/wasmd), the entry point for CosmWasm development. In terms of Polkadot SDK, [`polkadot-sdk-solochain-template`](https://github.com/paritytech/polkadot-sdk-solochain-template) is a basic generic template of a node. Similar to `x/wasm`, [`pallet-revive`](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/revive) is the module that adds RISC-V smart contract functionality to the chain. We provide the [ink-node](https://github.com/use-ink/ink-node), which is analogous to `wasmd` — a basic template node for smart contract development. ## Testnets For CosmWasm development and on-chain testing, `wasmd` can be operated as a local setup (single or multiple nodes), or connected to the `cliffnet` public test network. For testing, ink! contracts can be deployed on a few different options: - Locally, on a single or multiple node setup of [`ink-node`](https://github.com/use-ink/ink-node). - Westend's [Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-westend-rpc.dwellir.com#/explorer) - [Pop Testnet](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Frpc1.paseo.popnetwork.xyz#/explorer) (on Paseo). See [Pop CLI for one way to deploy](https://learn.onpop.io/contracts/guides/deploy). ## Development Workflow ### Dependencies and Environment Setup The first step in CosmWasm development is to [install dependencies and setup the environment](https://docs.cosmwasm.com/core/installation), namely Rust, the WebAssembly target, `cargo-generate` and `cargo-run-script`. For ink! you can also find [a setup guide](../getting-started/setup.md) which will help you with dependencies, namely Rust, `cargo-contract` and `ink-node`. ### Compile and Test CosmWasm provides a template at the [cw-template](https://github.com/CosmWasm/cw-template) repository. In order to generate a new project, all you have to do is run: ``` cargo generate --git https://github.com/CosmWasm/cw-template.git --name PROJECT_NAME ``` Replacing `PROJECT_NAME` with the name of your project. Similarly, ink! provides an [`examples`](https://github.com/use-ink/ink-examples/tree/main) directory of its main repository. A contract can be compiled from its directory via: ``` cargo contract build ``` and tested via: ``` cargo contract test ``` ### Deploy and Interact CosmWasm contracts are deployed and instantiated with help of the `wasmd` executable. The list of step is provided [here](https://docs.cosmwasm.com/wasmd). It is possible to deploy and interact with ink! contracts using either a CLI (`cargo-contract`), or a web UI ([`contracts-ui`](https://ui.use.ink)). - [Instructions for `cargo-contract`](https://github.com/use-ink/cargo-contract/blob/master/crates/extrinsics/README.md) - [Instructions for `contracts-ui`](../getting-started/deploying.md) ```` ## File: docs/background/ink-vs-solidity.md ````markdown --- title: ink! vs. Solidity hide_title: true slug: /background/ink-vs-solidity ---  # ink! vs. Solidity The following table gives a brief comparison of features between ink! and Solidity:cargo-contract about type compatibility?```json "messages": [ { "args": [], "docs": [ " Flips the current value of the Flipper's boolean." ], "label": "flip", "mutates": true, "payable": false, "returnType": { "displayName": [ "ink", "MessageResult" ], "type": 1 }, "selector": "0x633aa551" }], "lang_error": { "displayName": [ "ink", "LangError" ], "type": 3 }, { "id": 3, "type": { "def": { "variant": { "variants": [ { "index": 1, "name": "CouldNotReadInput" } ] } }, "path": [ "ink_primitives", "LangError" ] } } ```
The following chains are in production and support ink! 5.0, if you are not using any of the
four functions mentioned above:
### `cargo-contract` 4.0
Together with ink! 5.0 we've released `cargo-contract` 4.0.
:::info
You have to use `cargo-contract` >= 4.0 for ink! 5.0 contracts!
You can upgrade via:
```rust
cargo install cargo-contract --version ^4
```
:::
Make sure that e.g. your CI also uses at least `cargo-contract` 4.0 with ink! v5.0.
If you have wrapper scripts around `cargo-contract`, you should
ensure that this version is enforced, otherwise users will get an error.
### Tooling & Libraries
- Stable Rust >= 1.75
- `cargo-contract` >= v4.0
- `polkadot-js/api` and `polkadot-js/api-contract` >= 10.12.1
- [`use-inkathon`](https://github.com/scio-labs/use-inkathon): upgrade the `polkadot-js/api` and `polkadot-js/api-contract` dependencies in your project to >= 10.12.1
- [ink!athon](https://inkathon.xyz/) >= 0.7.0
- [`typechain-polkadot`](https://github.com/Brushfam/typechain-polkadot) >= 1.2.0
## Important Changes
We had to introduce a number of changes that require you to manually upgrade
your contract from 4.x to 5.0. The steps to do this are explained in this section.
### `scale` dependencies were moved to `ink` entrance crate
This change was done to ensure that you always use the correct scale dependency versions
with an ink! version. The relevant PR is [#1890](https://github.com/use-ink/ink/pull/1890).
We removed the requirement for contracts to have direct dependencies on `parity-scale-codec`
and `scale-info` in their `Cargo.toml`.
You can now remove those dependencies from your contracts `Cargo.toml`:
```diff
ink = { version = "4.3", default-features = false }
-scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
-scale-info = { version = "2.6", default-features = false, features = ["derive"], optional = true }
```
Both crates have been re-exported from the `ink` umbrella crate: `ink::scale_info` and `ink::scale`.
We created a convenience macro to derive the re-exported traits `ink::scale::Encode`,
`ink::scale::Decode` and `ink::scale_info::TypeInfo`.
```rust
// Previously
#[scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(::scale_info::TypeInfo))]
pub enum Error {}
// Now
#[ink::scale_derive(Encode, Decode, TypeInfo)]
pub enum Error {}
```
The documentation of the macro can be found [here](https://docs.rs/ink/5.0.0/ink/attr.scale_derive.html).
### Wildcard selectors: only one other message is allowed in the contract besides the wildcard selector
Following [our security review by OpenZeppelin](https://blog.openzeppelin.com/security-review-ink-cargo-contract),
we've tightened the usage of wildcard selectors.
With ink! 5.0 we allow only exactly one other contract message with a well-known reserved
selector to be defined. In ink! 4.x, more than one other message was allowed.
Read more in [the PR](https://github.com/use-ink/ink/pull/1708) and [IIP-2: Limit contracts with a wildcard selector to one other message](https://github.com/use-ink/ink/issues/1676).
The proposal is to restrict contracts with a wildcard selector to only have one other message
with a reserved/well-known selector. This guarantees that there are no selector clashes,
either by chance or malicious intent, and that the Proxy will only handle messages intended for it.
If a contract uses a wildcard selector `#[ink(message, payable, selector = _)]` it _MAY_ define one
other message. This message _MUST_ use the reserved selector `@`.
This selector _MUST_ only be used in conjunction with a wildcard selector.
```rust
/// Handles any message with no matching selector in this proxy contract
#[ink(message, selector = _)]
pub fn fallback(&self) {
// forward call to the "logic" contract which actually executes the call
}
#[ink::scale_derive(Decode)]
pub enum ProxyMessage {
UpgradeContract(Hash),
}
/// One other message allowed to handle messages.
/// Fails to compile unless `@` is used as the selector.
#[ink(message, selector = @)]
pub fn handler(&self, msg: ProxyMessage) {
match msg {
ProxyMessage(hash) => { }
}
}
/// An additional message. Fails to compile when uncommented.
// #[ink(message)]
// pub fn additional_message(&self, msg: ProxyMessage) {
// match msg {
// ProxyMessage(hash) => ...
// }
// }
```
### Events 2.0
In prior ink! versions, events were defined inside the `#[ink::contract]` macro.
With ink! 5.0 we decouple events from the `#[ink::contract]` macro,
allowing events to be shared between contracts.
We've updated [the Events documentation page](../basics/events.md) accordingly.
The syntax of defining events within the main `#[ink::contract]` macro will continue to work,
no code changes in existing contracts are required to update to the new syntax.
:::caution
The topic calculation changed in general, so also for events that are declared inside the
`#[ink::contract]` macro!
This is a breaking change for any client code which uses topics to filter events.
Please see [#1827](https://github.com/use-ink/ink/pull/1827) for details.
:::
#### Custom signature topics
In [#2031](https://github.com/use-ink/ink/pull/2031) we introduced an
optional attribute `signature_topic` to the `#[ink::event]` and `#[ink(event)]` macros.
It can be used to specify the signature topic for a specific event manually, instead of the
automatic topic calculation.
### No more unchecked arithmetic
Unchecked arithmetic operations in a contract are no longer supported for arithmetic
safety reasons. Compiling a contract that contains those will fail gracefully.
If you haven't already done, you now need to handle overflows that could occur.
Rust supports different possibilities of doing so (saturating, "wrap around",
and unchecked arithmetic operations) .
See [this](https://doc.rust-lang.org/book/ch03-02-data-types.html#scalar-types) section
of the Rust Programming Language for a thorough explanation on how to do safe arithmetic
operations in Rust.
This change was introduced in [#1831](https://github.com/use-ink/ink/pull/1831).
### Fail when decoding from storage and not all bytes consumed
If a contract previously relied on successful decoding which does not consume all bytes,
then recompiling with a version of ink! which includes this change will cause that contract
to trap at runtime when attempting to decode.
A simple example would be if a storage cell contains some bytes which were in the first place
an encoded `u32`. If the contract attempts to decode those into a `u8`
this would previously have succeeded, now the contract would trap.
Here's a code example of behavior that previously worked for ink! 4.x, but
would error now:
```rust
let key = 0u32;
let value = [0x42; 32];
ink::env::set_contract_storage(&key, &value);
// Only attempt to read the first byte (the `u8`) of the storage value data
let _loaded_value: Option
At the time of the ink! v5 release (March 2024) no parachain with ink! support
had upgraded to `polkadot-v1.8.0` yet.
Please note that if you are using trait definitions for cross-contract calls,
direct calls from the `contract_ref!` macro are only supported with the `call_v2`.
Otherwise, you need to get the `CallBuilder` from the structure
and build the call manually.
```rust
type Erc20Wrapper = contract_ref!(Erc20);
let erc20: Erc20Wrapper = new_erc20.into();
let erc20_builder = erc20.call();
erc20_builder.total_supply().call_v1().invoke()
```
### Metadata Changes
#### Events 2.0
See [#1827](https://github.com/use-ink/ink/pull/1827) for the full details.
Two fields werere added to the objects in the `events` array:
`module_path` and `signature_topic`.
Previously the order of the events in the `events` array was significant (i.e. the first
one had an implied index of `0`), and this index could be used to determine which event
to decode.
Now that is replaced by the `signature_topic`, and the order of the events in the metadata
no longer has any significance.
See the section "[Events 2.0](#events-20)" on this page for more info.
ink! 4.0:
```json
"events": [
{
"args": [ ... ],
"docs": [ ... ],
"label": "Transfer"
},
...
]
```
ink! 5.0:
```diff
"events": [
{
"args": [ ... ],
"docs": [ ... ],
"label": "...",
+ "module_path": "erc20::erc20",
+ "signature_topic": "0xb5b61a3e6a21a16be4f044b517c28ac692492f73c5bfd3f60178ad98c767f4cb"
},
...
]
```
#### New field: `staticBufferSize`
With [#1880](https://github.com/use-ink/ink/pull/1880) we added a `"staticBufferSize"` field to
the metadata file. The unit is bytes.
See the section "[Buffer size can be customized](#buffer-size-can-be-customized)" on this page for
more info.
Example:
```diff
"maxEventTopics": 4,
+ "staticBufferSize": 16384,
"timestamp": { ... }
```
#### Metadata storage keys encoding change
Storage keys used to access storage data are SCALE encoded. Previously,
the contract metadata used big endian encoding to represent storage keys.
With the ink! 5.0 release, these encoding formats have been aligned,
and SCALE encoding (little endian) is now used for the metadata storage keys.
This is a breaking change, and client tools that use the storage keys from contract
metadata will need to adapt accordingly.
Please see: [#2048](https://github.com/use-ink/ink/pull/2048) for details.
Example:
```diff
"storage": {
"root": {
"layout": {
"struct": {
"fields": [
{
"layout": {
"leaf": {
- "key": "0x00000159",
+ "key": "0x59010000",
"ty": 0
}
},
"name": "value"
}
],
"name": "Flipper"
}
},
- "root_key": "0x00000159",
+ "root_key": "0x59010000",
"ty": 1
}
},
```
## Interesting New Features
### End-To-End testing with a chain snapshot
With ink! 5.0 we introduce the possibility of running your tests against the
fork (i.e. snapshot) of a live chain.
See [this page](../testing/testing-with-live-state.md) in our documentation for details.
### New lints
The new lints are:
- [`no_main`](../linter/rules/no_main.md): enforces `no_main` for contracts.
- [`primitive_topic`](../linter/rules/primitive_topic.md): no number types are allowed as event topics.
- [`storage_never_freed`](../linter/rules/storage_never_freed.md): what is written into storage can be removed again.
- [`strict_balance_equality`](../linter/rules/strict_balance_equality.md): detects usage of strict balance equality checks, a common smart contract vulnerability.
- [`non_fallible_api`](../linter/rules/non_fallible_api.md): detects the usage of potentially unsafe methods for which there are safer alternatives.
With `cargo-contract` 4.0 we added a couple new lints for common smart contract issues
and best practices.
You can run the linter via `cargo contract build --lint`.
Details on each lint can be found [here](../linter/overview.md).
### New `cargo-contract` commands
We added a bunch of helpful new commands to `cargo-contract` 4.0.
For all these commands you can also supply the `--help` cli flag to get more
info (e.g. `cargo contract storage --help`).
- `cargo contract verify`: contract verification ([#1404](https://github.com/use-ink/cargo-contract/pull/1404), [#1306](https://github.com/use-ink/cargo-contract/pull/1306))
- `cargo contract info` now outputs the language of the deployed contract, using a heuristic ([#1329](https://github.com/use-ink/cargo-contract/pull/1329))
- `cargo contract info --binary`: outputs the on-chain Wasm of the contract ([#1311](https://github.com/use-ink/cargo-contract/pull/1311/))
- `cargo contract info --all`: displays all addresses of deployed contracts on a particular chain ([#1319](https://github.com/use-ink/cargo-contract/pull/1319))
- `cargo contract storage`: displays the storage of an on-chain contract ([#1395](https://github.com/use-ink/cargo-contract/pull/1395), [#1414](https://github.com/use-ink/cargo-contract/pull/1414))

### Alternative off-chain E2E testing backend support: DRink!
DRink! is a toolbox for ink! developers that allows for testing your contracts
without any running node.
It has a number of features that are pretty great:
- deploy and call your contracts synchronously, _without any delays_ related to block production or networking.
- enhanced debugging and call tracing.
- supports _arbitrary runtime_ configurations, including custom chain extensions and runtime calls.
- full control over runtime state, including block number, timestamp, etc.
See the [DRink!](https://github.com/inkdevhub/drink) page for more details.
### Contract Verification
We added a bunch of helpful documentation and `cargo-contract` commands for
contract verification. Please see the page on contract verification under "Basics"
for more details.
### We improved the contract example illustrating upgradeable contracts via `delegate_call`
See [here](https://github.com/use-ink/ink-examples/tree/main/upgradeable-contracts)
for the contract example.
### Upgradeable Contracts: `delegate_dependency`
We've added support for two new host functions:
- `lock_delegate_dependency`: prevents the code at the given code hash from being removed.
- `unlock_delegate_dependency`: releases the lock on preventing the code from being removed
from the current contract.
Having a delegate dependency allows contracts to safely delegate to another `code_hash` with
the guarantee that it cannot be deleted.
We've updated the [`upgradeable-contracts/delegator`](https://github.com/use-ink/ink-examples/tree/main/upgradeable-contracts#delegator)
example to demonstrate these new calls.
For that purpose we've also added a [`remove_code`](https://docs.rs/ink_e2e/5.0.0/ink_e2e/trait.ContractsBackend.html#method.remove_code)
function to the E2E API.
These two functions are only available from `polkadot-1.8.0` on.
You can find out if a chain supports these new functions by
querying the `contracts::apiVersion` constant. It has to be `2`.
You can use the [polakdot.js app](https://polkadot.js.org/apps/) to do this:
Developer » Chain State » Constants » `contracts` » `apiVersion` » Click on the `+` on the right.
At the time of the ink! v5 release (March 2024) no parachain with ink! support
had upgraded to `polkadot-v1.8.0` yet.
### We made `set_code_hash` generic
The `self.env().set_code_hash()` method now accepts the `Hash` environment type instead
of a concrete `[u8; 32]`.
```rust
// Previously
pub fn set_code(&mut self, code_hash: [u8; 32]) {
ink::env::set_code_hash(&code_hash).unwrap_or_else(|err| {});
}
// Now
pub fn set_code(&mut self, code_hash: Hash) {
self.env().set_code_hash(&code_hash).unwrap_or_else(|err| {});
}
```
More details in [#1906](https://github.com/use-ink/ink/pull/1906).
### Buffer size can be customized
With [#1869](https://github.com/use-ink/ink/pull/1869) we added a possibility
of setting a custom static buffer size for ink! to use.
ink! uses a static buffer for interacting with pallet-contracts, i.e. to move data
between `pallet-contracts` and a smart contract. The advantage of a static buffer
is that no gas-expensive heap allocations are necessary, all allocations are done
using simple pointer arithmetic.
The default static buffer size is 16 kB, which is enough for on-chain smart
contracts. However, the [Phala Network](https://phala.network/) parachain on Polkadot
allows the deployment of ink! contracts off-chain. Hence, for their chain certain high
computation contracts might require a larger buffer size.
### Stabilized `call_runtime`
We stabilized `call_runtime` in [#1749](https://github.com/use-ink/ink/pull/1749).
It can be used to call a runtime dispatchable from an ink! contract.
You can find a contract example and a comparison with chain extensions
[here](https://github.com/use-ink/ink-examples/tree/main/call-runtime).
We've added an example of how to end-to-end test
`call_runtime` [here](https://github.com/use-ink/ink-examples/tree/main/e2e-call-runtime).
````
## File: docs/faq/migrating-from-ink-5-to-6.md
````markdown
---
title: "Migration: ink! v5 → v6"
slug: /faq/migrating-from-ink-5-to-6
---
import useBaseUrl from '@docusaurus/useBaseUrl';
The following chains are in production and support ink! 6.0.
## Important Changes
We had to introduce a number of changes that require you to manually upgrade
your contract from 5.x to 6.0. The steps are explained in this section.
### Restrict which `cfg` attributes can be used
This change was done as a recommendation from the ink! 5.x audit.
In a nutshell it prevents developers from hiding functionality in a contract,
that would not be visible in the metadata (so e.g. on a block explorer).
The relevant PR is [#2313](https://github.com/use-ink/ink/pull/2313).
From ink! 6.0 on only these attributes are allowed in `#[cfg(…)]`: - `test` - `feature` (without `std`) - `any` - `not` - `all`
### Metadata Changes
The field `source.wasm` was renamed to `source.contract_binary`.
### Types
#### Contract Balance: `U256`
For the type of a contract's balance, `pallet-revive` uses depending on the context
* either the configured `pallet_revive::Config::Currency` type (which corresponds
to the `ink::Environment::Balance` type.
* or a hardcoded `U256` (which corresponds to what Ethereum uses).
In this alpha release we just adhere to requiring the types that `pallet-revive` uses.
In an upcoming beta release this could be simplified to reduce UX friction by just
using one type everywhere and converting to the `pallet-revive` one.
#### Contract Address: `Address` / `H160`
For a contract's account, `pallet-revive` is using either the configured `AccountId` type
of the `polkadot-sdk` runtime, or `H160`.
`Address` is a more semantically named type alias for `H160` defined in `ink_primitives`,
and re-exported in the `ink` crate.
Finding the `Address`/`H160` for an `AccountId` is done via an address derivation scheme
derived in [#7662](https://github.com/paritytech/polkadot-sdk/pull/7662).
After instantiating a contract, the address is no longer returned by `pallet-revive`.
Instead one has to derive it from given parameters (see the linked PR). `cargo-contract`
does that automatically.
For contract instantiations and contract calls the pallet requires that a 1-to-1 mapping
of an `AccountId` to an `Address`/`H160` has been created. This can be done via the
`map_account`/`unmap_account` API.
The PR [#6096](https://github.com/paritytech/polkadot-sdk/pull/6096) contains more
information.
Besides the publicly exposed crate functions, we've introduced a new subcommand
`cargo contract account` that allows resolving the `H160` contract address to the
Polkadot SDK `AccountId` which it is mapped to.
#### Contract Hash: `H256`
For a contract's hash value, `pallet-revive` uses a fixed `H256`, Previously,
the `ink::Environment::Hash` type referenced the hash type being used for the
contract's hash. Now it's just a fixed `H256`.
### Contract delegates can no longer be done by code
In `pallet-contracts` (and hence up until ink! v5), a pattern for upgradeable
contracts was to delegate the contract execution to a different code, e.g. to
a new version of the contract's code.
This distinction of contract code that was uploaded to a chain vs. an instantiated
contract from this code no longer exists in `pallet-revive`. If you want to
delegate the execution, you will have to specify another contract's address
to which code you want to delegate to. This other contract needs to be instantiated
on-chain.
For the execution, the context of the contract that delegates will continue
to be used (storage, caller, value).
Specifically the delegate API changed like this:
```rust
/// ink! v5
#[derive(Clone)]
pub struct DelegateCall
You can interact with your node using `cargo-contract`, `pop` or [the Contracts UI](https://ui.use.ink/). If you use the Contracts UI, you have to configure it to connect to the locally running node:
- Click on the dropdown selector at the top left corner.
- Choose "Local Node".

# Set up a Local Polkadot Hub Environment
You can easily launch a full Polkadot Hub setup locally using the [Pop CLI](https://learn.onpop.io/contracts/guides/deploy). This includes a local relay chain and one or more system parachains, allowing for end-to-end smart contract development and testing.
To spin up the environment with the Paseo relay chain and system chains like `asset-hub` and `passet-hub`, run:
```bash
pop up paseo -p asset-hub,passet-hub
```
This command will launch:
- A local Paseo relay chain
- [Passet Hub](../intro/where-to-deploy.md#passet-hub) as a parachain, connected and ready to deploy smart contracts
You can also include additional system parachains in your local environment, such as `people` and `pop`, by extending the command:
```bash
pop up paseo -p asset-hub,passet-hub,people,pop
```
Need more options or configuration details? Check out the CLI help:
```bash
pop up paseo --help
```
## Deploy the contract
Now that we have generated the contract binary from our source code and connected to a local node, we want to deploy this contract onto our local node.
Smart contract deployment on Polkadot is a little different than on traditional smart contract blockchains.
For example, the standard ERC20 token has been deployed to Ethereum thousands of times, sometimes only with changes to the initial configuration (through the Solidity `constructor` function). Each of these instances take up space on the blockchain equivalent to the contract source code size, even though no code was actually changed.
The contract deployment process in Polkadot is split into two steps:
1. Putting your contract code on the blockchain
2. Creating an instance of your contract
With this pattern, contract code like the ERC20 standard can be put on the blockchain one single time, but instantiated any number of times. No need to continually upload the same source code over and waste space on the blockchain.
## Using the Terminal
With `cargo-contract` or `pop` it's just a simple sequence of:
Our "Hello, World!".
» view example
An ERC-20 implementation.
» view example
An upgradeable contract.
» view example
A multi-signature wallet.
» view example
Calling Solidity contracts.
» view example
Our "Hello, World!".
» view example
An ERC-20 implementation.
» view example
An upgradeable contract.
» view example
A multi-signature wallet.
» view example
Allow runtime access.
» view example
You can deploy your contract with PAS token on [Pop's Testnet](https://learn.onpop.io/contracts/tutorials/your-first-ink-smart-contract). See [Pop's guide to getting tokens](https://learn.onpop.io/contracts/guides/bridge-tokens-to-pop-network).
````
## File: docs/testing/testnet/Faucet.tsx
````typescript
import React, { useMemo, useState } from 'react'
import ReCAPTCHA from 'react-google-recaptcha'
const RECAPTCHA_SITE_KEY = '6LcgFI4nAAAAAATrEMoJ6zBacsx5udc1UhGFXemH'
const FAUCET_URL = 'https://rococo-faucet.parity-testnet.parity.io/drip/web'
const Faucet = () => {
const [captcha, setCaptcha] = useState{error}
}
### (3) Deploy Your Contract
Once you have `PAS` on Paseo you can [bridge them from Paseo to Pop](https://learn.onpop.io/contracts/guides/bridge-tokens-to-pop-network) and deploy by following the instructions in the Pop Docs [here](https://learn.onpop.io/contracts/guides/deploy#deploy-to-custom-or-public-network).
````
## File: docs/testing/e2e.md
````markdown
---
title: "Full E2E"
hide_title: true
slug: /contract-testing/end-to-end-e2e-testing
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# End-to-End (E2E) Tests
E2E testing enables developers to write a test that will not only test the contract in an
isolated manner; instead the contract will be tested _together_ with all components that
will be involved on-chain – so from end to end. This way of testing resembles closely
how the contract will actually behave in production.
As part of the test, the contract will be compiled and deployed to a Polkadot SDK node that
is running in the background. ink! offers API functions that enable developers to then
interact with the contract via transactions that they create and submit to the blockchain.
You as a developer can define assertions on the outcome of their transactions, such as checking
for state mutations, transaction failures or incurred gas costs.
Your chain configuration will be tested together with the smart contract. And if your
chain has pallets that are involved with the smart contract execution, those will be
part of the test execution as well.
ink! does not put any requirements on the Polkadot SDK node in the background – for example,
you can run a node that contains a snapshot of a live network.
## Example
The following code example illustrates a basic E2E test for the
[flipper example](https://github.com/use-ink/ink-examples/blob/main/flipper/lib.rs).
```rust
#[ink_e2e::test]
async fn default_works
````
## File: docs/testing/unit-integration.md
````markdown
---
title: Unit & Integration
hide_title: true
slug: /contract-testing/unit-integration-tests
---

# Tests
On this page we lay out the different use-cases for unit vs. integration tests.
## Unit Tests
Testing contracts off-chain is done by `cargo contract test` and users can simply use the standard Rust
routines of creating unit test modules within the ink! project:
```rust
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn my_test() { ... }
}
```
Test instances of contracts can be created with something like:
```rust
let contract = MyContract::my_constructor(a, b);
```
Messages can simply be called on the returned instance as if `MyContract::my_constructor` returns a
`Self` instance.
See the [flipper example](https://github.com/use-ink/ink-examples/blob/main/flipper/lib.rs).
## Integration Tests
For integration tests, the test is annotated with our `#[ink::test]`
attribute instead of `#[test]`. This attribute denotes that
the test is then executed in a simulated, mocked blockchain environment.
Here functions are available to influence how the test environment
is configured (e.g. setting a specified balance of an account to
simulate how a contract would behave when interacting with it).
If you annotate a test with the `#[ink::test]` attribute it
will be executed in a simulated environment, similar to as it
would be run on-chain.
You then have fine-grained control over how a contract is called;
for example you can influence the block advancement, the value transferred to it,
by which account it is called, which storage it is run with, etc..
See the [`examples/erc20`](https://github.com/use-ink/ink-examples/blob/main/erc20/lib.rs) contract on how to utilize those or [the documentation](https://use-ink.github.io/ink/ink/attr.test.html) for details.
At the moment there are some known limitations to our off-chain environment,
and we are working on making it behave as close to the real chain environment
as possible.
:::note
One limitation of the off-chain testing framework is that it
currently only supports a `DefaultEnvironment`.
See [here](../basics/environment.md) for an explanation of what an environment is.
:::
### Example
```rust
#[cfg(test)]
mod tests {
// Conventional unit test that works with assertions.
#[ink::test]
fn test1() {
// test code comes here as usual
}
// Conventional unit test that returns some Result.
// The test code can make use of operator-`?`.
#[ink::test]
fn test2() -> Result<(), ink::env::Error> {
// test code that returns a Rust Result type
}
}
```
## How do you find out if a test requires the off-chain environment?
If the test recursively uses or invokes methods that call a function defined
in `self.env()` or `Self::env()`.
An example is the following:
```rust
let caller: AccountId = self.env().caller();
```
````