PageSourceSearch

https://use.ink/assets/js/f115fbba.79c6237f.js

js use.ink collected 2026-10-03 21:45:58 UTC 20,458 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunkink_docs=self.webpackChunkink_docs||[]).push([[5065],{65404:(e,n,t)=>{t.d(n,{R:()=>a,x:()=>l});var s=t(36672);const i={},r=s.createContext(i);function a(e){const n=s.useContext(r);return s.useMemo(function(){return"function"==typeof e?e(n):{...n,...e}},[n,e])}function l(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(i):e.components||i:a(e.components),s.createElement(r.Provider,{value:n},e.children)}},91334:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>l,default:()=>u,frontMatter:()=>a,metadata:()=>s,toc:()=>o});const s=JSON.parse('{"id":"macros-attributes/contract","title":"#[ink::contract]","description":"This macro is the entry point for writing ink! smart contracts.","source":"@site/versioned_docs/version-v3/macros-attributes/contract.md","sourceDirName":"macros-attributes","slug":"/macros-attributes/contract","permalink":"/docs/v3/macros-attributes/contract","draft":false,"unlisted":false,"editUrl":"https://github.com/use-ink/ink-docs/edit/master/versioned_docs/version-v3/macros-attributes/contract.md","tags":[],"version":"v3","frontMatter":{"title":"#[ink::contract]","slug":"/macros-attributes/contract"},"sidebar":"reference","previous":{"title":"Overview","permalink":"/docs/v3/macros-attributes"},"next":{"title":"#[ink(anonymous)]","permalink":"/docs/v3/macros-attributes/anonymous"}}');var i=t(23420),r=t(65404);const a={title:"#[ink::contract]",slug:"/macros-attributes/contract"},l="Description",c={},o=[{value:"Header Arguments",id:"header-arguments",level:2},{value:"<code>compile_as_dependency: bool</code>",id:"compile_as_dependency-bool",level:3},{value:"<code>env: impl Environment</code>",id:"env-impl-environment",level:3},{value:"Analysis",id:"analysis",level:2},{value:"Interacting with the Contract Executor",id:"interacting-with-the-contract-executor",level:2},{value:"Events",id:"events",level:2},{value:"Example: Flipper",id:"example-flipper",level:2}];function d(e){const n={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",li:"li",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,r.R)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(n.p,{children:"This macro is the entry point for writing ink! smart contracts."}),"\n",(0,i.jsxs)(n.p,{children:["If you are a beginner trying to learn ink! we recommend you to check out\nour extensive ",(0,i.jsx)(n.a,{href:"https://docs.substrate.io/tutorials/smart-contracts/",children:"ink! workshop"}),"."]}),"\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.strong,{children:"Note:"})," In all below examples we will be using ",(0,i.jsx)(n.code,{children:"ink_lang"})," crate aliased as just ",(0,i.jsx)(n.code,{children:"ink"}),".\nYou can do this yourself by adding the following line to your code:\n",(0,i.jsx)(n.code,{children:"use ink_lang as ink;"})]}),"\n",(0,i.jsx)(n.header,{children:(0,i.jsx)(n.h1,{id:"description",children:"Description"})}),"\n",(0,i.jsx)(n.p,{children:"The macro does analysis on the provided smart contract code and generates\nproper code."}),"\n",(0,i.jsx)(n.p,{children:"ink! smart contracts can compile in several different modes.\nThere are two main compilation modes using either"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:["on-chain mode: ",(0,i.jsx)(n.code,{children:"no_std"})," + WebAssembly as target"]}),"\n",(0,i.jsxs)(n.li,{children:["off-chain mode: ",(0,i.jsx)(n.code,{children:"std"})]}),"\n"]}),"\n",(0,i.jsxs)(n.p,{children:["We generally use the on-chain mode for actual smart contract deployment\nwhereas we use the off-chain mode for smart contract testing using the\noff-chain environment provided by the ",(0,i.jsx)(n.code,{children:"ink_env"})," crate."]}),"\n",(0,i.jsx)(n.h1,{id:"usage",children:"Usage"}),"\n",(0,i.jsx)(n.h2,{id:"header-arguments",children:"Header Arguments"}),"\n",(0,i.jsxs)(n.p,{children:["The ",(0,i.jsx)(n.code,{children:"#[ink::contract]"})," macro can be provided with some additional comma-separated\nheader arguments:"]}),"\n",(0,i.jsx)(n.h3,{id:"compile_as_dependency-bool",children:(0,i.jsx)(n.code,{children:"compile_as_dependency: bool"})}),"\n",(0,i.jsxs)(n.p,{children:["Tells the ink! code generator to ",(0,i.jsx)(n.strong,{children:"always"})," or ",(0,i.jsx)(n.strong,{children:"never"}),"\ncompile the smart contract as if it was used as a dependency of another ink!\nsmart contract."]}),"\n",(0,i.jsx)(n.p,{children:"Normally this flag is only really useful for ink! developers who\nwant to inspect code generation of ink! smart contracts.\nThe author is not aware of any particular practical use case for users that\nmakes use of this flag but contract writers are encouraged to disprove this."}),"\n",(0,i.jsxs)(n.p,{children:["Note that it is recommended to make use of the built-in crate feature\n",(0,i.jsx)(n.code,{children:"ink-as-dependency"})," to flag smart contract dependencies listed in a contract's\n",(0,i.jsx)(n.code,{children:"Cargo.toml"})," as actual dependencies to ink!."]}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.strong,{children:"Usage Example:"})}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"use ink_lang as ink;\n\n#[ink::contract(compile_as_dependency = true)]\nmod my_contract {\n    #[ink(storage)]\n    pub struct MyStorage;\n\n    impl MyStorage {\n        #[ink(constructor)]\n        pub fn construct() -> Self { MyStorage {} }\n\n        #[ink(message)]\n        pub fn message(&self) {}\n    }\n    // ...\n}\n"})}),"\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.strong,{children:"Default value:"})," Depends on the crate feature propagation of ",(0,i.jsx)(n.code,{children:"Cargo.toml"}),"."]}),"\n",(0,i.jsx)(n.h3,{id:"env-impl-environment",children:(0,i.jsx)(n.code,{children:"env: impl Environment"})}),"\n",(0,i.jsxs)(n.p,{children:["Tells the ink! code generator which environment to use for the ink! smart contract.\nThe environment must implement the ",(0,i.jsx)(n.code,{children:"Environment"})," (defined in ",(0,i.jsx)(n.code,{children:"ink_env"}),") trait and provides\nall the necessary fundamental type definitions for ",(0,i.jsx)(n.code,{children:"Balance"}),", ",(0,i.jsx)(n.code,{children:"AccountId"})," etc."]}),"\n",(0,i.jsxs)(n.p,{children:["When using a custom ",(0,i.jsx)(n.code,{children:"Environment"})," implementation for a smart contract all types\nthat it exposes to the ink! smart contract and the mirrored types used in the runtime\nmust be aligned with respect to SCALE encoding and semantics."]}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.strong,{children:"Usage Example:"})}),"\n",(0,i.jsxs)(n.p,{children:["Given a custom ",(0,i.jsx)(n.code,{children:"Environment"})," implementation:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub struct MyEnvironment;\n\nimpl ink_env::Environment for MyEnvironment {\n    const MAX_EVENT_TOPICS: usize = 3;\n\n    type AccountId = u64;\n    type Balance = u128;\n    type Hash = [u8; 32];\n    type Timestamp = u64;\n    type BlockNumber = u32;\n    type ChainExtension = ::ink_env::NoChainExtension;\n}\n"})}),"\n",(0,i.jsxs)(n.p,{children:["A user might implement their ink! smart contract using the above custom ",(0,i.jsx)(n.code,{children:"Environment"}),"\nimplementation as demonstrated below:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"use ink_lang as ink;\n#[ink::contract(env = MyEnvironment)]\nmod my_contract {\n    pub struct MyEnvironment;\n\n    impl ink_env::Environment for MyEnvironment {\n        const MAX_EVENT_TOPICS: usize = 3;\n        type AccountId = u64;\n        type Balance = u128;\n        type Hash = [u8; 32];\n        type Timestamp = u64;\n        type BlockNumber = u32;\n        type ChainExtension = ::ink_env::NoChainExtension;\n    }\n\n    #[ink(storage)]\n    pub struct MyStorage;\n\n    impl MyStorage {\n        #[ink(constructor)]\n        pub fn construct() -> Self { MyStorage {} }\n\n        #[ink(message)]\n        pub fn message(&self) {}\n    }\n    // ...\n}\n"})}),"\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.strong,{children:"Default value:"})," ",(0,i.jsx)(n.code,{children:"DefaultEnvironment"})," defined in ",(0,i.jsx)(n.code,{children:"ink_env"})," crate."]}),"\n",(0,i.jsx)(n.h2,{id:"analysis",children:"Analysis"}),"\n",(0,i.jsxs)(n.p,{children:["The ",(0,i.jsx)(n.code,{children:"#[ink::contract]"})," macro fully analyses its input smart contract\nagainst invalid arguments and structure."]}),"\n",(0,i.jsx)(n.p,{children:"Some example rules include but are not limited to:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:["\n",(0,i.jsxs)(n.p,{children:["There must be exactly one ",(0,i.jsx)(n.code,{children:"#[ink(storage)]"})," struct."]}),"\n",(0,i.jsx)(n.p,{children:"This struct defines the layout of the storage that the ink! smart contract operates on.\nThe user is able to use a variety of built-in facilities, combine them in various ways\nor even provide their own implementations of storage data structures."}),"\n",(0,i.jsxs)(n.p,{children:["For more information visit the ",(0,i.jsx)(n.code,{children:"ink_storage"})," crate documentation."]}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.strong,{children:"Example:"})}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"use ink_lang as ink;\n\n#[ink::contract]\nmod flipper {\n    #[ink(storage)]\n    pub struct Flipper {\n        value: bool,\n    }\n\n    impl Flipper {\n        #[ink(constructor)]\n        pub fn construct() -> Self { Flipper { value: false } }\n\n        #[ink(message)]\n        pub fn message(&self) {}\n    }\n}\n"})}),"\n"]}),"\n",(0,i.jsxs)(n.li,{children:["\n",(0,i.jsxs)(n.p,{children:["There must be at least one ",(0,i.jsx)(n.code,{children:"#[ink(constructor)]"})," defined method."]}),"\n",(0,i.jsxs)(n.p,{children:["Methods flagged with ",(0,i.jsx)(n.code,{children:"#[ink(constructor)]"})," are special in that they are dispatchable\nupon contract instantiation. A contract may define multiple such constructors which\nallow users of the contract to instantiate a contract in multiple different ways."]}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.strong,{children:"Example:"})}),"\n",(0,i.jsxs)(n.p,{children:["Given the ",(0,i.jsx)(n.code,{children:"Flipper"})," contract definition above we add an ",(0,i.jsx)(n.code,{children:"#[ink(constructor)]"}),"\nas follows:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"use ink_lang as ink;\n\n#[ink::contract]\nmod flipper {\n    #[ink(storage)]\n    pub struct Flipper {\n        value: bool,\n    }\n\n    impl Flipper {\n        #[ink(constructor)]\n        pub fn new(initial_value: bool) -> Self {\n            Flipper { value: false }\n        }\n\n        #[ink(message)]\n        pub fn message(&self) {}\n    }\n}\n"})}),"\n"]}),"\n",(0,i.jsxs)(n.li,{children:["\n",(0,i.jsxs)(n.p,{children:["There must be at least one ",(0,i.jsx)(n.code,{children:"#[ink(message)]"})," defined method."]}),"\n",(0,i.jsxs)(n.p,{children:["Methods flagged with ",(0,i.jsx)(n.code,{children:"#[ink(message)]"})," are special in that they are dispatchable\nupon contract invocation. The set of ink! messages defined for an ink! smart contract\ndefine its API surface with which users are allowed to interact."]}),"\n",(0,i.jsx)(n.p,{children:"An ink! smart contract can have multiple such ink! messages defined."}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.strong,{children:"Note:"})}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:["An ink! message with a ",(0,i.jsx)(n.code,{children:"&self"})," receiver may only read state whereas an ink! message\nwith a ",(0,i.jsx)(n.code,{children:"&mut self"})," receiver may mutate the contract's storage."]}),"\n"]}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.strong,{children:"Example:"})}),"\n",(0,i.jsxs)(n.p,{children:["Given the ",(0,i.jsx)(n.code,{children:"Flipper"})," contract definition above we add some ",(0,i.jsx)(n.code,{children:"#[ink(message)]"})," definitions\nas follows:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"use ink_lang as ink;\n\n#[ink::contract]\nmod flipper {\n    #[ink(storage)]\n    pub struct Flipper {\n        value: bool,\n    }\n\n    impl Flipper {\n        #[ink(constructor)]\n        pub fn new(initial_value: bool) -> Self {\n            Flipper { value: false }\n        }\n\n        /// Flips the current value.\n        #[ink(message)]\n        pub fn flip(&mut self) {\n            self.value = !self.value;\n        }\n\n        /// Returns the current value.\n        #[ink(message)]\n        pub fn get(&self) -> bool {\n            self.value\n        }\n    }\n}\n"})}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.strong,{children:"Payable Messages:"})}),"\n",(0,i.jsxs)(n.p,{children:["An ink! message by default will reject calls that additional fund the smart contract.\nAuthors of ink! smart contracts can make an ink! message payable by adding the ",(0,i.jsx)(n.code,{children:"payable"}),"\nflag to it. An example below:"]}),"\n",(0,i.jsx)(n.p,{children:"Note that ink! constructors are always implicitly payable and thus cannot be flagged\nas such."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"use ink_lang as ink;\n\n#[ink::contract]\nmod flipper {\n    #[ink(storage)]\n    pub struct Flipper {\n        value: bool,\n    }\n\n    impl Flipper {\n        #[ink(constructor)]\n        pub fn new(initial_value: bool) -> Self {\n            Flipper { value: false }\n        }\n\n        /// Flips the current value.\n        #[ink(message)]\n        #[ink(payable)] // You can either specify payable out-of-line.\n        pub fn flip(&mut self) {\n            self.value = !self.value;\n        }\n\n        /// Returns the current value.\n        #[ink(message, payable)] // ...or specify payable inline.\n        pub fn get(&self) -> bool {\n            self.value\n        }\n    }\n}\n"})}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.strong,{children:"Controlling the messages selector:"})}),"\n",(0,i.jsx)(n.p,{children:"Every ink! message and ink! constructor has a unique selector with which the\nmessage or constructor can be uniquely identified within the ink! smart contract.\nThese selectors are mainly used to drive the contract's dispatch upon calling it."}),"\n",(0,i.jsxs)(n.p,{children:["An ink! smart contract author can control the selector of an ink! message or ink!\nconstructor using the ",(0,i.jsx)(n.code,{children:"selector"})," flag. An example is shown below:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'use ink_lang as ink;\n\n#[ink::contract]\nmod flipper {\n    #[ink(storage)]\n    pub struct Flipper {\n        value: bool,\n    }\n\n    impl Flipper {\n        #[ink(constructor)]\n        #[ink(selector = "0xDEADBEEF")] // Works on constructors as well.\n        pub fn new(initial_value: bool) -> Self {\n            Flipper { value: false }\n        }\n\n        /// Flips the current value.\n        #[ink(message)]\n        #[ink(selector = "0xCAFEBABE")] // You can either specify selector out-of-line.\n        pub fn flip(&mut self) {\n            self.value = !self.value;\n        }\n\n        /// Returns the current value.\n        #[ink(message, selector = "0xFEEDBEEF")] // ...or specify selector inline.\n        pub fn get(&self) -> bool {\n            self.value\n        }\n    }\n}\n'})}),"\n"]}),"\n"]}),"\n",(0,i.jsx)(n.h2,{id:"interacting-with-the-contract-executor",children:"Interacting with the Contract Executor"}),"\n",(0,i.jsxs)(n.p,{children:["The ",(0,i.jsx)(n.code,{children:"ink_env"})," crate provides facilities to interact with the contract executor that\nconnects ink! smart contracts with the outer world."]}),"\n",(0,i.jsx)(n.p,{children:"For example it is possible to query the current call's caller via:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"use ink_env;\nink_env::test::run_test::<ink_env::DefaultEnvironment, _>
1(|_| {\n    let caller = ink_env::caller::<ink_env::DefaultEnvironment>();\n    let _caller = caller;\n    Ok(())\n}).unwrap();\n"})}),"\n",(0,i.jsx)(n.p,{children:"However, ink! provides a much simpler way to interact with the contract executor\nvia its environment accessor. An example below:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'use ink_lang as ink;\n\n#[ink::contract]\nmod greeter {\n    #[ink(storage)]\n    pub struct Greeter;\n\n    impl Greeter {\n        #[ink(constructor)]\n        pub fn new() -> Self {\n            let caller = Self::env().caller();\n            let message = format!("thanks for instantiation {:?}", caller);\n            ink_env::debug_println(&message);\n            Greeter {}\n        }\n\n        #[ink(message, payable)]\n        pub fn fund(&mut self) {\n            let caller = self.env().caller();\n            let value = self.env().transferred_balance();\n            let message = format!("thanks for the funding of {:?} from {:?}", value, caller);\n            ink_env::debug_println(&message);\n        }\n    }\n}\n'})}),"\n",(0,i.jsx)(n.h2,{id:"events",children:"Events"}),"\n",(0,i.jsx)(n.p,{children:"An ink! smart contract may define events that it can emit during contract execution.\nEmitting events can be used by third party tools to query information about a contract's\nexecution and state."}),"\n",(0,i.jsxs)(n.p,{children:["The following example ink! contract shows how an event ",(0,i.jsx)(n.code,{children:"Transferred"})," is defined and\nemitted in the ",(0,i.jsx)(n.code,{children:"#[ink(constructor)]"}),"."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:" use ink_lang as ink;\n\n #[ink::contract]\n mod erc20 {\n     /// Defines an event that is emitted every time value is transferred.\n     #[ink(event)]\n     pub struct Transferred {\n         from: Option<AccountId>,\n         to: Option<AccountId>,\n         value: Balance,\n     }\n\n     #[ink(storage)]\n     pub struct Erc20 {\n         total_supply: Balance,\n         // more fields ...\n     }\n\n     impl Erc20 {\n         #[ink(constructor)]\n         pub fn new(initial_supply: Balance) -> Self {\n             let caller = Self::env().caller();\n             Self::env().emit_event(Transferred {\n                 from: None,\n                 to: Some(caller),\n                 value: initial_supply,\n             });\n             Self { total_supply: initial_supply }\n         }\n\n         #[ink(message)]\n         pub fn total_supply(&self) -> Balance {\n             self.total_supply\n         }\n     }\n }\n"})}),"\n",(0,i.jsx)(n.h2,{id:"example-flipper",children:"Example: Flipper"}),"\n",(0,i.jsx)(n.p,{children:'The below code shows the complete implementation of the so-called Flipper\nink! smart contract.\nFor us it acts as the "Hello, World!" of the ink! smart contracts because\nit is minimal while still providing some more or less useful functionality.'}),"\n",(0,i.jsxs)(n.p,{children:["It controls a single ",(0,i.jsx)(n.code,{children:"bool"})," value that can be either ",(0,i.jsx)(n.code,{children:"false"})," or ",(0,i.jsx)(n.code,{children:"true"}),"\nand allows the user to flip this value using the ",(0,i.jsx)(n.code,{children:"Flipper::flip"})," message\nor retrieve the current value using ",(0,i.jsx)(n.code,{children:"Flipper::get"}),"."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"use ink_lang as ink;\n\n#[ink::contract]\npub mod flipper {\n    #[ink(storage)]\n    pub struct Flipper {\n        value: bool,\n    }\n\n    impl Flipper {\n        /// Creates a new flipper smart contract initialized with the given value.\n        #[ink(constructor)]\n        pub fn new(init_value: bool) -> Self {\n            Self { value: init_value }\n        }\n\n        /// Flips the current value of the Flipper's bool.\n        #[ink(message)]\n        pub fn flip(&mut self) {\n            self.value = !self.value;\n        }\n\n        /// Returns the current value of the Flipper's bool.\n        #[ink(message)]\n        pub fn get(&self) -> bool {\n            self.value\n        }\n    }\n}\n"})})]})}function u(e={}){const{wrapper:n}={...(0,r.R)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(d,{...e})}):d(e)}}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.