├── .gitignore
├── LICENSE
├── README.md
├── config.example.js
├── doc
├── NFT-Workshop.pdf
├── combine.png
└── marketplace.png
├── images
├── brow1.png
├── brow2.png
├── brow3.png
├── cover.png
├── eye1.png
├── eye2.png
├── eye3.png
├── hair1.png
├── hair2.png
├── hair3.png
├── hair4.png
├── hair5.png
├── head1.png
├── mouth1.png
├── mouth2.png
├── mouth3.png
├── nose1.png
├── nose2.png
└── nose3.png
├── package-lock.json
├── package.json
├── scripts
├── create-zip.js
├── generate-image.worker.js
├── initialize-sdk.js
├── upload-images.js
└── utils.js
├── step1-nft-generator.js
├── step2-image-generator.js
├── step3-create-collection.js
└── step4-create-items.js
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | lerna-debug.log*
8 |
9 | # Diagnostic reports (https://nodejs.org/api/report.html)
10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
11 |
12 | # Runtime data
13 | pids
14 | *.pid
15 | *.seed
16 | *.pid.lock
17 |
18 | # Directory for instrumented libs generated by jscoverage/JSCover
19 | lib-cov
20 |
21 | # Coverage directory used by tools like istanbul
22 | coverage
23 | *.lcov
24 |
25 | # nyc test coverage
26 | .nyc_output
27 |
28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
29 | .grunt
30 |
31 | # Bower dependency directory (https://bower.io/)
32 | bower_components
33 |
34 | # node-waf configuration
35 | .lock-wscript
36 |
37 | # Compiled binary addons (https://nodejs.org/api/addons.html)
38 | build/Release
39 |
40 | # Dependency directories
41 | node_modules/
42 | jspm_packages/
43 |
44 | # TypeScript v1 declaration files
45 | typings/
46 |
47 | # TypeScript cache
48 | *.tsbuildinfo
49 |
50 | # Optional npm cache directory
51 | .npm
52 |
53 | # Optional eslint cache
54 | .eslintcache
55 |
56 | # Microbundle cache
57 | .rpt2_cache/
58 | .rts2_cache_cjs/
59 | .rts2_cache_es/
60 | .rts2_cache_umd/
61 |
62 | # Optional REPL history
63 | .node_repl_history
64 |
65 | # Output of 'npm pack'
66 | *.tgz
67 |
68 | # Yarn Integrity file
69 | .yarn-integrity
70 |
71 | # dotenv environment variables file
72 | .env
73 | .env.test
74 |
75 | # parcel-bundler cache (https://parceljs.org/)
76 | .cache
77 |
78 | # Next.js build output
79 | .next
80 |
81 | # Nuxt.js build / generate output
82 | .nuxt
83 | dist
84 |
85 | # Gatsby files
86 | .cache/
87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js
88 | # https://nextjs.org/blog/next-9-1#public-directory-support
89 | # public
90 |
91 | # vuepress build output
92 | .vuepress/dist
93 |
94 | # Serverless directories
95 | .serverless/
96 |
97 | # FuseBox cache
98 | .fusebox/
99 |
100 | # DynamoDB Local files
101 | .dynamodb/
102 |
103 | # TernJS port file
104 | .tern-port
105 |
106 | # Application specific
107 | /generated-nfts
108 | config.js
109 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Tutorial: Create your own NFT Collection
2 |
3 | ## Who is this tutorial for
4 |
5 | This tutorial is created for technologically skillful people (e.g. game developers) who desire to create NFT collections from auto-generated images such as Substrapunks, Crypto-kitties, etc.
6 |
7 | ## Prerequisites
8 |
9 | * OS: Ubuntu 18.04 or 20.04
10 | * NodeJS 16 or up
11 | * Image editor of your choice
12 |
13 | ## Design image parts
14 |
15 | The image parts should generally include some background and combinable parts with transparent background. Store them in `images` folder. In this example there is a single background image that is stored in `head1.png` file:
16 |
17 |
18 |
19 | If you had three background images, store them respectively in `images/head1.png`, `images/head2.png`, and `images/head3.png` files.
20 |
21 | The combinable parts are stored as `eye*.png`, `brow*.png`, `nose*.png`, `hair*.png`, and `mouth*.png`, so when a particular combination of parts is composed, it results in a unqiue NFT image:
22 |
23 | 
24 |
25 | The combinable parts are also stored in numbered files like `images/eye1.png`, `images/eye2.png` ... and `images/nose1.png`, `images/nose2.png` ...
26 |
27 | If you want to set a `cover` for a collection, then save the cover file in `images` folder. Store the cover file name in the `coverFileName` property in the `config.js` file. If you do not need to create a cover, then assign an empty string to `coverFileName`.
28 |
29 | ## Describe NFT traits
30 |
31 | Generally, combinable parts produce NFT traits. For example, if the `nose1.png` image is used to generate the NFT image, it will have `Snub Nose` trait. Here is how to code this:
32 |
33 | Create `config.js` from `config.example.js` file. The property `attributes` in `config.js` file should describe traits of your NFT collection. Each trait should have
34 |
35 | * A `name` field that is used as a file name prefix for accessing your NFT part images. For example, all "nose" images are kept in files like `images/nose1.png`, `images/nose2.png`, etc.
36 | * A `required` field basically tells the image generator that a certain trait should always be present or not
37 | * The `values` field contains trait names. For example, the `images/nose1.png` adds a Snub Nose to the NFT. If you want to make a particular trait more frequent, add a `weight` to the value of the trait name.
38 |
39 | ```
40 | attributes: [
41 | { name: "head", required: true, values: ["Regular Head"] },
42 | { name: "eye", required: true, values: ["Normal Eyes", "Tired Eyes", "Brused Eyes"] },
43 | { name: "brow", required: true, values: ["Thick Brows", "Greyish Brows", "Flat Brows"] },
44 | { name: "nose", required: true, values: ["Snub Nose", "Button Nose", "Droopy Nose"] },
45 | { name: "hair", required: false, values: ["Normal Hair", "Hipster Style", "Messy Hair", "Overdue for Haircut", "Bald Patches"] },
46 | { name: "mouth", required: true, values: ["Smirk", "Regular Smile", {value: "Wide Smile", weight: 3}] }
47 | ]
48 | ```
49 |
50 | The order in which traits come is important: It is used as a z-order when images are merged. The traits (parts) that come lower in the list of traits will be added to the image later, so they will cover up parts that come earlier.
51 |
52 | ## Prepare Substrate Address with Seed
53 |
54 | If you have never worked with Substrate addresses and seeds before, use these steps from the Marketplace README guide:
55 |
56 | * [Install Polkadot{.js} Extension](https://github.com/UniqueNetwork/marketplace-docker#step-1---install-polkadotjs-extension)
57 | * [Create Admin Address](https://github.com/UniqueNetwork/marketplace-docker#step-2---create-admin-address)
58 | * [Get Unique Tokens](https://github.com/UniqueNetwork/marketplace-docker#step-3---get-unique)
59 |
60 |
61 | ## Configure Collection Owner Seed
62 |
63 | Once you have the Seed Phrase ready, add your Seed Phrase to the `config.js` in `ownerSeed` field (replace `//Alice`):
64 |
65 | ```
66 | const config = {
67 | endpoint: 'https://rest.unique.network/opal',
68 | ownerSeed: '//Alice',
69 |
70 | imagePartsFolder: './images',
71 | imagePrefix: 'workoholic_',
72 | imageWidth: 1706,
73 | ...
74 | ```
75 |
76 | #### Public endpoints
77 |
78 | You can use public endpoints for access Rest:
79 |
80 | #### Opal
81 | ```
82 | https://rest.unique.network/opal/v1
83 | ```
84 |
85 | #### Quartz
86 | ```
87 | https://rest.unique.network/quartz/v1
88 | ```
89 |
90 | #### Unique
91 | ```
92 | https://rest.unique.network/unique/v1
93 | ```
94 |
95 | ## Step 1: Generate NFT Properties
96 |
97 | Set the required number of tokens in the `config` file using the `requiredCount` filed.
98 |
99 | Execute following commands in the terminal. The `step1-nft-generator.js` script will generate a unique set of NFT properties for each NFT.
100 |
101 | ```
102 | npm install
103 | node step1-nft-generator.js
104 | ```
105 |
106 | This script will create `generated-nfts` folder, and save two files: `nfts.json` - array of NFT properties for each NFT.
107 |
108 | ## Step 2: Generate NFT Images
109 |
110 | First, set the correct image width in the `imageWidth` method in `config.js` property as shown below so that the image merging library knows how to offset image parts:
111 | ```
112 | imageWidth: 1706,
113 | ```
114 |
115 | This script will generate NFT images from image parts using the NFT properties generated in the previous step.
116 |
117 | ```
118 | node step2-image-generator.js
119 | ```
120 |
121 | This script will add NFT images to `generated-nfts` folder.
122 |
123 | ## Step 3: Create Collection
124 |
125 | At this step you will host images on IPFS, create the NFT collection and set it's properties on-chain.
126 |
127 | First, configure the main collection properties such as name, description, and token prefix in `step3-create-collection.js` file. Note that these properties cannot be changed after the collection is created:
128 | ```
129 | const inputDataForCreateCollection = {
130 | mode: 'Nft',
131 | name: 'NFTWorkshop',
132 | description: 'NFT Workshop collection',
133 | tokenPrefix: 'TMP',
134 | metaUpdatePermission: 'ItemOwner',
135 | ...
136 | ```
137 |
138 | Now you are ready to execute the blockchain transactions:
139 | ```
140 | node step3-create-collection.js
141 | ```
142 |
143 | A typical terminal output for this script should look like follows:
144 |
145 |
146 | Click to expand
147 |
148 | ```
149 | $ node step3-create-collection.js
150 | /usr/bin/node /home/anna/Desktop/projects/main-workshop/nft-workshop/step3-create-collection.js
151 | === Upload images ===
152 | Images uploaded and available by https://ipfs.uniquenetwork.dev/ipfs/QmcBmP2AerP9TdpoXEs3SFkMcVZ78Uy31tFVemvZonuDHj
153 | === Create collection ===
154 | Collection created: 224
155 | ```
156 |
157 |
158 |
159 | Note the output of the collection ID:
160 | ```
161 | Collection created: 224
162 | ```
163 |
164 | ## Step 4: Mint NFTs
165 |
166 | 1. Configure collection ID in `config.js` file in field `collectionId`:
167 |
168 | ...
169 | collectionId: 224
170 | ...
171 |
172 | 2. Now it's time to mint NFTs. Execute this script and wait for it to complete:
173 | ```
174 | node step4-create-items.js
175 | ```
176 |
177 | A typical terminal output for this script should look like follows:
178 |
179 |
180 | Click to expand
181 |
182 | ```
183 | $ node step4-create-items.js
184 | === Create items ===
185 | successfully created batch of tokens 1
186 | successfully created batch of tokens 2
187 | Items created
188 | Token Ids: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
189 | ```
190 |
191 |
192 |
193 | ## See your NFTs in the wallet
194 |
195 | Open [https://wallet.unique.network](https://wallet.unique.network) and enjoy your new collection!
196 |
197 | ## Optional Step: Start your own marketplace to trade your collection
198 |
199 | Follow this guide to start the marketplace (and remember to configure the collection ID in fronend .env file):
200 |
201 | [https://github.com/UniqueNetwork/marketplace-docker](https://github.com/UniqueNetwork/marketplace-docker)
202 |
203 | After your marketplace is up, you will see your collection in your wallet:
204 |
205 | 
206 |
--------------------------------------------------------------------------------
/config.example.js:
--------------------------------------------------------------------------------
1 | const config = {
2 | endpoint: 'https://rest.unique.network/opal/v1',
3 | ownerSeed: '//Alice',
4 |
5 | imagePartsFolder: './images',
6 | imagePrefix: 'workoholic_',
7 | imageWidth: 1706,
8 | coverFileName: 'cover.png',
9 | collectionName: 'NFTWorkshop',
10 | collectionDescription: 'NFT Workshop collection',
11 | tokenPrefix: 'TMP',
12 |
13 | desiredCount: 120,
14 | numberOfTokensGeneratedAtOnce: 50,
15 |
16 | attributes: [
17 | { name: 'head', required: true, values: ['Regular Head'] },
18 | { name: 'eye', required: true, values: ['Normal Eyes', 'Tired Eyes', 'Brused Eyes'] },
19 | { name: 'brow', required: true, values: ['Thick Brows', 'Greyish Brows', 'Flat Brows'] },
20 | { name: 'nose', required: true, values: ['Snub Nose', 'Button Nose', 'Droopy Nose'] },
21 | { name: 'hair', required: false, values: ['Normal Hair', 'Hipster Style', 'Messy Hair', 'Overdue for Haircut', 'Bald Patches'] },
22 | { name: 'mouth', required: true, values: ['Smirk', 'Regular Smile', {value: 'Wide Smile', weight: 3}] }
23 | ],
24 | outputFolder: './generated-nfts',
25 | outputJSON: 'nfts.json',
26 | imagesInParallel: require('os').cpus().length,
27 | }
28 |
29 | module.exports = config;
30 |
--------------------------------------------------------------------------------
/doc/NFT-Workshop.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/doc/NFT-Workshop.pdf
--------------------------------------------------------------------------------
/doc/combine.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/doc/combine.png
--------------------------------------------------------------------------------
/doc/marketplace.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/doc/marketplace.png
--------------------------------------------------------------------------------
/images/brow1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/brow1.png
--------------------------------------------------------------------------------
/images/brow2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/brow2.png
--------------------------------------------------------------------------------
/images/brow3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/brow3.png
--------------------------------------------------------------------------------
/images/cover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/cover.png
--------------------------------------------------------------------------------
/images/eye1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/eye1.png
--------------------------------------------------------------------------------
/images/eye2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/eye2.png
--------------------------------------------------------------------------------
/images/eye3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/eye3.png
--------------------------------------------------------------------------------
/images/hair1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/hair1.png
--------------------------------------------------------------------------------
/images/hair2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/hair2.png
--------------------------------------------------------------------------------
/images/hair3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/hair3.png
--------------------------------------------------------------------------------
/images/hair4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/hair4.png
--------------------------------------------------------------------------------
/images/hair5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/hair5.png
--------------------------------------------------------------------------------
/images/head1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/head1.png
--------------------------------------------------------------------------------
/images/mouth1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/mouth1.png
--------------------------------------------------------------------------------
/images/mouth2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/mouth2.png
--------------------------------------------------------------------------------
/images/mouth3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/mouth3.png
--------------------------------------------------------------------------------
/images/nose1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/nose1.png
--------------------------------------------------------------------------------
/images/nose2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/nose2.png
--------------------------------------------------------------------------------
/images/nose3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UniqueNetwork/nft-workshop/82c7a08339ef0f7652b285154d55537817bf91e8/images/nose3.png
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "decodednft",
3 | "version": "1.0.0",
4 | "description": "NFT Collection Dedicated to Polkadot Decoded 2021",
5 | "main": "",
6 | "directories": {
7 | "test": "test"
8 | },
9 | "scripts": {
10 | "test": ""
11 | },
12 | "author": "",
13 | "license": "Apache 2.0",
14 | "homepage": "",
15 | "dependencies": {
16 | "@polkadot/api": "6.0.5",
17 | "@unique-nft/accounts": "^0.3.4",
18 | "@unique-nft/client": "^0.1.6",
19 | "@unique-nft/sdk": "^0.1.13",
20 | "adm-zip": "^0.5.9",
21 | "bignumber.js": "^9.0.0",
22 | "fs": "^0.0.1-security",
23 | "merge-img": "^2.1.3",
24 | "png-crop": "^0.0.2",
25 | "sprintf-js": "^1.1.2",
26 | "threads": "^1.7.0"
27 | },
28 | "standard": {
29 | "globals": [
30 | "it",
31 | "assert",
32 | "beforeEach",
33 | "afterEach",
34 | "describe",
35 | "contract",
36 | "artifacts"
37 | ]
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/scripts/create-zip.js:
--------------------------------------------------------------------------------
1 | const config = require('../config');
2 | const AdmZip = require('adm-zip');
3 | const path = require('path');
4 | const fs = require('fs');
5 | const faces = JSON.parse(fs.readFileSync(`${config.outputFolder}/${config.outputJSON}`));
6 |
7 |
8 | async function createZipArchive() {
9 | try {
10 | const zipPath = path.resolve(
11 | config.outputFolder,
12 | 'archive.zip',
13 | );
14 |
15 | const zip = new AdmZip();
16 |
17 | if (config.coverFileName) {
18 | zip.addLocalFile(path.resolve(
19 | config.imagePartsFolder,
20 | config.coverFileName,
21 | ));
22 | }
23 |
24 | const indexes = Array.from({ length: config.desiredCount },(_, i) => i+1);
25 | indexes.forEach((i) => {
26 | const face = faces[i-1];
27 | if (face) {
28 | zip.addLocalFile(path.resolve(
29 | config.outputFolder,
30 | `${config.imagePrefix}${i}.png`,
31 | ));
32 | }
33 | });
34 |
35 | zip.writeZip(zipPath);
36 | return zipPath;
37 | } catch (e) {
38 | throw new Error(`error creating zip: ${e}`);
39 | }
40 | }
41 |
42 | module.exports = createZipArchive;
43 |
--------------------------------------------------------------------------------
/scripts/generate-image.worker.js:
--------------------------------------------------------------------------------
1 | const { expose } = require("threads/worker");
2 | const mergeImg = require('merge-img');
3 |
4 | expose(async function generateImage({images, output, num}) {
5 | const img = await mergeImg(images);
6 | await new Promise(resolve => {
7 | img.write(output, () => resolve());
8 | });
9 | return num;
10 | });
11 |
--------------------------------------------------------------------------------
/scripts/initialize-sdk.js:
--------------------------------------------------------------------------------
1 | const config = require('../config');
2 | const { KeyringProvider } = require("@unique-nft/accounts/keyring");
3 | const { Sdk } = require("@unique-nft/sdk");
4 |
5 | async function initializeSdk() {
6 | try {
7 | const provider = new KeyringProvider({ type: 'sr25519' });
8 | await provider.init();
9 | const signer = provider.addSeed(config.ownerSeed);
10 |
11 | const clientOptions = {
12 | baseUrl: config.endpoint,
13 | signer
14 | };
15 | return {
16 | sdk: new Sdk(clientOptions),
17 | signer
18 | };
19 | } catch (e) {
20 | throw new Error(`error initialize sdk: ${e}`);
21 | }
22 | }
23 |
24 | module.exports = initializeSdk;
25 |
--------------------------------------------------------------------------------
/scripts/upload-images.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | const { writeData } = require('./utils');
3 |
4 | async function uploadImages(sdk, zipPath) {
5 | try {
6 | console.log('=== Upload images ===');
7 | const { fileUrl } = await sdk.ipfs.uploadZip({ file: fs.readFileSync(zipPath) });
8 |
9 | console.log(`Images uploaded and available at ${fileUrl}`);
10 | await writeData('fileUrl', fileUrl);
11 | return fileUrl;
12 | } catch (e) {
13 | throw new Error(`error upload images: ${e}`);
14 | }
15 | }
16 |
17 | module.exports = uploadImages;
18 |
--------------------------------------------------------------------------------
/scripts/utils.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | const path = require('path');
3 | const config = require('../config');
4 |
5 | async function writeData(field, value) {
6 | try {
7 | const filePath = path.resolve(
8 | config.outputFolder,
9 | 'data.json',
10 | );
11 | let data = {};
12 | if (fs.existsSync(filePath)) data = JSON.parse(fs.readFileSync(filePath));
13 | data[field] = value;
14 | fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
15 | } catch(e) {
16 | throw new Error(`error write value: ${e}`);
17 | };
18 | }
19 |
20 | async function readData(field) {
21 | try {
22 | const filePath = path.resolve(
23 | config.outputFolder,
24 | 'data.json',
25 | );
26 | if (!fs.existsSync(filePath)) return null;
27 | const data = JSON.parse(fs.readFileSync(filePath));
28 | return data[field];
29 | } catch(e) {
30 | throw new Error(`error read value: ${e}`);
31 | };
32 | }
33 |
34 | module.exports = {
35 | writeData,
36 | readData
37 | };
38 |
--------------------------------------------------------------------------------
/step1-nft-generator.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | var BigNumber = require('bignumber.js');
3 | const config = require('./config.js');
4 |
5 | const attributes = config.attributes;
6 |
7 | function getRandomInt(max) {
8 | return BigNumber.random(20)
9 | .multipliedBy(max - 1)
10 | .plus(1)
11 | .integerValue();
12 | }
13 |
14 | function attributeName(i) {
15 | return attributes[i].name;
16 | }
17 |
18 | function propertyName(i, j) {
19 | const property = attributes[i].values[j - 1];
20 | return property?.value ? property?.value : property;
21 | }
22 |
23 | function logAttributes(prefix, face) {
24 | console.log(prefix, face.map((value, index) => {
25 | return [attributeName(index), propertyName(index, value)];
26 | }));
27 | }
28 |
29 | function getLenByWeights(values, required = false) {
30 | const weight = values.reduce((acc, v) => {
31 | return acc + (typeof v === "object" && v.weight ? v.weight : 1);
32 | }, 0);
33 | return weight + !+required;
34 | }
35 |
36 | function mapValueByWeight(values, property) {
37 | const map = {};
38 | values.forEach((value, index) => {
39 | const weight = typeof value === "object" && value.weight ? value.weight : 1;
40 | const lastIndex = Object.keys(map).length;
41 | for (let i=0; i=0; i--) {
52 |
53 | const len = getLenByWeights(
54 | attributes[i].values,
55 | attributes[i].required,
56 | );
57 |
58 | let property = parseInt(code.mod(len).toFixed()) + +attributes[i].required;
59 |
60 | arr[i] = mapValueByWeight(attributes[i].values, property);
61 |
62 | code = code.minus(arr[i]).dividedBy(len).integerValue();
63 | }
64 |
65 | return arr;
66 | }
67 |
68 | function bnIncludes(arr, bn) {
69 | for (let i=0; i 0) {
14 | const img = {
15 | src: `${config.imagePartsFolder}/${attributes[i].name}${arr[i]}.png`,
16 | offsetX: (i == 0) ? 0 : -config.imageWidth,
17 | offsetY: 0,
18 | }
19 | images.push(img);
20 | }
21 | }
22 |
23 | return images;
24 | }
25 |
26 | function printAttributes(i) {
27 | let attrs = '[' + faces[i] + '] => ';
28 | for (let j=0; j 0) {
30 | attrs += attributes[j].values[faces[i][j]-1] + ", ";
31 | }
32 | }
33 |
34 | console.log(`Attributes for NFT ${i+1}:`, attrs);
35 | }
36 |
37 | async function generateImages() {
38 |
39 | const pool = Pool(() => spawn(new Worker('./scripts/generate-image.worker')), config.imagesInParallel);
40 |
41 | for (let i=0; i {
50 | const num = await generateImage({ images, output, num: i });
51 | printAttributes(num);
52 | });
53 | }
54 |
55 | await pool.completed()
56 | await pool.terminate()
57 |
58 | }
59 |
60 | async function main() {
61 | faces = JSON.parse(fs.readFileSync(`${config.outputFolder}/${config.outputJSON}`));
62 | console.time('images');
63 | await generateImages();
64 | console.timeEnd('images');
65 | }
66 |
67 | main();
68 |
69 |
--------------------------------------------------------------------------------
/step3-create-collection.js:
--------------------------------------------------------------------------------
1 | const config = require('./config');
2 | const attributes = config.attributes;
3 | const createZipArchive = require('./scripts/create-zip');
4 | const initializeSdk = require('./scripts/initialize-sdk');
5 | const uploadImages = require('./scripts/upload-images');
6 | const { readData, writeData } = require('./scripts/utils');
7 |
8 | const inputDataForCreateCollection = {
9 | mode: 'Nft',
10 | name: config.collectionName,
11 | description: config.collectionDescription,
12 | tokenPrefix: config.tokenPrefix,
13 | metaUpdatePermission: 'ItemOwner',
14 | readOnly: true,
15 | schema: {
16 | coverPicture: {},
17 | image: {
18 | urlTemplate: '/ipfs//{infix}'
19 | },
20 | schemaName: 'unique',
21 | schemaVersion: '1.0.0',
22 | attributesSchemaVersion: '1.0.0'
23 | }
24 | }
25 |
26 | async function main() {
27 |
28 | const zipPath = await createZipArchive();
29 | const { sdk, signer } = await initializeSdk();
30 | // todo remove with @unique-nft/sdk@^0.1.6
31 | sdk.instance.defaults.maxBodyLength = Infinity;
32 | let fileUrl = await readData('fileUrl');
33 | if (!fileUrl) fileUrl = await uploadImages(sdk, zipPath);
34 |
35 | console.log('=== Create collection ===');
36 | const attributesSchema = {};
37 | attributes.forEach(({ name, required, values }, i) => {
38 | const enumValues = {};
39 | values.forEach((value, j) => {
40 | enumValues[j.toString()] = { _: value.value ?? value };
41 | });
42 | attributesSchema[i.toString()] = {
43 | name: {
44 | _: name,
45 | },
46 | type: 'string',
47 | optional: !required,
48 | isArray: false,
49 | enumValues: enumValues
50 | };
51 | });
52 |
53 | inputDataForCreateCollection.schema.attributesSchema = attributesSchema;
54 | inputDataForCreateCollection.schema.image.urlTemplate = `${fileUrl}/{infix}`;
55 | inputDataForCreateCollection.schema.coverPicture = config.coverFileName
56 | ? { urlInfix: config.coverFileName }
57 | : { ipfsCid: '' };
58 |
59 | const { parsed: { collectionId }} =
60 | await sdk.collections.creation.submitWaitResult(
61 | {
62 | ...inputDataForCreateCollection,
63 | address: signer.instance.address
64 | },
65 | );
66 | await writeData('collectionId', collectionId);
67 | console.log(`Collection created: ${collectionId}`);
68 | }
69 |
70 | main().catch(console.error).finally(() => process.exit());
71 |
--------------------------------------------------------------------------------
/step4-create-items.js:
--------------------------------------------------------------------------------
1 | const config = require('./config');
2 | const faces = require(`${config.outputFolder}/${config.outputJSON}`);
3 | const initializeSdk = require('./scripts/initialize-sdk');
4 | const { readData } = require('./scripts/utils');
5 |
6 | async function main() {
7 | console.log('=== Create items ===');
8 |
9 | const collectionId = await readData('collectionId');
10 | if (!collectionId) throw new Error('not found collectionId');
11 |
12 | const { sdk, signer } = await initializeSdk();
13 |
14 | const { tokenId: lastTokenId } = await sdk.collections.lastTokenId({ collectionId });
15 | const offset = lastTokenId || 0;
16 | if (config.desiredCount <= offset) {
17 | console.log('tokens already created');
18 | return;
19 | }
20 |
21 | const data = Array(config.desiredCount)
22 | .slice(offset || 0)
23 | .fill({})
24 | .map((el, i) => {
25 | const n = i + 1;
26 | const image = { urlInfix: `${config.imagePrefix}${n}.png`};
27 | const encodedAttributes = {};
28 | faces[i].forEach((el, j) => {
29 | if (el) {
30 | encodedAttributes[j] = el - 1;
31 | }
32 | });
33 | return {
34 | data: {
35 | image,
36 | encodedAttributes
37 | }
38 | }
39 | });
40 |
41 | let result = [];
42 | let chunkNumber = 0;
43 | while (result.length + offset < config.desiredCount) {
44 | if (chunkNumber > config.desiredCount / config.numberOfTokensGeneratedAtOnce) throw new Error('unexpected value chunkNumber');
45 | const chunkData = data.slice(chunkNumber * config.numberOfTokensGeneratedAtOnce, (chunkNumber + 1) * config.numberOfTokensGeneratedAtOnce);
46 | const { parsed } = await sdk.tokens.createMultiple.submitWaitResult({
47 | address: signer.instance.address,
48 | collectionId: collectionId,
49 | tokens: chunkData
50 | });
51 |
52 | result = [ ...result, ...parsed];
53 | await new Promise(resolve => setTimeout(resolve, 1000));
54 | chunkNumber++;
55 | console.log(`successfully created ${chunkNumber} part of tokens`);
56 | }
57 |
58 | console.log('Items created');
59 | console.log(`Token Ids: ${result.map(el => el.tokenId).join(', ')}`);
60 | }
61 |
62 | main().catch(console.error).finally(() => process.exit());
63 |
--------------------------------------------------------------------------------