• Stars
    star
    1,316
  • Rank 34,291 (Top 0.7 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created over 5 years ago
  • Updated 17 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Parity's ink! to write smart contracts.
ink!

Parity's ink! for writing smart contracts

linux codecov coveralls loc stack-exchange

squink, the ink! mascotink! is an eDSL to write smart contracts in Rust for blockchains built on the Substrate framework. ink! contracts are compiled to WebAssembly.


Guided Tutorial for BeginnersΒ Β β€’Β Β  ink! Documentation PortalΒ Β β€’Β Β  Developer Documentation


More relevant links:

Table of Contents

Play with It

The best way to start is to check out the Getting Started page in our documentation.

If you want to have a local setup you can use our substrate-contracts-node for a quickstart. It's a simple Substrate blockchain which includes the Substrate module for smart contract functionality β€’ the contracts pallet (see How it Works for more).

We also have a live testnet named "Contracts" on Rococo. Rococo is a Substrate based parachain which supports ink! smart contracts. For further instructions on using this testnet, follow the instructions in our documentation.

The Contracts UI can be used to instantiate your contract to a chain and interact with it.

Usage

A prerequisite for compiling smart contracts is to have Rust and Cargo installed. Here's an installation guide.

We recommend installing cargo-contract as well. It's a CLI tool which helps set up and manage WebAssembly smart contracts written with ink!:

cargo install cargo-contract --force

Use the --force to ensure you are updated to the most recent cargo-contract version.

In order to initialize a new ink! project you can use:

cargo contract new flipper

This will create a folder flipper in your work directory. The folder contains a scaffold Cargo.toml and a lib.rs, which both contain the necessary building blocks for using ink!.

The lib.rs contains our hello world contract β€’ the Flipper, which we explain in the next section.

In order to build the contract just execute this command in the flipper folder:

cargo contract build

As a result you'll get a target/flipper.wasm file, a flipper.json file and a <contract-name>.contract file in the target folder of your contract. The .contract file combines the Wasm and metadata into one file and needs to be used when instantiating the contract.

Hello, World! β€’ The Flipper

The Flipper contract is a simple contract containing only a single bool value.

It provides methods to:

  • flip its value from true to false (and vice versa) and
  • return the current state.

Below you can see the code using ink!.

#[ink::contract]
mod flipper {
    /// The storage of the flipper contract.
    #[ink(storage)]
    pub struct Flipper {
        /// The single `bool` value.
        value: bool,
    }

    impl Flipper {
        /// Instantiates a new Flipper contract and initializes
        /// `value` to `init_value`.
        #[ink(constructor)]
        pub fn new(init_value: bool) -> Self {
            Self {
                value: init_value,
            }
        }

        /// Flips `value` from `true` to `false` or vice versa.
        #[ink(message)]
        pub fn flip(&mut self) {
            self.value = !self.value;
        }

        /// Returns the current state of `value`.
        #[ink(message)]
        pub fn get(&self) -> bool {
            self.value
        }
    }

    /// Simply execute `cargo test` in order to test your contract
    /// using the below unit tests.
    #[cfg(test)]
    mod tests {
        use super::*;

        #[ink::test]
        fn it_works() {
            let mut flipper = Flipper::new(false);
            assert_eq!(flipper.get(), false);
            flipper.flip();
            assert_eq!(flipper.get(), true);
        }
    }
}

The flipper/src/lib.rs file in our examples folder contains exactly this code. Run cargo contract build to build your first ink! smart contract.

Examples

In the examples repository you'll find a number of examples written in ink!.

Some of the most interesting ones:

  • basic_contract_ref β€’ Implements cross-contract calling.
  • trait-erc20 β€’ Defines a trait for Erc20 contracts and implements it.
  • erc721 β€’ An exemplary implementation of Erc721 NFT tokens.
  • dns β€’ A simple DomainNameService smart contract.
  • …and more, just rummage through the folder πŸ™ƒ.

To build a single example navigate to the root of the example and run:

cargo contract build

You should now have an <name>.contract file in the target folder of the contract.

For information on how to upload this file to a chain, please have a look at the Play with It section or our smart contracts workshop.

How it Works

  • Substrate's Framework for Runtime Aggregation of Modularized Entities (FRAME) contains a module which implements an API for typical functions smart contracts need (storage,querying information about accounts, …). This module is called the contracts pallet,
  • The contracts pallet requires smart contracts to be uploaded to the blockchain as a Wasm blob.
  • ink! is a smart contract language which targets the API exposed by contracts. Hence ink! contracts are compiled to Wasm.
  • When executing cargo contract build an additional file <contract-name>.json is created. It contains information about e.g. what methods the contract provides for others to call.

ink! Macros & Attributes Overview

Entry Point

In a module annotated with #[ink::contract] these attributes are available:

Attribute Where Applicable Description
#[ink(storage)] On struct definitions. Defines the ink! storage struct. There can only be one ink! storage definition per contract.
#[ink(message)] Applicable to methods. Flags a method for the ink! storage struct as message making it available to the API for calling the contract.
#[ink(constructor)] Applicable to method. Flags a method for the ink! storage struct as constructor making it available to the API for instantiating the contract.
#[ink(event)] On struct definitions. Defines an ink! event. A contract can define multiple such ink! events.
#[ink(anonymous)] Applicable to ink! events. Tells the ink! codegen to treat the ink! event as anonymous which omits the event signature as topic upon emitting. Very similar to anonymous events in Solidity.
#[ink(signature_topic = _)] Applicable to ink! events. Specifies custom signature topic of the event that allows to use manually specify shared event definition.
#[ink(topic)] Applicable on ink! event field. Tells the ink! codegen to provide a topic hash for the given field. Every ink! event can only have a limited number of such topic fields. Similar semantics as to indexed event arguments in Solidity.
#[ink(payable)] Applicable to ink! messages. Allows receiving value as part of the call of the ink! message. ink! constructors are implicitly payable.
#[ink(selector = S:u32)] Applicable to ink! messages and ink! constructors. Specifies a concrete dispatch selector for the flagged entity. This allows a contract author to precisely control the selectors of their APIs making it possible to rename their API without breakage.
#[ink(selector = _)] Applicable to ink! messages. Specifies a fallback message that is invoked if no other ink! message matches a selector.
#[ink(namespace = N:string)] Applicable to ink! trait implementation blocks. Changes the resulting selectors of all the ink! messages and ink! constructors within the trait implementation. Allows to disambiguate between trait implementations with overlapping message or constructor names. Use only with great care and consideration!
#[ink(impl)] Applicable to ink! implementation blocks. Tells the ink! codegen that some implementation block shall be granted access to ink! internals even without it containing any ink! messages or ink! constructors.

See here for a more detailed description of those and also for details on the #[ink::contract] macro.

Trait Definitions

Use #[ink::trait_definition] to define your very own trait definitions that are then implementable by ink! smart contracts. See e.g. the examples/trait-erc20 contract on how to utilize it or the documentation for details.

Off-chain Testing

The #[ink::test] procedural macro enables off-chain testing. See e.g. the examples/erc20 contract on how to utilize those or the documentation for details.

Developer Documentation

We have a very comprehensive documentation portal, but if you are looking for the crate level documentation itself, then these are the relevant links:

Crate Docs Description
ink Language features exposed by ink!. See here for a detailed description of attributes which you can use in an #[ink::contract].
ink_storage Data structures available in ink!.
ink_env Low-level interface for interacting with the smart contract Wasm executor. Contains the off-chain testing API as well.
ink_prelude Common API for no_std and std to access alloc crate types.

Community Badges

Normal Design

Built with ink!

[![Built with ink!](https://raw.githubusercontent.com/paritytech/ink/master/.images/badge.svg)](https://github.com/paritytech/ink)

Flat Design

Built with ink!

[![Built with ink!](https://raw.githubusercontent.com/paritytech/ink/master/.images/badge_flat.svg)](https://github.com/paritytech/ink)

Contributing

Visit our contribution guidelines for more information.

Use the scripts provided under scripts/check-* directory in order to run checks on either the workspace or all examples. Please do this before pushing work in a PR.

License

The entire code within this repository is licensed under the Apache License 2.0.

Please contact us if you have questions about the licensing of our products.

More Repositories

1

substrate

Substrate: The platform for blockchain innovators
Rust
8,212
star
2

polkadot

Polkadot Node Implementation
Rust
6,865
star
3

wasmi

WebAssembly (Wasm) interpreter.
Rust
1,269
star
4

polkadot-sdk

The Parity Polkadot Blockchain SDK
Rust
979
star
5

jsonrpc

Rust JSON-RPC implementation
Rust
752
star
6

parity-bitcoin

The Parity Bitcoin client
Rust
725
star
7

cumulus

Write Parachains on Substrate
Rust
618
star
8

parity-signer

Air-gapped crypto wallet.
Rust
539
star
9

frontier

Ethereum compatibility layer for Substrate.
Rust
496
star
10

polkadot-launch

Simple CLI tool to launch a local Polkadot test network
TypeScript
458
star
11

jsonrpsee

Rust JSON-RPC library on top of async/await
Rust
457
star
12

parity-wasm

WebAssembly serialization/deserialization in rust
Rust
395
star
13

subxt

Submit extrinsics (transactions) to a substrate node via RPC
Rust
317
star
14

parity-bridge

Rust
317
star
15

smoldot

Alternative client for Substrate-based chains.
Rust
286
star
16

parity-common

Collection of crates used in Parity projects
Rust
274
star
17

substrate-telemetry

Polkadot Telemetry service
Rust
268
star
18

parity-bridges-common

Collection of Useful Bridge Building Tools πŸ—οΈ
Rust
265
star
19

parity-db

Experimental blockchain database
Rust
245
star
20

banana_split

Shamir's Secret Sharing for people with friends
TypeScript
241
star
21

parity-scale-codec

Lightweight, efficient, binary serialization and deserialization codec
Rust
238
star
22

cargo-contract

Setup and deployment tool for developing Wasm based smart contracts via ink!
Rust
226
star
23

substrate-api-sidecar

REST service that makes it easy to interact with blockchain nodes built using Substrate's FRAME framework.
TypeScript
226
star
24

substrate-connect

Run Wasm Light Clients of any Substrate based chain directly in your browser.
TypeScript
217
star
25

trie

Base-16 Modified Patricia Merkle Tree (aka Trie)
Rust
201
star
26

substrate-archive

Blockchain Indexing Engine
Rust
197
star
27

shasper

Parity Shasper beacon chain implementation using the Substrate framework.
Rust
196
star
28

parity-zcash

Rust implementation of Zcash protocol
Rust
183
star
29

cachepot

cachepot is `sccache` with extra sec, which in turn is `ccache` with cloud storage
Rust
174
star
30

libsecp256k1

Pure Rust Implementation of secp256k1.
Rust
166
star
31

homebrew-paritytech

Homebrew tap for ethcore
Ruby
160
star
32

zombienet

A cli tool to easily spawn ephemeral Polkadot/Substrate networks and perform tests against them.
TypeScript
147
star
33

polkadot-staking-dashboard

A dashboard for Polkadot staking, nomination pools, and everything around it.
TypeScript
146
star
34

xcm-format

Polkadot Cross Consensus-system Message format.
143
star
35

finality-grandpa

finality gadget for blockchains using common prefix agreement
Rust
139
star
36

substrate-contracts-node

Minimal Substrate node configured for smart contracts via pallet-contracts.
Rust
109
star
37

capi

[WIP] A framework for crafting interactions with Substrate chains
TypeScript
105
star
38

grandpa-bridge-gadget

A Bridge Gadget to Grandpa Finality.
Rust
99
star
39

substrate-debug-kit

A collection of debug tools, scripts and libraries on top of substrate.
Rust
95
star
40

ink-examples

A set of examples for ink! smart contract language. Happy hacking!
Rust
89
star
41

wasm-utils

Rust
82
star
42

subport

Parity Substrate(-based) chains usage and development support
Rust
81
star
43

trappist

Rust
80
star
44

substrate-playground

Start hacking your substrate runtime in a web based VSCode like IDE
TypeScript
74
star
45

scale-info

Info about SCALE encodable Rust types
Rust
72
star
46

substrate-light-ui

Minimal, WASM-light-client-bundled Substrate wallet for balance transfers
TypeScript
72
star
47

substrate-ui

Bondy Polkadot UI
JavaScript
72
star
48

statemint

Statemint Node Implementation
Rust
72
star
49

parity-tokio-ipc

Parity tokio-ipc
Rust
71
star
50

txwrapper-core

Tools for FRAME chain builders to publish chain specific offline transaction generation libraries.
TypeScript
71
star
51

canvas

Node implementation for Canvas β€’ a Substrate parachain for smart contracts.
Rust
70
star
52

substrate-up

Scripts for working with new Substrate projects
Shell
66
star
53

useink

A React hooks library for ink!
TypeScript
62
star
54

stateless-blockchain

Stateless Blockchain on Substrate using RSA Accumulators
Rust
60
star
55

txwrapper

Helper funtions for offline transaction generation.
TypeScript
59
star
56

contracts-ui

Web application for deploying wasm smart contracts on Substrate chains that include the FRAME contracts pallet
TypeScript
58
star
57

awesome-ink

A curated list of awesome projects related to Parity's ink!.
56
star
58

srtool

A fork of chevdor's srtool
Shell
56
star
59

cargo-unleash

cargo release automatisation tooling for massiv mono-repos
Rust
55
star
60

ss58-registry

Registry for SS58 account types
Rust
54
star
61

oo7

The Bonds framework along with associated modules.
JavaScript
53
star
62

diener

Diener - dependency diener is a tool for easily changing https://github.com/paritytech/substrate or https://github.com/paritytech/polkadot dependency versions
Rust
52
star
63

lunarity

Lunarity - a Solidity parser in Rust
Rust
50
star
64

nohash-hasher

An implementation of `std :: hash :: Hasher` which does not hash at all.
Rust
49
star
65

arkworks-extensions

Library to integrate arkworks-rs/algebra into Substrate
Rust
44
star
66

wasm-instrument

Instrument and transform wasm modules.
Rust
42
star
67

fleetwood

Testbed repo for trying out ideas of what a smart contract API in Rust would look like
Rust
41
star
68

scripts

Collection of Dockerfiles, scripts and related resources
Dockerfile
41
star
69

trappist-extra

Dart
38
star
70

parity-extension

Parity Chrome Extension
JavaScript
37
star
71

rhododendron

Asynchronously safe BFT consensus, implementation in Rust
Rust
36
star
72

desub

Decode Substrate with Backwards-Compatible Metadata
Rust
36
star
73

ethkey

Ethereum key generator
Rust
35
star
74

asset-transfer-api

Typescript API aiming to provide clear, and simple to use tools for transferring assets across common good parachains.
TypeScript
35
star
75

substrate-bip39

Rust
34
star
76

primitives

Rust
34
star
77

parity-config-generator

Parity Config Generator
JavaScript
34
star
78

polkadot-introspector

A collection of tools focused on debugging and monitoring the relay chain and parachain progress from a 🐦-view
Rust
34
star
79

substrate-open-working-groups

The Susbstrate Open Working Groups (SOWG) are community-based mechanisms to develop standards, specifications, implementations, guidelines or general initiatives in regards to the Substrate framework. It could, but not restricted to, lead to new Polkadot Standards Proposals. SOWG is meant as a place to find and track ongoing efforts and enable everybody with similar interests to join and contribute.
34
star
80

Nomidot

Staking Portal for Polkadot and Kusama
TypeScript
32
star
81

subdb

Experimental domain-specific database for Substrate
Rust
32
star
82

polkadot-api

TypeScript
31
star
83

polkassembly

Polkassembly now has a new home:
TypeScript
30
star
84

pallet-contracts-waterfall

Collection of simple Substrate smart contract examples written in Rust, AssemblyScript, Solang and the smart contract language ink! to test substrates pallet-contracts module
TypeScript
30
star
85

vscode-substrate

Substrate Marketplace VSCode Plugin
TypeScript
28
star
86

oo7-bare

The Bond API.
JavaScript
27
star
87

metadata-portal

Metadata portal for Parity Signer
TypeScript
27
star
88

bigint

Rust
27
star
89

sub-flood

Flooding substrate node with transactions
TypeScript
26
star
90

polkadot-scripts

Collection of random scripts and utilities written for Polkadot
TypeScript
26
star
91

polkadot-cloud

[BETA] A library and automated platform for developing and publishing assets for Polkadot dapps.
TypeScript
25
star
92

ink-playground

Browser Based Playground for editing, sharing & compiling ink! Smart Contracts
Rust
25
star
93

sms-verification

SMS verification for Parity.
JavaScript
25
star
94

link

Unstoppable URL shortener built with the ink! smart contract language.
TypeScript
25
star
95

parachains-integration-tests

Tool to make Parachains integrations tests development easier and faster
TypeScript
25
star
96

extended-parachain-template

Node template to build parachains with all the required pallets. Slightly opinionated based on what majority of parachain teams are using.
Rust
25
star
97

orchestra

A partial actor pattern with a global orchestrator.
Rust
25
star
98

zombienet-sdk

ZombieNet SDK
Rust
25
star
99

polkadot-onboard

A wallet integration SDK to facilitate adding different type of wallets (extension, WC, Ledger) to Dapps.
TypeScript
24
star
100

frame-metadata

A set of tools to parse FRAME metadata retrieved from Substrate-based nodes.
Rust
24
star