├── rust-toolchain ├── .cargo └── config ├── .gitignore ├── Cargo.toml ├── src └── lib.rs ├── LICENSE └── README.md /rust-toolchain: -------------------------------------------------------------------------------- 1 | nightly-2019-04-20 -------------------------------------------------------------------------------- /.cargo/config: -------------------------------------------------------------------------------- 1 | [target.wasm32-unknown-unknown] 2 | rustflags = [ 3 | "-C", "overflow-checks=on", 4 | "-C", "link-args=-z stack-size=65536 --import-memory" 5 | ] -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore build artifacts from the local tests sub-crate. 2 | /target/ 3 | 4 | # Ignore backup files creates by cargo fmt. 5 | **/*.rs.bk 6 | 7 | # Remove Cargo.lock when creating an executable, leave it for libraries 8 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 9 | Cargo.lock 10 | 11 | .DS_Store -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "nftoken" 3 | version = "0.1.0" 4 | authors = ["[your_name] <[your_email]>"] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | ink_core = { git = "https://github.com/paritytech/ink", package = "ink_core" } 9 | ink_model = { git = "https://github.com/paritytech/ink", package = "ink_model" } 10 | ink_lang = { git = "https://github.com/paritytech/ink", package = "ink_lang" } 11 | parity-codec = { version = "3.3", default-features = false, features = ["derive"] } 12 | 13 | [lib] 14 | name = "nftoken" 15 | crate-type = ["cdylib"] 16 | 17 | [features] 18 | default = [] 19 | test-env = [ 20 | "ink_core/test-env", 21 | "ink_model/test-env", 22 | "ink_lang/test-env", 23 | ] 24 | generate-api-description = [ 25 | "ink_lang/generate-api-description" 26 | ] 27 | 28 | [profile.release] 29 | panic = "abort" 30 | lto = true 31 | opt-level = "z" -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2017-2019 JKRB Investments Limited. 2 | // 3 | // You should have received a copy of the GNU General Public License 4 | // along with this file. If not, see . 5 | 6 | #![cfg_attr(not(any(test, feature = "std")), no_std)] 7 | 8 | use ink_core::{env::AccountId, storage}; 9 | use ink_lang::contract; 10 | 11 | contract! { 12 | 13 | /// Storage values of the contract 14 | struct NFToken { 15 | /// Owner of contract 16 | owner: storage::Value, 17 | /// Total tokens minted 18 | total_minted: storage::Value, 19 | /// Mapping: token_id(u64) -> owner (AccountID) 20 | id_to_owner: storage::HashMap, 21 | /// Mapping: owner(AccountID) -> tokenCount (u64) 22 | owner_to_token_count: storage::HashMap, 23 | /// Mapping: token_id(u64) to account(AccountId) 24 | approvals: storage::HashMap, 25 | } 26 | 27 | /// compulsary Demploy method 28 | impl Deploy for NFToken { 29 | /// Initializes our initial total minted value to 0. 30 | fn deploy(&mut self, init_value: u64) { 31 | self.total_minted.set(0); 32 | // set ownership of contract 33 | self.owner.set(env.caller()); 34 | // mint initial tokens 35 | if init_value > 0 { 36 | self.mint_impl(env.caller(), init_value); 37 | } 38 | } 39 | } 40 | 41 | /// Events 42 | event EventMint { owner: AccountId, value: u64 } 43 | event EventTransfer { from: AccountId, to: AccountId, token_id: u64 } 44 | event EventApproval { owner: AccountId, spender: AccountId, token_id: u64, approved: bool } 45 | 46 | /// Public methods 47 | impl NFToken { 48 | 49 | // Returns whether an account is approved to send a token 50 | pub(external) fn is_approved(&self, token_id: u64, approved: AccountId) -> bool { 51 | let approval = self.approvals.get(&token_id); 52 | if let None = approval { 53 | return false; 54 | } 55 | if *approval.unwrap() == approved { 56 | return true; 57 | } 58 | false 59 | } 60 | 61 | /// Return the total amount of tokens ever minted 62 | pub(external) fn total_minted(&self) -> u64 { 63 | let total_minted = *self.total_minted; 64 | total_minted 65 | } 66 | 67 | /// Return the balance of the given address. 68 | pub(external) fn balance_of(&self, owner: AccountId) -> u64 { 69 | let balance = *self.owner_to_token_count.get(&owner).unwrap_or(&0); 70 | balance 71 | } 72 | 73 | /// Transfers a token_id to a specified address from the caller 74 | pub(external) fn transfer(&mut self, to: AccountId, token_id: u64) -> bool { 75 | // carry out the actual transfer 76 | if self.transfer_impl(env.caller(), to, token_id) == true { 77 | env.emit(EventTransfer { from: env.caller(), to: to, token_id: token_id }); 78 | return true; 79 | } 80 | false 81 | } 82 | 83 | /// Transfers a token_id from a specified address to another specified address 84 | pub(external) fn transfer_from(&mut self, to: AccountId, token_id: u64) -> bool { 85 | // make the transfer immediately if caller is the owner 86 | if self.is_token_owner(&env.caller(), token_id) { 87 | let result = self.transfer_impl(env.caller(), to, token_id); 88 | if result == true { 89 | env.emit(EventTransfer { from: env.caller(), to: to, token_id: token_id }); 90 | } 91 | return result; 92 | 93 | // not owner: check if caller is approved to move the token 94 | } else { 95 | let approval = self.approvals.get(&token_id); 96 | if let None = approval { 97 | return false; 98 | } 99 | 100 | //carry out transfer if caller is approved 101 | if *approval.unwrap() == env.caller() { 102 | // carry out the actual transfer 103 | let result = self.transfer_impl(env.caller(), to, token_id); 104 | if result == true { 105 | env.emit(EventTransfer { from: env.caller(), to: to, token_id: token_id }); 106 | } 107 | return result; 108 | } else { 109 | return false; 110 | } 111 | } 112 | } 113 | 114 | /// Mints a specified amount of new tokens to a given address 115 | pub(external) fn mint(&mut self, to: AccountId, value: u64) -> bool { 116 | if env.caller() != *self.owner { 117 | return false; 118 | } 119 | 120 | // carry out the actual minting 121 | if self.mint_impl(to, value) == true { 122 | env.emit(EventMint { owner: to, value: value }); 123 | return true; 124 | } 125 | false 126 | } 127 | 128 | /// Approves or disapproves an Account to send token on behalf of an owner 129 | pub(external) fn approval(&mut self, to: AccountId, token_id: u64, approved: bool) -> bool { 130 | // return if caller is not the token owner 131 | let token_owner = self.id_to_owner.get(&token_id); 132 | if let None = token_owner { 133 | return false; 134 | } 135 | 136 | let token_owner = *token_owner.unwrap(); 137 | if token_owner != env.caller() { 138 | return false; 139 | } 140 | 141 | let approvals = self.approvals.get(&token_id); 142 | 143 | // insert approval if 144 | if let None = approvals { 145 | if approved == true { 146 | self.approvals.insert(token_id, to); 147 | } else { 148 | return false; 149 | } 150 | 151 | } else { 152 | let existing = *approvals.unwrap(); 153 | 154 | // remove existing owner if disapproving 155 | if existing == to && approved == false { 156 | self.approvals.remove(&token_id); 157 | } 158 | 159 | // overwrite or insert if approving is true 160 | if approved == true { 161 | self.approvals.insert(token_id, to); 162 | } 163 | } 164 | 165 | env.emit(EventApproval { owner: env.caller(), spender: to, token_id: token_id, approved: approved }); 166 | true 167 | } 168 | } 169 | 170 | /// Private Methods 171 | impl NFToken { 172 | 173 | fn is_token_owner(&self, of: &AccountId, token_id: u64) -> bool { 174 | let owner = self.id_to_owner.get(&token_id); 175 | if let None = owner { 176 | return false; 177 | } 178 | let owner = *owner.unwrap(); 179 | if owner != *of { 180 | return false; 181 | } 182 | true 183 | } 184 | 185 | /// Transfers token from a specified address to another address. 186 | fn transfer_impl(&mut self, from: AccountId, to: AccountId, token_id: u64) -> bool { 187 | if !self.is_token_owner(&from, token_id) { 188 | return false; 189 | } 190 | 191 | self.id_to_owner.insert(token_id, to); 192 | 193 | //update owner token counts 194 | let from_owner_count = *self.owner_to_token_count.get(&from).unwrap_or(&0); 195 | let to_owner_count = *self.owner_to_token_count.get(&to).unwrap_or(&0); 196 | 197 | self.owner_to_token_count.insert(from, from_owner_count - 1); 198 | self.owner_to_token_count.insert(to, to_owner_count + 1); 199 | true 200 | } 201 | 202 | /// minting of new tokens implementation 203 | fn mint_impl(&mut self, receiver: AccountId, value: u64) -> bool { 204 | 205 | let start_id = *self.total_minted + 1; 206 | let stop_id = *self.total_minted + value; 207 | 208 | // loop through new tokens being minted 209 | for token_id in start_id..stop_id { 210 | self.id_to_owner.insert(token_id, receiver); 211 | } 212 | 213 | // update total supply of owner 214 | let from_owner_count = *self.owner_to_token_count.get(&self.owner).unwrap_or(&0); 215 | self.owner_to_token_count.insert(*self.owner, from_owner_count + value); 216 | 217 | // update total supply 218 | self.total_minted += value; 219 | true 220 | } 221 | } 222 | } 223 | 224 | #[cfg(all(test, feature = "test-env"))] 225 | mod tests { 226 | use super::*; 227 | use std::convert::TryFrom; 228 | 229 | #[test] 230 | fn it_works() { 231 | 232 | // deploying and minting initial tokens 233 | let mut _nftoken = NFToken::deploy_mock(100); 234 | let alice = AccountId::try_from([0x0; 32]).unwrap(); 235 | let bob = AccountId::try_from([0x1; 32]).unwrap(); 236 | let charlie = AccountId::try_from([0x2; 32]).unwrap(); 237 | let dave = AccountId::try_from([0x3; 32]).unwrap(); 238 | 239 | let total_minted = _nftoken.total_minted(); 240 | assert_eq!(total_minted, 100); 241 | 242 | // transferring token_id from alice to bob 243 | _nftoken.transfer(bob, 1); 244 | 245 | let alice_balance = _nftoken.balance_of(alice); 246 | let mut bob_balance = _nftoken.balance_of(bob); 247 | 248 | assert_eq!(alice_balance, 99); 249 | assert_eq!(bob_balance, 1); 250 | 251 | // approve charlie to send token_id 2 from alice's account 252 | _nftoken.approval(charlie, 2, true); 253 | assert_eq!(_nftoken.is_approved(2, charlie), true); 254 | 255 | // overwrite charlie's approval with dave's approval 256 | _nftoken.approval(dave, 2, true); 257 | assert_eq!(_nftoken.is_approved(2, dave), true); 258 | 259 | // remove dave from approvals 260 | _nftoken.approval(dave, 2, false); 261 | assert_eq!(_nftoken.is_approved(2, dave), false); 262 | 263 | // transfer_from function: caller is token owner 264 | _nftoken.approval(charlie, 3, true); 265 | assert_eq!(_nftoken.is_approved(3, charlie), true); 266 | 267 | _nftoken.transfer_from(bob, 3); 268 | bob_balance = _nftoken.balance_of(bob); 269 | 270 | assert_eq!(bob_balance, 2); 271 | } 272 | } 273 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ink! Non Fungible Token 2 | 3 | ### A bare-bones non-fungible token implemented in ink! 4 | 5 | [Part 1 now published](https://medium.com/block-journal/introducing-substrate-smart-contracts-with-ink-d486289e2b59) @ The Block Journal on Medium 6 | 7 | [Part 2 now published](https://medium.com/@rossbulat/writing-a-substrate-smart-contract-with-ink-1f178849f931) @ The Block Journal on Medium 8 | 9 | [Part 3 now published](https://medium.com/block-journal/deploying-an-ink-smart-contract-to-a-substrate-chain-f52a2a36efec) @ The Block Journal on Medium 10 | 11 | # Tutorial 12 | 13 | ## ink!: Substrate’s smart contract language 14 | 15 | Parity’s Substrate blockchain framework, of which Polkadot is being built on top of, is in active development and making rapid progress towards a final release. Ink (or ink! as the name is commonly termed in documentation) is Parity’s solution to writing smart contracts for a Substrate based blockchain. 16 | 17 | Like Substrate, Ink is built on top of Rust, and therefore adheres to Rust language rules and syntax. This tutorial will walk through an example smart contract replicating a non-fungible token, commonly referred to as ERC721 tokens on the Ethereum blockchain. Specifically, the contract resembles a non-fungible token contract that will support 3 main features: minting tokens, transferring tokens, and approving another account to send tokens on your behalf. 18 | 19 | ### A note on non-fungible tokens 20 | 21 | Non-fungible tokens, or NFTs, differ from ERC20 style tokens whereby every token is unique. In our contract, each token will have a unique ID used to represent the token. From here, each token could have its own value, its own metadata, or have a specific use within an application or value system. 22 | 23 | Approving non-owner accounts to transfer or manage the token is also different, and has to be done on a per-token basis with Non-fungible tokens. Cryptokitties is the best known example where Non-fungible tokens have been implemented — each token representing a kitten on the platform. 24 | 25 | NFTs present different challenges to a standard token, and therefore give us more to explore in terms of Ink syntax and capabilities. 26 | 27 | ## Setting up the Ink Project 28 | 29 | The easiest way to bootstrap an Ink project currently is to install the "Hello World" contract of Ink, named Flipper. With Flipper installed, we can build upon what is already included and not have to worry about configuration and compile scripts — these are provided in Flipper. 30 | 31 | Note: Both Substrate and Ink are in rapid development and are not yet feature complete, therefore the smart contract environment, and the smart contract code itself, will most likely change as Parity get nearer to a final release of the framework. 32 | 33 | To jump start our Ink project fetch Flipper using cargo: 34 | 35 | ``` 36 | # fetch the Flipper Ink contract 37 | 38 | cargo contract new flipper 39 | ``` 40 | 41 | Flipper provides us a project boilerplate needed to start writing the smart contract. Included is: 42 | 43 | The folder structure and configuration metadata of the project 44 | A bare-bones Flipper contract in src/lib.rs, that simply “flips” a boolean value between true and false via a flip() method, and gets this value on-chain using the get() method. We will be replacing this file with the NFT contract 45 | The Rust specific Cargo.toml file, outlining the project dependencies and module metadata, a .gitignore file, and a build.sh file. The build.sh file is what we run to compile our smart contract, resulting in a compiled .wasm file of the contract, a JSON abstraction of the contract, and more. We’ll explore the built contract further down. 46 | 47 | *__Note__: Now is a good time to check out src/lib.rs to get a feel of the contract syntax.* 48 | 49 | Let’s change the name flipper to a more suitable name: nftoken. Amend the following: 50 | 51 | * `flipper/` folder name to /nftoken 52 | * `Cargo.tom`l: Change `[package] name` and `[lib] name` to `nftoken` 53 | * `build.sh`: amend `PROJNAME=nftoken` 54 | 55 | Also, ensure we have permissions to run `nftoken/build.sh`: 56 | ``` 57 | cd nftoken 58 | chmod +x build.sh 59 | ``` 60 | Lastly, add the /nftoken folder to a VS Code Workspace, and we are ready to start writing. 61 | 62 | ## About Ink 63 | Ink has [multiple levels](https://github.com/paritytech/ink#structure) of abstraction, where higher levels abstract over the lower levels. We will be using the highest level, which is dubbed the language level, or `lang` level. These levels have also been separated into modules that can be explored [here](https://paritytech.github.io/ink/pdsl_core/index.html). 64 | 65 | Below the `lang` module are the `model` and `core` modules, that focus on mid-level abstractions and core utilities respectively. Below the `core` module we can also expect a CLI specifically for creating and managing Ink contracts. 66 | 67 | Although there is little coverage on how to use these modules at the time of writing, we do indeed have the raw API docs to browse through, both for the [core](https://paritytech.github.io/ink/pdsl_core/index.html) module and [model](https://paritytech.github.io/ink/pdsl_model/index.html) module. If you are following this article these docs can be browsed through now, although our contract below will utilise some of these APIs intended to show how they are used in the context of the `lang` level via the non-fungible token contract. 68 | 69 | With this in mind, let’s next examine what the structure of our lang derived contract looks like, and compare it to what we expect from a Solidity based smart contract. 70 | 71 | ## Contract Structure 72 | 73 | Structuring an Ink contract is similar to that of a Solidity contract, where the major components we have come to expect with Solidity are also consistent in Ink: contract variables, events, public functions and private functions, as well as environment variables to grab the caller address and more. 74 | 75 | Below is an abstraction of how the NFToken contract is structured: 76 | 77 | ``` 78 | // declare modules 79 | use parity:: 80 | ... 81 | 82 | //wrap entire contract inside the contract! macro 83 | contract! { 84 | 85 | // contract variables as a struct 86 | struct NFToken { 87 | owner: storage::Value, 88 | ... 89 | } 90 | 91 | // compulsory deploy method that is run upon the initial contract instantiation 92 | impl Deploy for NFToken { 93 | fn deploy(&mut self, init_value: u64){} 94 | } 95 | 96 | // define events 97 | event EventMint { owner: AccountId, value: u64 } 98 | ... 99 | 100 | // public contract methods in an impl{} block 101 | impl NFToken { 102 | pub(external) fn total_minted(&self) -> u64 {} 103 | ... 104 | } 105 | 106 | // private contract methods in a separate impl{} block 107 | imp NFToken { 108 | fn is_token_owner( 109 | &self, 110 | of: &AccountId, 111 | token_id: u64) -> bool {} 112 | ... 113 | } 114 | } 115 | 116 | // test functions 117 | mod tests { 118 | fn it_works() {} 119 | ... 120 | } 121 | ``` 122 | 123 | Let’s briefly visit these sections and how they differ from what we have come to expect from a Solidity contract. Ink is built upon Rust, so all the syntax here is valid Rust syntax. 124 | 125 | * Our module declaration section is where we bring external functionality into the contract, and is the similar in nature to Solidity’s `using` declarations. 126 | 127 | ``` 128 | // Ink 129 | use ink_core::{ 130 | env::{self, AccountId}, 131 | memory::format, 132 | storage, 133 | }; 134 | use ink_lang::contract; 135 | use parity_codec::{Decode, Encode}; 136 | 137 | // Solidity 138 | interface ContractName { 139 | using SafeMath for uint256; 140 | using AddressUtils for address; 141 | } 142 | ``` 143 | * Events are declared inside the `!contract` macro, whereas with Solidity we define our events within a contract interface, typing each as an `event`: 144 | 145 | ``` 146 | // Ink 147 | event Transfer { from: AccountId, to: AccountId, token_id: u64 } 148 | 149 | // Solidity 150 | event Transfer( 151 | address indexed from, 152 | address indexed to, 153 | uint256 indexed _tokenId 154 | ); 155 | ``` 156 | * Where a Solidity contract is embedded within an `interface` block, an Ink contract is embedded within a `contract!` macro. Our events are declared inside of this macro, whereas events are declared within a Solidity interface. This is described below. 157 | 158 | *__Note__: A [macro](https://doc.rust-lang.org/book/macros.html) in Rust is a a declaration that represents a block of syntax that the wrapped expressions will be surrounded by. Macros abstract at a syntactic level, so the `contract!` macro is wrapping its contents with more syntax.* 159 | 160 | ``` 161 | // Ink 162 | contract! { 163 | // contract 164 | } 165 | 166 | // Solidity 167 | interface ContractName { 168 | // contract 169 | } 170 | ``` 171 | 172 | * With Ink, our contract variables are written in a struct of the name of our contract. Hash maps derived from Rust’s `HashMap` type are in place of Solidity’s `mapping` type, providing `key => value` lists. 173 | 174 | ### How Substrate stores values 175 | 176 | Any piece of data persisted on a Substrate chain is called an *extrinsic*, and Ink provides us the means to store extrinsics on-chain via the `storage` module, that lives within the `core` module of the language. In other words, all contract variables that you plan to persist on chain will use a type from `storage`. Conversely, the `memory` module is also available for data structures to operate on memory. 177 | 178 | Solidity on the other hand adopts a different approach to this. From Solidity 0.5, `storage` and `memory` reference types were introduced to function arguments or function variables, so the contract knows where to reference those variables. However, this is not necessary for contract variables in Solidity. 179 | 180 | Primitive types are also available and consistent throughout both languages; where Rust uses `u64`, Solidity adopts a more verbose `uint64` type declaration. Overall it is quite simple to achieve the same contract variable structure between the two languages. 181 | 182 | ``` 183 | // Ink 184 | struct NFToken { 185 | owner: storage::Value, 186 | approvals: storage::HashMap, 187 | } 188 | 189 | // Solidity 190 | address owner; 191 | mapping (uint64 => address) approvals; 192 | ``` 193 | 194 | In the above example, the type of values that `storage` objects handle are passed in via the angled brackets in place of the type’s generics. 195 | 196 | * The concept of an initialisation function is present within both Ink and Solidity, albeit implemented in different ways. With Ink, we explicitly define a `deploy()` method within a `Deploy{}` implementation block. The parameters we define for this method are representative of what data we send when initialising the contract. E.g. for our non-fungible token, we will provide an initial amount of tokens to be minted: 197 | 198 | ``` 199 | // Inks initialisation function, deploy() 200 | impl Deploy for NFToken { 201 | fn deploy(&mut self, init_value: u64) { 202 | ... 203 | } 204 | } 205 | ``` 206 | 207 | * Public and private methods are also defined within `impl` blocks, where public methods are explicitly defined with `pub(external)`. Again, when comparing this syntax to that of Solidity’s, `internal` and `external` are used to define a private or public resource. 208 | 209 | *__Note__: In Rust, functions, modules, traits and structs are private by default, and must be defined with the `pub` keyword in order for them to be externally reachable. The `(external)` extension to `pub` here is Ink specific, and is compulsory to include with public Ink functions.* 210 | 211 | ``` 212 | // public functions 213 | impl NFToken { 214 | pub(external) fn total_minted(&self) -> u64 {} 215 | } 216 | // private functions 217 | impl NFToken { 218 | fn mint_impl( 219 | &mut self, 220 | receiver: AccountId, 221 | value: u64) -> bool { 222 | } 223 | } 224 | ``` 225 | 226 | Again, we have separated our private and public functions in separate `impl` blocks, and have included `pub(external)` for public functions defined. 227 | 228 | As the last building block of our contract, a `tests` module is defined that asserts various conditions as our functions are tested. Within the `tests` module, we can test our contract logic without having to compile and deploy it to a Substrate chain, allowing speedy ironing out of bugs and verification that the contract works as expected. 229 | 230 | ## Contract syntax in depth 231 | 232 | To review, the structure of an Ink contract, is as follows: 233 | 234 | ``` 235 | // Ink smart contract structure 236 | module declarations 237 | event definitions 238 | contract macro 239 | struct containing contract variables 240 | deploy function 241 | public methods 242 | private methods 243 | tests 244 | ``` 245 | 246 | Let’s explore how these sections are implemented in more detail. 247 | 248 | ### Module Declarations 249 | 250 | Ink does not rely on the Rust standard library — instead, we import Ink modules to code all our contract logic. Let’s take a quick look at what we are importing into our smart contract: 251 | 252 | ``` 253 | use ink_core::{ 254 | env::{self, AccountId}, 255 | memory::format, 256 | storage, 257 | }; 258 | use ink_lang::contract; 259 | use parity_codec::{Decode, Encode}; 260 | ``` 261 | 262 | We are exposing which modules need to be used in our smart contract here, importing the `ink_core` vital modules of `storage` and `memory`, as well as some `env` objects, exposing critical data such as the caller of an address. In addition, `Encode` and `Decode` have been declared from `parity_codec` to be used for encoding events into a raw format. 263 | 264 | ### Module Declaration 265 | 266 | You will also notice the following before our module declarations: 267 | 268 | ``` 269 | #![cfg_attr(not(any(test, feature = "std")), no_std)] 270 | ``` 271 | 272 | This line is declaring that we are using the standard library if we run the tests module, or if we use a std feature flag within our code. Otherwise the contract will always compile with `no_std`. Ink contracts do not utilise the Rust standard library, so it is omitted from compilation unless we explicitly define it not to. 273 | 274 | The `AccountId` type is provided by Ink core; if you recall the previous section, we imported both types via destructuring syntax from the `env` module within `ink_core`. `AccountId` represents an account (the equivalent of Ethereum’s `address` type. Another type that is available, `Balance`, is a `u64` type, or a 64 bit unsigned integer. 275 | 276 | *__Note__: We could have use the Balance type in place of u64 to represent token values here. Although it is preferable that the Balance type be used with token values, I experienced some ambiguity working with the type, where the compiled contract did not like addition of u64 values to Balance values. It is conceivable that Balance will be enhanced in the future as Ink is further developed, providing more attributes that further represent a balance, such as the type of units. Balance will be implemented in the NFToken contract once the ambiguity surrounding its usage is cleared up.* 277 | 278 | 279 | *__Note__: In Rust, omitting the semi-colon from the last expression of a function __returns__ the result of that expression, removing the need to write `return`, although it is perfectly valid to do so if you’d like to return further up the function.* 280 | 281 | ### A note on Rust’s ownership mechanism 282 | 283 | Another important Rust (and therefore Ink) programming concept to understand is that of ownership. The `deposit_event` function (no longer implemented in NFToken) utilises ownership. Take a look at `&` used before the `event` argument in `env::deposit_raw_event`: 284 | 285 | ``` 286 | deposit_raw_event(&event.encode()[..]) 287 | ^ 288 | we are referencing `event` here 289 | ``` 290 | 291 | In Rust, `&` represents a reference to an object. 292 | 293 | Had we not used a reference, `env::deposit_raw_event` would take ownership of `event`, and thus would no longer be available to use in `deposit_event()`. `event` would “move” into the containing function, and would no longer be in scope in the outer function. If we attempted to use `event` after this point, we would receive an error , as event would no longer exist in that scope. 294 | 295 | Even though our `deposit_event()` function only has one line of code, and therefore moving `event` out of scope would have no impact of the rest of the function, `env::deposit_raw_event` actually expects a reference. Take a look at the error we receive when removing the reference: 296 | 297 | 298 | 299 | The editor is extremely helpful when dealing with Rust ownership, and will ensure that you iron out ownership issues before attempting to compile the program. In this case, it actually tells us how to fix this error under the help section. 300 | 301 | To read more about Rust ownership, The Rust Book has a great section explaining the concepts; it is advised to understand Rust ownership before endeavouring into Ink smart contract programming. 302 | 303 | With our events defined (and the helper function for emitting those events), let’s now explore the contents of the `contract!` macro itself. 304 | 305 | ### Contract Variables 306 | 307 | Contract variables can be thought of as class properties that are accessed within functions via `self`. Here are the contract variables of our NFToken contract: 308 | 309 | ``` 310 | struct NFToken { 311 | /// owner of the contract 312 | owner: storage::Value, 313 | 314 | /// total tokens minted 315 | total_minted: storage::Value, 316 | 317 | /// mapping of token id -> token owner 318 | id_to_owner: storage::HashMap, 319 | 320 | /// mapping of token owner -> amount of tokens they are holding 321 | owner_to_token_count: storage::HashMap, 322 | 323 | /// mapping of token id -> approved account 324 | approvals: storage::HashMap, 325 | } 326 | ``` 327 | 328 | The first two variables are of type `storage::Value`, and the following three of `storage::HashMap`. In fact, the `ink_core` `storage` module has to be used for any contract data we wish to persist on chain. 329 | 330 | `storage` types are generic, and as such we explicitly provide the type of data we are storing, in angle brackets. 331 | 332 | With the required contract data defined, let’s explore some of the contract implementation, highlighting some key logic and syntax. 333 | 334 | ### Deployment 335 | 336 | The deploy function is compulsory in any Ink contract, and is called when instantiating a contract once it is deployed to a chain. 337 | 338 | Wrap the `deploy()` function within an `impl Deploy for ` block. The actual implementation of deploy is very straight forward; here it is in its entirety: 339 | 340 | ``` 341 | impl Deploy for NFToken { 342 | fn deploy(&mut self, init_value: u64) { 343 | 344 | // set initial total minted tokens to 0 345 | self.total_minted.set(0); 346 | 347 | // set the contract owner to the caller 348 | self.owner.set(env::caller()); 349 | 350 | // if initial token value provided, call the minting function 351 | if init_value > 0 { 352 | self.mint_impl(env::caller(), init_value); 353 | } 354 | } 355 | } 356 | ``` 357 | 358 | We are simply setting default values here, with the addition of some initial token minting. We will explore the minting implementation next. 359 | 360 | ### Minting Implementation 361 | 362 | Minting is the process of generating new tokens. For our NFToken contract the following conditions need to be met for minting: 363 | 364 | * Each token must have a unique index represented by a `token_id` 365 | * An `AccountId` to mint the tokens to needs to be provided 366 | * Only the contract owner can mint new tokens 367 | 368 | The public function `mint()` is declared to handle calls to mint tokens: 369 | 370 | ``` 371 | // mint function signature 372 | 373 | pub(external) fn mint( 374 | &mut self, 375 | value: u64) -> bool { 376 | } 377 | ``` 378 | 379 | Mint accepts two arguments; the account to mint tokens to, and an amount of tokens to be minted. The first parameter to our function signature is *always a reference to `self`*. In addition we can also include `mut` to declare that `self` can be updated, essentially providing a mutable reference to the contract instance. 380 | 381 | `mint()` calls the private `mint_impl()` function, that carries out the actual minting process. This pattern of exposing a private function via a public one is also consistent for transferring and approving. 382 | 383 | `mint_impl()` will carry out the following tasks: 384 | 385 | * Work out the first new `token_id` and the last `token_id` to be minted. This is calculated based on the `self.total_minted` contract variable. 386 | 387 | * We define a for loop that will increment token ids and insert each one into the `self.id_to_owner` hash map. The specific syntax for this loop is interesting, adopting a `for in` structure, and adopting a spread operator: 388 | 389 | ``` 390 | for token_id in start_id..stop_id { 391 | self.id_to_owner.insert(token_id, receiver); 392 | // ^ ^ 393 | // new id owner of the token 394 | } 395 | ``` 396 | 397 | Ink’s implementation of `HashMap` closely mirrors that of the standard Rust implementation. `insert()` will add a new record to our mapping. Check out the full reference [here](https://paritytech.github.io/ink/pdsl_core/storage/struct.HashMap.html) for all the ways we can manipulate a `HashMap`. 398 | 399 | #### A note on dereferencing, with * 400 | 401 | To obtain the raw value of our contract variables we need to “dereference” them. The concept of dereferencing is explained in detail [here](https://doc.rust-lang.org/book/ch15-02-deref.html#following-the-pointer-to-the-value-with-the-dereference-operator) in The Rust Book, but essentially dereferencing allows us get to an underlying value of a pointer or a reference. 402 | 403 | Let’s take a look at how we calculate `start_id` inside `mint_impl()` as an example of where dereferencing has been used: 404 | 405 | 406 | 407 | Hovering over `self.total_minted` reveals that we need to dereference `storage::Value` to obtain the underlying `u64` value. Like referencing, the editor is intelligent enough to realise when an expression does not make sense — e.g. trying to add `1` to a `storage::Value` object, that would result in an error. 408 | 409 | Even though dereferencing may not be suggested as a fix, it should be obvious to the programmer once the error is pointed out in the editor. 410 | 411 | #### Back to minting implementation 412 | 413 | Once the new tokens have been assigned to `id_to_owner`, the `owner_to_token_count` mapping is also updated reflecting the new amount of tokens the owner has. In addition, `total_minted` is also updated to reflect the newly minted tokens. 414 | 415 | You may have noticed the way we update the `owner_to_token_count` hash map may be slightly confusing upon first inspection. Here are the lines of code that do so: 416 | 417 | ``` 418 | // get the current owner count if it exists 419 | let from_owner_count = *self.owner_to_token_count.get(&self.owner).unwrap_or(&0); 420 | 421 | // insert new token count, or overwrite if self.owner exists already 422 | self.owner_to_token_count.insert(*self.owner, from_owner_count + value); 423 | ``` 424 | 425 | The first line of code attempts to retrieve an existing token count from the hash map with `get()`, or assign a value of 0 to `from_owner_count` if none are found. The next line should be familiar, where we use `insert()` to either insert a new record or overwrite an existing one. 426 | 427 | But what does `unwrap_or()` actually do? Well, instead of returning the token count itself, `get()` actually returns an `Option` enum, which we can then unwrap in the event a value exists. In the event a value does not exist, we can provide an alternative value, as an argument of `unwrap_or()`, which is 0 in the above case. 428 | 429 | Let’s briefly explore this concept further; not only it is used in other areas of the contract, `Option` it is a fundamental design pattern in Rust. 430 | 431 | #### Understanding the Rust Option enum 432 | 433 | As we have determined already, fetching values from `HashMap` contract variables will actually result in an `Option` enum. The `Option` enum in Rust provides two possible values: `Some` or `None`. This essentially avoids `null` values, returning `None` in the case a value does not exist. 434 | 435 | Now, a common convention used in our NFToken smart contract is to firstly check if a value exists within a `HashMap`, and returning false in some cases where a `None` option is returned. In the case a `Some` value is present, we then use an unwrap modifier on the `Option` value to obtain the value that `Some` is wrapping. 436 | 437 | The `is_token_owner()` function is one example that adheres to this pattern: 438 | 439 | ``` 440 | // attempt to get a value from the mapping 441 | let owner = self.id_to_owner.get(&token_id); 442 | 443 | // if a None option is fetched, return false 444 | if let None = owner { 445 | return false; 446 | } 447 | 448 | // must be Some option - unwrap (and dereference) value 449 | let owner = *owner.unwrap(); 450 | ``` 451 | 452 | Instead of using `unwrap_or()` such as in the previous example, `unwrap()` simply assumes that `owner` is a `Some` option; we have already dealt with the case that owner is a `None` value, so it is safe to assume that a `Some` value exists to unwrap. 453 | 454 | To conclude `is_token_owner()`, we then check to see if the retrieved token owner matches the `AccountId` we provided in the function call: 455 | 456 | ``` 457 | ... 458 | // return false if owner does not match provided account 459 | if owner != *of { 460 | return false; 461 | } 462 | // owner must be `of`, return true 463 | return true; 464 | } 465 | ``` 466 | 467 | Our minting implementation has introduced us to the concepts and conventions used within the rest of the contract implementation. Let’s visit the transfer function text. 468 | 469 | ### Transferring Implementation 470 | 471 | The transferring of tokens is arguably the most important feature of our contract, allowing us to transfer tokens to and from accounts. The public `transfer()` function is available to send transfer requests to, and has the following signature: 472 | 473 | ``` 474 | pub(external) fn transfer( 475 | &mut self, 476 | to: AccountId, 477 | token_id: u64) -> bool { 478 | } 479 | ``` 480 | 481 | This function calls the private `transfer_impl()` function to carry out the actual transferring logic. It ensures the following conditions are met for transferring: 482 | 483 | * We immediately check if the caller is the token owner, and return false if not 484 | * The `id_to_token` mapping is updated, overwriting the value of the `token_id` index to the new owner’s account 485 | * Token counts are updated, decreasing the senders’ count and increasing the receivers’ count 486 | * The `EventTransfer` event is emitted if `transfer_impl()` returns true 487 | 488 | Arguably a simpler function than the minting process, this transfer implementation allows tokens to be sent on an individual basis. The underlying mechanism here is simply to update the `id_to_owner` mapping, keeping track of who owns what. From here, the sender and receiver `owner_to_token_count` records are also updated to keep track of tokens owned on an individual account basis. 489 | 490 | The last feature of NFToken is the ability to approve another account to send a token on your behalf. Let’s see how that works. 491 | 492 | ### Approving Implementation 493 | 494 | Approvals are a mechanism by which a token owner can assign someone else to transfer a token on their behalf. In order to do so, an additional function has been implemented specifically for approving or disapproving an account for a particular `token_id`. 495 | 496 | *__Note__: The contract is currently limited to one approval per token until the Ink language is further developed.* 497 | 498 | The public `approvals()` function accepts three arguments when being called: 499 | 500 | * The `token_id` we are adding or removing an approval to 501 | * The `AccountId` we wish to approve or disapprove 502 | * An `approved` boolean, indicating whether we wish to approve or disapprove the `AccountId` 503 | 504 | The signature of `approvals()` looks like the following: 505 | 506 | ``` 507 | pub(external) fn approval( 508 | &mut self, 509 | to: AccountId, 510 | token_id: u64, 511 | approved: bool) -> bool { 512 | } 513 | ``` 514 | 515 | The approval process boils down to the following logic, ensuring that only the token owner can make the approval, and that the approval can successfully be inserted or removed: 516 | 517 | * We firstly check whether an owner for the token exists, via the `id_to_owner` mapping. A `None` value here will suggest the token does not exist, in which case we exit the function. 518 | * With a token successfully fetched, we then check whether the caller (`env.caller()`), is indeed the owner of the token we’re configuring the approval for. If not, we exit the function, returning false once again. 519 | * Next, we attempt to get an existing approval record: 520 | 521 | ``` 522 | // returns an Option of either Some or None 523 | 524 | let approvals = self.approvals.get(&token_id); 525 | ``` 526 | 527 | * __If an approval record does not exist__, we then refer to `approved` to see if the caller intended to either approve or disapprove the provided account. If the caller did wish to approve, the provided account is added to approvals. If not, there will be nothing to remove as the record was not found — we return false. 528 | * __If an approval record exists__, the value is unwrapped with `unwrap()`, and we again check the intention of the caller. If a disapproval was intended, we remove the record from `approvals` via the HashMap `remove()` method. On the other hand, we insert the record again, overwriting the existing record, in the event the caller intended to insert (or update) the approval. 529 | * Finally, the `EventApproval` event is emitted and we return `true`: 530 | 531 | ``` 532 | env.emit(EventApproval { owner: env.caller(), spender: to, token_id: token_id, approved: approved }); 533 | true 534 | ``` 535 | 536 | ## Testing Ink Contracts 537 | 538 | Testing an Ink smart contract can (and should) be done both off-chain and on-chain. The prior can be done via a `tests` module within the contract itself, and the latter on a local Substrate dev chain. 539 | 540 | Your first means of testing an Ink contract is via the `tests` module under your `contract!` macro. The boilerplate looks like the following: 541 | 542 | ``` 543 | // test function boilerplate 544 | 545 | #[cfg(all(test, feature = "test-env"))] 546 | mod tests { 547 | 548 | use super::*; 549 | use std::convert::TryFrom; 550 | #[test] 551 | fn it_works() { 552 | // test function... 553 | } 554 | } 555 | ``` 556 | 557 | The test functions are wrapped in a separate `tests` module, that import everything from the parent module and thus knows about everything about the smart contract in question. Let’s break down some of the more ambiguous lines of code, starting with the top `cfg` flag. 558 | 559 | ``` 560 | // config flag to only compile in a test environment 561 | 562 | #[cfg(all(test, feature = "test-env"))] 563 | ``` 564 | 565 | Tests are not compiled with the smart contract — they would take up unnecessary space on chain. We’ve also included two `use` statements within the `tests` module: 566 | 567 | ``` 568 | // use everything from super module (the smart contract) 569 | use super::*; 570 | 571 | // use the TryFrom trait - allowing safe type conversions 572 | use std::convert::TryFrom; 573 | ``` 574 | 575 | The first line, `super::*` is quite self explanatory; the `tests` module needs to be aware of the smart contract it is testing, so everything is bought into scope with `*` from the parent module — the smart contract itself. The second argument brings the `TryFrom` trait into scope. 576 | 577 | The `TryFrom` trait implements simple and safe type conversions that may fail in a controlled way under some circumstances. 578 | 579 | We use the `try_from()` method, derived from the `TryFrom` trait, to try to obtain `AccountId` addresses for use in our testing. This is in fact the first thing we do within the `it_works()` test after initialising a contract instance: 580 | 581 | ``` 582 | #[test] 583 | fn it_works() { 584 | 585 | // initialise a contract instance to test 586 | let mut _nftoken = NFToken::deploy_mock(100); 587 | 588 | // try to obtain alice's account 589 | let alice = AccountId::try_from([0x0; 32]).unwrap(); 590 | ... 591 | } 592 | ``` 593 | 594 | An `AccountId` in Substrate consists of 32 characters, therefore Alice’s address is simply declared as 32 zeros. The account is unwrapped to obtain the actual address from either a `Result` or `Error` enum. 595 | 596 | A `#[test]` statement exists before the function definition; this is Rust syntax that lets the compiler know we intend this function to be a test function. VS Code will embed a test button under each function that is labelled as a test in this way — but clicking this button to invoke `cargo test` will fail, as we need a slightly modified test command to test Ink contracts. We will visit that command further down. 597 | 598 | Within `it_works()`, we initialise a mutable instance of the contract using `deploy_mock()`, a mock deployment function provided by the Ink framework. The contract can now be called and manipulated via the `_nftoken` variable. `deploy_mock()` will call the contract’s `deploy()` method — which expects an init_value argument — so the value of `100` has been provided, consequently minting 100 tokens at test runtime. 599 | 600 | ### Using Assertions in Tests 601 | 602 | From here the rest of `it_works()` is simple to follow. We have taken advantage of Rust’s assertion macros to ensure that our contract’s state is changing as we expect when transferring tokens and approving other accounts to send tokens. 603 | 604 | Rust includes three assertion macros available for us to use in the standard library: 605 | 606 | ``` 607 | // assert! - true or false 608 | assert!(some_expression()); 609 | 610 | // assert_eq! - asserts that 2 expressions are equal 611 | assert_eq!(a, b, "Testing if {} and {} match", a, b); 612 | 613 | // assert_ne! - asserts that 2 expressions are not equal 614 | assert_ne!(a, b, "Testing that a and b are not equal"); 615 | ``` 616 | 617 | Where an assertion fails, the test function will also fail and be reported as a failure once the tests complete. to test our Ink contract we run the following command: 618 | 619 | ``` 620 | cargo test --features test-env -- --nocapture 621 | ``` 622 | 623 | Using `--no-capture` will provide more verbose output, including `println()` output where it has been used within the tests module. The `test-env` *feature* ensures that we are only testing the Ink environment, as defined in `Cargo.toml`: 624 | 625 | ``` 626 | [features] 627 | default = [] 628 | test-env = [ 629 | "ink_core/test-env", 630 | "ink_model/test-env", 631 | "ink_lang/test-env", 632 | ] 633 | ... 634 | ``` 635 | 636 | A successful test will result in the following output: 637 | 638 | 639 | 640 | ### Compiling the contract 641 | 642 | With tests passing, we can now compile the contract. Run `build.sh` within the project directory to do so: 643 | 644 | ``` 645 | ./build.sh 646 | ``` 647 | 648 | The resulting files will be sitting in your `target/` folder: 649 | 650 | ``` 651 | nftoken.wat 652 | nftoken-fixed.wat 653 | nftoken.wasm 654 | nftoken-opt.wasm 655 | nftoken-pruned.wasm 656 | NFToken.json 657 | ``` 658 | 659 | Ink contracts are compiled into the web binary standard WebAssembly, or `.wasm`. We are interested in two files from the above compiled output that we will upload to Substrate: 660 | 661 | * `nftoken-pruned.wasm`: an optimised `.wasm` file we’ll upload to our Substrate chain 662 | * `NFToken.json`: the contract ABI code in JSON format 663 | 664 | *__Note__: Although we are not WebAssembly focussed, it is worth mentioning that the format is being heavily used in the blockchain space for a more efficient runtime. Ethereum 2.0 will rely on a subset of WebAssembly they have dubbed eWasm, and of course, Substrate chains are also adopting the standard. Although primarily aimed for the web, WebAssembly is by no means limited to the browser. The WebAssembly spec is under development and we can expect more features to be released in the coming years, making it a very interesting technology to work with.* 665 | 666 | You may be familiar with contract ABI from Ethereum based contracts, that provide front-end Dapps the means to communicate to the contract on-chain. They essentially describe the structure of the contract including its functions and variables within a JSON object, making it particularly simple for Javascript based apps to integrate. 667 | 668 | Now, to deploy the contract, spin up your local Substrate chain if you have not done so already, and let’s turn to the Polkadot JS app to manage our deployment. 669 | 670 | ``` 671 | # run your local Substrate chain 672 | 673 | substrate --dev 674 | ``` 675 | 676 | ### Deploying Ink Contracts 677 | 678 | Deploying and instantiating a contract on a Substrate chain involves firstly deploying the contract, and then instantiating it. This two step process allows developers to deploy a particular standard — perhaps a token standard — where other interested parties could then instantiate that same contract with their own token details. This removes the need to upload duplicates of the same contract for essentially identical functionality and identical ABI code. 679 | 680 | To reiterate, this two step process involves: 681 | 682 | * Uploading the contract onto a Substrate chain 683 | * Instantiating the contract, which can then be interacted with 684 | 685 | Both these tasks can be achieved via the Polkadot JS app, an open source Typescript and React based project [available on Github](https://github.com/polkadot-js/apps). 686 | 687 | #### Polkadot JS 688 | 689 | Now we’ll be uploading our compiled `.wasm` and `.json` ABI to a Substrate dev chain. To do so, the Polkadot JS client is needed. 690 | 691 | You can either clone the project to run on your local machine, or simply visit [https://polkadot.js.org/apps](https://github.com/polkadot-js/apps) to access it online. Load up the client to commence the deployment process that follows. 692 | 693 | __Step 1: Ensure the client is connected to your local Substrate node__ 694 | 695 | We firstly need to ensure that the client is connected to the correct chain. Navigate to the `Settings` tab and ensure that the `remote node/endpoint to connect to` is set to `Local Node (127.0.0.1:9944)`. Hit `Save and Reload` if a change is needed. 696 | 697 | *__Note__: The other chains, `Alexander` and `Emberic Elm`, are Substrate based chains that are managed by Parity. Working with other Substrate chains such as Polkadot is out of the scope of this article, however, the Pokakdot JS client is actually designed to work with __any__ Substrate based blockchain, and therefore is extremely dynamic in what is presented throughout the app.* 698 | 699 | __Step 2: Deploy the compiled contract onto your node__ 700 | 701 | To deploy our contract, navigate to the `Contracts` page from the side bar, and ensure you are on the `Code` tab. If you have not yet deployed a contract onto your node, the `Code` tab will be the only one available. The UI will be similar to the following: 702 | 703 | 704 | 705 | Now on the Code tab: 706 | 707 | * Ensure the `deployment account` is set to `ALICE`. Alice will have a sufficient balance for us to deploy, instantiate and test the contract 708 | * Drag `nftoken-pruned.wasm` onto the `compiled contract WASM` field 709 | * Optional: Amend the `code bundle name` value for a more human-friendly name 710 | * Drag `NFToken.json` onto the `contract ABI` field 711 | * Set the `maximum gas allowed` to 500,000 to ensure that we supply enough gas to process the transaction 712 | 713 | Once configured, hit `Deploy` and then confirm once again. The transactions will take place and the contract will be deployed. 714 | 715 | __Step 3: Instantiating the contract__ 716 | 717 | You will now notice that two additional tabs are available, `Instance` and `Call`. We will firstly use the `Instance` tab to instantiate the contract, then the `Call` tab to test our functions. The `Instance` tab will resemble something similar to the following: 718 | 719 | 720 | 721 | Within the Instance tab: 722 | 723 | * Check the `code for this contract` value is pointing to your deployed contract 724 | * Set an initial token amount to be minted as the `initValue` value. 725 | 726 | *__Note__: The Polkadot UI is now picking up on our contract structure, and specifically the arguments that need to be supplied for the deploy function we defined for the contract, including the expected data type. This is one example of the dynamic nature of the Polkadot UI and how its designed to cater for a wide-range of contract types.* 727 | 728 | * Set the `endowment` value to 1,000 to ensure the new contract account is minted with some value. This is an advised value from the official Ink docs. Like Ethereum contracts, Ink contracts are deployed to a separate address with their own unique `AccountId` and balance. 729 | * Again, set the `maximum gas allowed` to 500,000 to ensure that we supply enough gas for the transaction 730 | * Hit `Initiate` and confirm to carry out the transaction 731 | 732 | Upon a successful transaction, the contract will now be instantiated and functions callable. 733 | 734 | __Step 4: Calling functions from instantiated contract__ 735 | 736 | Our final job is now to ensure that functions are working as expected. You will notice that all the `pub(external)` functions we defined in the contract are now available to call and test within the `Call` tab: 737 | 738 | 739 | 740 | Polkadot JS does not yet provide feedback from calls in the client itself, but your node feed in your terminal should reflect the transactions as new blocks are validated. What we have in terms of UX now are success or failure event notifications that pop up on the top right of your browser window as a function call is processed. 741 | 742 | *__Note__: Feedback mechanisms will be posted here as and when they become available, either on the command line or in the Polkadot JS client.* 743 | 744 | ## Summary 745 | 746 | We have completed the Ink smart contract deployment journey, from Installation to Instantiation on chain. As a brief summary, let’s visit the various pieces that made the process possible: 747 | 748 | * Bootstrapping of the basic `Flipper` Ink contract to obtain the Ink boilerplate, including environment configuration and `build.sh` file 749 | * Writing the NFToken contract adhering to Rust concepts and conventions, with minting, transferring and approval functionalities, along with event emission 750 | * Testing via the `tests` module, before compiling the contract with `build.sh` 751 | * Deploying, instantiating and testing function calls via the Polkadot JS client, connected to your local Substrate dev chain 752 | --------------------------------------------------------------------------------