<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Eto Vass on Medium]]></title>
        <description><![CDATA[Stories by Eto Vass on Medium]]></description>
        <link>https://medium.com/@eto.vass.art?source=rss-0d29e5d3cc9b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zmWdlqFkfE6Z0ZUZvcqi3g.png</url>
            <title>Stories by Eto Vass on Medium</title>
            <link>https://medium.com/@eto.vass.art?source=rss-0d29e5d3cc9b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:19:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eto.vass.art/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Fully On-Chain SVG NFTs — Part 4: Efficient String Concatenation with (Dynamic) Buffers]]></title>
            <link>https://medium.com/@eto.vass.art/fully-on-chain-svg-nfts-part-4-efficient-string-concatenation-with-dynamic-buffers-c1938d55c7d0?source=rss-0d29e5d3cc9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1938d55c7d0</guid>
            <dc:creator><![CDATA[Eto Vass]]></dc:creator>
            <pubDate>Tue, 27 May 2025 20:02:53 GMT</pubDate>
            <atom:updated>2025-05-27T20:02:53.173Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fully On-Chain SVG NFTs — Part 4: Efficient String Concatenation with (Dynamic) Buffers</h3><h3>Recap/Intro</h3><p>In the first 3 articles for fully on-chain SVG NFTs, we covered all of the basics that would allow you to create such NFTs. Starting from part 4, we will cover more advanced concepts that are beyond the scope of the basics but are important to enhance your knowledge. The first 3 articles are linked here:</p><ul><li><a href="https://medium.com/@eto.vass.art/how-to-create-fully-on-chain-svg-nft-part-1-basic-svg-rendering-17b8fea08739">Fully On-Chain SVG NFT — Part 1: Basic SVG Rendering</a></li><li><a href="https://medium.com/@eto.vass.art/fully-on-chain-svg-nfts-part-2-erc-721-ntf-contract-89a8880efd82">Fully On-Chain SVG NFTs — Part 2: ERC-721 NTF Contract</a></li><li><a href="https://medium.com/@eto.vass.art/fully-on-chain-svg-nfts-part-3-minting-website-b7c372ce7344">Fully On-Chain SVG NFTs — Part 3: Minting Website</a></li></ul><h3>Problem Statement</h3><p>When developing fully on-chain SVG NFTs, you generate SVG content with Solidity code. They are also called EVM-Generated NFTs.</p><p>SVG generation is a core part of each EVM-generated NFT. Thus, it has to be efficient and consume as <strong>little</strong> gas as possible.</p><h3>GAS</h3><p>Gas is an essential element of the Ethereum network. It is important for transactions and read operations (tokenURI, for example). Every EVM node has a limit for read gas.</p><p>As a rule of thumb:</p><ul><li>public/free nodes have a read gas limit of <strong>30M</strong></li><li>commercial nodes like Alchemy, Infura etc, have different higher limits, it is safe to assume that <strong>300M</strong> is the <strong>lower</strong> limit for them. Marketplaces like Opensea use these nodes, thus they will be able to display your on-chain SVG NFT if they consume under 300M read gas</li></ul><p>Although 300M is a practical limit, we recommend trying to fit in 30M gas limit if you want to be a real on-chain maxi. 30M makes SVG NFTs much more interesting from a technical standpoint due to the gas limit.</p><h3>String Concatenation</h3><p>When constructing SVG content with Solidity, string concatenation is one of the most important operations. Thus, it has to be efficient. In this article we will test several ways of concatenating strings:</p><h3>1. string.concat()</h3><pre>string memory svg = &quot;&quot;;<br>svg = string.concat(svg, &#39;&lt;circle cx=&quot;10&quot; cy=&quot;10&quot; r=&quot;10&quot; fill=&quot;red&quot;/&gt;&#39;);</pre><h3>2. abi.encodePacked()</h3><pre>string memory svg = &quot;&quot;;<br>svg = string(abi.encodePacked(svg, &#39;&lt;circle cx=&quot;10&quot; cy=&quot;10&quot; r=&quot;10&quot; fill=&quot;red&quot;/&gt;&#39;));</pre><h3>3. (Dynamic) Buffers</h3><p>(Dynamic) Buffers is a method for concatenating strings, using a pre-allocated buffer that can be fixed or can grow. This approach is much more gas efficient that string.concat() and abi.encodePacked(), because the other two methods technically create new memory allocation on each concatenation, thus could be very inefficient.</p><p>Multiple implementations are available for Dynamic Buffers. We will test several implementations:</p><p><strong>3.1. Dynamic Buffer</strong> that was initially created by David Huber (<a href="https://x.com/cxkoda">https://x.com/cxkoda</a>) and Simon Fremaux (<a href="https://x.com/dievardump">https://x.com/dievardump</a>), which was further enhanced by <strong>0xthedude</strong> (<a href="https://x.com/0xthedude">https://x.com/0xthedude</a>) in <a href="https://github.com/intartnft/scripty.sol"><strong>scripty.sol</strong></a>. Implementation is available here: <a href="https://github.com/intartnft/scripty.sol/blob/main/contracts/scripty/utils/DynamicBuffer.sol">https://github.com/intartnft/scripty.sol/blob/main/contracts/scripty/utils/DynamicBuffer.sol</a></p><p><strong>3.2 Solady (</strong><a href="https://x.com/optimizoor"><strong>https://x.com/optimizoor</strong></a><strong>) Dynamic Buffer</strong> <a href="https://github.com/Vectorized/solady/blob/main/src/utils/DynamicBufferLib.sol">https://github.com/Vectorized/solady/blob/main/src/utils/DynamicBufferLib.sol</a></p><p><strong>3.3 no_side (</strong><a href="https://x.com/no_side666"><strong>https://x.com/no_side666</strong></a><strong>) Dynamic Buffer</strong> <a href="https://etherscan.io/address/0xE3ccab3bC1A943Edd01d3a4B0F7C2B3D74C2b7B0#code#F31#L1">https://etherscan.io/address/0xE3ccab3bC1A943Edd01d3a4B0F7C2B3D74C2b7B0#code#F31#L1</a></p><p><strong>no_side</strong> recently released a platform for fully on-chain pixel art. Don’t miss out on checking it out; it is an impressive work. Here:</p><p><a href="https://dreamstack.xyz/">DreamStack</a></p><h3>Putting It All Together</h3><p>In directory <strong><em>tutorial-4-buffers</em></strong> I put all of the code for this tutorial. It is mainly the file <strong><em>src/BasicSVGRenderer2.sol</em></strong>, which renders certain number of circle into SVG (through tokenId param), so we can measure how much gas each of the methods consume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7z4EmavAs2pEGkqzvkwug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXq_K2INzBWNVpgQjLjgzw.png" /></figure><p>We also modified test files in <strong><em>test/</em> </strong>directory and created a script called <strong><em>run-tests.sh</em></strong></p><p>This script will run BasicSVGRenderer contract with 10 50 100 200 300 500 1000 1200 1500 2000 3000 5000 10000 15000 as value for tokenId (i.e number of circles) and for each of the SVG rendering methods, to compare the GAS consumption.</p><h3>Results</h3><p>Running the script will create a results.csv file, which measures the gas consumption for each method for a specific number of circles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYi7vmYMtLZpjMZr0QX3Og.png" /></figure><p>From this results it is very visible that string.concat() and abi.encodePacked() are very similar in gas consumption. But also very inefficient.</p><p>Thus, if your project involves many string concatenations, it is highly recommended that you use some of the (Dynamic) Buffers implementation.</p><p>It is visible that <strong>no_side</strong> implementation is the most gas-efficient for smaller outputs of up to around 50K. For bigger outputs, <strong>the_dude</strong> outperforms it, since <strong>no_side</strong> implementation allocates double the amount of memory, but it is really dynamic — i.e., you don’t need to know the output in advance. The biggest disadvantage of <strong>the_dude</strong> implementation is that you need to estimate the size of the buffer you will need since it must be pre-allocated. Sokady and no_side implementations allow dynamic resizing.</p><h3>Links</h3><p><strong>Git Repo for this tutorial:</strong></p><ul><li><a href="https://github.com/etovass/svg-nft-tutorials">https://github.com/etovass/svg-nft-tutorials</a></li><li>FOCM3 — a fully on-chain match 3 puzzle game as NFT in ERC 721 token — <a href="https://focm3.etovass.xyz/">https://focm3.etovass.xyz/</a></li><li>Advanced technical article on how FOCM3 was created:</li></ul><p><a href="https://medium.com/@eto.vass.art/fully-on-chain-nft-game-the-technical-story-of-focm3-ec291a1b87ff">Fully on-chain NFT Game — The technical story of FOCM3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1938d55c7d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fully on-chain NFT Game — The technical story of FOCM3]]></title>
            <link>https://medium.com/@eto.vass.art/fully-on-chain-nft-game-the-technical-story-of-focm3-ec291a1b87ff?source=rss-0d29e5d3cc9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec291a1b87ff</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[on-chain-game]]></category>
            <category><![CDATA[nft]]></category>
            <dc:creator><![CDATA[Eto Vass]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 17:12:53 GMT</pubDate>
            <atom:updated>2025-01-06T23:04:54.628Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fully On-chain NFT Game — The Technical Story of FOCM3</h3><p>An year ago I was fascinated with the idea to release a puzzle game as NFT. This turned into reality with <strong>FOCM3</strong>, which was released in January 2025.</p><p>FOCM3 stands for <strong>F</strong>ully <strong>O</strong>n-<strong>C</strong>hain <strong>M</strong>atch <strong>3 </strong>and is exactly what the acronym says — a fully on-chain Match 3 puzzle game. This article will focus on the technical aspects of FOCM3, which is interesting, since many technical challenges were solved during the development of FOCM3.</p><p>The technical goal of this project was:</p><ol><li>everything to be fully on-chain and</li><li>token rendering to take less than 30M gas.</li></ol><p><strong>Both goals are successfully achieved in the released FOCM3 collection.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*NemtivEFrOsawON2NFn3uA.gif" /><figcaption>Playing the game in OpenSea</figcaption></figure><h3>Introduction</h3><p>This article will focus on the technical aspects of creating on-chain NFT as a game, following the technical aspect of FOCM3. Most of the techniques used are agnostic to match 3 games, even agnostic to games and may be applied in other situations.</p><p>By NFT, I mean ERC-721 contract. If you want to deep dive in ERC-721, I have another post that focuses on creating such contracts:</p><p><a href="https://medium.com/@eto.vass.art/fully-on-chain-svg-nfts-part-2-erc-721-ntf-contract-89a8880efd82">https://medium.com/@eto.vass.art/fully-on-chain-svg-nfts-part-2-erc-721-ntf-contract-89a8880efd82</a></p><p>For the purpose of this article, we focus mainly on tokenURI() function, this is the function that actually returns the on-chain NFT itself as JSON Metadata, encoded as Data URI. Good description for the metadata can be found here: <a href="https://docs.opensea.io/docs/metadata-standards">https://docs.opensea.io/docs/metadata-standards</a></p><p>There are two metadata attributes that we will focus on:</p><ul><li><strong>image</strong> — this is the thumbnail, in the preview page of marketplaces. Can be image, but cannot be HTML/JS; Restricted to SVG/PNG/GIF/BMP/WEBP/etc..</li></ul><figure><img alt="image attribute" src="https://cdn-images-1.medium.com/max/1024/1*oEgI7JxFWArWR7FA3RLfaQ.png" /><figcaption>image attribute</figcaption></figure><ul><li><strong>animation_url</strong> — this is the full NFT, can be HTML/JS and be interactive</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjhiA0fN2tiGtxrnRl695Q.png" /></figure><h3>tokenURI()</h3><p>The output of ERC-721 tokenURI() can be summarized with the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6dxjWAp3WCZgORqN_p7YQ.png" /><figcaption>tokenURI</figcaption></figure><p>The diagram shows that:</p><ul><li>game assets and initial puzzle are generated/loaded on-chain and delivered as SVG in <strong>“image”</strong> attribute from the metadata</li><li>game logic as JS is loaded on-chain and inlined in HTML, together with game assets and initial puzzle from the previous step and delivered in <strong>“animation_url”</strong> attribute</li></ul><h3>Game Assets Generation</h3><p>Game assets are either generated or loaded fully on-chain. Geometric figures and stars are procedurally generated, while others are SVG paths that are stored (compressed) on-chain (SSTORE2).</p><p><strong>PathsManager</strong> is the contract that is responsible for creating SVG paths — by either loading them or generating them. <a href="https://etherscan.io/address/0x9de148312e87ce15266f074bcd9305af0a52c799#code">https://etherscan.io/address/0x9de148312e87ce15266f074bcd9305af0a52c799#code</a></p><p>PathsManager uses another contract for loading SVG paths on-chain — <strong>AssetsSSTORE2</strong> — <a href="https://etherscan.io/address/0xefb64111fc6368f9a3f3a15a00f1d02a61293f96">https://etherscan.io/address/0xefb64111fc6368f9a3f3a15a00f1d02a61293f96</a>. This contract uses SSTORE2 and LibZip (since SVG paths are stored compressed and they need to be decompressed on-chain) libraries.</p><p>In this contract, there are several interesting libraries:</p><ul><li><strong>FigurePaths.sol</strong>, specially 1) getFigureCollection() function — this generates figure collection; 2) outlineArraty() function — creates polygon with n sides, 3) outlineStarArray() function — creates stars</li><li><strong>Lib2D.sol</strong>, reusable solidity 2d library, focused on bonding boxes and path rounding</li><li><strong>Trigonometry.sol</strong>, sin/cos, used in polygons/stars generation</li></ul><p>So … the purpose of <strong>PathsManager</strong> is to generate SVG path for one or multiple figures. For example, the chain symbol</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*4o3kek5jToTUDAmm6MZ3RA.png" /><figcaption>chain</figcaption></figure><p>is SVG path: <em>M160 352c-12–12–12–32 0–44L308 160c12–12 32–12 44 0 12 12 12 32 0 44L205 352c-12 12–32 12–44 0Zm342–272c6 16 10 32 10 48s-3 ….</em> (1045 characters total).</p><p><strong>GameRenderer </strong>is a multi purpose contract, focused on 3 things:</p><ul><li>create image: attribute — i.e. the preview of the puzzle</li><li>generate game assets, including converting SVG paths to colored tiles</li><li>decode the initial puzzle for certain tokenId</li></ul><p>Game asset generation is actually converting SVG paths to colored tiles. I.e. this conversion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUyZGV1NrdveL5jinWlacw.png" /><figcaption>path to tile</figcaption></figure><p>Several libraries are used for this conversion:</p><ul><li><strong>Palettes.sol </strong>— generate the color palette for the specific puzzle. It heavily utilizes HSL color model (Hue, Saturation, Lightness) which allow generating visually distinctive colors, changing mainly the Hue.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYSNMxkWSkTaDJosNAi0og.png" /><figcaption>getPalette() from Palettes.sol</figcaption></figure><p>Note: this function may not be used for arbitrary distinctive colors generation. It is only useful for small number of distinctive colors — <strong>6 or less</strong>. For more distinctive colors — different techniques must be used.</p><ul><li><strong>FigureGenerator.sol </strong>— is another important library used by GameRenderer contract and it is focused on adding colors, shadows, wrapping figure in a box, etc. Basically for the conversion of SVG path to colored tile.</li></ul><h3>Loading and Decoding Initial Puzzle</h3><p>Match 3 puzzle generation is compute intensive task. It is NP-complete algorithmically and unfeasible to be done from Solidity code, due to gas constraints. Puzzle generation happens in the JavaScript code, where Genetic Algorithm are used. This will be covered later in the article.</p><p>Considering that it is unfeasible to generate match 3 puzzles from Solidity, the initial puzzle that is viewable in <strong>image:</strong> and <strong>animation_url:</strong> attributes for each tokens are pre-generated. Specifically 400 puzzles are pre-generated and on token mint, one unused (randomly selected) is taken.</p><p>These 400 pre-generated puzzles takes 27kb to describe, which are compressed with LZ77 down to 23kb. Not much savings, but below 24kb, which allow the whole set to be stored with single SSTORE2 block.</p><p>Internally — puzzles are encoded in 2d arrays, where</p><ul><li>0 is <strong>empty block</strong></li><li>7 is <strong>stone</strong> (unmatchable block)</li><li>1–6 are <strong>different tiles used in the puzzle</strong></li></ul><p>Here is an example how a puzzle is encoded to 2d array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-IXtf_ixxb6K4SzM9p7qQ.png" /><figcaption>puzzle encoded as 2d array</figcaption></figure><p>Since possible values are 8, each cell in the puzzle can fit in 4 bits. In the other 4 bits I store hint index, there is a hidden eastern egg in the game that shows hints for first 2 or all of the swaps. As shown here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/0*xD3eC-2qmwj9Bn8p" /><figcaption>hints</figcaption></figure><p>So 1 byte for every cell. Or for puzzle 10x10, 100 bytes. There is also a lookup table to speedup finding the specific puzzle. But how I fit 400 puzzles into 27kb? (400 * 100 = 40,000). The reason for fitting 400 puzzles is that not all of the puzzles are 10x10. Some are 6x6 which take only 36 bytes. Puzzle rows vary from 6 to 10, same for puzzle columns. Thus taking much less space than 10x10.</p><p>PuzzleDecoder.sol is about decoding the puzzle on-chain, which is used to generate <strong>image:</strong> attribute and also passed to HTML for the <strong>animation_url: </strong>attribute</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqZo0PX7bCQlvrB6VHwADQ.png" /></figure><h3>JavaScript — the core game code</h3><p>The main game loop, plus the code for generating new puzzles are in JavaScript. Technically, I used TypeScript, since it is a complex project and I benefit from type-safety. Transpired and minimized with Terser — the JavaScript code is about 50kb. Not good enough if I want to fit in 30MB for gas in tokenURI().</p><p>Thus I compressed it. Using relatively unknown tool called <strong>Roadroller</strong>.</p><p><strong>Roadroller</strong> (<a href="https://github.com/lifthrasiir/roadroller">https://github.com/lifthrasiir/roadroller</a>) is used for compressing JS files for demos that are restricted by the size and thus is very proper for FOCM3 case. Roadroller produces a self-decompressing JS code, that you can just place in HTML and it will work. Roadroller compress the minimized JS file to about 20kb, which is now something we can fit in 30MB gas for tokenURI().</p><p>During the development of game core logic, I wanted to keep the output JS file as small as possible. Thus didn’t use any third party libraries or dependencies. Everything is written from scratch. But in a smart way!</p><p>For example — in order to avoid using animation libraries, SVG SMIL animations are used. They are very powerful and easy to use. For example, for the gravity fall-down effect of the tiles — the following simple SVG animation is used, for every tile that falls due to a mach below it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jaSiDNLz64HLj3UJXb-jYA.png" /><figcaption>Fall animation</figcaption></figure><p>The game graphics itself is SVG content, that is driven by JavaScript. This allow having animations, game core loop and many other benefits, without using any third party libraries.</p><p>One hack for smoother animations — SVG tiles are converted to base64 PNGs at the start of the game. This make the animation very fluent, since browsers now work with binary images (PNGs) and not with vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vsgbw0UhwSZpHH8v5fojDQ.png" /><figcaption>svg</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cm5fdrZcOy0Vw1vKmREAgQ.png" /><figcaption>cached SVG to PNG</figcaption></figure><h3>Puzzle Generation</h3><p>Puzzle Generation is NP complete task. It requires a lot of compute power, and it is not proper to be done on-chain. Thus puzzle generation happens in the JavaScript code of the collection. The puzzle generation code is quite complex and many factors (which are decided randomly based on some weightsP) are taken into account. Here is just a preview of some of the enums used in puzzle generation code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*CtaRhoeedt4Cr9ObcdUrEQ.png" /></figure><p>Genetic algorithm is used to generate puzzles. Basically, we keep a list of N best puzzles generated so far and make an evolution step with each of these to add new insert and extend the puzzle with more figures.</p><p>On each step, we try to expand the puzzle, adding more elements to it. And until a certain limits of tiles in the board is met. Here is the code of the evolution step, this is probably the most interesting part of the algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IA4AkK3HzTpKqGuTVPPxQ.png" /></figure><h3>Putting it all together</h3><p>GameRenderer is also responsible for inlining game assets and initial puzzle data, together delivering the JS into a single HTML file that is generated in <strong>animation_url:</strong> attribute. The template HTML file is very simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_yRKWsJ5kXtxQmckgv_Og.png" /></figure><p>GameRenderer inserts all needed data and JS in the HTML file at the pointed location. This happens with the following function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8WBM6yokjmaY7KqzC-1rg.png" /></figure><p>This function injects the game assets and initial puzzle in the HTML file. JavaScript is injected before storing HTML parts on-chain, with a script that preprocess the HTML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*GrSparvcWjnbc6oTnezq7A.png" /></figure><p>Hope you enjoyed reading about FOCM3 — unique fully on-chain NFT puzzle match 3 game.</p><p>FOCM3 is <strong>minting now</strong> at <a href="https://focm3.etovass.xyz/">https://focm3.etovass.xyz/</a> but not for long. There is no better time to mint a token from this unique NTF collection.</p><p>If you are interested in fully on-chain artwork or technical articles on how to create them, please check my LinkTree profile where you will find my on-chain NFT collections, as well, all my articles. Here: <a href="https://linktr.ee/etovass">https://linktr.ee/etovass</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec291a1b87ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fully On-Chain SVG NFTs — Part 3: Minting Website]]></title>
            <link>https://medium.com/@eto.vass.art/fully-on-chain-svg-nfts-part-3-minting-website-b7c372ce7344?source=rss-0d29e5d3cc9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7c372ce7344</guid>
            <dc:creator><![CDATA[Eto Vass]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 00:08:48 GMT</pubDate>
            <atom:updated>2025-03-07T15:56:04.721Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fully On-Chain SVG NFTs — Part 3: Minting Website</h3><p>In our previous two tutorials (<a href="https://medium.com/@eto.vass.art/how-to-create-fully-on-chain-svg-nft-part-1-basic-svg-rendering-17b8fea08739">part 1</a> and <a href="https://medium.com/@eto.vass.art/fully-on-chain-svg-nfts-part-2-erc-721-ntf-contract-89a8880efd82">part 2</a>), I covered creating an SVG rendering contract and an ERC-721 mint-able contract with OpenZeppelin libraries and deploying the contracts on the blockchain.</p><p>In this third tutorial, I will present how to create a minting website for your on-chain (and not only) projects.</p><h3>Intro</h3><p>Ethereum network operates as a set of nodes that communicate with each other. To communicate with the Ethereum network, your app must make RPC calls to some nodes. Fortunately, you don’t need to run your own nodes; there are node providers like Alchemy, Infura, Thirdweb, Quicknode, and many others that simplify this process. There are also free options (Cloudflare, etc) that can used for testing, but they are not recommended for production since they are rate-limited. A very simplified diagram of what we will cover in this tutorial:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kN_IjygCSZAjnIuV.png" /></figure><p>We will create a Dapp that allows users to interact with your ERC-721 contract — like mint, get contact information, show tokens owned by wallet, etc.</p><h3>Mint.fun</h3><p>Before I continue, sometimes your on-chain collection may be simple enough not to need a full-blown minting website. Marketplaces are suitable for listing your collection, and you can use sites like Mint.fun, which allows you to quickly build a simple minting web page for your ERC-721 contracts without coding skills.</p><p>Here is an example with <a href="https://alienrunes.xyz/">Alien Runes</a>, my first on-chain collection: <a href="https://mint.fun/ethereum/0xb44298c4ef2f474a25A570CE23EcE36Ecfcd45D3">https://mint.fun/ethereum/0xb44298c4ef2f474a25A570CE23EcE36Ecfcd45D3</a></p><p>If you still need a minting website — please continue reading…</p><h3>Technical stack</h3><p>For this tutorial, we will use the following frameworks and libraries:</p><ul><li><a href="https://react.dev/">React</a> — one of the most commonly used libraries for web apps.</li><li><a href="https://nextjs.org/">Next.js</a> — opinionated (IMO — in a good way) and very easy-to-use framework that allows quickly building React apps (that support server-side rendering out of the box).</li><li><a href="https://tailwindcss.com/">Tailwind</a> —a very easy-to-use CSS framework</li><li><a href="https://wagmi.sh/">Wagmi </a>— a library for interacting with Ethereum</li><li><a href="https://www.rainbowkit.com/">RainbowKit</a> — an easy and user-friendly library to connect wallets to your web app</li></ul><h3>Setup</h3><p>As with the previous tutorial, I’ll guide you through each of the steps. If you want to go directly to the code — you can find it in the tutorial <a href="https://github.com/etovass/svg-nft-tutorials">Github</a> repo.</p><p>Create directory <strong>tutorial-3-minting-website</strong>, and install React and Next.js, create Next.js app. Select Yes for everything or defaults. Name your project <strong>nft-mint</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYkcBDV_DHk3GhikYQEGRg.png" /></figure><p>This will install React, Next.js, and Tailwind and will create Next.js app. It will create a folder called <strong>nft-mint</strong> where all of the code will be. Go to this folder and run <strong>npm run dev</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*Zm3YzTCUwwoymi5VRT4IWw.png" /></figure><p>If everything is OK, you will be able to see the default Next.js page by going to <a href="http://localhost:3000:">http://localhost:3000</a>.</p><p>Next:</p><ol><li>Edit <strong>src/app/globals.css</strong> and select your default foreground/text and background colors in :root</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*n5U3-MhSrz8OLZesDrsjtA.png" /><figcaption>src/app/globals.css</figcaption></figure><p>2. Edit <strong>src/app/layout.tsx </strong>— metadata, to give your site title and description (that will be visible in browsers)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*EXvoSivgTdUepUgYMW_6sw.png" /><figcaption>src/app/layout.tsx</figcaption></figure><p>3. Edit <strong>src/app/page.tsx</strong> to show a minimal site with one line of text:</p><pre>export default function Home() {<br>  return (<br>    &lt;main className=&quot;mt-10 flex flex-col gap-8 items-center justify-center &quot;&gt;<br>      &lt;h1&gt;SVG NFT Minting Website&lt;/h1&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>If everything is correct, once you save the files, you will see the updated home page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*26GuPVB5mlr-3uUfCGb7gA.png" /></figure><h3>Wagmi &amp; RainbowKit</h3><p>Now, we are ready to start creating code to interact with the contract. First, we need to install Wagmi and RainbowKit in the <strong>nft-mint</strong> directory.</p><pre>npm install --save @rainbow-me/rainbowkit wagmi viem@2.x @tanstack/react-query</pre><p>This will install Wagmi, RainbowKit and also Viem, and Tanstack, which are needed peer dependencies.</p><p>Create file <strong>src/wagmi.ts</strong> with the following content:</p><pre>import &#39;@rainbow-me/rainbowkit/styles.css&#39;;<br><br>import { fallback, http } from &#39;wagmi&#39;;<br>import { sepolia }  from &#39;wagmi/chains&#39;;<br>import { web3config } from &#39;./dapp.config&#39;;<br>import { darkTheme, getDefaultConfig } from &#39;@rainbow-me/rainbowkit&#39;;<br><br>export const wagmiConfig = getDefaultConfig({<br>    appName: &#39;My NFT Minting App&#39;,<br>    projectId: &#39;YOUR_WALLET_CONNECT_PROJECT_ID&#39;,<br>    chains: [sepolia],<br>    transports: {<br>        [sepolia.id]: fallback([<br>            http(`https://eth-sepolia.g.alchemy.com/v2/${web3config.alchemyApiKey}`),<br>        ])<br>    <br>    },<br>    ssr: true<br>});<br><br>export const myRainbowTheme = darkTheme({<br>    accentColor: &#39;#C2410C&#39;,<br>    accentColorForeground: &#39;white&#39;,<br>    borderRadius: &#39;large&#39;<br>});</pre><p>This file contains the configuration for Wagmi and Rainbow. In <strong>wagmiConfig</strong>, we define the supported chains (in our case, Ethereum Sepolia) and the nodes that will be used to access them. It is an excellent practice to have more than 1 in case some are not responding, or you hit some limits if your collection is very successful. Check <a href="https://www.rainbowkit.com/docs/installation">https://www.rainbowkit.com/docs/installation</a> and <a href="https://wagmi.sh/react/getting-started">https://wagmi.sh/react/getting-started</a> for more details on how to use other chains. Localhost is also supported for locally running test nodes, which is very helpful if you haven’t finalized the contract yet. If your app relies on WalletConnect, you need to obtain a <strong>projectId</strong> from <a href="https://cloud.walletconnect.com/">WalletConnect Cloud</a> (it is free).</p><p>In <strong>myRainbowTheme, </strong>we customize some of the visuals for RainbowKit—in our case, to match the visuals of the minting site. Check here for the full details on how to customize it <a href="https://www.rainbowkit.com/docs/theming">here</a>.</p><p>Create file <strong>src/app/providers.tsx</strong> with the following content:</p><pre>&#39;use client&#39;;<br><br>import React from &#39;react&#39;;<br>import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;;<br>import { WagmiProvider } from &#39;wagmi&#39;;<br>import { RainbowKitProvider } from &#39;@rainbow-me/rainbowkit&#39;;<br><br>import { wagmiConfig, myRainbowTheme } from &#39;../wagmi&#39;;<br><br>const queryClient = new QueryClient();<br><br>export function Providers({ children }: { children: React.ReactNode }) {<br>  return (<br>    &lt;WagmiProvider config={wagmiConfig}&gt;<br>      &lt;QueryClientProvider client={queryClient}&gt;<br>        &lt;RainbowKitProvider theme={myRainbowTheme}&gt;{children}&lt;/RainbowKitProvider&gt;<br>      &lt;/QueryClientProvider&gt;<br>    &lt;/WagmiProvider&gt;<br>  );<br>}</pre><p>This file is needed to inject Wagmi and RainbowKit to our React app.</p><p>And edit <strong>src/app/layout.tsx</strong> to wrap <strong>{children}</strong> with <strong>&lt;Providers&gt;:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0bVCr4Bo1uaLTYy2udh2Q.png" /></figure><p>Once this is done, our React app will have access to Rainbow and Wagmi, and we can take the next step.</p><h3>Connecting your wallet</h3><p>Before you can mint, you shall connect your wallet. This happens with just several lines of code, thanks to Wagmi and RainbowKit.</p><p>Modify <strong>src/app/page.tsx</strong> and add <strong>‘use client’</strong> to the top, this will make the page client side. Also, import <strong>ConnectButton</strong> from RainbowKit and add it to the page:</p><pre>&#39;use client&#39;<br><br>import { ConnectButton } from &quot;@rainbow-me/rainbowkit&quot;;<br>import { useAccount } from &quot;wagmi&quot;;<br><br>export default function Home() {<br>  const {address, isConnected} = useAccount();<br><br>  return (<br>    &lt;main className=&quot;mt-10 flex flex-col gap-8 items-center justify-center &quot;&gt;<br>      &lt;h1&gt;SVG NFT Minting Website&lt;/h1&gt;<br><br>      &lt;ConnectButton label=&quot;Connect Wallet to Mint&quot; /&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>Now the page will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZ4LSPSaeNft0vJ0zCe0Ug.png" /><figcaption>home page</figcaption></figure><p>and if you click the button and connect your wallet — it will be show on the page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uwbt_0ill5rmC20jFPCPA.png" /><figcaption>home page</figcaption></figure><h3>Wagmi CLI</h3><p>Wagmi CLI is a great addition to Wagmi that allows you to achieve full type safety when calling contracts from Typescript code. You can install it with:</p><pre>npm install --save-dev @wagmi/cli</pre><p>Then you can configure it by adding <strong>src/wagmi.config.ts</strong> with the following content</p><pre>import { defineConfig } from &#39;@wagmi/cli&#39;<br>import { actions, foundry, react } from &#39;@wagmi/cli/plugins&#39;<br><br>export default defineConfig({<br>  out: &#39;src/contracts-generated.ts&#39;,<br>  contracts: [],<br>  plugins: [<br>    foundry({<br>      artifacts: &quot;../../tutorial-2-NFT-contract&quot;,<br>      include: [<br>          &quot;NFTManager.sol/**&quot;<br>      ]<br>    }),<br>  ],<br>})</pre><p>This instructs Wagmi CLI to look at the ABI definition of NFTManager.sol and generate a file <strong>src/contracts-generated.ts</strong> that Wagmi can use for type safety. You can also generate Wagmi actions and react hooks from the contract, get contact information from Etherscan, integrate with Foundry and Hardhat, and many others. Check <a href="https://wagmi.sh/cli/api/plugins">Wagmi CLI plugin documentation</a> for more details. In this tutorial, I use Foundry plugin and tell Wagmi CLI where to look for contract data (<strong>artifacts</strong> attribute) as well, the contract name we will interact with (<strong>include</strong> attribute).</p><p>Also add the following in <strong>package.json</strong></p><pre>&quot;scripts&quot;: {    <br>   ...<br>   &quot;wagmi:generate&quot;: &quot;cd ../../tutorial-2-NFT-contract &amp;&amp; forge clean &amp;&amp; forge build &amp;&amp; cd ../tutorial-3-minting-website/nft-mint &amp;&amp; wagmi generate&quot;<br>   ...</pre><p>Now if you run:</p><pre>npm run wagmi:generate</pre><p>then Foundry contracts will be compiled, <strong>src/contracts-generated.ts</strong> will be created, and you can use it in Wagmi.</p><h3>Putting things together</h3><p>We now have everything needed to create mint functionality.</p><p>Create a file <strong>src/dapp.config.ts </strong>with the following content:</p><pre>export const web3config = {<br>    alchemyApiKey: &#39;&lt;YOUR_ALCHEMY_API_KEY&gt;&#39;,<br>    contractAddress: &#39;0x331dbe16931a959055b73ce6cd2a1006ce79972b&#39;,<br>};</pre><p>Put your Alchemy API key in <strong>alchemyApiKey</strong>. In GitHub, I will leave one of my keys restricted only to Sepolia so you can quickly get this up and running. But I cannot guarantee that this key will work forever. If it gets abused, I will disable it.</p><blockquote>Note: putting API keys in your code is not a best practice, and it is not secure. It will be best to put them in environment variables and use them as such in the code. It is outside this tutorial&#39;s scope to dive deep into how to pass env variables to the Next.js application. This is very well documented in Next.js documentation here: <a href="https://nextjs.org/docs/app/building-your-application/configuring/environment-variables">https://nextjs.org/docs/app/building-your-application/configuring/environment-variables</a></blockquote><p><strong>contractAdddress</strong> is the address of the deployed contract in Sepolia, which will be used for minting. By default, I use the same contract that was deployed to Sepolia in <a href="https://medium.com/@eto.vass.art/fully-on-chain-svg-nfts-part-2-erc-721-ntf-contract-89a8880efd82">Part 2</a>, but at some point, it may get minted out. The best thing to do is to replace it with your own contract.</p><p>Next we need to modify <strong>src/app/page.tsx </strong>to implement minting functionality.</p><p>Import all dependencies that you will need:</p><pre>&#39;use client&#39;<br><br>import { ConnectButton } from &quot;@rainbow-me/rainbowkit&quot;;<br>import { useAccount, useReadContract } from &quot;wagmi&quot;;<br>import { web3config } from &quot;../dapp.config&quot;;<br>import { Address } from &quot;viem&quot;;<br>import { nftManagerAbi } from &quot;../contracts-generated&quot;;<br>import { useState } from &quot;react&quot;;<br>import { formatEther } from &quot;viem&quot;;<br>import { writeContract, waitForTransactionReceipt, readContract } from &quot;wagmi/actions&quot;;<br>import { wagmiConfig } from &quot;@/wagmi&quot;;</pre><p>Continue with adding <em>{isConnected &amp;&amp; &lt;MintNFT /&gt;}</em> after <em>&lt;ConnectButton&gt;</em></p><pre>&lt;ConnectButton label=&quot;Connect Wallet to Mint&quot; /&gt;<br><br>{isConnected &amp;&amp; &lt;MintNFT /&gt;}</pre><p>Define <strong>MintState</strong> enum after the imports, this enum will define where we are in the mint process:</p><pre>enum MintState {<br>  IDLE,<br>  WAIT_TO_CONFIRM_TRANSACTION,<br>  WAITING_FOR_TRANSACTION_RECEIPT,<br>  TRANSACTION_CONFIRMED,<br>  TRANSACTION_ERROR<br>}</pre><p>Then, we need to implement MintNFT component, starting with:</p><pre>function MintNFT() {<br>  const {address} = useAccount();<br>  const [mintState, setMintState] = useState(MintState.IDLE);<br>  const [error, setError] = useState(&#39;&#39;);<br>  const [mintedId, setMintedId] = useState(&#39;&#39;);<br>  const [mintedTokenURI, setMintedTokenURI] = useState(&#39;&#39;);</pre><p>There are the state variables that will be used in MintNFT component.</p><ul><li><strong>address</strong> is the connected wallet’s address, NFTs will be minted to this address.</li><li><strong>mintState</strong> is where we are in the minting process. IDLE means it hasn’t started yet.</li><li><strong>error</strong> is used in case mint fails</li><li><strong>mintedId</strong> is the ID of the token that was recently minted</li><li><strong>mintedTokeURI</strong> is the URI of the token that was recently minted</li></ul><p>Then add:</p><pre>  const {data: price, isLoading: isLoadingPrice, isError: isErrorPrice, error: errorPrice} = useReadContract({<br>    address: web3config.contractAddress as Address,<br>    abi: nftManagerAbi,<br>    functionName: &#39;PRICE&#39;<br>  });</pre><p>This will read the mint price from the deployed contract. It uses <strong>useReadContract</strong> hook from Wagmi. The ‘PRICE’ is a public constant defined in tutorial-2-NFT-contract/src/NFTManager.sol:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*GATo3tYKevFHdWVoHAQ9hw.png" /><figcaption>NFTManager.sol</figcaption></figure><p>This is helpful to avoid hardcoding mint price in your Dapp, but instead — to retrieve it from the contract at mint time.</p><p>Add function <strong>mint</strong>. This is <strong><em>where the mint magic happens</em></strong>:</p><pre>  const mint = async () =&gt; {<br>    setMintState(MintState.WAIT_TO_CONFIRM_TRANSACTION);<br><br>    try {  <br>      const mintPriceInWei = price;<br><br>      // 1 - call safeMint<br>      let tx = await writeContract(wagmiConfig, {<br>          address: web3config.contractAddress as Address,<br>          abi: nftManagerAbi,<br>          functionName: &quot;safeMint&quot;,<br>          args: [address as Address],<br>          value: mintPriceInWei,<br>      });<br><br>      setMintState(MintState.WAITING_FOR_TRANSACTION_RECEIPT);<br><br>      // 2 - wait for transaction receipt<br>      let receipt = await waitForTransactionReceipt(wagmiConfig, {<br>          hash: tx<br>      });<br><br>      // 3 - get minted ID<br>      const mintedID = BigInt(receipt?.logs[0]?.topics[3] as string);<br>      setMintedId(mintedID.toString());<br><br>      // 4 - get token URI<br>      const tokenURI = await readContract(wagmiConfig, {<br>        address: web3config.contractAddress as Address,<br>        abi: nftManagerAbi,<br>        functionName: &quot;tokenURI&quot;,<br>        args: [mintedID]<br>      });<br><br>      setMintedTokenURI(tokenURI);<br><br>      setMintState(MintState.TRANSACTION_CONFIRMED);<br>    } catch (error) {<br>      setMintState(MintState.TRANSACTION_ERROR);<br>      setError(error?.toString() ?? &#39;Unknown error&#39;);<br>    }<br>  }</pre><p>There are 4 major steps in this function</p><p><strong>Step 1: </strong>Calls <strong>safeMint()</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*uWTE-u405kzE9ZxHZef77Q.png" /><figcaption>pages.tsx</figcaption></figure><p>This calls the <strong>safeMint()</strong> from <strong>NTFManager.sol</strong> and passes the address to which the new NFT will be minted, as well — the amount (in <strong>value</strong> attribute) that will be paid for the mint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*_9KoPw5pV5x-wTJ3eQvi2w.png" /><figcaption>NFTManager.sol</figcaption></figure><p><strong>Step 2:</strong> Wait for the transaction receipt (transaction to be completed):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*T0kpCk90Nk3kGkbx-aQ-_A.png" /><figcaption>page.tsx</figcaption></figure><p><strong>Step 3: </strong>Gets minted ID from transaction log</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*MhtY3F4D-DWm7rFksGsxug.png" /><figcaption>page.tsx</figcaption></figure><p>This is extracting the minted ID from the transaction log, as viewed in Etherscan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9iWHo54X6gsbWNUf_nXag.png" /><figcaption>Etherscan</figcaption></figure><p><strong>Step 4: </strong>Calls <strong>tokenURI()</strong> from the contract to get information for the newly minted token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*0GqB8Z3lh_amijYhaCh3sA.png" /><figcaption>page.tsx</figcaption></figure><p>This calls the following function from <strong>NFTManager.sol</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPxBehBP2uesC2eDoY64IQ.png" /><figcaption>NFTManager.sol</figcaption></figure><p>Add two more functions:</p><pre>  function formatTokenURI(tokenURI: string) {<br>    const json = JSON.parse(atob(tokenURI.split(&#39;,&#39;)[1]));<br>    delete json.image;<br>    return JSON.stringify(json, null, 2);<br>  }<br><br>  function getImageURL(mintedTokenURI: string): string | undefined {<br>    const json = JSON.parse(atob(mintedTokenURI.split(&#39;,&#39;)[1]));<br>    return json.image;<br>  }</pre><p>The first will base64 decode the JSON returned by tokenURI(), which will later be visualized on successful mint. <strong>image</strong> attribute is deleted, since it is extracted separately and is not necessary to be show, it may also be very big.</p><p>The second function will base64 decode the JSON returned by tokenURI(), and will return an <strong>image</strong> that can be used in &lt;img&gt; tag</p><p>Add return statement for the component and all visualization logic:</p><pre>return (<br>    &lt;div&gt;<br>      {isLoadingPrice &amp;&amp; &lt;p&gt;Loading price...&lt;/p&gt;}<br>      {isErrorPrice &amp;&amp; &lt;span&gt;Error: {errorPrice.message}&lt;/span&gt;}<br>      {price &amp;&amp;<br>        &lt;div className=&quot;flex flex-col items-center&quot;&gt;<br>          &lt;p&gt;Minting from contract address: {web3config.contractAddress}&lt;/p&gt;<br>          &lt;div className=&quot;flex flex-col items-center mt-4 font-bold&quot;&gt;<br>            {(mintState === MintState.IDLE || mintState === MintState.TRANSACTION_CONFIRMED) &amp;&amp;<br>                &lt;button onClick={mint} className=&quot;bg-[#C2410C] text-white px-4 py-2 rounded-lg&quot;&gt;Mint for {formatEther(price)} ETH&lt;/button&gt;<br>            }<br>            {mintState === MintState.WAIT_TO_CONFIRM_TRANSACTION &amp;&amp;<br>              &lt;p&gt;Please confirm the transaction from your wallet...&lt;/p&gt;<br>            }<br>            {mintState === MintState.WAITING_FOR_TRANSACTION_RECEIPT &amp;&amp;<br>              &lt;p&gt;Waiting for transaction receipt...&lt;/p&gt;<br>            }<br>            {mintState === MintState.TRANSACTION_CONFIRMED &amp;&amp;<br>              &lt;div className=&quot;flex flex-col items-center justify-center mt-4 font-bold text-green-500&quot;&gt;<br>                &lt;p&gt;Transaction confirmed!&lt;/p&gt;<br>                &lt;p&gt;Minted ID: {mintedId}&lt;/p&gt;<br>                &lt;img className=&quot;m-4 w-[256px] h-[256px] border-2 rounded-lg border-gray-500 p-4&quot; src={getImageURL(mintedTokenURI)} alt=&quot;NFT&quot; /&gt;<br>                &lt;pre className=&quot;m-4 text-sm whitespace-break-spaces break-all border-2 rounded-lg border-gray-500 p-4&quot; &gt;Token URI: &lt;br/&gt;{formatTokenURI(mintedTokenURI)}&lt;/pre&gt;<br>              &lt;/div&gt;<br>            }<br>            {mintState === MintState.TRANSACTION_ERROR &amp;&amp;<br>              &lt;div&gt;<br>                &lt;p className=&quot;text-red-500&quot;&gt;Transaction failed!&lt;/p&gt;<br>                &lt;pre className=&quot;text-red-500&quot;&gt;{error}&lt;/pre&gt;<br>              &lt;/div&gt;<br>            }<br>          &lt;/div&gt;          <br>        &lt;/div&gt;<br>      }<br>    &lt;/div&gt;<br>  );</pre><p>This is where the visualization happened. Based on the <strong>mintState</strong>, different things will be show on in the app.</p><h3>Testing the mint page</h3><p>After the previous step, we have everything needed to mint. We can test it now.</p><p>If you connect your wallet, you will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZiWhPup_IZAFn_J_1Te5Q.png" /></figure><p>Clicking on Mint will ask you to confirm the transaction in your wallet. Once you do this, the mint process will start. On success (it takes a few seconds), you will see the newly minted token and its traits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZoychT9XetFSAbWw3H-GQ.png" /></figure><p>Congratulations, you implemented the mint functionality for your contracts.</p><h3>List tokens owned by a wallet</h3><p>The contract in part 2 that we use here uses the <strong>ERC721Enumerable</strong> extension (a good description of the extension can be found here: <a href="https://medium.com/@juanxaviervalverde/erc721enumerable-extension-what-how-and-why-8ba3532ea195">https://medium.com/@juanxaviervalverde/erc721enumerable-extension-what-how-and-why-8ba3532ea195</a>) which allows us to enumerate all tokens that are owned by a particular wallet. We can use this to show tokens owned by a specific wallet address.</p><p>Add the following to <strong>src/app/page.tsx</strong>:</p><pre>function ShowMyButton() {<br>  return (<br>    &lt;Link href=&#39;/my-tokens&#39;&gt;<br>      &lt;button className=&quot;bg-[#C2410C] font-bold text-white px-4 py-2 rounded-lg&quot;&gt;View My Tokens&lt;/button&gt;<br>    &lt;/Link&gt;<br>  );<br>}</pre><p>and also</p><pre>{isConnected &amp;&amp; &lt;ShowMyButton /&gt;}</pre><p>after <strong>&lt;ConnectButton … &gt;</strong></p><p>This will add a new button <strong>View My Tokens</strong> that will redirect to <strong>/my-tokens</strong> page to show the tokens owned by an address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U8Ft8YK2vnIhlS8ibdPyBA.png" /></figure><p>We need to implement <strong>/my-tokens</strong> page now. Since we are using the App router for Next.js, we need to add a directory called <strong>my-tokens</strong> in <strong>src/app</strong>. Create a file called <strong>page.tsx</strong> in this new directory. This new file will be responsible for rendering <strong>/my-tokens</strong> page.</p><p>Put the following content in new <strong>pages.tsx</strong></p><pre>&#39;use client&#39;<br><br>import { nftManagerAbi } from &quot;@/contracts-generated&quot;;<br>import { web3config } from &quot;@/dapp.config&quot;;<br>import { ConnectButton } from &quot;@rainbow-me/rainbowkit&quot;;<br>import { Address } from &quot;viem&quot;;<br>import { useAccount, useReadContract } from &quot;wagmi&quot;;<br><br>function getImageURL(mintedTokenURI: string): string | undefined {<br>  const json = JSON.parse(atob(mintedTokenURI.split(&#39;,&#39;)[1]));<br>  return json.image;<br>}<br><br>function GetTokenURI({address, tokenId }: { address: string, tokenId: number }) {<br>  const {data: tokenURI, isLoading: isLoadingTokenURI, isError: isErrorTokenURI, error: errorTokenURI} = useReadContract({<br>    address: web3config.contractAddress as Address,<br>    abi: nftManagerAbi,<br>    functionName: &quot;tokenURI&quot;,<br>    args: [BigInt(tokenId)]<br>  })<br><br>  if (isLoadingTokenURI) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (isErrorTokenURI) return &lt;div&gt;Error: {errorTokenURI?.message}&lt;/div&gt;;<br><br>  return &lt;div className=&quot;w-[128px] h-[128px] flex flex-col items-center p-4 border-2 border-gray-300 rounded-lg&quot;&gt;&lt;img src={getImageURL(tokenURI as string)} /&gt;&lt;/div&gt;;<br>}<br><br>function GetAndShowToken({address, tokenNumber }: { address: string, tokenNumber: number }) {<br>  const {data: tokenId, isLoading: isLoadingToken, isError: isErrorToken, error: errorToken} = useReadContract({<br>    address: web3config.contractAddress as Address,<br>    abi: nftManagerAbi,<br>    functionName: &quot;tokenOfOwnerByIndex&quot;,<br>    args: [address as Address, BigInt(tokenNumber)]<br>  })<br><br>  if (isLoadingToken) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (isErrorToken) return &lt;div&gt;Error: {errorToken?.message}&lt;/div&gt;;<br><br>  return (<br>    &lt;div&gt;<br>        &lt;GetTokenURI address={address} tokenId={Number(tokenId)} /&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>function VisualizeMyTokens({address, balance}: {address: string, balance: number}) {<br>  let tokens = [];<br><br>  for (let i = 0; i &lt; balance; i++) {<br>    tokens.push(&lt;GetAndShowToken address={address} tokenNumber={i} /&gt;);<br>  }<br>  <br>  return (<br>    &lt;div className=&quot;flex flex-row flex-wrap items-center justify-center gap-4&quot;&gt;<br>        {tokens}<br>    &lt;/div&gt;<br>  );<br>}<br><br>function ShowMyTokens({address}: {address: string}) {<br>  const {data: tokens, isLoading: isLoadingTokens, isError: isErrorTokens, error: errorTokens} = useReadContract({<br>    address: web3config.contractAddress as Address,<br>    abi: nftManagerAbi,<br>    functionName: &quot;balanceOf&quot;,<br>    args: [address as Address]<br>  })<br><br>  if (isLoadingTokens) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (isErrorTokens) return &lt;div&gt;Error: {errorTokens?.message}&lt;/div&gt;;<br><br>  return (<br>    &lt;div className=&quot;flex flex-col items-center justify-center gap-4&quot;&gt;<br>        &lt;h1&gt;My Tokens: {tokens?.toString()}&lt;/h1&gt;<br>        &lt;VisualizeMyTokens address={address} balance={Number(tokens)} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default function MyTokens() {<br>  const {isConnected, address} = useAccount();<br><br>  return (<br>    &lt;main className=&quot;mt-10 flex flex-col gap-8 items-center justify-center &quot;&gt;<br>      &lt;ConnectButton label=&quot;Connect Wallet to view your tokens&quot; /&gt;<br><br>      {isConnected &amp;&amp; &lt;ShowMyTokens address={address as string} /&gt;}<br>    &lt;/main&gt;<br>  );<br>}</pre><p>The components in the file above are responsible for:</p><ul><li><strong>MyTokens</strong> — to make sure that we have a connected address.</li><li><strong>ShowMyTokens</strong> — to extract the number of tokens an address owns, this is done by calling <strong>balanceOf()</strong> of the contract.</li><li><strong>VisualizeMyTokens</strong> — from the balance, will create a new component (GetAndShowToken) for each owned token.</li><li><strong>GetAndShowToken</strong> — extracts the tokenId for the current token, by calling <strong>tokenOfOwnerByIndex</strong>.</li><li><strong>GetTokenURI</strong> — calls the <strong>tokenURI()</strong> from the conract and visualizes the image attribute.</li></ul><p>The code above could potentially be simplified using useEffect(), useState() and async Wagmi calls, but for the purpose of the tutorial, I wanted to show how this can be done with Wagmi hooks, which requires a little bit more code, but is straightforward to implement and comprehense.</p><p>If everything is OK, after clicking on <strong>View My Tokens</strong>, you will see the tokens owned by the current address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewQ67h7rYzlzFIcF_mh2YQ.png" /></figure><h3>Final words</h3><p>Congratulations, you learned how to create NFT minting website. This tutorial gave you the basics that you can extend for your minting website. Do not hesitate to contact me at <a href="https://x.com/EtoVass">https://x.com/EtoVass</a> if you have questions.</p><p>I’m also looking forward to seeing your fully on-chain collections released.</p><h3>That is all, hope you enjoyed the tutorial!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*VaQdyomfAUN81koj.png" /><figcaption>Alien Rune #0</figcaption></figure><p>Thank you for reading. If you like this tutorial, please support the author by minting one or more Alien Runes. Alien Runes is a fully on-chain NFT collection that generates SVG content from Solidity code and has complex algorithms to produce infinite unique runes. Available here: <a href="https://alienrunes.xyz/">https://alienrunes.xyz/</a></p><h3>Links</h3><p><strong>Git Repo for this tutorial:</strong></p><ul><li><a href="https://github.com/etovass/svg-nft-tutorials">https://github.com/etovass/svg-nft-tutorials</a></li><li>Part 1: <a href="https://medium.com/@eto.vass.art/how-to-create-fully-on-chain-svg-nft-part-1-basic-svg-rendering-17b8fea08739">https://medium.com/@eto.vass.art/how-to-create-fully-on-chain-svg-nft-part-1-basic-svg-rendering-17b8fea08739</a></li><li>Part 2: <a href="https://medium.com/@eto.vass.art/fully-on-chain-svg-nfts-part-2-erc-721-ntf-contract-89a8880efd82">https://medium.com/@eto.vass.art/fully-on-chain-svg-nfts-part-2-erc-721-ntf-contract-89a8880efd82</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7c372ce7344" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fully On-Chain SVG NFTs — Part 2: ERC-721 NTF Contract]]></title>
            <link>https://medium.com/@eto.vass.art/fully-on-chain-svg-nfts-part-2-erc-721-ntf-contract-89a8880efd82?source=rss-0d29e5d3cc9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/89a8880efd82</guid>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[onchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Eto Vass]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 09:32:24 GMT</pubDate>
            <atom:updated>2024-11-02T14:28:35.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fully On-Chain SVG NFTs — Part 2: ERC-721 NFT Contract</h3><h3>Intro</h3><p>In the previous tutorial, we created a Solidity contract that generates SVG content. In this tutorial, we will turn these SVG outputs into NFTs that anyone can mint, and that can be listed on the major NTF marketplaces (like OpenSea, Rarible, etc.).</p><h3>ERC-721 Standard</h3><p>ERC-721 is one of the standards behind non-fungible tokens a.k.a NFTs (ERC-1155 is the other one, which provides flexibility by supporting multiple token types in a single contract. ERC-1155 is outside the scope of this particular tutorial, but may be covered in a future one).</p><p>There is a great in-depth article on ERC-721 that was released several days before this tutorial, and I’d strongly recommend reading it since it provides quite helpful and detailed information. It is available here:</p><p><a href="https://medium.com/coinmonks/unlocking-nfts-a-deep-dive-into-erc-721-on-ethereum-75b5fd492741">The Power Of NFTs And ERC-721 on Ethereum</a></p><p>In short, the ERC-721 standard defines a set of methods and events that every compatible NFT must implement. Once implemented, these NFTs can be viewed in the NFT marketplaces and traded there.</p><h3>Methods</h3><pre>function balanceOf(address _owner) external view returns (uint256);<br>function ownerOf(uint256 _tokenId) external view returns (address);<br>function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;<br>function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;<br>function transferFrom(address _from, address _to, uint256 _tokenId) external payable;<br>function approve(address _approved, uint256 _tokenId) external payable;<br>function setApprovalForAll(address _operator, bool _approved) external;<br>function getApproved(uint256 _tokenId) external view returns (address);<br>function isApprovedForAll(address _owner, address _operator) external view returns (bool);</pre><ul><li><strong>balanceOf</strong>: count all NFTs assigned to an owner</li><li><strong>ownerOf</strong>: find the owner of an NFT</li><li><strong>safeTransferFrom</strong>: transfers the ownership of an NFT from one address to another address</li><li><strong>transferFrom</strong>: transfer ownership of an NFT. The caller is responsible to confirm that the _to address is capable of receiving NFTs or else the NFT may be permanently lost.</li><li><strong>setApprovalForAll</strong>: enable or disable approval for a third party (marketplaces, like OpenSea) to manage all of msg.sender’s assets. This method allows an NFT owner to grant another address permission to transfer all of their tokens on their behalf. This can be useful for a variety of purposes, such as listing NFTs on marketplaces, liquidity minting/staking, etc. More details how this method works, can be find <a href="https://support.thirdweb.com/smart-contracts/rtHYyzspnPaHmmANmJQz1k/setapprovalforall-what-it-means-to-grant-access-to-all-your-nfts/iYkvUnFKSMwZapY42BED15">here</a>.</li><li><strong>getApproved</strong>: returns the account that has been approved to transfer a specific token on behalf of the owner. Used together with <strong>approve</strong> method</li><li><strong>approve</strong>: change or reaffirm the approved address for a specific token</li><li><strong>isApprovedForAll</strong>: query if an address is an authorized operator for another address</li></ul><h3>Events</h3><pre>event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);<br>event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);<br>event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);</pre><ul><li><strong>Transfer</strong>: this emits when ownership of any NFT changes by any mechanism.</li><li><strong>Approval</strong>: this emits when the approved address for an NFT is changed or reaffirmed.</li><li><strong>ApprovalForAll</strong>: this emits when an operator is enabled or disabled for an owner. The operator can manage all NFTs of the owner.</li></ul><h3>Metadata Extension</h3><p>There is an ERC-721 extension that also describes the metadata for the NFT. It has the following methods:</p><pre>function name() external view returns (string _name);<br>function symbol() external view returns (string _symbol);<br>function tokenURI(uint256 _tokenId) external view returns (string);</pre><ul><li><strong>name:</strong> returns the name (description) of the NFT (for example: AlienRunes)</li><li><strong>symbol:</strong> a short symbol that represents the NFT (for example: 0xAR)</li><li><strong>tokenURI: </strong>returns URL to a JSON file that describes the NFT. This will be covered in detail later in the tutorial.</li></ul><h3>OpenZeppelin</h3><p>Fortunately, there are several well-tested ERC-721 implementations that cover most of the complexity related to ERC-721 and make the life of the NFT creators easier. The most commonly used is <a href="https://www.openzeppelin.com/">OpenZeppelin</a> (note: OpenZeppelin ERC-721 implementation is not the most gas-efficient. For my NFTs, I prefer Chiru Labs ERC-721A implementation, which can be found <a href="https://github.com/chiru-labs/ERC721A">here</a>. For the purpose of this tutorial, we will use OpenZeppelin since it is the most common one, and other more efficient implementations can be covered in more advanced tutorials in the future).</p><h3>Our First ERC-721 Contract</h3><p>OpenZeppelin also provides a <a href="https://wizard.openzeppelin.com/#erc721">friendly wizard</a> that can help you configure everything needed for your NFT contract.</p><p>The code for this tutorial is available at <a href="https://github.com/etovass/svg-nft-tutorials/tree/main/tutorial-2-NFT-contract">https://github.com/etovass/svg-nft-tutorials/tree/main/tutorial-2-NFT-contract</a>. If you prefer to use already created code, go ahead and check out the repository from GitHub, and then you can directly proceed to section <em>Test the NFT Contract</em>.</p><p>If you want to follow the follow the tutorial step by step, then continue reading this section.</p><p>Now go to <a href="https://wizard.openzeppelin.com/#erc721">https://wizard.openzeppelin.com/#erc721</a> and enter Name and Symbol and select Mintable, Auto Increment Ids, Enumerable and Ownable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdZ8MsZS3XtrtnnPv_U9ig.png" /></figure><p>Open your favourite IDE, create a directory called <strong><em>tutorial-2-NFT-contract</em></strong> to be a sibling to <strong><em>tutorial-1-basic-svg-rendering</em></strong>, and initialize Foundry for that directory (described in detail in the previous tutorial — Part 1). Now open your IDE (I prefer to use Visual Studio Code), copy the code from the wizard to a new file called <strong><em>NFTManager.sol</em></strong> (also rename the contract to be called <em>NFTManager</em>), and place that file in a <strong><em>src</em></strong> directory. You also need to change the solidity version at the top of the file to 0.8.21 since all other files use that version.</p><p>You may see some errors in your Visual Studio Code / IDE , in order to remove them you need to install OpenZeppelin contracts. In <strong><em>tutorial-2-NFT-contract</em></strong> directory, execute the following command:</p><pre>npm install --save-dev @openzeppelin/contracts</pre><p>Also, edit <strong><em>foundry.toml </em></strong>in the same directory and add the following section at the end of the file:</p><pre>remappings = [<br>    &quot;@openzeppelin/=node_modules/@openzeppelin&quot;,<br>]</pre><p>After these steps, all of the errors in Visual Studio Code / IDE must disappear.</p><p>You can also manually verify that everything is configured well, executing <strong><em>‘forge build’</em></strong> in the same directory, and it must finish with success.</p><h3>Adding Features to NFTManager.sol</h3><p>NFTManager.sol is still not ready; we need to add several more things there to make it work.</p><p>Add the following two constants to NFTManager.sol:</p><pre>uint256 public constant PRICE = 0.005 ether;<br>uint256 public constant MAX_NFT_ITEMS = 121;</pre><p>The first one is the price per mint — in our case 0.005 ethers. The second is the limit of the NFTs in this collection, in our case 121.</p><p>Then add <strong><em>mintIsOpen</em></strong> modifier and modify safeMint as follows:</p><pre>modifier mintIsOpen {<br>    require(totalSupply() &lt; MAX_NFT_ITEMS, &quot;Mint has ended&quot;);<br>    _;<br>}<br><br>function safeMint(address to) public mintIsOpen payable {<br>    require(msg.value &gt;= PRICE, &quot;Insufficient funds&quot;);<br><br>    uint256 tokenId = _nextTokenId++;<br>    _safeMint(to, tokenId);<br>}</pre><p><strong><em>mintIsOpen</em></strong> is a Solidity modifier that can be added to methods. It ensures that the collection is not fully minted before invoking <strong><em>safeMint</em></strong> (it will revert the call if it is). We also made <strong><em>safeMint</em></strong> payable and with <strong><em>msg.value &gt;= PRICE</em></strong> we verify that our contract will receive at least 0.005 ethers from everyone who wants to mint our NFT.</p><p>Change also the constructor to:</p><pre>constructor() ERC721(&quot;Eto Vass NFT Tutorial&quot;, &quot;0xEV&quot;) Ownable(msg.sender) {<br>}</pre><p>This will ensure that the contract&#39;s owner will be the address that will create it.</p><p>We are just one step away from having a mintable contract — the token URI method is still missing, and this is how we present the NFT data to the world.</p><h3>tokenURI Method</h3><p>We need to implement tokenURI method to present our NFT to the world. We have to render our SVG in this method and wrap it with some metadata. The method has the following signature</p><pre>function tokenURI(uint256 _tokenId) external view returns (string);</pre><p>and <strong><em>tokenURI</em></strong> returns URL to a JSON file that describes the NFT and its metadata. And since we are building fully on-chain NFT, our URL must be data URL encoded (check <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs">here</a> for the details).</p><p>OpenSea has a decent description of what the metadata has to contain and it is available here: <a href="https://docs.opensea.io/docs/metadata-standards">https://docs.opensea.io/docs/metadata-standards</a></p><p>We need to provide the metadata as JSON that is data URL encoded and to include attributes like:</p><ul><li><strong><em>name</em></strong> — the specific NFT</li><li><strong><em>description</em></strong> — of the specific NFT</li><li><strong><em>image</em></strong> — this is the URL of the image for a specific NFT. It must be also data URL encoded in our case since we are creating on-chain NFT (there are two other attributes that can also be used —<em> image_data</em> and <em>animation_url</em>. They will be covered in the future in more advanced tutorial that will focus on how NFT marketplaces render our NFT arts)</li><li><strong><em>attributes</em></strong> — an array of attributes that marketplaces will show and that define the traits of every individual NFT (see <a href="https://docs.opensea.io/docs/metadata-standards#attributes">https://docs.opensea.io/docs/metadata-standards#attributes</a>)</li></ul><h3>Additional Solidity Files</h3><p>Before we continue with the implementation of the <strong><em>tokenURI</em></strong> method, you need to get the following files from the <a href="https://github.com/etovass/svg-nft-tutorials">GitHub repository</a> and place them in the same directory as <em>NFTManager.sol</em></p><ul><li><a href="https://github.com/etovass/svg-nft-tutorials/blob/main/tutorial-2-NFT-contract/src/Random.sol"><strong><em>Random.sol</em></strong></a><strong><em> </em></strong>:<strong><em> </em></strong>a collection of pseudo-random methods that help us achieve some randomness in our collection</li><li><a href="https://github.com/etovass/svg-nft-tutorials/blob/main/tutorial-2-NFT-contract/src/Utils.sol"><strong><em>Utils.sol</em></strong></a> : helpful utility methods, most notable are gas-optimized toString() and Base64 encoder methods</li><li><a href="https://github.com/etovass/svg-nft-tutorials/blob/main/tutorial-2-NFT-contract/src/Traits.sol"><strong><em>Traits.sol </em></strong></a>: a library that generates traits that can be used by SVGRenderer.sol and that can be serialized to JSON, i.e., can be included in our <em>tokenURI</em> method.</li><li><a href="https://github.com/etovass/svg-nft-tutorials/blob/main/tutorial-2-NFT-contract/src/SVGRenderer.sol"><strong><em>SVGRender.sol</em></strong> </a>: a contract that outputs the SVG Content of our NFT collection.</li></ul><h3>Our SVG NFT Collection</h3><p>The idea for the SVG NFT collection in this tutorial is simple. Select a random base hue and then draw up to 100 figures with different saturation, lightning and opacity. Figures are with random coordinates and can be lines, circles, rectangles and round rectangles. Here are visual examples for each of the four types of figures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*oMnxLUM2FAYlB7dH0zQXoA.png" /><figcaption>lines</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*aEgslfhZO_FcciPoJt_euQ.png" /><figcaption>circles</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*WSzLLFjepMF5xRp0u0FOtw.png" /><figcaption>rectangles</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*ZFuXmcFvijuAAM88WqeO-w.png" /><figcaption>round rectangles</figcaption></figure><h3>Traits</h3><p>Traits for this NFT collection are three:</p><ul><li><em>figure</em> — Can be line (10% probability), circle (20% probability), rectangle, (30% probability), round rectangle (40% probability)</li><li><em>num figures</em> — or how many figures to draw. Can be 25 (10% probability), 50 (20% probability), 75 (30% probability), 100 (40% probability)</li><li><em>starting Hue</em> — a random hum to start with, can be between 0 and 359 with equal probability</li></ul><p>Traits are described in <strong><em>Traits.sol</em></strong> library:</p><pre>enum Figure {<br>    LINE,<br>    CIRCLE,<br>    RECTANGLE,<br>    ROUND_RECTANGLE<br>}    <br><br>struct TraitsInfo {<br>    Figure figure;<br>    uint numFigures;<br>    uint startingHue;<br>}</pre><p><strong><em>randomTraits</em></strong> method generate random traits, based on the probabilities described above:</p><pre>function randomTraits(RandomCtx memory rndCtx) internal pure returns (TraitsInfo memory) {<br>    TraitsInfo memory traits = TraitsInfo({<br>        figure: Figure(Random.randWithProbabilities(rndCtx, Random.probabilityArray(10, 20, 30, 40))),<br>        numFigures: (1 + Random.randWithProbabilities(rndCtx, Random.probabilityArray(10, 20, 30, 40))) * 25,<br>        startingHue: uint(Random.randRange(rndCtx, 0, 359))<br>    });<br><br>    return traits;<br>}</pre><p><strong><em>getTraitsAsJson</em></strong> — serializes traits as JSON array, to be included in <strong><em>tokenURL </em></strong>method.</p><h3>Renderer</h3><p><em>SVGRender</em> contract is responsible for generating SVG and Traits for a specific token id.</p><pre>function renderSVG(uint tokenId) public pure returns (string memory svg, string memory traitsAsString) {<br>    RandomCtx memory ctx = Random.initCtx(tokenId);<br><br>    Traits.TraitsInfo memory traits = Traits.randomTraits(ctx);<br>    traitsAsString = Traits.getTraitsAsJson(traits);<br>    <br>    svg = &quot;&quot;;<br><br>    uint hue = traits.startingHue;<br>    <br>    for (uint i=0; i &lt; traits.numFigures; i++) { <br>        int x1 = Random.randRange(ctx, 0, 512);<br>        int y1 = Random.randRange(ctx, 0, 512);<br>        int x2 = Random.randRange(ctx, 0, 512);<br>        int y2 = Random.randRange(ctx, 0, 512);<br>        int r = Random.randRange(ctx, 10, 64);<br>        int sat = Random.randRange(ctx, 0, 100);            <br>        int opacity = Random.randRange(ctx, 10, 39);<br><br>        string memory fill = string.concat(&#39;&quot;hsl(&#39;,Utils.toString(hue), &#39;,&#39;, Utils.toString(sat),&#39;%, 50%)&quot; opacity=&quot;0.&#39;, Utils.toString(opacity), &#39;&quot;&#39;);<br><br>        if (traits.figure == Traits.Figure.LINE) {<br>            svg = string.concat(svg, <br>                &#39;&lt;line x1=&quot;&#39;, Utils.toString(x1), &#39;&quot; y1=&quot;&#39;, Utils.toString(y1), <br>                    &#39;&quot; x2=&quot;&#39;, Utils.toString(x2), &#39;&quot; y2=&quot;&#39;, Utils.toString(y2), &#39;&quot; stroke=&#39;, fill, &#39; stroke-width=&quot;10&quot;/&gt;&#39;);<br>        } else if (traits.figure == Traits.Figure.CIRCLE) {<br>            svg = string.concat(svg, &#39;&lt;circle cx=&quot;&#39;, Utils.toString(x1), &#39;&quot; cy=&quot;&#39;, Utils.toString(y1), <br>            &#39;&quot; r=&quot;&#39;, Utils.toString(r),&#39;&quot; fill=&#39;,fill, &#39;/&gt;&#39;);<br>        } else {    <br>            string memory rx = &quot;&quot;;<br><br>            if (traits.figure == Traits.Figure.ROUND_RECTANGLE) {<br>                rx = string.concat(&#39;rx=&quot;&#39;, Utils.toString(r), &#39;&quot;&#39;);<br>            }<br><br>            svg = string.concat(svg, <br>                &#39;&lt;rect x=&quot;&#39;, Utils.toString(Utils.min(x1, x2)), &#39;&quot; y=&quot;&#39;, Utils.toString(Utils.min(y1, y2)), <br>                    &#39;&quot; width=&quot;&#39;, Utils.toString(Utils.abs(x2-x1)), &#39;&quot; height=&quot;&#39;, Utils.toString(Utils.abs(y2-y1)),<br>                    &#39;&quot; &#39;, rx, &#39; fill=&#39;, fill, &#39;/&gt;&#39;);<br>        }<br>    }<br><br>    svg = string.concat(&#39;&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; preserveAspectRatio=&quot;xMinYMin meet&quot; viewBox=&quot;0 0 512 512&quot;&gt;&#39;,svg,&#39;&lt;/svg&gt;&#39;);<br>}</pre><p>The method initializes a random context with <strong><em>tokenId</em></strong> (which ensures repeatability of the random numbers for specific <strong><em>tokenId</em></strong><em>)</em><strong><em>. </em></strong>Then generates traits, and based on these traits — the SVG content. The method returns the SVG content, together with the trait attributes.</p><h3>Putting It All Together</h3><p>Now we have everything to fully implement the NFT contract and can complete it. We need to implement the <strong><em>tokenURI</em></strong> method in <strong><em>NFTManager.sol</em></strong>. It looks like this:</p><pre>function tokenURI(uint256 tokenId) public view override returns (string memory) {<br>    _requireOwned(tokenId);<br><br>    return renderAsDataUri(tokenId);<br>}<br><br>function renderAsDataUri(uint256 _tokenId) public view returns (string memory) {<br>    string memory svg;<br>    string memory attributes;<br><br>    (svg, attributes) = renderer.renderSVG(_tokenId);<br><br>    string memory image = string.concat(&#39;&quot;image&quot;:&quot;data:image/svg+xml;base64,&#39;, Utils.encode(bytes(svg)),&#39;&quot;&#39;);<br><br>    string memory json = string.concat(<br>        &#39;{&quot;name&quot;:&quot;On-chain SVG NFT Tutorial #&#39;,<br>        Utils.toString(_tokenId),<br>        &#39;&quot;,&quot;description&quot;:&quot;This is NFT from the On-chain SVG NFT Tutorial by Eto Vass &quot;,&#39;,<br>        attributes,<br>        &#39;,&#39;, image,<br>        &#39;}&#39;<br>    );<br><br>    return<br>        string.concat(<br>            &quot;data:application/json;base64,&quot;,<br>            Utils.encode(bytes(json))<br>        );    <br>}</pre><ul><li><strong><em>_requireOwned(tokenId): </em></strong>verifies that NFT with a specific id is already minted, to ensure that only minted are visible (for non-minted, error will be thrown)</li><li><strong><em>renderAsDataUri(tokenId):</em></strong> generates SVG and Traits (through SVGRеnderer), encode SVG as base64 encoded data URL, create the JSON content and encode it again as base64 data URL.</li></ul><h3>Feature: Reserve NFT Tokens for the Team</h3><p>Sometimes it is a practice for NFT author(s) to reserve some tokens for themself on collection launch. We can easily do that if you change the constructor of NFTManager, to:</p><pre>constructor(uint256 _reservedForTeam) ERC721(&quot;Eto Vass NFT Tutorial&quot;, &quot;0xEV&quot;) Ownable(msg.sender) {<br>    renderer = new SVGRenderer();<br><br>    for (uint i=0; i &lt; _reservedForTeam; i++) {<br>        uint256 tokenId = _nextTokenId++;<br>        _safeMint(msg.sender, tokenId);<br>    }<br>}</pre><p>If you don’t want to reserve anything for the author(s), then you can pass 0. <em>Note</em>: <em>for simplicity, this code does not verify if reserved for team exceeds the limit of NTFs in this collection.</em></p><h3>Test the NFT Contract</h3><p>We have everything in place now, a fully built ERC-721 minting contract. We can test it now.</p><p>Copy <a href="https://github.com/etovass/svg-nft-tutorials/tree/main/tutorial-2-NFT-contract/test">https://github.com/etovass/svg-nft-tutorials/tree/main/tutorial-2-NFT-contract/test</a> into <strong><em>test</em></strong> directory, which must be sibling to <strong><em>src</em></strong>. Testing contracts are very similar to those from the first tutorial. Create a file <strong><em>NFTManager.t.sol</em></strong>, instantiate the contract with 0 reserved for the team and call <strong><em>renderAsDataUri</em></strong> method (which was made public in order to directly callable) in the right place.</p><pre>contract NFTManagerTest is AbstractTest {<br>  NFTManager public renderer;<br><br>  function setUp() public {<br>      renderer = new NFTManager(0);<br>  }<br><br>  function renderContract(uint tokenId) internal override returns(string memory svg) {        <br>      return renderer.renderAsDataUri(tokenId);<br>  }<br><br>  function testSvgRenderer() public {<br>      super.testRenderer();<br>  }<br>}</pre><p>You can now test the contact. Go to <strong><em>tutorial-2-NFT-contract</em></strong> and execute:</p><pre>npm --prefix ../ts-tooling run hot-reload ../tutorial-2-NFT-contract/ test/NFTManager.t.sol testSvgRenderer 0</pre><p>(for convenience, you can just call <strong><em>start-hot-reload.sh</em></strong> if you use the code from the GitHub).</p><p>If successful, you can navigate to <a href="http://localhost:9901/">http://localhost:9901/</a> and see the contract output and its JSON metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gn0xaQ6jjA5-bl2koRr-NQ.png" /></figure><p>I extended the tooling used in Part 1 also to support JSON metadata, and to parse it and show the JSON, plus the image.</p><p>I also created another tool, called <em>qa-collection</em> (inspired by <a href="https://github.com/w1nt3r-eth/hot-chain-svg/">https://github.com/w1nt3r-eth/hot-chain-svg/</a>). With this tool, you can generate many SVGs, they will also be validated and rendered as PNGs for convenience.</p><p>If you run the tool you will see how it is used:</p><pre>Usage:<br>    npm run qa-collection - &lt;FOUNDRY_PROJECT_ROOT_PATH&gt; &lt;TEST_CONTRACT&gt; &lt;TEST_METHOD&gt; &lt;START_ID&gt; &lt;END_ID<br>Example:<br>    npm run qa-collection - ../tutorial-2-NFT-contract/ test/NFTManager.t.sol testSvgRenderer 0 100</pre><p>If you want to run the tool from <strong><em>tutorial-2-NFT-contract</em></strong> then you can use:</p><pre>npm --prefix ../ts-tooling run qa-collection ../tutorial-2-NFT-contract/ test/NFTManager.t.sol testSvgRenderer 0 120</pre><p>or <strong><em>start-qa-collection.sh</em></strong> if you got it from GitHub.</p><p>The tool will generate many NFT items in batch, will calculate minimum and maximum GAS that was used, will warn if GAS is close or above 30M and will also show the occurrences for each of the traits. <strong>This tool is extremely helpful for any on-chain NFT developer.</strong></p><p>Here is a sample output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNsrZp-peYCbhhaNnz0m3g.png" /></figure><h3>Deploying the Contract</h3><p>After we tested our contract, it is now time to deploy it to the Ethereum network.</p><p>The best way to do that is to use Foundry Deploy Script.</p><p>Create directory called <strong><em>script</em></strong> inside <strong><em>tutorial-2-NFT-contract</em></strong> and create a file called <strong><em>Deploy.s.sol</em></strong> in this directory with the following content:</p><pre>pragma solidity ^0.8.21;<br><br>import &quot;forge-std/Script.sol&quot;;<br>import &quot;../src/NFTManager.sol&quot;;<br><br>contract Deploy is Script {<br>    function run() external {<br>        uint256 deployerPrivateKey = vm.envUint(&quot;PRIVATE_KEY&quot;);<br>        vm.startBroadcast(deployerPrivateKey);<br><br>        NFTManager ntfManager = new NFTManager(15);<br><br>        vm.stopBroadcast();<br>    }<br>}</pre><p>This is a simple script that will deploy your contract when executed properly. If you have multiple contracts that depends on each other — you just instantiate them in the right order after <em>vm.startBroadcast()</em> and before <em>vm.stopBroadcast()</em>. You will also need to have environment variable called <em>PRIVATE_KEY</em> that will contain the private key of the wallet/address that is deploying the contract for the Ethereum network where you are deploying.</p><h3>Deploying Locally</h3><p>Before deploying to a public network, it is usually a good practice to deploy on a local node and test locally. Foundry provides a tool called Anvil, which is exactly this — a local test node.</p><p>You can run it just with executing <strong><em>anvil</em></strong> in your shell. Upon starting, Anvil will create 10 accounts and will provide their private keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7u_vtwY2Pmj-smGoNXVCw.png" /></figure><p>Select one of the private keys, for example 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80.</p><p>By default Anvil is using port 8545.</p><p>Now create a script called <strong><em>deploy-local.sh</em></strong> in <strong><em>tutorial-2-NFT-contract </em></strong>with the following content:</p><pre>#!/bin/sh<br><br>export PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80<br><br>forge script ./script/Deploy.s.sol:Deploy --fork-url http://localhost:8545 --broadcast -vvvv </pre><p>Note: you may need to give <strong><em>deploy-local.sh</em></strong> execution permissions with <strong><em>chmod +x ./deploy-local.sh</em></strong></p><p><a href="http://localhost:8545/">http://localhost:8545</a> is the URL to the Ethereum node, in case you are deploying to testnet or mainnet you have to change it. For now use localhost to deploy the contract locally (your Anvil instance must be running).</p><p>Execute <strong><em>deploy-local.sh</em></strong>. Upon success your contract will be deployed on the local node and you will see the contract address:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kId0K7vvndmGr8VVvkqcCw.png" /></figure><p>I have developed another very useful tool, called NFT viewer. It is available here: <a href="https://viewer.etovass.xyz/">https://viewer.etovass.xyz/</a></p><p>(also available in <a href="https://github.com/etovass/svg-nft-tutorials/tree/main/nextjs-tooling/nft-viewer">https://github.com/etovass/svg-nft-tutorials/tree/main/nextjs-tooling/nft-viewer</a> if you want to run it locally)</p><p>With this tool you can test any contract deployed locally or on a public/private node. Localhost is also supported, since the magic happen in the browser, which is running on your machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQBRGHdAVcUZ35iydnLiSA.png" /><figcaption>viewer.etovass.xyz</figcaption></figure><p>In <em>address </em>field provide the address of your contract. For <em>network</em> — select <em>Custom</em>. For <em>node url </em>— put <a href="http://localhost:8545."><em>http://localhost:8545</em>.</a> <em>Function</em> — this is the method you want to test. In our case — you can use <em>tokenURI</em> for tokens from 0 to 14, since in <em>Deploy.s.sol</em>, we initialized <em>NFTManager</em> to mint and reserve the first 15 tokens to the author.</p><p>You can also test <strong><em>renderAsDataUri</em></strong>, since it is a public method. In this case — you are not restricted to minted tokens and can provide any value and see how it will be rendered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJT_k3UzoEZYz0K5Q_1HBg.png" /></figure><h3>Deploying on Testnet</h3><p>Next and the last step of this tutorial will be to deploy the contract to a testnet. This tutorial will work with <a href="https://sepolia.etherscan.io/">Sepolia</a>.</p><p>You will need:</p><ul><li>Address with some Sepolia ethers. You can use Sepolia Faucet to send some test ethers to your account. Both <a href="https://sepoliafaucet.com/">Alchemy</a> and <a href="https://www.infura.io/faucet/sepolia">Infura</a> are good options, you have to create a free account to use their faucets.</li><li>Private key of your address. You can get it from your wallet. If you use MetaMask which is one of the most popular wallets — see this <a href="https://support.metamask.io/hc/en-us/articles/360015289632-How-to-export-an-account-s-private-key">link</a>.</li><li>Etherscan API Key (to verify your contract). You can get it from <a href="https://etherscan.io/myapikey">https://etherscan.io/myapikey</a>, where you can register for a free account.</li></ul><p>Create a file called <strong><em>deploy-sepolia.sh</em></strong> and place it in <strong><em>tutorial-2-NFT-contract. </em></strong>With the following content:</p><pre>#!/bin/sh<br><br>export PRIVATE_KEY=&lt;YOUR_PRIVATE_KEY&gt;<br>export NODE_URL=https://ethereum-sepolia.publicnode.com<br>export ETHERSCAN_API_KEY=&lt;YOUR_ETHERSCAN_API_KEY&gt;<br><br>forge script script/Deploy.s.sol:Deploy --fork-url $NODE_URL --broadcast --verify -vvvv</pre><p>Note — replace <em>&lt;YOUR_PRIVATE_KEY&gt;</em> and <em>&lt;YOUR_ETHERSCAN_API_KEY&gt;</em> with their actual values.</p><p>The script is very similar to the one we used for local Anvil deployment. This one has one additional parameter “verify” that publishes the contract source code to Etherscan and verifies it.</p><p>This script will take a little longer to execute and if successful — you will have your NFT contracts deployed to Sepolia and verified in Etherscan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P49Vcjnw6pwB08X-BegwLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZ2ZtlOoXmBzNWQ7dOY0Mw.png" /></figure><p><strong>Congratulations</strong> — you have your ERC-721 contract now deployed to testnet. It is also visible through OpenSea. Just open <a href="https://testnets.opensea.io/">https://testnets.opensea.io/</a> and place the contract address (0x331dbe16931a959055b73ce6cd2a1006ce79972b) in the search bar and you will be redirected to <a href="https://testnets.opensea.io/collection/eto-vass-nft-tutorial">https://testnets.opensea.io/collection/eto-vass-nft-tutorial</a>.</p><p>You can also play with the deployed contract <a href="https://viewer.etovass.xyz/?address=0x331dbe16931a959055b73ce6cd2a1006ce79972b&amp;network=sepolia&amp;hasSecondParam=false&amp;secondParamValue=1&amp;secondParamType=uint256&amp;function=tokenURI&amp;tokenIdType=uint256&amp;customNodeUrl=&amp;viewWidth=255&amp;tokenId=3&amp;responsive=false&amp;showBorder=true">here</a>.</p><h3>Deploying on Mainnet</h3><p>Deployment to Ethereum mainnet is very similar. You just need to set NODE_URL to <a href="https://ethereum.publicnode.com/">https://ethereum.publicnode.com</a> in your script and you will be able to deploy on Mainnet.</p><h3>That is all, hope you enjoyed the tutorial!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*VaQdyomfAUN81koj.png" /><figcaption>Alien Rune #0</figcaption></figure><p>Thank you for reading. If you like this tutorial, please support the author by minting one or more Alien Runes. Alien Runes is a fully on-chain NFT collection that generates SVG content from Solidity code and has complex algorithms to produce infinite unique runes. Available here: <a href="https://alienrunes.xyz/">https://alienrunes.xyz/</a></p><h3>Links</h3><p><strong>Git Repo for this tutorial:</strong></p><ul><li><a href="https://github.com/etovass/svg-nft-tutorials">https://github.com/etovass/svg-nft-tutorials</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89a8880efd82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fully On-Chain SVG NFT — Part 1: Basic SVG Rendering]]></title>
            <link>https://medium.com/@eto.vass.art/how-to-create-fully-on-chain-svg-nft-part-1-basic-svg-rendering-17b8fea08739?source=rss-0d29e5d3cc9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/17b8fea08739</guid>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[onchain]]></category>
            <category><![CDATA[on-chain-art]]></category>
            <category><![CDATA[on-chain-data]]></category>
            <category><![CDATA[nft]]></category>
            <dc:creator><![CDATA[Eto Vass]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 21:55:36 GMT</pubDate>
            <atom:updated>2024-11-02T14:25:34.953Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fully On-Chain SVG NFTs — Part 1: Basic SVG Rendering</h3><p>On-chain NFTs refer to non-fungible tokens where the metadata and the actual media of the NFT (like an image, video, or text) are stored directly on the blockchain. Unlike most NFTs, where only the ownership and transaction records are stored on chain, on-chain NFTs store everything on-chain including the media.</p><h3>Intro</h3><p>On-chain NFTs come in various forms, each utilizing the blockchain’s capabilities in different ways. One type embeds traditional image formats like PNGs or JPGs directly onto the blockchain. These are visually similar to conventional digital images but are immutable and permanently stored on the blockchain. Some on-chain NFTs embed JavaScript and HTML, incorporating libraries like p5.js or three.js. Others generate SVGs (Scalable Vector Graphics) on the fly, directly from the Solidity contract. This tutorial will cover these SVG NTFs specifically. The tutorial will consist of several parts and will cover all aspects of development, testing, deployment, and supporting fully on-chain SVG NFTs, specifically:</p><ul><li>Part 1: Basic SVG Rendering (this post)</li><li>Part 2: ERC-721 NTF Contract (to be released)</li><li>Part 3: Minting website (to be released)</li><li>Part 4: TBD</li></ul><h3>Some Notable On-Chain SVG NTFs</h3><p>Before understanding how to create fully on-chain SVG NFTs, it will be helpful to explore several notable on-chain SVG NTF collections (this is not an exhaustive list. There are hundreds, if not thousands, SVG NFTs available. Check the next section for two amazing resources that list fully on-chain NFTs, many of which are SVG NTFs):</p><ul><li><a href="https://mirror.xyz/chainleft.eth/uTQ2JAgjV35asUTx8KVJKqlKYGJz7wfZUxRrEd0loL8">Pushersleft (ART PONZI) </a>— this NFT is pushing the boundaries of SVG NFTs, having a lot of innovative optimizations so the work can be stored on-chain.</li><li><a href="https://www.chainleft.art/chaos-roads">Chaos Roads</a> — it is more than SVG NFT. The thumbnail is SVG generated, but there is much more. It is an interactive painting, a music piece, and a poem.</li><li><a href="https://onchainmonkey.com/">OnChainMonkey</a> is one of the very successful fully on-chain SVG NFT collections.</li><li><a href="https://stars.miragenesi.art/">Advent Stars</a> — fully on-chain, dynamic NFT. Quoting the creator: “Every day until the 24th, a new star will illuminate the night sky, occasionally surrounded by colorful nebulae. On Christmas Eve, the celestial display will be fully realized, thus completing the cosmic artwork. Next year? Restart it, and the magic will happen again.”</li><li><a href="https://alienrunes.xyz/">Alien Runes</a> — this is my own fully on-chain SVG collection. Every rune is unique, and the algorithm can generate infinite runes. The algorithm for rune generation is complex, and it may not be an overstatement to say that this collection generates one of the most complex SVGs among fully on-chain NTFs.</li></ul><h3>On-Chain NFT Resources</h3><p>If you like on-chain NFTs, there are two great resources to explore:</p><ul><li><a href="https://onchainchecker.xyz/collections">On-Chain Checker (OCC)</a> — a collection of 200+ fully on-chain NFTs. A lot of them are SVG NFTs. On-Chain Checker can also check programmatically whether a given contract produces fully on-chain NFTs.</li><li><a href="https://www.fullyonchain.art/">Fully on Chain</a> — portal for fully on-chain NFTs. Has close to 200 fully on-chain collections and many other helpful resources. I highly recommend subscribing to its newsletter if you are interested in on-chain NFTs.</li></ul><p>If you want to understand more about On-Chain NFT, I also recommend the following article — <a href="https://metaversal.banklesshq.com/p/onchain-nfts">https://metaversal.banklesshq.com/p/onchain-nfts</a></p><h3>Tutorial Requirements</h3><p>This tutorial assumes that you have basic knowledge of Solidity — the programming language behind Ethereum Smart Contract and some basic JavaScript / TypeScript knowledge (most of the code we will write will be Solidty code; There are some TypeScript tooling that we will use in the tutorial, but you can use it as it is; TypeScript knowledge will be required only if you want to enhance the tooling). This tutorial also assumes that you have some knowledge of SVG (Scalable Vector Format) and a basic understanding of GitHub and shell/bash.</p><p>The following tools are required to be installed on your machine:</p><ul><li><strong>nodejs </strong>— JavaScript runtime<strong> </strong>(install from here: <a href="https://nodejs.org/en/download">https://nodejs.org/en/download</a>)</li><li><strong>ts-node</strong> — TypeScript runtime, a very convenient tool to run typescript without precompiling it (install from here: <a href="https://typestrong.org/ts-node/docs/installation/">https://typestrong.org/ts-node/docs/installation/</a>)</li><li><strong>Foundry</strong> — one of the best and fastest toolkits for developing and testing Solidity contracts (install from here: <a href="https://book.getfoundry.sh/getting-started/installation">https://book.getfoundry.sh/getting-started/installation</a>)</li><li>A text editor or IDE — <strong>Visual Studio Code (</strong><a href="https://code.visualstudio.com/download">https://code.visualstudio.com/download</a>) is recommended, together with this amazing Solidity plugin that integrates well with Foundry (<a href="https://marketplace.visualstudio.com/items?itemName=NomicFoundation.hardhat-solidity">https://marketplace.visualstudio.com/items?itemName=NomicFoundation.hardhat-solidity</a>)</li></ul><p>In these tutorials, I’ll guide you in creating an on-chain SVG NFT <strong>from scratch</strong> (you will need to download the tooling, though).</p><h3>Disclaimer</h3><p>The purpose of this tutorial is not to teach you about Solidity or SVG. Neither is to write the most optimized code. The main idea is to show you the tooling and the workflow, that can empower you to create great on-chain SVG NFTs. In the current Part 1 — we will cover the basics, or how to generate and test SVG content, generated by Solidity code.</p><h3>First Steps</h3><p>We will first focus on creating a Solidity contract that will output SVG and the tooling that will compile and test this contract. In the next tutorial (Part 2), we will focus on implementing an ERC-721 contract, which would enable “mint” and list the NFT on exchanges (like OpenSea)</p><p>To start, create a directory for the contacts, I will use <strong>tutorial-1-basic-svg-rendering</strong> in this tutorial. Now go to this directory and initialize Foundry:</p><pre>cd tutorial-1-basic-svg-rendering/<br>forge init --no-git</pre><blockquote><strong>Please note!</strong> You have to run <strong>forge init</strong> in <strong>tutorial-1-basic-svg-rendering</strong> folder. If you run the command in the parent directory or in a different subfolder, this will mess up your Foundry configuration, and the rest of the tutorial may not work properly.</blockquote><p>Foundry will initialize the current directory (<strong>tutorial-1-basic-svg-rendering </strong>in my example) and will create a few files and directories.</p><p>Delete <em>script</em> directory (we will not need it for now) as well as the <em>src/Counter.sol</em> and <em>test/Counter.sol</em></p><p>Your directory now looks like this — nice and clean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*vw3fjAv8nXg8NPXuwDbOwA.png" /></figure><p>Now create a file in the <em>src</em> directory called <em>BasicSVGRenderer.sol </em>and populate it with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a70214bd1899e4825f908a72f689611/href">https://medium.com/media/7a70214bd1899e4825f908a72f689611/href</a></iframe><p><strong>Congratulations, you now have a Solidity contract that can output SVG content.</strong></p><p>Run the following command to compile the contract.</p><pre>forge build</pre><p>If successful, you will see two new directories created — <em>cached</em> and <em>out</em>. In <em>out,</em> Forge will output the compiled contract in JSON format.</p><p>Next is creating a test to output the SVG content to the console.</p><p>Create<strong> </strong><em>BasicSVGRenderer.t.sol</em> in <em>test</em> directory and populate it with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7feb67bba619441035e2225bb086399b/href">https://medium.com/media/7feb67bba619441035e2225bb086399b/href</a></iframe><p>Now run</p><pre>forge test -vv</pre><p>And you will get the following output to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-lbeUCZ6aGE0AJGCKj4YA.png" /></figure><p>Please note that you must include the <em>“-vv”</em> parameter; otherwise, Forge will not output the result from the console.log() function.</p><p>Now if you want to generate an SVG file from this output, you have to use the following:</p><pre>forge test -vv | awk &#39;/&lt;svg /,/&lt;\/svg&gt;/&#39; | awk &#39;{$1=$1;print}&#39; &gt; test.svg</pre><p>And if you open the generated SVG file (<em>test.svg</em>) with a browser, you will see its content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*bRgTwiwWHWxfddVaA25cDg.png" /></figure><h3>Hot Reload</h3><p>The tooling presented above can get you started with on-chain SVG NFTs, but will not make you productive or efficient. Thus, I have developed tooling (initially based on <a href="https://github.com/w1nt3r-eth/hot-chain-svg/">https://github.com/w1nt3r-eth/hot-chain-svg/</a>, but also with many enhancements and improvements and based on Foundry, which is faster than Hardhat) that can greatly improve your productivity. The tooling (as well as the source code of all of the tutorials from the series) is available in the following git repo:</p><ul><li><a href="https://github.com/etovass/svg-nft-tutorials">https://github.com/etovass/svg-nft-tutorials</a></li></ul><p>Here is a short demo of what to expect with the Hot Reload:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4t7c9NqZkV-wlhFMfIZLw.gif" /></figure><p>To work with the hot reload, you must either download <em>ts-tooling</em> directory from <a href="https://github.com/etovass/svg-nft-tutorials/tree/main/ts-tooling">https://github.com/etovass/svg-nft-tutorials/tree/main/ts-tooling</a> or clone the repo with:</p><pre>$ git clone https://github.com/etovass/svg-nft-tutorials</pre><p>Once you have the <em>ts_tooling</em> directory, go to it and execute <em>npm update</em> to download the dependencies.</p><pre>$ cd svg-nft-tutorials<br>$ cd ts-tooling<br>$ npm update</pre><p>Now you can use the tooling. Before continuing the Solidity code, let me quickly explain what <em>ts-tooling</em> is about. In short, <em>ts-tooling</em> is a collection of useful scripts that greatly enhance the development experience while working with on-chain SVG NFTs. For this particular tutorial, we will consider only one tool — Hot Reload.</p><p>Hot Reload allows you to get instant feedback on the SVG content that your smart contract generates. Run the tool, modify your contract, and save it — and instantly, the browser will update with the new result. See the demo gif above.</p><p>You will be running the tool from the root Foundry directory of your project (in our case — <em>tutorial-1-basic-svg-rendering</em>) with the following (for convenience, you will find a script called <em>start-hot-reload</em> that invokes it)</p><pre>npm  --prefix ../ts-tooling run hot-reload ../tutorial-1-basic-svg-rendering/ test/BasicSVGRenderer.t.sol testSvgRenderer 123</pre><p>where:</p><ul><li><strong><em>../tutorial-1-basic-svg-rendering/</em></strong> is the root directory of the Foundry project</li><li><strong><em>test/BasicSVGRenderer.t.sol</em></strong> is the relative path (from the root Foundry project directory) to the test that we want to execute</li><li><strong><em>testSvgRenderer</em></strong> is the test method in the test contract</li><li><strong><em>123 </em></strong>is the default/initial ID of the token that will be shown. You can change it later in the browser easily.</li></ul><p>You need to get the following two files into <strong><em>../tutorial-1-basic-svg-rendering/src</em> </strong>directory:</p><ul><li><a href="https://github.com/etovass/svg-nft-tutorials/blob/main/tutorial-1-basic-svg-rendering/src/Random.sol">https://github.com/etovass/svg-nft-tutorials/blob/main/tutorial-1-basic-svg-rendering/src/Random.sol</a></li><li><a href="https://github.com/etovass/svg-nft-tutorials/blob/main/tutorial-1-basic-svg-rendering/src/Utils.sol">https://github.com/etovass/svg-nft-tutorials/blob/main/tutorial-1-basic-svg-rendering/src/Utils.sol</a></li></ul><p>I will explain these two solidity libraries in another post since this one focuses on workflow and tooling. In short, <em>Random.sol</em> allows you to generate pseudo-random numbers based on some input, while <em>Utils.sol</em> provides useful utilities to convert int/uint numbers to strings.</p><p>In the same directory, also create a file named <em>BasicSVGRenderer2.sol</em> with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1135938f1a5b0cb1eeff405983d434cd/href">https://medium.com/media/1135938f1a5b0cb1eeff405983d434cd/href</a></iframe><p>As you can see from the code, this contract has only one function — <em>renderSVG</em> that takes a single param — <em>tokenId</em>. Then, it uses the <em>tokenId</em> to initialize the random context, which means that every time we use the same <em>tokedId</em>, the same random numbers will be generated.</p><p>Then it “draws” 50 circles filled with the same color but with different coordinates, radius, opacity, and saturation. This function produces SVG content that, when rendered, will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*npwkcGNXU1-dj4BKFe-oaQ.png" /></figure><p>Once we have the renderer, we need to update the tests since <em>ts_tooling</em> depends on a specific output from the tests.</p><p>You need to copy <a href="https://github.com/etovass/svg-nft-tutorials/blob/main/tutorial-1-basic-svg-rendering/test/AbstractTest.t.sol">https://github.com/etovass/svg-nft-tutorials/blob/main/tutorial-1-basic-svg-rendering/test/AbstractTest.t.sol</a> to <em>tutorial-1-basic-svg-rendering/test/AbstractTest.t.sol</em></p><p>I will explain the AbstractTest.t.sol in another post since this one focuses on tooling and workflow. In short, this file is responsible for outputting SVG (and gas consumption) to the console, in a specific format so that <em>ts-tooling</em> can understand it.</p><p>Then you have to modify <em>test/BasicSVGRenderer.t.svg</em> to have the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64b358b8fffdd90dbf3c649c5fd4f0b4/href">https://medium.com/media/64b358b8fffdd90dbf3c649c5fd4f0b4/href</a></iframe><p>And finally, if you run <em>./start-hot-reload.sh</em> from <em>tutorial-1-basic-svg-rendering</em> and navigate your browser to <a href="http://localhost:9901,">http://localhost:9901,</a> you will see the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rMl_KLRBmcOOKpl5tE1-bw.png" /></figure><p>Congratulations! This means that your tooling is successfully set up, and we are ready for Part 2, which will cover how to create a mintable NFT contract, based on ERC-721.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*VaQdyomfAUN81koj.png" /><figcaption>Alien Rune #0</figcaption></figure><p>Thank you for reading. If you like this tutorial, please support the author by minting one or more Alien Runes. Alien Runes is a fully on-chain NFT collection that generates SVG content from Solidity code and has complex algorithms to produce infinite unique runes. Available here: <a href="https://alienrunes.xyz/">https://alienrunes.xyz/</a></p><h3>Links</h3><p><strong>Git Repo for this tutorial:</strong></p><ul><li><a href="https://github.com/etovass/svg-nft-tutorials">https://github.com/etovass/svg-nft-tutorials</a></li></ul><p><strong>SVG Tutorials:</strong></p><ul><li><a href="https://www.w3schools.com/graphics/svg_intro.asp">https://www.w3schools.com/graphics/svg_intro.asp</a></li><li><a href="https://jenkov.com/tutorials/svg/index.html">https://jenkov.com/tutorials/svg/index.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17b8fea08739" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>