### Swanky CLI Installation Example Source: https://github.com/use-ink/ink-docs/blob/master/src/css/ea.html Instructions for installing the Swanky CLI on different operating systems. This example shows paths for MacOS and Debian/Ubuntu. ```bash bin directory or somewhere similar. MacOS Debian/ ``` -------------------------------- ### Install Dependencies and Start Development Server Source: https://github.com/use-ink/ink-docs/blob/master/README.md Use these commands to install project dependencies with pnpm and start the development server. Ensure Corepack is enabled to manage the correct pnpm version. ```bash corepack enable pnpm install pnpm start ``` -------------------------------- ### Setup Inkathon App Source: https://github.com/use-ink/ink-docs/blob/master/tutorials/frontend-development/inkathon-erc20.md Installs and starts the Inkathon boilerplate project. Ensure you have Node.js and Bun installed. ```bash npx create-inkathon-app@latest cd bun run dev ``` -------------------------------- ### Development Server Start Command Source: https://github.com/use-ink/ink-docs/blob/master/docs/solidity-interop/wagmi-integration.md Run this command in your terminal to start the development server for your dApp. ```bash npm run dev ``` -------------------------------- ### Ink! Unit Testing Environment Setup Source: https://github.com/use-ink/ink-docs/blob/master/docs/background/ink-vs-solidity.md These examples show how to manipulate the Ink! testing environment for unit tests. Use `default_accounts` to get predefined accounts, `set_caller` to specify the caller, and `set_callee` to set the contract's address. You can also transfer value, advance blocks, and generate arbitrary IDs. ```rust // get the default accounts (alice, bob, ...) let accounts = ink::env::test::default_accounts::(); accounts.alice //usage example ``` ```rust // set which account calls the contract ink::env::test::set_caller::(accounts.bob); ``` ```rust // get the contract's address let callee = ink::env::account_id::(); ``` ```rust // set the contracts address. // by default, this is alice's account ink::env::test::set_callee::(callee); ``` ```rust // transfer native currency to the contract ink::env::test::set_value_transferred::(2); ``` ```rust // increase block number (and block timestamp). // this can be placed in a loop to advance the block many times ink::env::test::advance_block::(); ``` ```rust // generate arbitrary AccountId AccountId::from([0x01; 32]); ``` ```rust // generate arbitrary Hash Hash::from([0x01; 32]) ``` ```rust // macro for tests that are expected to panic. #[should_panic] ``` -------------------------------- ### Install POP CLI Source: https://github.com/use-ink/ink-docs/blob/master/tutorials/frontend-development/typink-erc20.md Install the POP CLI tool, which is used for generating and building ink! smart contracts. ```bash cargo install --git https://github.com/r0gue-io/pop-cli ``` -------------------------------- ### Install Pop CLI via Homebrew Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/setup.md Install the Pop CLI using Homebrew for an enhanced ink! smart contract development experience. ```bash brew install r0gue-io/pop-cli/pop ``` -------------------------------- ### Install and Use Pop CLI Source: https://github.com/use-ink/ink-docs/blob/master/docs/intro/sub0-hackathon.mdx Install the Pop CLI using Homebrew or from source. Use it to set up your environment, create new contracts, build, deploy, and interact with them. The Pop CLI automatically launches a local node for deployment. ```bash # Install Pop CLI via brew $ brew install r0gue-io/pop-cli/pop # From source $ cargo install --force --locked pop-cli # Setup environment $ pop install # Create a simple contract $ pop new # Build your contract $ pop build --release # Pop CLI automatically launches a local node when deploying $ pop up # Interact with your contract $ pop call # If you get an error saying your account is not mapped: $ pop call chain --pallet Revive --function map_account --url wss://passet-hub-paseo.ibp.network/ --use-wallet ``` -------------------------------- ### Main Application Page Setup Source: https://github.com/use-ink/ink-docs/blob/master/docs/solidity-interop/wagmi-integration.md Integrate the FlipperContract component into your main application page. This example conditionally renders the contract interaction based on wallet connection status. ```tsx "use client"; import { ConnectWallet } from "./components/ConnectWallet"; import { FlipperContract } from "./components/FlipperContract"; import { useAccount } from "wagmi"; export default function Home() { const { isConnected } = useAccount(); return (

Wagmi - Polkadot Hub Smart Contracts

{isConnected ? : Connect your wallet}
); } ``` -------------------------------- ### Install and Use Pop CLI Source: https://github.com/use-ink/ink-docs/blob/master/ink-llms.txt Commands for installing the Pop CLI via Homebrew or from source, setting up the environment, creating new contracts, building, deploying, and interacting with them. Includes a specific command for mapping accounts if an error occurs. ```bash # Install Pop CLI via brew $ brew install r0gue-io/pop-cli/pop # From source $ cargo install --force --locked pop-cli # Setup environment $ pop install # Create a simple contract $ pop new # Build your contract $ pop build --release # Pop CLI automatically launches a local node when deploying $ pop up # Interact with your contract $ pop call # If you get an error saying your account is not mapped: $ pop call chain --pallet Revive --function map_account --url wss://passet-hub-paseo.ibp.network/ --use-wallet ``` -------------------------------- ### Install Pop CLI from Source Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/setup.md Install the Pop CLI directly from its source using cargo. Ensure you have the latest stable Rust and Cargo installed. ```bash cargo install --force --locked pop-cli ``` -------------------------------- ### Start Development Server Command Source: https://github.com/use-ink/ink-docs/blob/master/tutorials/frontend-development/typink-erc20.md Execute this command in your terminal to start the development server. This allows you to view the integrated ERC20 token information in your browser. ```bash pnpm dev ``` -------------------------------- ### Install Rust and Cargo Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/setup.md Install a stable Rust version and cargo, which are prerequisites for compiling smart contracts. ```bash curl https://sh.rustup.rs -sSf | sh ``` -------------------------------- ### Install and Use cargo-contract CLI Source: https://github.com/use-ink/ink-docs/blob/master/docs/intro/sub0-hackathon.mdx Install the `cargo-contract` CLI tool, which optimizes contract builds and facilitates deployment and interaction. Ensure Rust source components are installed. Use it to create, build, instantiate, and call contracts. ```bash # Install our cli tool: `cargo-contract`. # It wraps around Rust's `cargo build` to build contracts with optimal # flags for blockchains. It also allows for deploying + interacting # with contracts. $ rustup component add rust-src $ cargo install --locked --force --version 6.0.0-beta.1 cargo-contract # Create a simple contract. $ cargo contract new flipper && cd flipper $ cargo contract build --release # Download our local development node. # Find the binary here: https://github.com/use-ink/ink-node/releases/latest # Start your local development node in a separate shell session $ ink-node # Instantiate your contract on-chain. $ cargo contract instantiate --suri //Alice # Dry-run a call of it. $ cargo contract call --suri //Alice --contract 0x… --message get # Execute a contract call, as a transaction on-chain. $ cargo contract call --suri //Alice --contract 0x… --message flip -x ``` -------------------------------- ### Example Contract Using Mapping for Balances Source: https://github.com/use-ink/ink-docs/blob/master/docs/advanced/datastructures/mapping.md A full contract example demonstrating deposit and withdrawal functionality using a Mapping to store user balances. ```rust #![cfg_attr(not(feature = "std"), no_std, no_main)] #[ink::contract] mod mycontract { use ink::storage::Mapping; #[ink(storage)] pub struct MyContract { /// Assign a balance to every account ID balances: Mapping, } impl MyContract { /// Constructor to initialize the contract with an empty mapping. #[ink(constructor, payable)] pub fn new() -> Self { let balances = Mapping::default(); Self { balances } } /// Retrieve the balance of the caller. #[ink(message)] pub fn get_balance(&self) -> Option { let caller = self.env().caller(); self.balances.get(caller) } /// Credit more money to the contract. #[ink(message, payable)] pub fn transfer(&mut self) { let caller = self.env().caller(); let balance = self.balances.get(caller).unwrap_or(0); let endowment = self.env().transferred_value(); self.balances.insert(caller, &(balance + endowment)); } /// Withdraw all your balance from the contract. pub fn withdraw(&mut self) { let caller = self.env().caller(); let balance = self.balances.get(caller).unwrap(); self.balances.remove(caller); self.env().transfer(caller, balance).unwrap() } } } ``` -------------------------------- ### Set up Pop CLI Environment Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/setup.md After installing the Pop CLI, run this command to set up your development environment. ```bash pop install ``` -------------------------------- ### Build and Instantiate Flipper Contract Source: https://github.com/use-ink/ink-docs/blob/master/docs/development/testing/testing-with-live-state.md Builds the flipper example contract and instantiates it with initial state. Ensure you are in the contract's directory. ```bash cd ink-examples/flipper/ cargo contract build --release cargo contract instantiate --suri //Alice --args true -x ``` -------------------------------- ### Install DRink! CLI Tool Source: https://github.com/use-ink/ink-docs/blob/master/docs/development/testing/sandbox.md Install the DRink! command-line interface tool using cargo to interact with DRink! through a TUI. ```shell cargo install drink-cli ``` -------------------------------- ### Usage Example for ERC-20 Contract Source: https://github.com/use-ink/ink-docs/blob/master/ink-llms.txt Demonstrates how to instantiate and interact with the `Erc20` contract after its definition. This example assumes the `Erc20::new` constructor and `total_supply` message are implemented. ```rust let mut erc20 = Erc20::new(1000); assert_eq!(erc20.total_supply(), 1000); ``` -------------------------------- ### Install cargo-contract CLI Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/setup.md Install the `cargo-contract` CLI tool, essential for managing ink! smart contracts. This command also installs the `rust-src` component. ```bash rustup component add rust-src cargo install --force --locked --version 6.0.0-beta.1 cargo-contract ``` -------------------------------- ### Install Dependencies for Wagmi dApp Source: https://github.com/use-ink/ink-docs/blob/master/docs/solidity-interop/wagmi-integration.md Install necessary packages for creating a React dApp with Wagmi integration. ```bash npx create-next-app@latest wagmi-asset-hub cd wagmi-asset-hub npm install wagmi viem @tanstack/react-query ``` -------------------------------- ### Verify ink-node Installation Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/setup.md Confirm that the ink-node has been installed correctly by checking its version. This command should output the version information if the installation was successful. ```bash ./ink-node --version ``` -------------------------------- ### Install ink! Toolchain and Scaffold Project Source: https://context7.com/use-ink/ink-docs/llms.txt Installs Rust, the cargo-contract CLI, and scaffolds a new ink! contract project. Includes commands for building in debug and release modes, and running tests. ```bash curl https://sh.rustup.rs -sSf | sh rustup component add rust-src cargo install --force --locked --version 6.0.0-beta.1 cargo-contract brew install r0gue-io/pop-cli/pop pop install cargo contract new flipper cd flipper cargo contract build cargo contract build --release cargo contract test cargo contract test --features e2e-tests ``` -------------------------------- ### Build and Instantiate with cargo-contract Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/deploying.md Build your contract using cargo-contract and then instantiate it on a running node. This example uses the //Alice account for instantiation. ```bash cargo contract build --release cargo contract instantiate --suri //Alice --args true ``` -------------------------------- ### Create Hardhat Project Source: https://github.com/use-ink/ink-docs/blob/master/docs/solidity-interop/hardhat-deployment.md Initializes a new Hardhat project and installs necessary dependencies for Polkadot interaction. ```bash mkdir hardhat-example cd hardhat-example npm init -y ``` ```bash npm install --save-dev @parity/hardhat-polkadot ``` ```bash npx hardhat-polkadot init npm install ``` -------------------------------- ### Solidity Contract Example Source: https://github.com/use-ink/ink-docs/blob/master/docs/background/ink-vs-solidity.md This is an example of a simple contract written in Solidity, demonstrating state variables, events, constructors, and functions. ```solidity // SPDX-License-Identifier: MIT\npragma solidity ^0.8.1;\n\ncontract MyContract {\n bool private _theBool;\n event UpdatedBool(bool indexed _theBool);\n\n constructor(bool theBool) {\n require(theBool == true, "theBool must start as true");\n\n _theBool = theBool;\n }\n\n function setBool(bool newBool) public returns (bool boolChanged) {\n if (_theBool == newBool) {\n boolChanged = false;\n } else {\n boolChanged = true;\n }\n\n _theBool = newBool;\n\n // emit event\n emit UpdatedBool(newBool);\n }\n} ``` -------------------------------- ### Flipper Contract Example Source: https://github.com/use-ink/ink-docs/blob/master/docs/reference/macros-attributes/message.md An example of a simple Flipper smart contract demonstrating the use of `#[ink(constructor)]` and `#[ink(message)]` for its methods. ```APIDOC ## Flipper Contract Example This example shows a basic ink! smart contract with a constructor and two messages: one for flipping a boolean value and one for retrieving it. ### Contract Definition ```rust #[ink::contract] mod flipper { #[ink(storage)] pub struct Flipper { value: bool, } impl Flipper { #[ink(constructor)] pub fn new(initial_value: bool) -> Self { Flipper { value: false } } /// Flips the current value. #[ink(message)] pub fn flip(&mut self) { self.value = !self.value; } /// Returns the current value. #[ink(message)] pub fn get(&self) -> bool { self.value } } } ``` ``` -------------------------------- ### Run ink-node Source: https://github.com/use-ink/ink-docs/blob/master/docs/development/testing/testing-with-live-state.md Starts a local ink! node for testing purposes. Note the RPC server address and port. ```bash ink-node 2023-09-26 07:58:28.885 INFO main sc_cli::runner: ink! Node 2023-09-26 07:58:28.887 INFO main sc_cli::runner: ✌️ version 0.30.0-124c159ba94 2023-09-26 07:58:28.887 INFO main sc_cli::runner: ❤️ by Parity Technologies , 2021-2023 2023-09-26 07:58:28.887 INFO main sc_cli::runner: 📋 Chain specification: Development 2023-09-26 07:58:28.887 INFO main sc_cli::runner: 🏷 Node name: chilly-desire-6458 2023-09-26 07:58:28.887 INFO main sc_cli::runner: 👤 Role: AUTHORITY 2023-09-26 07:58:28.887 INFO main sc_cli::runner: 💾 Database: ParityDb at /tmp/substrateoKCAts/chains/dev/paritydb/full 2023-09-26 07:58:38.723 INFO main sc_rpc_server: Running JSON-RPC server: addr=127.0.0.1:9944, allowed origins=["*"] ``` -------------------------------- ### MyContract Example Source: https://context7.com/use-ink/ink-docs/llms.txt Demonstrates the basic structure of an ink! contract with a constructor and simple messages for state management. ```APIDOC ## `#[ink(constructor)]` — Contract constructor ### Description Initializes a new instance of the `MyContract` with provided admin and name. ### Method `new` ### Parameters - **admin** (AccountId) - The administrator account. - **name** (String) - The name for the contract. ### Response Example ```json { "example": "MyContract instance" } ``` ``` ```APIDOC ## `#[ink(message)]` — Get count ### Description Retrieves the current value of the `count` state variable. ### Method `get_count` ### Parameters None ### Response Example ```json { "example": "u32" } ``` ``` ```APIDOC ## `#[ink(message)]` — Increment count ### Description Increments the `count` state variable by one. ### Method `increment` ### Parameters None ### Response Example ```json { "example": "None" } ``` ``` -------------------------------- ### Start Forked Node and Replay Transactions Source: https://github.com/use-ink/ink-docs/blob/master/docs/development/debugging/replays.md Start a local fork of your chain from a specific block hash using Chopstick. Connect to the fork to submit extrinsics and observe detailed execution logs. ```bash npx @acala-network/chopsticks@latest \ --endpoint $ENDPOINT \ --block $BLOCK_HASH \ --runtime-log-level 5 ``` ```bash cargo contract call \ --contract $CONTRACT_ADDR \ --message inc_by --args 1 \ --suri //Alice \ --url ws://localhost:8000 ``` ```text runtime::contracts TRACE: call ExportedFunction::Call account: , input_data: [254, 91, 216, 234, 2, 0, 0, 0] runtime::contracts TRACE: call result ExecReturnValue { flags: (empty), data: [0] } runtime::contracts DEBUG: Execution finished with debug buffer: seal0::value_transferred(out_ptr: 65488, out_len_ptr: 65516) = Ok(()) seal0::input(out_ptr: 65536, out_len_ptr: 65524) = Ok(()) seal1::get_storage(key_ptr: 65536, key_len: 4, out_ptr: 65540, out_len_ptr: 65524) = Ok(Success) seal2::set_storage(key_ptr: 65536, key_len: 4, value_ptr: 65540, value_len: 4) = Ok(4) seal0::seal_return(flags: 0, data_ptr: 65536, data_len: 1) = Err(TrapReason::Return(ReturnData { flags: 0, data: [0] })) ``` -------------------------------- ### Flipper Contract Example Source: https://github.com/use-ink/ink-docs/blob/master/docs/reference/macros-attributes/contract.md An example of a simple Flipper smart contract demonstrating the use of #[ink::contract], #[ink(constructor)], and #[ink(message)] attributes, including custom selectors. ```APIDOC ## Flipper Contract This example demonstrates a basic Flipper smart contract. ### Contract Definition ```rust #[ink::contract] mod flipper { #[ink(storage)] pub struct Flipper { value: bool, } impl Flipper { #[ink(constructor)] #[ink(selector = "0xDEADBEEF")] pub fn new(initial_value: bool) -> Self { Flipper { value: false } } /// Flips the current value. #[ink(message)] #[ink(selector = "0xCAFEBABE")] pub fn flip(&mut self) { self.value = !self.value; } /// Returns the current value. #[ink(message, selector = "0xFEEDBEEF")] pub fn get(&self) -> bool { self.value } } } ``` ### Constructors - **`new(initial_value: bool)`**: Initializes the contract. Can be called with a specific selector `0xDEADBEEF`. ### Messages - **`flip(&mut self)`**: Flips the boolean value. Can be called with a specific selector `0xCAFEBABE`. - **`get(&self) -> bool`**: Returns the current boolean value. Can be called with a specific selector `0xFEEDBEEF`. ``` -------------------------------- ### Cargo Contract Call Example Source: https://context7.com/use-ink/ink-docs/llms.txt Example of calling a message on a deployed ink! contract using `cargo-contract`. Demonstrates dry-run execution before a real transaction. ```bash cargo contract call --contract 0x427b4c31ce5cdc19ec19bc9d2fb0e22ba69c84c3 \ --message flip_and_get --suri //Alice --dry-run ``` -------------------------------- ### Start Local ink-node Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/deploying.md Start a local development chain using ink-node. This node is configured with pallet-revive for smart contracts. Note that --dev flag is used by default. ```bash ink-node ``` -------------------------------- ### Instantiating a Contract for Testing Source: https://github.com/use-ink/ink-docs/blob/master/docs/development/testing/unit-integration.md Example of creating a contract instance for testing purposes. The constructor is called as if it returns `Self`. ```rust let contract = MyContract::my_constructor(a, b); ``` -------------------------------- ### Ink! Function Call Example Source: https://github.com/use-ink/ink-docs/blob/master/src/css/ea.html Shows how to call a function with multiple arguments in Ink!. The syntax `(someValue, someOtherValue)` is used for passing arguments. ```rust (someValue, someOtherValue) ``` -------------------------------- ### Configure ink_sandbox Backend for Runtime-Only Testing Source: https://github.com/use-ink/ink-docs/blob/master/ink-llms.txt Swap the backend in `#[ink_sandbox::test]` to use the runtime-only sandbox for E2E-style tests without starting `ink-node`. ```rust #[ink_sandbox::test(backend(runtime_only( sandbox = sandbox_runtime::ContractCallerSandbox, client = ink_sandbox::SandboxClient )))] ``` -------------------------------- ### Flipper Contract with Messages Source: https://github.com/use-ink/ink-docs/blob/master/docs/reference/macros-attributes/message.md Example of a Flipper smart contract demonstrating constructor, a state-modifying message (`flip`), and a read-only message (`get`). ```rust #[ink::contract] mod flipper { #[ink(storage)] pub struct Flipper { value: bool, } impl Flipper { #[ink(constructor)] pub fn new(initial_value: bool) -> Self { Flipper { value: false } } /// Flips the current value. #[ink(message)] pub fn flip(&mut self) { self.value = !self.value; } /// Returns the current value. #[ink(message)] pub fn get(&self) -> bool { self.value } } } ``` -------------------------------- ### Example Contract Using StorageVec for Logging Source: https://github.com/use-ink/ink-docs/blob/master/docs/advanced/datastructures/storagevec.md This contract uses StorageVec to log donations on-chain. It includes functions to add logs, get the log length, and retrieve the last log entry. ```rust #![cfg_attr(not(feature = "std"), no_std, no_main)] #[ink::contract] mod mycontract { use ink::prelude::{format, string::String}; use ink::storage::StorageVec; #[ink(storage)] pub struct MyContract { on_chain_log: StorageVec, } impl MyContract { #[ink(constructor)] pub fn new() -> Self { Self { on_chain_log: Default::default(), } } /// Donate money to the contract. #[ink(message, payable)] pub fn donate(&mut self) { let caller = self.env().caller(); let endowment = self.env().transferred_value(); let log_message = format!( "{caller:?}" donated {endowment}); self.on_chain_log.push(&log_message); } /// How many donations had the contract so far? #[ink(message)] pub fn log_length(&self) -> u32 { self.on_chain_log.len() } /// What was the last donation to the contract? #[ink(message)] pub fn last_donation(&self) -> Option { self.on_chain_log.peek() } } } ``` -------------------------------- ### Navigate to the project directory Source: https://github.com/use-ink/ink-docs/blob/master/docs/basics/contract-template.md Change your current directory to the newly created project folder. ```bash cd foobar/ ``` -------------------------------- ### Build Smart Contract (Pop) Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/compiling.md Use this command to build your smart contract with the 'pop' tool. This generates binary, metadata, and a bundled .contract file. ```bash pop build ``` -------------------------------- ### Example Decoded Output Source: https://github.com/use-ink/ink-docs/blob/master/docs/development/debugging/decoding.md This is an example of the output you can expect after successfully decoding a transaction's data payload. ```text Decoded data: inc_by { n: 1 } ``` -------------------------------- ### Full Example: Calculating Contract Storage Keys Source: https://github.com/use-ink/ink-docs/blob/master/docs/advanced/datastructures/storage-in-metadata.md Demonstrates the complete process of calculating the `PrefixedStorageKey` for a contract's child trie and the hashed key for a storage item. This combined key can be used with RPC calls. ```rust use frame_support::{sp_runtime::AccountId32, Blake2_128Concat, Blake2_256, StorageHasher}; use parity_scale_codec::Encode; use sp_core::{crypto::Ss58Codec, storage::ChildInfo}; use std::ops::Deref; fn main() { // Find the child storage trie ID let account_id = "5DjcHxSfjAgCTSF9mp6wQBJWBgj9h8uh57c7TNx1mL5hdQp4"; let account: AccountId32 = Ss58Codec::from_string(account_id).unwrap(); let instantiation_nonce = 1u64; let trie_id = (account, instantiation_nonce).using_encoded(Blake2_256::hash); assert_eq!( hex::encode(trie_id), "2fa252b7f996d28fd5d8b11098c09e56295eaf564299c6974421aa5ed887803b" ); // Calculate the PrefixedStorageKey based on the trie ID let prefixed_storage_key = ChildInfo::new_default(&trie_id).into_prefixed_storage_key(); println!("0x{}", hex::encode(prefixed_storage_key.deref())); // 0x3a6368696c645f73746f726167653a64656661756c743a2fa252b7f996d28fd5d8b11098c09e56295eaf564299c6974421aa5ed887803b // Calculate the storage key using transparent hashing let storage_key = Blake2_128Concat::hash(&[0, 0, 0, 0]); println!("0x{}", hex::encode(&storage_key)); // 0x11d2df4e979aa105cf552e9544ebd2b500000000 } ``` -------------------------------- ### Build and Deploy with Pop CLI Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/deploying.md Use Pop CLI to build your contract and deploy it. Pop CLI automatically launches a local node if one is not specified. ```bash pop build --release pop up ``` -------------------------------- ### Ink! Event Emission Example Source: https://github.com/use-ink/ink-docs/blob/master/src/css/ea.html Example of emitting an event in Ink!. Ensure the event struct is correctly defined. ```rust emit event.Transferred { from: Some(from), to: Some(to), amount: initial_supply } ``` -------------------------------- ### Chopsticks Node Output Example Source: https://github.com/use-ink/ink-docs/blob/master/docs/development/testing/testing-with-live-state.md Example output indicating that the Chopsticks node is running and listening on port 8000. ```bash npx @acala-network/chopsticks@latest --config=configs/dev.yml [08:22:31.231] INFO (rpc/3037748): Development RPC listening on port 8000 ``` -------------------------------- ### Create New Typink Project Source: https://github.com/use-ink/ink-docs/blob/master/tutorials/frontend-development/typink-erc20.md Use the Typink CLI to create a new project. Follow the interactive prompts to select the contract type and networks. ```bash pnpm create typink@latest ``` -------------------------------- ### Get Contract Address: Solidity vs. Ink! Source: https://github.com/use-ink/ink-docs/blob/master/docs/background/ink-vs-solidity.md Compares how to get the current contract's address in Solidity and Ink!. ```solidity address(this) ``` ```rust self.env().account_id() ``` -------------------------------- ### Docusaurus Admonition Examples Source: https://github.com/use-ink/ink-docs/blob/master/src/pages/components-cheatsheet.mdx Provides examples of different admonition types (note, tip, info, caution, danger) with and without custom titles. ```md :::note The content and title *can* include markdown. ::: :::note Your Title The content and title *can* include markdown. ::: :::tip You can specify an optional title Heads up! Here's a pro-tip. ::: :::info Useful information. ::: :::caution Warning! You better pay attention! ::: :::danger Danger danger, mayday! ::: ``` -------------------------------- ### Manual Root Storage Key in ink! Source: https://github.com/use-ink/ink-docs/blob/master/docs/advanced/datastructures/storage-layout.md Demonstrates setting a custom root storage key for a contract using `ManualKey<0xcafebabe>`. ```rust /// Manually set the root storage key of `MyContract` to be `0xcafebabe`. #[ink(storage)] pub struct MyContract> { value: bool, } ``` -------------------------------- ### Cargo Contract Build and Instantiate Example Source: https://context7.com/use-ink/ink-docs/llms.txt Commands to build an ink! contract and instantiate it on-chain using `cargo-contract`. This includes specifying constructor arguments and a salt. ```bash cargo contract build --release cargo contract instantiate --constructor new \ --args 0xd051d56ffc5077e006d1fdb14a2311276873aa86 \ --suri //Alice --salt $(date +%s) -x ``` -------------------------------- ### Install Linter Dependencies Source: https://github.com/use-ink/ink-docs/blob/master/docs/development/linter/overview.md Installs the required Rust toolchain version and linter crates. This specific nightly toolchain is required due to its use of internal Rust compiler APIs. ```bash export TOOLCHAIN_VERSION=nightly-2025-05-14 rustup install $TOOLCHAIN_VERSION rustup component add rust-src --toolchain $TOOLCHAIN_VERSION rustup run $TOOLCHAIN_VERSION cargo install cargo-dylint dylint-link ``` -------------------------------- ### Deploy with Pop CLI Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/deploying.md Use Pop CLI to deploy your contract to the Passet Hub testnet. Ensure you have PAS tokens in your account before deploying. ```bash pop up --url wss://testnet-passet-hub.polkadot.io ``` -------------------------------- ### Attacker Contract Example Source: https://github.com/use-ink/ink-docs/blob/master/docs/development/linter/rules/strict_balance_equality.md An example of an attacker contract that sends its funds to a target contract upon termination. This demonstrates a scenario where strict balance equality in the target contract can be exploited. ```rust #[ink::contract] pub mod attacker { // ... #[ink(message)] pub fn attack(&mut self, target: &AccountId) { self.env().terminate_contract(target); } } ``` -------------------------------- ### Solidity Mapping Usage Source: https://github.com/use-ink/ink-docs/blob/master/docs/background/ink-vs-solidity.md Demonstrates basic usage of a mapping in Solidity, including inserting/updating a value and retrieving a value. ```c++ // solidity // insert / update aMap[aKey] = aValue; // get aMap[aKey] ``` -------------------------------- ### Deploy and Call Contract with DRink! Session Source: https://github.com/use-ink/ink-docs/blob/master/ink-llms.txt Example of deploying a contract bundle and interacting with it using DRink!'s session API. Requires `#[drink::contract_bundle_provider]` enum. ```rust #[cfg(test)] mod tests { #[drink::contract_bundle_provider] enum BundleProvider {} #[drink::test] fn deploy_and_call(mut session: Session) -> Result<(), Box> { let result: bool = session .deploy_bundle_and(BundleProvider::local(), "new", &["true"], NO_SALT, NO_ENDOWMENT)? .call_and("flip", NO_ARGS, NO_ENDOWMENT)? .call("get", NO_ARGS, NO_ENDOWMENT)??; assert!(!result); Ok(()) } } ``` -------------------------------- ### Flipper Contract Implementation Source: https://github.com/use-ink/ink-docs/blob/master/docs/reference/macros-attributes/contract.md A minimal ink! smart contract example demonstrating basic functionality: initializing a boolean value, flipping it, and retrieving its current state. ```rust @ink::contract] pub mod flipper { #[ink(storage)] pub struct Flipper { value: bool, } impl Flipper { /// Creates a new flipper smart contract initialized with the given value. #[ink(constructor)] pub fn new(init_value: bool) -> Self { Self { value: init_value } } /// Flips the current value of the Flipper's bool. #[ink(message)] pub fn flip(&mut self) { self.value = !self.value; } /// Returns the current value of the Flipper's bool. #[ink(message)] pub fn get(&self) -> bool { self.value } } } ``` -------------------------------- ### Instantiate with cargo-contract Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/deploying.md Connect to Passet Hub and instantiate your contract using cargo-contract. Replace YOUR_SEED_PHRASE with your actual seed phrase and adjust --args true for your constructor arguments. ```bash cargo contract instantiate \ --suri "YOUR_SEED_PHRASE" \ --url wss://testnet-passet-hub.polkadot.io \ --args true ``` -------------------------------- ### Clone Chopsticks Repository Source: https://github.com/use-ink/ink-docs/blob/master/docs/development/testing/testing-with-live-state.md Clone the Chopsticks repository to your local machine to begin setup. ```bash git clone https://github.com/AcalaNetwork/chopsticks ``` -------------------------------- ### Using CreateBuilder::instantiate() Source: https://github.com/use-ink/ink-docs/blob/master/docs/faq/migrating-from-ink-3-to-4.md Shows the method for instantiating contracts, which now returns the result directly and panics on error, replacing previous error handling mechanisms. ```rust CreateBuilder::instantiate() ``` -------------------------------- ### Build Multi-Contract Project Source: https://github.com/use-ink/ink-docs/blob/master/ink-llms.txt Builds a multi-contract project by specifying a relative manifest path to the root contract. Execute this command in the parent directory to ensure all contract directories are mounted. ```bash cargo contract build --verifiable --manifest-path ink-project-a/Cargo.toml ``` -------------------------------- ### Get Contract Balance: Solidity vs. Ink! Source: https://github.com/use-ink/ink-docs/blob/master/docs/background/ink-vs-solidity.md Compares how to retrieve the balance of a contract in Solidity and Ink!. ```solidity address(this).balance ``` ```rust self.env().balance() ``` -------------------------------- ### Get Contract Caller: Solidity vs. Ink! Source: https://github.com/use-ink/ink-docs/blob/master/docs/background/ink-vs-solidity.md Compares how to retrieve the address of the caller in Solidity and Ink!. ```solidity address caller = msg.sender; ``` ```rust let caller: Address = self.env().caller(); ``` -------------------------------- ### Transfer Tokens from Contract: Solidity vs. Ink! Source: https://github.com/use-ink/ink-docs/blob/master/docs/background/ink-vs-solidity.md Shows how to initiate a token transfer from a contract in Solidity and Ink!. ```solidity recipient.send(amount) ``` ```rust if self.env().transfer(recipient, amount).is_err() { panic!("error transferring") } ``` -------------------------------- ### Pop CLI for ink! Contract Deployment Source: https://context7.com/use-ink/ink-docs/llms.txt The Pop CLI simplifies contract deployment by automatically managing a local node. Use `pop build --release` to build the contract and `pop up` to deploy it. It also supports deploying to testnets by specifying the URL. ```bash # Using Pop CLI (auto-manages local node) pop build --release pop up pop up --url wss://testnet-passet-hub.polkadot.io # testnet ``` -------------------------------- ### Make ink-node Binary Executable Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/setup.md After downloading the ink-node binary, make it executable using chmod. This is a necessary step before running the node. ```bash chmod +x ./ink-node ``` -------------------------------- ### Cargo Contract: Read Contract State Source: https://github.com/use-ink/ink-docs/blob/master/docs/getting-started/calling.md Use cargo-contract to call the 'get()' function on a contract. This is a read-only operation. ```bash cargo contract call --contract --message get --suri //Alice ```