<?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 Sol Tech on Medium]]></title>
        <description><![CDATA[Stories by Sol Tech on Medium]]></description>
        <link>https://medium.com/@smile0307?source=rss-3f6da6942a46------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BM1Qet8HEw5tg1PyDgdHpA.png</url>
            <title>Stories by Sol Tech on Medium</title>
            <link>https://medium.com/@smile0307?source=rss-3f6da6942a46------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:46:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smile0307/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[How NFTs are represented in Solana | Owning digital assets in Solana]]></title>
            <link>https://medium.com/@smile0307/how-nfts-are-represented-in-solana-owning-digital-assets-in-solana-a622d8076ffd?source=rss-3f6da6942a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/a622d8076ffd</guid>
            <dc:creator><![CDATA[Sol Tech]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 08:26:49 GMT</pubDate>
            <atom:updated>2022-07-06T08:26:49.185Z</atom:updated>
            <content:encoded><![CDATA[<p>In a previous article, we saw how NFTs unlock new ways of owning data. Now let’s take a look at how NFTs actually work in Solana.</p><p>Since the Solana blockchain structures data differently than other blockchains, it may be confusing at first but, in my opinion, its model makes a lot of sense and is closer to how we represent things in the real world.</p><p>Thus, we’ll first start by looking at how we do things in the real world and gradually move our way towards the representation of an NFT.</p><p>Bear with me, we’re going on a little journey.</p><h3>Not your typical program</h3><p>This article is not about coding but it’s worth noting that, if you’re used to other blockchains such as Ethereum, then you’ll have a bit of unlearning to do.</p><p>In these blockchains or any typical piece of code, you add variables within your program, and your logic updates these variables. In Ethereum, a deployed “Smart Contract”, contains both the logic and the data needed for that contract to do its job.</p><p>That’s not the case for Solana. In Solana, a “Program” (the equivalent of a Smart Contract) interacts with “Accounts” that are stored outside of the program. This enables us to create more generic logic that can scale to new orders of magnitude since the data is no longer bound by the size of the program. Additionally, it enables the blockchain to run more efficiently since it can run the same program in parallel with different accounts.</p><p>The TL;DR; here is: <strong>Data in Solana is stored outside of programs, in reusable and scalable models called “Accounts”</strong>.</p><h3>The USD printing machine</h3><p>Alright, let’s step back into the real world for a minute and reflect on what makes us own the money that we own in a given currency.</p><p>Finance is a complex subject and there are many different ways to own money: cash, banks, assets, etc. To get closer to how we model things in Solana, we need to simplify our real-world model.</p><p>Imagine all of the money in the world for a given currency is generated by one bank and one bank only. Let’s call them “Printing Machines” since they would literally be able to control how much of that currency is in circulation. For instance, the “USD Printing Machine” would be responsible for managing all the US dollars in the world. Nice and simple.</p><p>FAILED</p><p>These “Printing Machines” would then allow individuals to own money via “Bank Accounts” where each individual can have as many bank accounts as they want. That way bank accounts act as many-to-many relationships between individuals and currencies.</p><p>In the example below, Alice owns US dollars and British pounds via three different bank accounts (two for USD and one for GBP) whereas Bob only owns British pounds via one bank account.</p><p>FAILED</p><p>Good, with that model in mind, let’s enter the world of tokens!</p><h3>Mints and tokens</h3><p>In the previous section, we created a simple model where people use bank accounts to access money in a given currency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TzGh5YkYdgV2k2wr.png" /></figure><p>Well, surprise surprise, <strong>that model is analogous to how tokens are represented in Solana</strong>. You can think of a token as a decentralised currency that lives on a blockchain.</p><p>Each type of token is defined by what we call a “Mint Account”. That account is analogous to a “Printing Machine” because it can literally be used to “mint tokens” which is equivalent to printing money.</p><p>Then, individuals can own tokens via “Token Accounts” which store the number of tokens owned.</p><p>Finally, there’s no such thing as individuals in blockchains since people interact with them through cryptographic key pairs called wallets. The public key of each wallet points to an account in Solana that stores the amount of SOL owned by the wallet. For that reason, I will refer to these accounts as “Wallet Accounts”.</p><p>So that leads us to the following analogy.</p><p>FAILED</p><p>Note that it is common for individuals to have multiple wallets — usually for security purposes. Therefore, the following analogy is more accurate.</p><p>FAILED</p><p>Before we move on to the next section, let’s take a quick example of token ownership in Solana.</p><p>Instead of US dollars and British pounds, we’ll use the tokens USDC and AVDO. These are real tokens in Solana. USDC is <a href="https://www.coinbase.com/usdc">a stablecoin</a> pegged to the US dollar and AVDO is <a href="https://www.avocadocoin.com/">a cryptocurrency backed by the avocado industry</a> (because why not).</p><p>FAILED</p><p>As you can see Alice owns some USDC and some AVDO via two wallets and three token accounts. On the other hand, Bob only owns AVDO through one wallet and two token accounts.</p><h3>What’s your IBAN?</h3><p>Now, there’s one big inconvenience with the model described so far.</p><p>To illustrate the issue, imagine that Alice, in our previous example, wanted to send some AVDO tokens to Bob.</p><p>Since Bob has two token accounts for his AVDO tokens, which token account should Alice choose to deposit her tokens? Should she ask Bob to send her the public key of the token account of his choice? Even worse, imagine Alice now wants to send some USDC tokens to Bob when Bob doesn’t currently have any USDC token accounts. Should she create a new token account for Bob and then send him its public key?</p><p>None of these issues makes it impossible to send tokens but they make our life harder than it should be.</p><p>When sending tokens to someone, you usually only have the public key of their wallet and you really don’t want to worry about which token account to use or if it even exists.</p><p>The solution to that problem is called “Program Derived Addresses” or PDA for short. These are public keys that are <strong>derived from other public keys</strong> using a special algorithm.</p><p>What that means for us is, given a “Wallet Account” and a “Mint Account”, <strong>we can deterministically find the associated Token Account</strong>. In fact, these accounts are called “Associated Token Accounts” (ATA for short) and they are managed by the “ <a href="https://spl.solana.com/associated-token-account">Associated Token Account Program</a> “.</p><p>Therefore, we end up with two ways of creating and using token accounts: One that’s deterministic (using PDAs) and one that’s not (using normal token accounts).</p><p>FAILED</p><p>Note the annotation above the PDA. These are the parameters required to derive the address of the associated token account. If you’d like to read more about PDAs, <a href="https://solanacookbook.com/core-concepts/pdas.html">the Solana Cookbook</a> is a good place to start.</p><p>Since we’re going to use this diagram a lot in this article, let’s shorten its representation slightly. We’ll use the following diagram to represent the generic connection between wallets and mint accounts. They could be using PDAs or they could not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XEnzLyZWa5JsOQ-E.png" /></figure><p>Before we move on from this important PDA parenthesis, let’s take a quick look at our previous example using only associated token accounts.</p><p>FAILED</p><p>Notice how we’ve now only got one token account per wallet per mint which means Alice knows where to send the AVDO tokens to Bob. Additionally, Alice knows where to send Bob some USDC even though the account does not exist yet.</p><p>Okay, let’s move on!</p><h3>Data on mints and tokens</h3><p>I appreciate your patience but you might be thinking: “Loris, what does that have anything to do with NFTs?”.</p><p>I promise we’re getting there! But to answer that, we first need to understand what data is stored in both the token accounts and the mint accounts.</p><p>To that end, let’s update our diagram to show all of the data available under each account and, whilst we’re at it, let’s also display the owner of the account — i.e. the Solana program responsible for creating it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F7nlEBAKCOe1QeNK.png" /></figure><p>Okay, we have a few things to notice here.</p><ul><li>First, notice how the token account (associated or not) keeps track of both the mint and the wallet accounts. I’ve highlighted these connections using dashed lines.</li><li>The next important piece of data on the token account is <strong>“Amount”</strong>. It stores the number of tokens available in the account.</li><li>The rest of the data is also important but out of scope for this article so I won’t be going through them. I’ll just say that when you see an <em>italic</em> attribute, that means it is optional.</li><li>Moving on to the mint account’s data. The first attribute is the optional <strong>“Mint Authority”</strong>. This represents the account that can mint more tokens — i.e. print more money. It is usually the wallet account that created it. It is optional because a mint authority can revoke its own right, therefore, making the mint account immutable — i.e. the number of tokens in circulation will never increase.</li><li>Speaking of, the next attribute — <strong>“Supply”</strong> — tells us the total amount of tokens currently in circulation. This attribute cannot be manually updated and is automatically kept up-to-date by the program.</li><li>Next, the <strong>“Decimals”</strong> attribute dictates how many decimal places we should use for that token. For instance, if a token account has Amount = 250 and the mint account has Decimals = 2, that means the token account actually owns 2.50 of that token. That way, all monetary values can be stored using integers.</li><li>We’ll also skip the rest of the attributes since they are out of scope for this article.</li></ul><p>In order to move closer to the representation of an NFT, let’s play with these attributes a little.</p><p>What if we created a mint account with <strong>zero decimals</strong> and immediately <strong>minted one token</strong> to a wallet account?</p><p>The result would be <strong>a mint account with only one token in circulation</strong> that cannot be broken down into smaller units — e.g. Alice and Bob cannot both have 0.5 of that token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WOLmpzqlHAWRfQ5F.png" /></figure><p>The only issue with that is nothing stops the “Mint Authority” to continue minting more tokens in the future. If they did, we’d suddenly have more than one token in circulation and, thus, more than one wallet could own them.</p><p>To prevent that, <strong>the mint authority needs to revoke its right</strong> to mint more tokens immediately <strong>after minting the first one</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4QUMBrRA60lk1Rq5.png" /></figure><p>What we end up with is a mint account whose supply will never go above one and whose token cannot be shared or divided.</p><p>Thus, <strong>there can only be one token holder for that mint</strong> at any given time.</p><h3>An NFT is just a special Mint</h3><p>And that, my frens, is a Non-Fungible Token! 🥳</p><p>The definition of a “Fungible” is:</p><blockquote><em>Being of such nature or kind as to be freely exchangeable or replaceable, in whole or in part, for another of like nature or kind.</em></blockquote><p>In other words, it can be replaced by something else of the same kind. For instance, olive oil is fungible. One litre of olive can be replaced with another litre of olive oil and we’ve not lost any value. The same goes for currencies: replace a 10 USD note with another 10 USD note and you’ve still got 10 dollars.</p><p>Therefore, for a token to be <em>non-fungible</em>, it needs to have such characteristics that it cannot be traded with something of the same kind. We have managed to achieve this by creating a mint account that will never have more than one token holder. Whoever owns this token, owns the mint account and therefore, owns the NFT.</p><p>To recap: <strong>An NFT is a mint account with zero decimals and whose supply will never exceed one</strong>.</p><p>I’d also like to take a second to appreciate how elegant that model is. Not only is its representation inlined with its definition, but by relying on token accounts and mint accounts, we can interact with NFTs the same way we can interact with tokens. Sending an NFT to someone is as simple as giving them your only token for that mint account.</p><h3>Where’s the picture?</h3><p>Okay, I’ll be honest we haven’t completely finished our journey in explaining NFTs in Solana. What we’ve explained so far is indeed an NFT by definition but not a very useful one. All it’s telling us is that we own a token and that no one else can own that token. Great! But what’s that token called? What is its purpose? Where’s the picture?!</p><p>Well, it sounds like we need to attach more data to our NFT to make it useful. That’s where Metaplex comes in!</p><p><a href="https://www.metaplex.com/">Metaplex</a> is a company that creates and maintains Solana programs. Their most popular program is called the <strong>“Token Metadata Program”</strong>. You guessed it, it adds metadata to our tokens!</p><p>It does that by using Program Derived Addresses (PDAs). If you remember, PDAs allow us to deterministically find an address using other addresses.</p><p>In this case, the Token Metadata program will create a new “Metadata Account” attached to that NFT. But can you guess which address it uses to derive its own address? Is it the mint account or the token account?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TQTXO02U0dO1IlVI.png" /></figure><p>The answer is: <strong>the mint account</strong>! The mint account is the most important account for an NFT. A token account is a relationship between an NFT and a wallet. If we attached a PDA to a token account and then sold our NFT, the new owner will lose all of that data. Therefore, <strong>the mint account is the main entry point of an NFT</strong>.</p><p>Alright, let’s see what sort of data Metaplex has blessed us with on the “Metadata Account”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RgVzSC0eARzWX262.png" /></figure><p>Let’s go through all of these attributes one by one.</p><ul><li>Key: This attribute is what we call a discriminator. Because Metaplex has many different types of account within the Token Metadata Program, this tells us which account we are dealing with. Here, the &quot;Metadata Account&quot; is identified by the MetadataV1 key. Note that the Token Program uses the size of the account instead of a discriminator to figure this out, which is more performant but less flexible.</li><li>Update Authority: This is the account that can update the &quot;Metadata Account&quot;.</li><li>Mint: This points back to the mint account.</li><li>Name: The on-chain name of the NFT - limited to 32 bytes.</li><li>Symbol: The on-chain symbol of the NFT - limited to 10 bytes. This is often left as an empty string but can be useful if you want your NFT collection to have a shared symbol. For instance, your &quot;Banana Blossom&quot; NFT drop could have the symbol &quot;BNBL&quot;.</li><li>URI: The URI of the NFT- limited to 200 bytes. <strong>This is one of the most important attributes.</strong> It contains a URI that points to a JSON file off-chain. This JSON file can either be stored in a traditional server (e.g. using AWS) or it can be stored using a permanent storage solution on another chain (e.g. using Arweave). We&#39;ll talk more about this JSON file in a minute.</li><li>Seller Fee Basis Points: The royalties shared by the creators in basis points - i.e. 550 means 5.5%.</li><li>Creators: An array of creators and their share of the royalties. This array is limited to 5 creators. A verified attribute exists on each creator to ensure they signed the NFT to prove its authenticity.</li><li>Primary Sale Happened: A boolean keeping track of whether the NFT has been sold before or not. This affects the royalties.</li><li>Is Mutable: A boolean indicating if the on-chain metadata of the NFT can be modified. Once flipped to false, it cannot be reverted.</li><li>Edition Nonce: This optional attribute is slightly out of scope but it is used to verify the edition number of limited edition NFTs.</li><li>Token Standard: This optional attribute captures the fungibility of the token. We&#39;ll talk more about this in this article.</li><li>Collection: This optional attribute links to the mint address of another NFT that acts as a Collection NFT. This is helpful for marketplaces to group NFTs together and safely verify these collections.</li><li>Uses: This optional attribute can make NFTs usable. Meaning you can load it with a certain amount of &quot;uses&quot; and use it until it has run out. You can even make it so the NFT destroys itself when it&#39;s been completely used out.</li></ul><p>Phew! As you can see, lot’s of cool features. I’m not going to go through them all here but I’m hoping to add more articles to this series on that subject. In the meantime, feel free to check <a href="https://docs.metaplex.com/token-metadata/specification">the official Metaplex documentation</a> for more information.</p><h3>Again, where’s the picture?</h3><p>So many attributes, yet, still no picture or digital asset? Isn’t that a big part of what an NFT is?</p><p>Yes! Worry not, we do have a place to store that information.</p><p>Remember that URI attribute that points to an off-chain JSON object? Well, that JSON object follows a certain standard in order to store even more data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uqvBAmaojhslISLw.png" /></figure><p>As you can see, we can provide, amongst other things, a name, a description and, finally, an image! Similarly to the URI attribute of the Metadata Account, that image attribute should be a URI that can be used to download the digital asset. There&#39;s also an animation_url attribute and a files array for NFTs that have more custom needs. All of these assets could be either stored off-chain (in a traditional server) or using a permanent storage solution (in another blockchain such as Arweave). Be sure to <a href="https://docs.metaplex.com/token-metadata/specification#token-standards">check out the Metaplex documentation</a> for more information on its NFT standard.</p><p>It is worth mentioning that you can add anything you want within that JSON object. If you’re planning on building an app that recognises your own NFTs that can be useful. But be aware that other applications and marketplaces will not be aware that this data exists and therefore will not be using it.</p><h3>Why two metadata storage?</h3><p>You might be wondering, why do we need two places to store the data of our NFT? Couldn’t we just store everything on the Metadata Account?</p><p>There are several issues with that.</p><ul><li>First, it costs money to store data on-chain. When designing accounts used by thousands of people, you want to be mindful of the price it will cost to create them.</li><li>Second, on-chain data is much less flexible. Once an account is created using a certain structure, it cannot easily be changed. Therefore, if we had to store everything on-chain, we would greatly limit the amount of data that can be attached to an NFT.</li></ul><p>As a result, we need to cleverly and safely split the data into two categories: on-chain and off-chain. For instance, the Creators array is on-chain because we need a trustless way of knowing if an NFT has truly been offered and signed by a given artist. The Is Mutable attribute is on-chain because we need to ensure that, once flipped to false it can never be reverted.</p><p>The bottom line is: <strong>the Token Metadata Program can create guarantees and expectations for on-chain data but cannot do that for off-chain data</strong>.</p><p>However, that doesn’t necessarily mean the off-chain JSON file is insecure and never to be trusted. Permanent storage blockchains such as Arweave are commonly used to store both the digital assets and the JSON metadata that references them, ensuring the immutability of the off-chain data. Additionally, NFTs can be made immutable ensuring that the URI attribute of the Metadata Account will never point elsewhere. This is the most secure configuration of an NFT as it is guaranteed nothing could even be done to alter it.</p><p>Also, note that some NFT projects might need their data to be mutable in ways that will benefit the NFT owners. For instance, if you’re planning on creating an NFT of a baby monkey that gradually grows into an adult monkey, you need the JSON metadata stored on a server you control in order to make these gradual changes. Next time, the NFT owners open up their wallets they will see another image but they will be delighted rather than outraged. My point is, as long as you trust the creators of your NFT — which are guaranteed by the Verified flag of the on-chain Creators attribute - mutable off-chain data can be genuine. But of course, always do your own research.</p><h3>Printing multiple editions</h3><p>Okay, surely we’ve now reached the final representation of an NFT in Solana?</p><p>For the most part, yes, but not quite.</p><p>There is another important account offered by the Token Metadata Program, derived from the mint account (using a PDA).</p><p>In fact, the account located inside that PDA can be one of two different types. It can either be a “Master Edition” or an “Edition”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9GMAY6yLongrWEwQ.png" /></figure><p>A “Master Edition” also known as an “Original Edition” is an NFT that can be duplicated by its owner a certain amount of times dictated by the “Max Supply” attribute.</p><p>An “Edition” also known as a “Print Edition” is an NFT that was duplicated from a “Master Edition”. Whenever a new “Edition” is created, it keeps track of its parent “Master Edition” and its edition number. It also increases the supply of its parent “Master Edition”. Once the supply reaches the max supply, no more NFTs can be printed that way. Note that the “Max Supply” of a “Master Edition” can be null, which means an unlimited amount of NFT can be printed from it.</p><p>Also note that another — lesser-known — PDA Account called “Edition Marker” exists on “Edition” NFTs to ensure there is no overlap between the edition numbers of a given “Master Edition”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FW5B0tbJyCk0fTOU.png" /></figure><p>One use-case for this feature is to allow artists to sell more than one copy of their art. For instance, they can release 100 limited editions of their 1/1 NFT and each of them will keep track of their edition number on-chain.</p><p>It is worth noting that printing multiple editions of an NFT is totally optional and most NFTs out there will set their “Max Supply” to 0 to prevent using it.</p><p>So why did I decide to mention “Master Editions” and “Editions” in this — rather long — article? Because, whilst printing editions is their primary purpose, <strong>they are responsible for more than just that.</strong></p><p>If you remember, we said earlier that for a “Mint Account” to be an NFT, it needed to:</p><ul><li>Have zero decimals.</li><li>Have minted exactly one token to a wallet.</li><li>Have revoked its right to mint additional tokens via the “Mint Authority” attribute.</li></ul><p>Well, the Token Metadata Program uses the edition PDA to guarantee these properties. When creating the edition PDA account (whether it’s a “Master Edition” or an “Edition”) it will check that the mint account has got zero decimals and a supply of exactly one. If either of these conditions fails, it will refuse to create the account. If they succeed, it will transfer the “Mint Authority” to that new edition PDA ensuring no wallet can ever mint additional tokens. What that means is, <strong>the simple fact that a “Master Edition” or “Edition” account exists on a mint account, is proof of its non-fungibility</strong>.</p><p>This is why “Master Edition” and “Edition” accounts are important in Solana NFTs and are worth mentioning in this article.</p><p>Here’s a little update on our NFT diagram. As you can see the “Mint Authority” is no longer null but points to the edition PDA which can only be controlled by the open-sourced and audited Token Metadata Program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4RDpgfm9wHQmYRHO.png" /></figure><h3>Token Standard and Semi-Fungible Tokens</h3><p>We now have the full picture of what makes a mint account an NFT in Solana!</p><p>However, this article wouldn’t be complete if I didn’t mention that the Token Metadata Program also supports what we call “ <strong>Semi-Fungible Tokens</strong> “ or SFT for short.</p><p>SFTs are basically the same as NFTs but without the non-fungible guarantees, we talked about earlier.</p><p>“But why?”, you might ask, “I thought non-fungibility was the whole point?”.</p><p>Well, it is for NFTs but, when you think about it, <strong>the core purpose of the “Metadata Account” is to add data to tokens</strong>. Why should we only restrict that feature to non-fungible tokens?</p><p>Why couldn’t our fungible Avocado token (AVDO) from earlier add on-chain data to its mint account? It could use that data to let decentralised exchanges know which symbol to use, which external links to list, which logo to display and so on.</p><p>Another use case for this would be creating a gaming asset as a zero-decimal token. For instance, you could create a token for the “Wood” resource in your game. Since players should be able to own and trade more than one wood, it makes little sense to have to create one single NFT for every single piece of wood in your game. That’s why making game resources fungible assets whilst still benefiting from on-chain data is super valuable.</p><p>As such, the Token Metadata Program allows us to create Metadata Accounts for mint accounts that are fungible. This is why, <strong>it is the responsibility of the edition PDA to guarantee non-fungibility</strong>.</p><p>To make our life easier, the Metadata Account keeps track of “how fungible” a token is via the “ <strong>Token Standard</strong> “ attribute. It can be one of the following values.</p><h3>NonFungible</h3><p>If the token standard is NonFungible, we know <strong>we are dealing with an NFT</strong>. This standard is applied if and only if a &quot;Master Edition&quot; or &quot;Edition&quot; account was created for that mint.</p><p>That means, we have the following guarantees:</p><ul><li>Mint supply is one.</li><li>Mint decimals are zero.</li><li>An account exists under the edition PDA.</li><li>Mint authority has been transferred to the edition PDA.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z_TFDzedEkAlCpe0.png" /></figure><h3>FungibleAsset</h3><p>If the token standard is FungibleAsset, we know <strong>we are dealing with a non-decimal SFT</strong>. For instance, our &quot;Wood&quot; resource example would be marked as a FungibleAsset.</p><p>That means we have the following guarantees:</p><ul><li>Mint decimals are zero.</li><li>No account exists under the edition PDA.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1xNu5ZRKqD7urK3A.png" /></figure><h3>Fungible</h3><p>If the token standard is Fungible, we know <strong>we are dealing with a decimal SFT</strong>. For instance, the Avocado token or the USDC token would both fit in this category.</p><p>That means we have the following guarantees:</p><ul><li>Mint decimals are strictly greater than zero.</li><li>No account exists under the edition PDA.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U6pfPjhBIf3eKEqy.png" /></figure><p>It is worth noting that the off-chain JSON metadata standard varies based on the “Token Standard” we’ve just discussed. You can find the JSON standard definition for each token type below.</p><h3>Conclusion</h3><p>Phew, what a journey!</p><p>Not only do we now have a full picture of what an NFT and an SFT look like in Solana, but we also understand why things are structured the way they are and how they compare to other models we are used to.</p><p>This article wouldn’t be complete without a final diagram resuming what we’ve learned here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3DN8ixLh6ZqiQAUR.png" /></figure><p>And for the sake of making this diagram even more useful for developers out there, let’s also add the offset and the size of each account attribute in bytes. I’ll use a tilde ~ for variable account sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1lsQlzL5LDAQnRkU.png" /></figure><p>Alright, I hope you’ve enjoyed this article and I’ll see you soon for more Solana and Metaplex adventures! ⛵️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a622d8076ffd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Rust from simple guess game.]]></title>
            <link>https://medium.com/@smile0307/learn-rust-from-simple-guess-game-8c8c834327dc?source=rss-3f6da6942a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c8c834327dc</guid>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Sol Tech]]></dc:creator>
            <pubDate>Fri, 24 Jun 2022 06:44:55 GMT</pubDate>
            <atom:updated>2024-05-23T12:55:02.327Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s jump into Rust by working through a hands-on project together! This article introduces you to a few common Rust concepts by showing you how to use them in a real program. You’ll learn about let, match, methods, associated functions, using external crates, and more!</p><p>We’ll implement a classic beginner programming problem: a guessing game. Here’s how it works: the program will generate a random integer between 1 and 100. It will then prompt the player to enter a guess. After a guess is entered, the program will indicate whether the guess is too low or too high. If the guess is correct, the game will print a congratulatory message and exit.</p><p>To set up a new project, go to the <em>projects</em> directory and make a new project using Cargo, like so:</p><pre>$ cargo new guessing_game $ cd guessing_game</pre><p>The first command, cargo new, takes the name of the project ( guessing_game) as the first argument. The second command changes to the new project&#39;s directory.</p><p>Look at the generated <em>Cargo.toml</em> file:</p><p>Filename: Cargo.toml</p><pre>[package] name = &quot;guessing_game&quot; version = &quot;0.1.0&quot; edition = &quot;2021&quot; # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies]</pre><p>As you know, cargo new generates a &quot;Hello, world!&quot; program for you. Check out the <em>src/main.rs</em> file:</p><p>Filename: src/main.rs</p><pre>fn main() { println!(&quot;Hello, world!&quot;); }</pre><p>Now let’s compile this “Hello, world!” program and run it in the same step using the cargo run command:</p><pre>$ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 1.50s Running `target/debug/guessing_game` Hello, world!</pre><p>The run command comes in handy when you need to rapidly iterate on a project, as we&#39;ll do in this game, quickly testing each iteration before moving on to the next one.</p><p>Reopen the <em>src/main.rs</em> file. You’ll be writing all the code in this file.</p><p>The first part of the guessing game program will ask for user input, process that input, and check that the input is in the expected form. To start, we’ll allow the player to input a guess. Enter the code in Listing 2–1 into <em>src/main.rs</em>.</p><p>Filename: src/main.rs</p><pre>use std::io; fn main() { println!(&quot;Guess the number!&quot;); println!(&quot;Please input your guess.&quot;); let mut guess = String::new(); io::stdin() .read_line(&amp;mut guess) .expect(&quot;Failed to read line&quot;); println!(&quot;You guessed: {}&quot;, guess); }</pre><p>By default, Rust has a few items defined in the standard library that it brings into the scope of every program. This set is called the <em>prelude</em>, and you can see everything in it <a href="https://doc.rust-lang.org/std/prelude/index.html">in the standard library documentation</a>.</p><p>If a type you want to use isn’t in the prelude, you have to bring that type into scope explicitly with a use statement. Using the std::io library provides you with a number of useful features, including the ability to accept user input.</p><p>As you know, the main function is the entry point into the program:</p><p>Here, println! is a macro that prints a string to the screen:</p><pre>use std::io; fn main() { println!(&quot;Guess the number!&quot;); println!(&quot;Please input your guess.&quot;); let mut guess = String::new(); io::stdin() .read_line(&amp;mut guess) .expect(&quot;Failed to read line&quot;); println!(&quot;You guessed: {}&quot;, guess); }</pre><p>This code is printing a prompt stating what the game is and requesting input from the user.</p><p>Next, we’ll create a <em>variable</em> to store the user input, like this:</p><p>Now the program is getting interesting! There’s a lot going on in this little line. We use the let statement to create the variable. Here&#39;s another example:</p><pre>let apples = 5;</pre><p>This line creates a new variable named apples and binds it to the value 5. In Rust, variables are immutable by default. To make a variable mutable, we add mut before the variable name:</p><pre>let apples = 5; // immutable let mut bananas = 5; // mutable</pre><blockquote><em>Note: The </em><em>// syntax starts a comment that continues until the end of the line. Rust ignores everything in comments.</em></blockquote><p>Returning to the guessing game program, you now know that let mut guess will introduce a mutable variable named guess. The equal sign (=) tells Rust we want to bind something to the variable now. On the right of the equals sign is the value that guess is bound to, which is the result of calling String::new, a function that returns a new instance of a String. is a string type provided by the standard library that is a growable, UTF-8 encoded bit of text.</p><p>The :: syntax in the ::new line indicates that new is an associated function of the String type. An <em>associated function</em> is a function that&#39;s implemented on a type, in this case String. This new function creates a new, empty string. You&#39;ll find a new function on many types, because it&#39;s a common name for a function that makes a new value of some kind.</p><p>In full, the let mut guess = String::new(); line has created a mutable variable that is currently bound to a new, empty instance of a String. Whew!</p><p>If we hadn’t imported the io library with use std::io at the beginning of the program, we could still use the function by writing this function call as std::io::stdin. The stdin function returns an instance of<a href="https://doc.rust-lang.org/std/io/struct.Stdin.html">std::io::Stdin</a>, which is a type that represents a handle to the standard input for your terminal.</p><p>Next, the line .read_line(&amp;mut guess) calls the method on the standard input handle to get input from the user. We&#39;re also passing&amp;mut guess as the argument to read_line to tell it what string to store the user input in. The full job of read_line is to take whatever the user types into standard input and append that into a string (without overwriting its contents), so we therefore pass that string as an argument. The string argument needs to be mutable so the method can change the string&#39;s content.</p><p>The &amp; indicates that this argument is a <em>reference</em>, which gives you a way to let multiple parts of your code access one piece of data without needing to copy that data into memory multiple times. References are a complex feature, and one of Rust&#39;s major advantages is how safe and easy it is to use references. You don&#39;t need to know a lot of those details to finish this program. For now, all you need to know is that like variables, references are immutable by default. Hence, you need to write&amp;mut guess rather than&amp;guess to make it mutable.</p><p>We’re still working on this line of code. Although we’re now discussing a third line of text, it’s still part of a single logical line of code. The next part is this method:</p><p>We could have written this code as:</p><pre>io::stdin().read_line(&amp;mut guess).expect(&quot;Failed to read line&quot;);</pre><p>However, one long line is difficult to read, so it’s best to divide it. It’s often wise to introduce a newline and other whitespace to help break up long lines when you call a method with the .method_name() syntax. Now let&#39;s discuss what this line does.</p><p>As mentioned earlier, read_line puts whatever the user enters into the string we pass to it, but it also returns a value-in this case, an . Rust has a number of types named Result in its standard library: a generic as well as specific versions for submodules, such as io::Result. The Result types are<a href="https://doc.rust-lang.org/book/ch06-00-enums.html"><em>enumerations</em></a>, often referred to as <em>enums</em>, which can have a fixed set of possibilities known as <em>variants</em>. Enums are often used with match, a conditional that makes it convenient to execute different code based on which variant an enum value is when the conditional is evaluated.</p><p>The purpose of these Result types is to encode error-handling information.</p><p>Result&#39;s variants are Ok and Err. The Ok variant indicates the operation was successful, and inside Ok is the successfully generated value. The Err variant means the operation failed, and Err contains information about how or why the operation failed.</p><p>Values of the Result type, like values of any type, have methods defined on them. An instance of io::Result has an <a href="https://doc.rust-lang.org/std/result/enum.Result.html#method.expect">expect method</a> that you can call. If this instance of io::Result is an Err value, expect will cause the program to crash and display the message that you passed as an argument to expect. If the read_line method returns an Err, it would likely be the result of an error coming from the underlying operating system. If this instance of io::Result is an Ok value, expect will take the return value that Ok is holding and return just that value to you so you can use it. In this case, that value is the number of bytes in the user&#39;s input.</p><p>If you don’t call expect, the program will compile, but you&#39;ll get a warning:</p><pre>$ cargo build Compiling guessing_game v0.1.0 (file:///projects/guessing_game) warning: unused `Result` that must be used --&gt; src/main.rs:10:5 | 10 | io::stdin().read_line(&amp;mut guess); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(unused_must_use)]` on by default = note: this `Result` may be an `Err` variant, which should be handled warning: `guessing_game` (bin &quot;guessing_game&quot;) generated 1 warning Finished dev [unoptimized + debuginfo] target(s) in 0.59s</pre><p>Rust warns that you haven’t used the Result value returned from read_line, indicating that the program hasn&#39;t handled a possible error.</p><p>The right way to suppress the warning is to actually write error handling, but in our case we just want to crash this program when a problem occurs, so we can use expect.</p><p>Aside from the closing curly bracket, there’s only one more line to discuss in the code so far:</p><p>This code would print x = 5 and y = 10.</p><p>Let’s test the first part of the guessing game. Run it using cargo run:</p><pre>$ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 6.44s Running `target/debug/guessing_game` Guess the number! Please input your guess. 6 You guessed: 6</pre><p>At this point, the first part of the game is done: we’re getting input from the keyboard and then printing it.</p><p>Next, we need to generate a secret number that the user will try to guess. The secret number should be different every time so the game is fun to play more than once. We’ll use a random number between 1 and 100 so the game isn’t too difficult. Rust doesn’t yet include random number functionality in its standard library. However, the Rust team does provide a with said functionality.</p><p>Remember that a crate is a collection of Rust source code files. The project we’ve been building is a <em>binary crate</em>, which is an executable. The rand crate is a <em>library crate</em>, which contains code intended to be used in other programs, and can&#39;t be executed on its own.</p><p>Cargo’s coordination of external crates is where Cargo really shines. Before we can write code that uses rand, we need to modify the <em>Cargo.toml</em> file to include the rand crate as a dependency. Open that file now and add the following line to the bottom beneath the[dependencies] section header that Cargo created for you. Be sure to specify rand exactly as we have here, with this version number, or the code examples in this tutorial may not work.</p><p>Filename: Cargo.toml</p><p>In the <em>Cargo.toml</em> file, everything that follows a header is part of that section that continues until another section starts. In[dependencies] you tell Cargo which external crates your project depends on and which versions of those crates you require. In this case, we specify the rand crate with the semantic version specifier 0.8.3. Cargo understands <a href="http://semver.org/">Semantic Versioning</a> (sometimes called <em>SemVer</em>), which is a standard for writing version numbers. The number 0.8.3 is actually shorthand for^0.8.3, which means any version that is at least 0.8.3 but below 0.9.0. Cargo considers these versions to have public APIs compatible with version 0.8.3, and this specification ensures you&#39;ll get the latest patch release that will still compile with the code. Any version 0.9.0 or greater is not guaranteed to have the same API as what the following examples use.</p><p>Now, without changing any of the code, let’s build the project, as shown in Listing 2–2.</p><pre>$ cargo build Updating crates.io index Downloaded rand v0.8.3 Downloaded libc v0.2.86 Downloaded getrandom v0.2.2 Downloaded cfg-if v1.0.0 Downloaded ppv-lite86 v0.2.10 Downloaded rand_chacha v0.3.0 Downloaded rand_core v0.6.2 Compiling rand_core v0.6.2 Compiling libc v0.2.86 Compiling getrandom v0.2.2 Compiling cfg-if v1.0.0 Compiling ppv-lite86 v0.2.10 Compiling rand_chacha v0.3.0 Compiling rand v0.8.3 Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 2.53s</pre><p>You may see different version numbers (but they will all be compatible with the code, thanks to SemVer!), different lines (depending on the operating system), and the lines may be in a different order.</p><p>When we include an external dependency, Cargo fetches the latest versions of everything that dependency needs from the <em>registry</em>, which is a copy of data from <a href="https://crates.io/">Crates.io</a>. Crates.io is where people in the Rust ecosystem post their open source Rust projects for others to use.</p><p>If you immediately run cargo build again without making any changes, you won&#39;t get any output aside from the Finished line. Cargo knows it has already downloaded and compiled the dependencies, and you haven&#39;t changed anything about them in your <em>Cargo.toml</em> file. Cargo also knows that you haven&#39;t changed anything about your code, so it doesn&#39;t recompile that either. With nothing to do, it simply exits.</p><p>If you open up the <em>src/main.rs</em> file, make a trivial change, and then save it and build again, you’ll only see two lines of output:</p><pre>$ cargo build Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs</pre><p>These lines show Cargo only updates the build with your tiny change to the <em>src/main.rs</em> file. Your dependencies haven’t changed, so Cargo knows it can reuse what it has already downloaded and compiled for those.</p><p>Cargo has a mechanism that ensures you can rebuild the same artifact every time you or anyone else builds your code: Cargo will use only the versions of the dependencies you specified until you indicate otherwise. For example, say that next week version 0.8.4 of the rand crate comes out, and that version contains an important bug fix, but it also contains a regression that will break your code. To handle this, Rust creates the <em>Cargo.lock</em> file the first time you run cargo build, so we now have this in the <em>guessing_game</em> directory.</p><p>When you build a project for the first time, Cargo figures out all the versions of the dependencies that fit the criteria and then writes them to the <em>Cargo.lock</em> file. When you build your project in the future, Cargo will see that the <em>Cargo.lock</em> file exists and use the versions specified there rather than doing all the work of figuring out versions again. This lets you have a reproducible build automatically. In other words, your project will remain at 0.8.3 until you explicitly upgrade, thanks to the <em>Cargo.lock</em> file.</p><p>When you <em>do</em> want to update a crate, Cargo provides the command update, which will ignore the <em>Cargo.lock</em> file and figure out all the latest versions that fit your specifications in <em>Cargo.toml</em>. Cargo will then write those versions to the <em>Cargo.lock</em> file. Otherwise, by default, Cargo will only look for versions greater than 0.8.3 and less than 0.9.0. If the rand crate has released the two new versions 0.8.4 and 0.9.0 you would see the following if you ran cargo update:</p><pre>$ cargo update Updating crates.io index Updating rand v0.8.3 -&gt; v0.8.4</pre><p>Cargo ignores the 0.9.0 release. At this point, you would also notice a change in your <em>Cargo.lock</em> file noting that the version of the rand crate you are now using is 0.8.4. To use rand version 0.9.0 or any version in the 0.9.x series, you&#39;d have to update the <em>Cargo.toml</em> file to look like this instead:</p><pre>[dependencies] rand = &quot;0.9.0&quot;</pre><p>The next time you run cargo build, Cargo will update the registry of crates available and reevaluate your rand requirements according to the new version you have specified.</p><p>There’s a lot more to say about <a href="http://doc.crates.io/">Cargo</a> and <a href="http://doc.crates.io/crates-io.html">its ecosystem</a> , but for now, that’s all you need to know. Cargo makes it very easy to reuse libraries, so Rustaceans are able to write smaller projects that are assembled from a number of packages.</p><p>Let’s start using rand to generate a number to guess. The next step is to update <em>src/main.rs</em>, as shown in Listing 2-3.</p><p>Filename: src/main.rs</p><pre>use std::io; use rand::Rng; fn main() { println!(&quot;Guess the number!&quot;); let secret_number = rand::thread_rng().gen_range(1..101); println!(&quot;The secret number is: {}&quot;, secret_number); println!(&quot;Please input your guess.&quot;); let mut guess = String::new(); io::stdin() .read_line(&amp;mut guess) .expect(&quot;Failed to read line&quot;); println!(&quot;You guessed: {}&quot;, guess); }</pre><p>First, we add the line use rand::Rng. The Rng trait defines methods that random number generators implement, and this trait must be in scope for us to use those methods.</p><p>Next, we’re adding two lines in the middle. In the first line, we call the rand::thread_rng function that gives us the particular random number generator that we&#39;re going to use: one that is local to the current thread of execution and seeded by the operating system. Then we call the gen_range method on the random number generator. This method is defined by the Rng trait that we brought into scope with the use rand::Rng statement. The gen_range method takes a range expression as an argument and generates a random number in the range. The kind of range expression we&#39;re using here takes the form start..end and is inclusive on the lower bound but exclusive on the upper bound, so we need to specify 1..101 to request a number between 1 and 100. Alternatively, we could pass the range 1..=100, which is equivalent.</p><blockquote><em>Note: You won’t just know which traits to use and which methods and functions to call from a crate, so each crate has documentation with instructions for using it. Another neat feature of Cargo is that running the </em><em>cargo doc --open command will build documentation provided by all of your dependencies locally and open it in your browser. If you&#39;re interested in other functionality in the </em><em>rand crate, for example, run </em><em>cargo doc --open and click </em><em>rand in the sidebar on the left.</em></blockquote><p>The second new line prints the secret number. This is useful while we’re developing the program to be able to test it, but we’ll delete it from the final version. It’s not much of a game if the program prints the answer as soon as it starts!</p><p>Try running the program a few times:</p><pre>$ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 2.53s Running `target/debug/guessing_game` Guess the number! The secret number is: 7 Please input your guess. 4 You guessed: 4 $ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.02s Running `target/debug/guessing_game` Guess the number! The secret number is: 83 Please input your guess. 5 You guessed: 5</pre><p>You should get different random numbers, and they should all be numbers between 1 and 100. Great job!</p><p>Now that we have user input and a random number, we can compare them. That step is shown in Listing 2–4. Note that this code won’t compile quite yet, as we will explain.</p><p>Filename: src/main.rs</p><p>First we add another use statement, bringing a type called std::cmp::Ordering into scope from the standard library. The Ordering type is another enum and has the variants Less, Greater, and Equal. These are the three outcomes that are possible when you compare two values.</p><p>Then we add five new lines at the bottom that use the Ordering type. The cmp method compares two values and can be called on anything that can be compared. It takes a reference to whatever you want to compare with: here it&#39;s comparing the guess to the secret_number. Then it returns a variant of the Ordering enum we brought into scope with the use statement. We use a expression to decide what to do next based on which variant of Ordering was returned from the call to cmp with the values in guess and secret_number.</p><p>A match expression is made up of <em>arms</em>. An arm consists of a <em>pattern</em> to match against, and the code that should be run if the value given to match fits that arm&#39;s pattern. Rust takes the value given to match and looks through each arm&#39;s pattern in turn. Patterns and the match construct are powerful Rust features that let you express a variety of situations your code might encounter and make sure that you handle them all.</p><p>Let’s walk through an example with the match expression we use here. Say that the user has guessed 50 and the randomly generated secret number this time is 38. When the code compares 50 to 38, the cmp method will return Ordering::Greater, because 50 is greater than 38. The match expression gets the Ordering::Greater value and starts checking each arm&#39;s pattern. It looks at the first arm&#39;s pattern, Ordering::Less, and sees that the value Ordering::Greater does not match Ordering::Less, so it ignores the code in that arm and moves to the next arm. The next arm&#39;s pattern is Ordering::Greater, which <em>does</em> match Ordering::Greater! The associated code in that arm will execute and print Too big! to the screen. The match expression ends because it has no need to look at the last arm in this scenario.</p><p>However, the code in Listing 2–4 won’t compile yet. Let’s try it:</p><pre>$ cargo build Compiling libc v0.2.86 Compiling getrandom v0.2.2 Compiling cfg-if v1.0.0 Compiling ppv-lite86 v0.2.10 Compiling rand_core v0.6.2 Compiling rand_chacha v0.3.0 Compiling rand v0.8.3 Compiling guessing_game v0.1.0 (file:///projects/guessing_game) error[E0308]: mismatched types --&gt; src/main.rs:22:21 | 22 | match guess.cmp(&amp;secret_number) { | ^^^^^^^^^^^^^^ expected struct `String`, found integer | = note: expected reference `&amp;String` found reference `&amp;{integer}` error[E0283]: type annotations needed for `{integer}` --&gt; src/main.rs:8:44 | 8 | let secret_number = rand::thread_rng().gen_range(1..101); | ------------- ^^^^^^^^^ cannot infer type for type `{integer}` | | | consider giving `secret_number` a type | = note: multiple `impl`s satisfying `{integer}: SampleUniform` found in the `rand` crate: - impl SampleUniform for i128; - impl SampleUniform for i16; - impl SampleUniform for i32; - impl SampleUniform for i64; and 8 more note: required by a bound in `gen_range` --&gt; /Users/carolnichols/.cargo/registry/src/github.com-1ecc6299db9ec823/rand-0.8.3/src/rng.rs:129:12 | 129 | T: SampleUniform, | ^^^^^^^^^^^^^ required by this bound in `gen_range` help: consider specifying the type arguments in the function call | 8 | let secret_number = rand::thread_rng().gen_range::&lt;T, R&gt;(1..101); | ++++++++ Some errors have detailed explanations: E0283, E0308. For more information about an error, try `rustc --explain E0283`. error: could not compile `guessing_game` due to 2 previous errors</pre><p>The core of the error states that there are <em>mismatched types</em>. Rust has a strong, static type system. However, it also has type inference. When we wrote let mut guess = String::new(), Rust was able to infer that guess should be a String and didn&#39;t make us write the type. The secret_number, on the other hand, is a number type. A few of Rust&#39;s number types can have a value between 1 and 100: i32, a 32-bit number; u32, an unsigned 32-bit number; i64, a 64-bit number; as well as others. Unless otherwise specified, Rust defaults to an i32, which is the type of secret_number unless you add type information elsewhere that would cause Rust to infer a different numerical type. The reason for the error is that Rust cannot compare a string and a number type.</p><p>Ultimately, we want to convert the String the program reads as input into a real number type so we can compare it numerically to the secret number. We do so by adding this line to the main function body:</p><p>Filename: src/main.rs</p><p>The line is:</p><pre>let guess: u32 = guess.trim().parse().expect(&quot;Please type a number!&quot;);</pre><p>We create a variable named guess. But wait, doesn&#39;t the program already have a variable named guess? It does, but helpfully Rust allows us to <em>shadow</em> the previous value of guess with a new one. Shadowing lets us reuse the guess variable name rather than forcing us to create two unique variables, such as guess_str and guess for example.</p><p>We bind this new variable to the expression guess.trim().parse(). The guess in the expression refers to the original guess variable that contained the input as a string. The trim method on a String instance will eliminate any whitespace at the beginning and end, which we must do to be able to compare the string to the u32, which can only contain numerical data. The user must press enter to satisfy read_line and input their guess, which adds a newline character to the string. For example, if the user types 5 and presses enter, guess looks like this: 5\n. The \n represents &quot;newline&quot;. (On Windows, pressing enter results in a carriage return and a newline,\r\n). The trim method eliminates \n or \r\n, resulting in just 5.</p><p>The <a href="https://doc.rust-lang.org/std/primitive.str.html#method.parse">parse method on strings</a> parses a string into some kind of number. Because this method can parse a variety of number types, we need to tell Rust the exact number type we want by using let guess: u32. The colon (:) after guess tells Rust we&#39;ll annotate the variable&#39;s type. Rust has a few built-in number types; the u32 seen here is an unsigned, 32-bit integer. It&#39;s a good default choice for a small positive number. Additionally, the u32 annotation in this example program and the comparison with secret_number means that Rust will infer that secret_number should be a u32 as well. So now the comparison will be between two values of the same type!</p><p>The parse method will only work on characters that can logically be converted into numbers and so can easily cause errors. If, for example, the string contained A👍%, there would be no way to convert that to a number. Because it might fail, the parse method returns a Result type, much as the read_line method does (discussed earlier in <a href="https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#handling-potential-failure-with-the-result-type">&quot;Handling Potential Failure with the </a><a href="https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#handling-potential-failure-with-the-result-type">Result Type&quot;</a>). We&#39;ll treat this Result the same way by using the expect method again. If parse returns an Err Result variant because it couldn&#39;t create a number from the string, the expect call will crash the game and print the message we give it. If parse can successfully convert the string to a number, it will return the Ok variant of Result, and expect will return the number that we want from the Ok value.</p><p>Let’s run the program now!</p><pre>$ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 0.43s Running `target/debug/guessing_game` Guess the number! The secret number is: 58 Please input your guess. 76 You guessed: 76 Too big!</pre><p>Nice! Even though spaces were added before the guess, the program still figured out that the user guessed 76. Run the program a few times to verify the different behavior with different kinds of input: guess the number correctly, guess a number that is too high, and guess a number that is too low.</p><p>We have most of the game working now, but the user can make only one guess. Let’s change that by adding a loop!</p><p>The loop keyword creates an infinite loop. We&#39;ll add a loop to give users more chances at guessing the number:</p><p>Filename: src/main.rs</p><p>As you can see, we’ve moved everything from the guess input prompt onward into a loop. Be sure to indent the lines inside the loop another four spaces each and run the program again. The program will now ask for another guess forever, which actually introduces a new problem. It doesn’t seem like the user can quit!</p><p>The user could always interrupt the program by using the keyboard shortcut ctrl-c. But there’s another way to escape this insatiable monster, as mentioned in the parse discussion in <a href="https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number">&quot;Comparing the Guess to the Secret Number&quot;</a>: if the user enters a non-number answer, the program will crash. We can take advantage of that to allow the user to quit, as shown here:</p><pre>$ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 1.50s Running `target/debug/guessing_game` Guess the number! The secret number is: 59 Please input your guess. 45 You guessed: 45 Too small! Please input your guess. 60 You guessed: 60 Too big! Please input your guess. 59 You guessed: 59 You win! Please input your guess. quit thread &#39;main&#39; panicked at &#39;Please type a number!: ParseIntError { kind: InvalidDigit }&#39;, src/main.rs:28:47 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace</pre><p>Typing quit will quit the game, but as you&#39;ll notice so will entering any other non-number input. This is suboptimal to say the least; we want the game to also stop when the correct number is guessed.</p><p>Let’s program the game to quit when the user wins by adding a break statement:</p><p>Filename: src/main.rs</p><p>Filename: src/main.rs</p><p>We switch from an expect call to a match expression to move from crashing on an error to handling the error. Remember that parse returns a Result type and Result is an enum that has the variants Ok and Err. We&#39;re using a match expression here, as we did with the Ordering result of the cmp method.</p><p>If parse is able to successfully turn the string into a number, it will return an Ok value that contains the resulting number. That Ok value will match the first arm&#39;s pattern, and the match expression will just return the num value that parse produced and put inside the Ok value. That number will end up right where we want it in the new guess variable we&#39;re creating.</p><p>If parse is <em>not</em> able to turn the string into a number, it will return an Err value that contains more information about the error. The Err value does not match the Ok(num) pattern in the first match arm, but it does match the Err(_) pattern in the second arm. The underscore, _, is a catchall value; in this example, we&#39;re saying we want to match all Err values, no matter what information they have inside them. So the program will execute the second arm&#39;s code, continue, which tells the program to go to the next iteration of the loop and ask for another guess. So, effectively, the program ignores all errors that parse might encounter!</p><p>Now everything in the program should work as expected. Let’s try it:</p><pre>$ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 4.45s Running `target/debug/guessing_game` Guess the number! The secret number is: 61 Please input your guess. 10 You guessed: 10 Too small! Please input your guess. 99 You guessed: 99 Too big! Please input your guess. foo Please input your guess. 61 You guessed: 61 You win!</pre><p>Awesome! With one tiny final tweak, we will finish the guessing game. Recall that the program is still printing the secret number. That worked well for testing, but it ruins the game. Let’s delete the println! that outputs the secret number. Listing 2-6 shows the final code.</p><p>Filename: src/main.rs</p><pre>use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!(&quot;Guess the number!&quot;); let secret_number = rand::thread_rng().gen_range(1..101); loop { println!(&quot;Please input your guess.&quot;); let mut guess = String::new(); io::stdin() .read_line(&amp;mut guess) .expect(&quot;Failed to read line&quot;); let guess: u32 = match guess.trim().parse() { Ok(num) =&gt; num, Err(_) =&gt; continue, }; println!(&quot;You guessed: {}&quot;, guess); match guess.cmp(&amp;secret_number) { Ordering::Less =&gt; println!(&quot;Too small!&quot;), Ordering::Greater =&gt; println!(&quot;Too big!&quot;), Ordering::Equal =&gt; { println!(&quot;You win!&quot;); break; } } } }</pre><p>At this point, you’ve successfully built the guessing game. Congratulations!</p><p>This project was a hands-on way to introduce you to many new Rust concepts: let, match, functions, the use of external crates, and more.</p><p>Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c8c834327dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js REST API Tutorial: Express.js and TypeScript]]></title>
            <link>https://medium.com/@smile0307/node-js-rest-api-tutorial-express-js-and-typescript-fe7dc07e060f?source=rss-3f6da6942a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe7dc07e060f</guid>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Sol Tech]]></dc:creator>
            <pubDate>Wed, 08 Jun 2022 13:28:26 GMT</pubDate>
            <atom:updated>2022-06-08T13:28:26.517Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IifBr4PAA9nn0LfZ.png" /></figure><h3>How Do I Write a REST API in Node.js?</h3><p>When building a back end for a REST API, Express.js is often the first choice among Node.js frameworks. While it also supports building static HTML and templates, in this series, we’ll focus on back-end development using TypeScript. The resulting REST API will be one that any front-end framework or external back-end service would be able to query.</p><p>You’ll need:</p><ul><li>Basic knowledge of JavaScript and TypeScript</li><li>Basic knowledge of Node.js</li><li>Basic knowledge of REST architecture (cf. <a href="https://www.toptal.com/nodejs/secure-rest-api-in-nodejs#anatomy-of-a-rest-api">this section</a> of my previous REST API article if needed)</li><li>A ready installation of Node.js (preferably version 14+)</li></ul><p>In a terminal (or command prompt), we’ll create a folder for the project. From that folder, run npm init. <a href="https://docs.npmjs.com/cli/init">That will create</a> some of the basic Node.js project files we need.</p><p>Next, we’ll add the Express.js framework and some helpful libraries:</p><pre>npm i express debug winston express-winston cors</pre><p>There are good reasons these libraries are <a href="https://www.toptal.com/nodejs">Node.js developer</a> favorites:</p><ul><li>debug is a module that we will use to avoid calling console.log() while developing our application. This way, we can easily filter debug statements during troubleshooting. They can also be switched off entirely in production instead of having to be removed manually.</li><li>winstonis responsible for logging requests to our API and the responses (and errors) returned. express-winston integrates directly with Express.js, so that all standard API-related winston logging code is already done.</li><li>cors is a piece of Express.js middleware that allows us to enable <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">cross-origin resource sharing</a>. Without this, our API would only be usable from front ends being served from the exact same subdomain as our back end.</li></ul><p>Our back end uses these packages when it’s running. But we also need to install some <em>development</em> dependencies for our TypeScript configuration. For that, we’ll run:</p><pre>npm i --save-dev @types/cors @types/express @types/debug source-map-support tslint typescript</pre><p>These dependencies are required to enable TypeScript for our app’s own code, along with the types used by Express.js and other dependencies. This can save a lot of time when we’re using an IDE like WebStorm or VSCode by allowing us to complete some function methods automatically while coding.</p><p>The final dependencies in package.json should be like this:</p><pre>&quot;dependencies&quot;: { &quot;debug&quot;: &quot;^4.2.0&quot;, &quot;express&quot;: &quot;^4.17.1&quot;, &quot;express-winston&quot;: &quot;^4.0.5&quot;, &quot;winston&quot;: &quot;^3.3.3&quot;, &quot;cors&quot;: &quot;^2.8.5&quot; }, &quot;devDependencies&quot;: { &quot;@types/cors&quot;: &quot;^2.8.7&quot;, &quot;@types/debug&quot;: &quot;^4.1.5&quot;, &quot;@types/express&quot;: &quot;^4.17.2&quot;, &quot;source-map-support&quot;: &quot;^0.5.16&quot;, &quot;tslint&quot;: &quot;^6.0.0&quot;, &quot;typescript&quot;: &quot;^3.7.5&quot; }</pre><p>Now that we have all our required dependencies installed, let’s start to build up our own code!</p><h3>TypeScript REST API Project Structure</h3><p>For this tutorial, we are going to create just three files:</p><p>The idea behind the project structure’s two folders ( common and users) is to have individual modules that have their own responsibilities. In this sense, we are eventually going to have some or all of the following for each module:</p><ul><li><strong>Route configuration</strong> to define the requests our API can handle</li><li><strong>Services</strong> for tasks such as connecting to our database models, doing queries, or connecting to external services that are required by the specific request</li><li><strong>Middleware</strong> for running specific request validations before the final controller of a route handles its specifics</li><li><strong>Models</strong> for defining data models matching a given database schema, to facilitate data storage and retrieval</li><li><strong>Controllers</strong> for separating the route configuration from the code that finally (after any middleware) processes a route request, calls the above service functions if necessary, and gives a response to the client</li></ul><p>This folder structure provides a <a href="https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/">basic REST API design</a>, an early starting point for the rest of this tutorial series, and enough to start practicing.</p><h3>A Common Routes File in TypeScript</h3><p>In the common folder, let&#39;s create the common.routes.config.ts file to look like the following:</p><pre>import express from &#39;express&#39;; export class CommonRoutesConfig { app: express.Application; name: string; constructor(app: express.Application, name: string) { this.app = app; this.name = name; } getName() { return this.name; } }</pre><p>The way that we are creating the routes here is optional. But since we are working with TypeScript, our routes scenario is an opportunity to practice using inheritance with the extends keyword, as we&#39;ll see shortly. In this project, all route files have the same behavior: They have a name (which we will use for debugging purposes) and access to the main Express.js Application object.</p><p>Now, we can start to create the users route file. At the users folder, let&#39;s create users.routes.config.ts and start to code it like this:</p><pre>import {CommonRoutesConfig} from &#39;../common/common.routes.config&#39;; import express from &#39;express&#39;; export class UsersRoutes extends CommonRoutesConfig { constructor(app: express.Application) { super(app, &#39;UsersRoutes&#39;); } }</pre><p>Here, we are importing the CommonRoutesConfig class and extending it to our new class, called UsersRoutes. With the constructor, we send the app (the main express.Application object) and the name UsersRoutes to CommonRoutesConfig &#39;s constructor.</p><p>This example is quite simple, but when scaling to create several route files, this will help us avoid duplicate code.</p><p>Suppose we would want to add new features in this file, such as logging. We could add the necessary field to the CommonRoutesConfig class, and then all the routes that extend CommonRoutesConfig will have access to it.</p><h3>Using TypeScript Abstract Functions for Similar Functionality Across Classes</h3><p>What if we would like to have some functionality that is <em>similar</em> between these classes (like configuring the API endpoints), but that needs a different implementation for each class? One option is to use a TypeScript feature called <strong>abstraction</strong>.</p><p>Let’s create a very simple abstract function that the UsersRoutes class (and future routing classes) will inherit from CommonRoutesConfig. Let&#39;s say that we want to force all routes to have a function (so we can call it from our common constructor) named configureRoutes(). That&#39;s where we&#39;ll declare the endpoints of each routing class&#39; resource.</p><p>To do this, we’ll add three quick things to common.routes.config.ts:</p><ol><li>The keyword abstract to our class line, to enable abstraction for this class.</li><li>A new function declaration at the end of our class, abstract configureRoutes(): express.Application;. This forces any class extending CommonRoutesConfig to provide an implementation matching that signature-if it doesn&#39;t, the TypeScript compiler will throw an error.</li><li>A call to this.configureRoutes(); at the end of the constructor, since we can now be sure that this function will exist.</li></ol><p>The result:</p><pre>import express from &#39;express&#39;; export abstract class CommonRoutesConfig { app: express.Application; name: string; constructor(app: express.Application, name: string) { this.app = app; this.name = name; this.configureRoutes(); } getName() { return this.name; } abstract configureRoutes(): express.Application; }</pre><p>With that, any class extending CommonRoutesConfig must have a function called configureRoutes() that returns an express.Application object. That means users.routes.config.ts needs updating:</p><pre>import {CommonRoutesConfig} from &#39;../common/common.routes.config&#39;; import express from &#39;express&#39;; export class UsersRoutes extends CommonRoutesConfig { constructor(app: express.Application) { super(app, &#39;UsersRoutes&#39;); } configureRoutes() { // (we&#39;ll add the actual route configuration here next) return this.app; } }</pre><p>As a recap of what we’ve made:</p><p>We are first importing the common.routes.config file, then the express module. We then define the UserRoutes class, saying that we want it to extend the CommonRoutesConfig base class, which implies that we promise that it will implement configureRoutes().</p><p>To send information along to the CommonRoutesConfig class, we are using the constructor of the class. It expects to receive the express.Application object, which we will describe in greater depth in the next step. With super(), we pass to CommonRoutesConfig&#39;s constructor the application and the name of our routes, which in this scenario is UsersRoutes. ( super(), in turn, will call our implementation of configureRoutes().)</p><h3>Configuring the Express.js Routes of the Users Endpoints</h3><p>The configureRoutes() function is where we will create the endpoints for users of our REST API. There, we will use the <a href="https://expressjs.com/en/4x/api.html#app">application</a> and its <a href="https://expressjs.com/en/4x/api.html#app.route">route</a> functionalities from Express.js.</p><p>The idea in using the app.route() function is to avoid code duplication, which is easy since we&#39;re creating a REST API with well-defined resources. The main resource for this tutorial is <strong>users</strong>. We have two cases in this scenario:</p><ul><li>When the API caller wants to create a new user or list all existing users, the endpoint should initially just have users at the end of the requested path. (We won&#39;t be getting into query filtering, pagination, or other such queries in this article.)</li><li>When the caller wants to do something specific to a specific user record, the request’s resource path will follow the pattern users/:userId.</li></ul><p>The way .route() works in Express.js lets us handle HTTP verbs with some elegant chaining. This is because .get(), .post(), etc., all return the same instance of the IRoute that the first .route() call does. The final configuration will be like this:</p><pre>configureRoutes() { this.app.route(`/users`) .get((req: express.Request, res: express.Response) =&gt; { res.status(200).send(`List of users`); }) .post((req: express.Request, res: express.Response) =&gt; { res.status(200).send(`Post to users`); }); this.app.route(`/users/:userId`) .all((req: express.Request, res: express.Response, next: express.NextFunction) =&gt; { // this middleware function runs before any request to /users/:userId // but it doesn&#39;t accomplish anything just yet--- // it simply passes control to the next applicable function below using next() next(); }) .get((req: express.Request, res: express.Response) =&gt; { res.status(200).send(`GET requested for id ${req.params.userId}`); }) .put((req: express.Request, res: express.Response) =&gt; { res.status(200).send(`PUT requested for id ${req.params.userId}`); }) .patch((req: express.Request, res: express.Response) =&gt; { res.status(200).send(`PATCH requested for id ${req.params.userId}`); }) .delete((req: express.Request, res: express.Response) =&gt; { res.status(200).send(`DELETE requested for id ${req.params.userId}`); }); return this.app; }</pre><p>The above code lets any REST API client call our users endpoint with a POST or a GET request. Similarly, it lets a client call our /users/:userId endpoint with a GET, PUT, PATCH, or DELETE request.</p><p>But for /users/:userId, we&#39;ve also added generic middleware using the all() function, which will be run before any of the get(), put(), patch(), or delete() functions. This function will be beneficial when (later in the series) we create routes that are meant to be accessed only by authenticated users.</p><p>You might have noticed that in our .all() function-as with any piece of middleware-we have three types of fields: Request, Response, and NextFunction.</p><ul><li>The <a href="https://expressjs.com/en/4x/api.html#req">Request</a> is the way Express.js represents the HTTP request to be handled. This type upgrades and extends the <a href="https://nodejs.org/api/http.html#http_class_http_incomingmessage">native Node.js</a> request type.</li><li>The <a href="https://expressjs.com/en/4x/api.html#res">Response</a> is likewise how Express.js represents the HTTP response, again extending the <a href="https://nodejs.org/api/http.html#http_class_http_serverresponse">native Node.js</a> response type.</li><li>No less important, the NextFunction serves as a callback function, allowing control to pass through any other middleware functions. Along the way, all middleware will share the same request and response objects before the controller finally sends a response back to the requester.</li></ul><h3>Our Node.js Entry-point File, app.ts</h3><p>Now that we have configured some basic route skeletons, we will start configuring the application’s entry point. Let’s create the app.ts file at the root of our project folder and begin it with this code:</p><pre>import express from &#39;express&#39;; import * as http from &#39;http&#39;; import * as winston from &#39;winston&#39;; import * as expressWinston from &#39;express-winston&#39;; import cors from &#39;cors&#39;; import {CommonRoutesConfig} from &#39;./common/common.routes.config&#39;; import {UsersRoutes} from &#39;./users/users.routes.config&#39;; import debug from &#39;debug&#39;;</pre><p>Only two of these imports are new at this point in the article:</p><ul><li>http is a Node.js-native module. It&#39;s required to start our Express.js application.</li><li>body-parser is middleware that comes with Express.js. It parses the request (in our case, as JSON) before control goes to our own request handlers.</li></ul><p>Now that we’ve imported the files, we will start declaring the variables that we want to use:</p><pre>const app: express.Application = express(); const server: http.Server = http.createServer(app); const port = 3000; const routes: Array&lt;CommonRoutesConfig&gt; = []; const debugLog: debug.IDebugger = debug(&#39;app&#39;);</pre><p>The express() function returns the main Express.js application object that we will pass around throughout our code, starting with adding it to the http.Server object. (We will need to start the http.Server after configuring our express.Application.)</p><p>We’ll listen on port 3000-which TypeScript <a href="https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-inferrable-types.md">will automatically infer</a> is a Number -instead of the standard ports 80 (HTTP) or 443 (HTTPS) because those would typically be used for an app&#39;s front end.</p><h3>Why Port 3000?</h3><p>There is no rule that the port should be 3000-if unspecified, <a href="https://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback">an arbitrary port</a> will be assigned-but 3000 is used throughout the documentation examples for both Node.js and Express.js, so we continue the tradition here.</p><h3>Can Node.js Share Ports With the Front End?</h3><p>We can still run locally at a custom port, even when we want our back end to respond to requests on standard ports. This would require a <a href="https://www.toptal.com/devops/simplified-nginx-load-balancing-with-loadcat#nginx-servers-and-upstreams">reverse proxy</a> to receive requests on port 80 or 443 with a specific domain or a subdomain. It would then redirect them to our internal port 3000.</p><p>The routes array will keep track of our routes files for debugging purposes, as we&#39;ll see below.</p><p>Finally, debugLog will end up as a function similar to console.log, but better: It&#39;s easier to fine-tune because it&#39;s automatically scoped to whatever we want to call our file/module context. (In this case, we&#39;ve called it &quot;app&quot; when we passed that in a string to the debug() constructor.)</p><p>Now, we’re ready to configure all our Express.js middleware modules and the routes of our API:</p><pre>// here we are adding middleware to parse all incoming requests as JSON app.use(express.json()); // here we are adding middleware to allow cross-origin requests app.use(cors()); // here we are preparing the expressWinston logging middleware configuration, // which will automatically log all HTTP requests handled by Express.js const loggerOptions: expressWinston.LoggerOptions = { transports: [new winston.transports.Console()], format: winston.format.combine( winston.format.json(), winston.format.prettyPrint(), winston.format.colorize({ all: true }) ), }; if (!process.env.DEBUG) { loggerOptions.meta = false; // when not debugging, log requests as one-liners } // initialize the logger with the above configuration app.use(expressWinston.logger(loggerOptions)); // here we are adding the UserRoutes to our array, // after sending the Express.js application object to have the routes added to our app! routes.push(new UsersRoutes(app)); // this is a simple route to make sure everything is working properly const runningMessage = `Server running at http://localhost:${port}`; app.get(&#39;/&#39;, (req: express.Request, res: express.Response) =&gt; { res.status(200).send(runningMessage) });</pre><p>The expressWinston.logger hooks into Express.js, automatically logging details-via the same infrastructure as debug -for every completed request. The options we&#39;ve passed to it will neatly format and colorize the corresponding terminal output, with more verbose logging (the default) when we&#39;re in debug mode.</p><p>Note that we have to define our routes <a href="https://www.npmjs.com/package/express-winston#user-content-request-logging">after</a> we set up expressWinston.logger.</p><p>Finally and most importantly:</p><pre>server.listen(port, () =&gt; { routes.forEach((route: CommonRoutesConfig) =&gt; { debugLog(`Routes configured for ${route.getName()}`); }); // our only exception to avoiding console.log(), because we // always want to know when the server is done starting up console.log(runningMessage); });</pre><p>This actually starts our server. Once it’s started, Node.js will run our callback function, which in debug mode reports the names of all the routes we’ve configured-so far, just UsersRoutes. After that, our callback notifies us that our back end is ready to receive requests, even when running in production mode.</p><h3>Updating package.json to Transpile TypeScript to JavaScript and Run the App</h3><p>Now that we have our skeleton ready to run, we first need some boilerplate configuration to enable TypeScript transpilation. Let’s add the file tsconfig.json in the project root:</p><pre>{ &quot;compilerOptions&quot;: { &quot;target&quot;: &quot;es2016&quot;, &quot;module&quot;: &quot;commonjs&quot;, &quot;outDir&quot;: &quot;./dist&quot;, &quot;strict&quot;: true, &quot;esModuleInterop&quot;: true, &quot;inlineSourceMap&quot;: true } }</pre><p>Then we just need to add the final touches to package.json in the form of the following scripts:</p><pre>&quot;scripts&quot;: { &quot;start&quot;: &quot;tsc &amp;&amp; node --unhandled-rejections=strict ./dist/app.js&quot;, &quot;debug&quot;: &quot;export DEBUG=* &amp;&amp; npm run start&quot;, &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot; },</pre><p>The test script is a placeholder that we&#39;ll replace later in the series.</p><p>The <strong>tsc</strong> in the start script belongs to TypeScript. It&#39;s responsible for transpiling our TypeScript code into JavaScript, which it will output into the dist folder. Then, we just run the built version with node ./dist/app.js.</p><p>We pass --unhandled-rejections=strict to Node.js (even with Node.js v16+) because in practice, debugging using a straight &quot;crash and show the stack&quot; approach is more straightforward than fancier logging with an expressWinston.errorLogger object. This is most often true even in production, where letting Node.js continue to run despite an unhandled rejection is likely to leave the server in an unexpected state, allowing further (and more complicated) bugs to occur.</p><p>The debug script calls the start script but first defines a DEBUG environment variable. This has the effect of enabling all of our debugLog() statements (plus similar ones from Express.js itself, which uses the same debug module we do) to output useful details to the terminal-details that are (conveniently) otherwise hidden when running the server in production mode with a standard npm start.</p><p>Try running npm run debug yourself, and afterward, compare that with npm start to see how the console output changes.</p><p><em>Tip: You can limit the debug output to our </em><em>app.ts file&#39;s own </em><em>debugLog() statements using </em><em>DEBUG=app instead of </em><em>DEBUG=*. The </em><em>debug module is generally quite flexible, and this feature </em><a href="https://github.com/visionmedia/debug#usage"><em>is no exception</em></a><em>.</em></p><p>Windows users will probably need to change the export to SET since export is how it works on Mac and Linux. If your project needs to support multiple development environments, <a href="https://www.npmjs.com/package/cross-env">the cross-env package</a> provides a straightforward solution here.</p><h3>Testing the Live Express.js Back End</h3><p>With npm run debug or npm start still going, our REST API will be ready to service requests on port 3000. At this point, we can use cURL, <a href="https://www.postman.com/">Postman</a>, <a href="https://insomnia.rest/">Insomnia</a>, etc. to test the back end.</p><p>Since we’ve only created a skeleton for the users resource, we can simply send requests without a body to see that everything is working as expected. For example:</p><pre>curl --request GET &#39;localhost:3000/users/12345&#39;</pre><p>Our back end should send back the answer GET requested for id 12345.</p><p>As for POST ing:</p><pre>curl --request POST &#39;localhost:3000/users&#39; \ --data-raw &#39;&#39;</pre><p>This and all other types of requests that we built skeletons for will look quite similar.</p><h3>Poised for Rapid Node.js REST API Development with TypeScript</h3><p>In this article, we started to create a REST API by configuring the project from scratch and diving into the basics of the Express.js framework. Then, we took our first step toward mastering TypeScript by building a pattern with UsersRoutesConfig extending CommonRoutesConfig, a pattern that we will reuse for the next article in this series. We finished by configuring our app.ts entry point to use our new routes and package.json with scripts to build and run our application.</p><p>But even the basics of a REST API made with Express.js and TypeScript are fairly involved. In the next part of this series, we focus on creating proper controllers for the users resource and dig into some useful patterns for services, middleware, controllers, and models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe7dc07e060f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL vs. REST — A GraphQL Tutorial]]></title>
            <link>https://medium.com/@smile0307/graphql-vs-rest-a-graphql-tutorial-1ce7ec9523f7?source=rss-3f6da6942a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ce7ec9523f7</guid>
            <dc:creator><![CDATA[Sol Tech]]></dc:creator>
            <pubDate>Wed, 08 Jun 2022 13:15:47 GMT</pubDate>
            <atom:updated>2022-06-08T13:15:47.624Z</atom:updated>
            <content:encoded><![CDATA[<h3>GraphQL vs. REST — A GraphQL Tutorial</h3><p>FAILED</p><p>You might have heard about the new kid around the block: GraphQL. If not, GraphQL is, in a word, a new way to fetch <a href="https://www.toptal.com/api-developers">APIs</a>, an alternative to REST. It started as an internal project at Facebook, and since it was open sourced, it has gained <a href="https://trends.google.com/trends/explore?date=today%205-y&amp;q=graphql">a lot of traction</a>.</p><p>The aim of this article is to help you make an easy transition from REST to GraphQL, whether you’ve already made your mind for GraphQL or you’re just willing to give it a try. No prior knowledge of GraphQL is needed, but some familiarity with REST APIs is required to understand the article.</p><p>The first part of the article will start by giving three reasons why I personally think GraphQL is superior to REST. The second part is a tutorial on how to add a GraphQL endpoint on your back-end.</p><h3>GraphQL vs. REST: Why Drop REST?</h3><p>If you are still hesitating on whether or not GraphQL is suited for your needs, a quite extensive and objective overview of “REST vs. GraphQL” is given <a href="https://philsturgeon.uk/api/2017/01/24/graphql-vs-rest-overview/">here</a>. However, for my top three reasons to use GraphQL, read on.</p><h3>Reason 1: Network Performance</h3><p>Say you have a user resource on the back-end with first name, last name, email, and 10 other fields. On the client, you generally only need a couple of those.</p><p>Making a REST call on the /users endpoint gives you back all the fields of the user, and the client only uses the ones it needs. There is clearly some data transfer waste, which might be a consideration on mobile clients.</p><p>GraphQL by default fetches the smallest data possible. If you only need first and last names of your users, you specify that in your query.</p><p>The interface below is called GraphiQL, which is like an API explorer for GraphQL. I created a small project for the purpose of this article. The code is hosted <a href="https://github.com/amaurymartiny/graphql-example">on GitHub</a>, and we’ll dive into it in the second part.</p><p>On the left pane of the interface is the query. Here, we are fetching all the users-we would do GET /users with REST-and only getting their first and last names.</p><p><strong>Query</strong></p><pre>query { users { firstname lastname } }</pre><p><strong>Result</strong></p><pre>{ &quot;data&quot;: { &quot;users&quot;: [ { &quot;firstname&quot;: &quot;John&quot;, &quot;lastname&quot;: &quot;Doe&quot; }, { &quot;firstname&quot;: &quot;Alicia&quot;, &quot;lastname&quot;: &quot;Smith&quot; } ] } }</pre><p>If we wanted to get the emails as well, adding an “email” line below “lastname” would do the trick.</p><p>Some REST back-ends do offer options like /users?fields=firstname,lastname to return partial resources. For what it&#39;s worth, <a href="https://developers.google.com/google-apps/tasks/performance#partial">Google recommends it</a>. However, it is not implemented by default, and it makes the request barely readable, especially when you toss in other query parameters:</p><ul><li>&amp;status=active to filter active users</li><li>&amp;sort=createdAat to sort the users by their creation date</li><li>&amp;sortDirection=desc because you obviously need it</li><li>&amp;include=projects to include the users&#39; projects</li></ul><p>These query parameters are patches added to the REST API to imitate a query language. GraphQL is above all a query language, which makes requests concise and precise from the beginning.</p><h3>Reason 2: The “Include vs. Endpoint” Design Choice</h3><p>Let’s imagine we want to build a simple project management tool. We have three resources: users, projects, and tasks. We also define the following relationships between the resources:</p><p>Here are some of the endpoints we expose to the world:</p><p>The endpoints are simple, easily readable, and well-organized.</p><p>Things get trickier when our requests get more complex. Let’s take the GET /users/:id/projects endpoint: Say I want to show only the projects&#39; titles on the home page, but projects+tasks on the dashboard, without making multiple REST calls. I would call:</p><ul><li>GET /users/:id/projects for the home page.</li><li>GET /users/:id/projects?include=tasks (for example) on the dashboard page so that the back-end appends all related tasks.</li></ul><p>It’s common practice to add query parameters ?include=... to make this work, and is even recommended by the <a href="http://jsonapi.org/">JSON API</a> specification. Query parameters like ?include=tasks are still readable, but before long, we will end up with ?include=tasks,tasks.owner,tasks.comments,tasks.comments.author.</p><p>In this case, would be it wiser to create a /projects endpoint to do this? Something like /projects?userId=:id&amp;include=tasks, as we would have one level of relationship less to include? Or, actually, a /tasks?userId=:id endpoint might work too. This can be a difficult design choice, <a href="https://stackoverflow.com/questions/6324547/how-to-handle-many-to-many-relationships-in-a-restful-api">even more complicated</a> if we have a many-to-many relationship.</p><p>GraphQL uses the include approach everywhere. This makes the syntax to fetch relationships powerful and consistent.</p><p>Here’s an example of fetching all projects and tasks from the user with id 1.</p><p><strong>Query</strong></p><pre>{ user(id: 1) { projects { name tasks { description } } } }</pre><p><strong>Result</strong></p><pre>{ &quot;data&quot;: { &quot;user&quot;: { &quot;projects&quot;: [ { &quot;name&quot;: &quot;Migrate from REST to GraphQL&quot;, &quot;tasks&quot;: [ { &quot;description&quot;: &quot;Read tutorial&quot; }, { &quot;description&quot;: &quot;Start coding&quot; } ] }, { &quot;name&quot;: &quot;Create a blog&quot;, &quot;tasks&quot;: [ { &quot;description&quot;: &quot;Write draft of article&quot; }, { &quot;description&quot;: &quot;Set up blog platform&quot; } ] } ] } } }</pre><p>As you can see, the query syntax is easily readable. If we wanted to go deeper and include tasks, comments, pictures, and authors, we wouldn’t think twice about how to organize our API. GraphQL makes it easy to fetch complex objects.</p><h3>Reason 3: Managing Different Types of Clients</h3><p>When building a back-end, we always start by trying to make the API as widely usable by all clients as possible. Yet clients always want to call less and fetch more. With deep includes, partial resources, and filtering, requests made by web and mobile clients may differ a lot one from another.</p><p>With REST, there are a couple of solutions. We can create a custom endpoint (i.e., an alias endpoint, e.g., /mobile_user), a custom representation ( Content-Type: application/vnd.rest-app-example.com+v1+mobile+json), or even a client-specific API (like <a href="https://medium.com/netflix-techblog/embracing-the-differences-inside-the-netflix-api-redesign-15fd8b3dc49d">Netflix once did</a>). All three of them require extra effort from the back-end development team.</p><p>GraphQL gives more power to the client. If the client needs complex requests, it will build the corresponding queries itself. Each client can consume the same API differently.</p><h3>How to Start with GraphQL</h3><p>In most debates about “GraphQL vs. REST” today, people think that they must choose either one of the two. This is simply not true.</p><p>Modern applications generally use several different services, which expose several APIs. We could actually think of GraphQL as a gateway or a wrapper to all these services. All clients would hit the GraphQL endpoint, and this endpoint would hit the database layer, an external service like ElasticSearch or Sendgrid, or other REST endpoints.</p><p>A second way of using both is to have a separate /graphql endpoint on your REST API. This is especially useful if you already have numerous clients hitting your REST API, but you want to try GraphQL without compromising the existing infrastructure. And this is the solution we are exploring today.</p><p>As said earlier, I will illustrate this tutorial with a small example project, available <a href="https://github.com/amaurymartiny/graphql-example">on GitHub</a>. It is a simplified project management tool, with users, projects, and tasks.</p><p>The technologies used for this project are Node.js and Express for the web server, SQLite as the relational database, and Sequelize as an ORM. The three models-user, project, and task-are defined in the folder. The REST endpoints , <a href="http://graphql-example.herokuapp.com/api/projects">/api/projects</a> and are exposed to the world, and are defined in the folder.</p><p>Do note that GraphQL can be installed on any type of back-end and database, using any programming language. The technologies used here are chosen for the sake of simplicity and readability.</p><p>Our goal is to create a /graphql endpoint without removing the REST endpoints. The GraphQL endpoint will hit the database ORM directly to fetch data, so that it is totally independant from the REST logic.</p><h3>Types</h3><p>The data model is represented in GraphQL by <strong>types</strong>, which are strongly typed. There should be a 1-to-1 mapping between your models and GraphQL types. Our User type would be:</p><pre>type User { id: ID! # The &quot;!&quot; means required firstname: String lastname: String email: String projects: [Project] # Project is another GraphQL type }</pre><h3>Queries</h3><p><strong>Queries</strong> define what queries you can run on your GraphQL API. By convention, there should be a RootQuery, which contains all the existing queries. I also pointed out the REST equivalent of each query:</p><pre>type RootQuery { user(id: ID): User # Corresponds to GET /api/users/:id users: [User] # Corresponds to GET /api/users project(id: ID!): Project # Corresponds to GET /api/projects/:id projects: [Project] # Corresponds to GET /api/projects task(id: ID!): Task # Corresponds to GET /api/tasks/:id tasks: [Task] # Corresponds to GET /api/tasks }</pre><h3>Mutations</h3><p>If queries are GET requests, <strong>mutations</strong> can be seen as POST/ PATCH/ PUT/ DELETE requests (although really they are synchronized versions of queries).</p><p>By convention, we put all our mutations in a RootMutation:</p><pre>type RootMutation { createUser(input: UserInput!): User # Corresponds to POST /api/users updateUser(id: ID!, input: UserInput!): User # Corresponds to PATCH /api/users removeUser(id: ID!): User # Corresponds to DELETE /api/users createProject(input: ProjectInput!): Project updateProject(id: ID!, input: ProjectInput!): Project removeProject(id: ID!): Project createTask(input: TaskInput!): Task updateTask(id: ID!, input: TaskInput!): Task removeTask(id: ID!): Task }</pre><p>Note that we introduced new types here, called UserInput, ProjectInput, and TaskInput. This is a common practice with REST too, to create an input data model for creating and updating resources. Here, our UserInput type is our User type without the id and projects fields, and notice the keyword input instead of type:</p><pre>input UserInput { firstname: String lastname: String email: String }</pre><h3>Schema</h3><p>With types, queries and mutations, we define the <strong>GraphQL schema</strong>, which is what the GraphQL endpoint exposes to the world:</p><pre>schema { query: RootQuery mutation: RootMutation }</pre><p>This schema is strongly typed and is what allowed us to have those handy autocompletes in <a href="https://graphql-example.herokuapp.com/graphiql?query=query%20%7B%0A%20%20users%20%7B%0A%20%20%20%20firstname%0A%20%20%20%20lastname%0A%20%20%20%20projects%20%7B%0A%20%20%20%20%20%20name%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D">GraphiQL</a>.</p><h3>Resolvers</h3><p>Now that we have the public schema, it is time to tell GraphQL what to do when each of these queries/mutations is requested. <strong>Resolvers</strong> do the hard work; they can, for example:</p><ul><li>Hit an internal REST endpoint</li><li>Call a microservice</li><li>Hit the database layer to do CRUD operations</li></ul><p>We are choosing the third option in our example app. Let’s have a look at our <a href="https://github.com/amaurymartiny/graphql-example/blob/master/graphql/resolvers.js">resolvers file</a>:</p><pre>const models = sequelize.models; RootQuery: { user (root, { id }, context) { return models.User.findById(id, context); }, users (root, args, context) { return models.User.findAll({}, context); }, // Resolvers for Project and Task go here }, /* For reminder, our RootQuery type was: type RootQuery { user(id: ID): User users: [User] # Other queries }</pre><p>This means, if the user(id: ID!) query is requested on GraphQL, then we return User.findById(), which is a Sequelize ORM function, from the database.</p><p>What about joining other models in the request? Well, we need to define more resolvers:</p><pre>User: { projects (user) { return user.getProjects(); // getProjects is a function managed by Sequelize ORM } }, /* For reminder, our User type was: type User { projects: [Project] # We defined a resolver above for this field # ...other fields } */</pre><p>So when we request the projects field in a User type in GraphQL, this join will be appended to the database query.</p><p>And finally, resolvers for mutations:</p><pre>RootMutation: { createUser (root, { input }, context) { return models.User.create(input, context); }, updateUser (root, { id, input }, context) { return models.User.update(input, { ...context, where: { id } }); }, removeUser (root, { id }, context) { return models.User.destroy(input, { ...context, where: { id } }); }, // ... Resolvers for Project and Task go here }</pre><p>You can play around with this here. For the sake of keeping the data on the server clean, I disabled the resolvers for mutations, which means that the mutations will not do any create, update or delete operations in the database (and thus return null on the interface).</p><p><strong>Query</strong></p><pre>query getUserWithProjects { user(id: 2) { firstname lastname projects { name tasks { description } } } } mutation createProject { createProject(input: {name: &quot;New Project&quot;, UserId: 2}) { id name } }</pre><p><strong>Result</strong></p><pre>{ &quot;data&quot;: { &quot;user&quot;: { &quot;firstname&quot;: &quot;Alicia&quot;, &quot;lastname&quot;: &quot;Smith&quot;, &quot;projects&quot;: [ { &quot;name&quot;: &quot;Email Marketing Campaign&quot;, &quot;tasks&quot;: [ { &quot;description&quot;: &quot;Get list of users&quot; }, { &quot;description&quot;: &quot;Write email template&quot; } ] }, { &quot;name&quot;: &quot;Hire new developer&quot;, &quot;tasks&quot;: [ { &quot;description&quot;: &quot;Find candidates&quot; }, { &quot;description&quot;: &quot;Prepare interview&quot; } ] } ] } } }</pre><p>It may take some time to rewrite all types, queries, and resolvers for your existing app. However, a lot of tools exist to help you. For instance, <a href="https://github.com/postgraphql/postgraphql">there </a><a href="https://github.com/mickhansen/graphql-sequelize">are </a><a href="https://github.com/rexxars/sql-to-graphql">tools</a> that translate a SQL schema to a GraphQL schema, including resolvers!</p><h3>Putting Everything Together</h3><p>With a well-defined schema and resolvers on what to do on each query of the schema, we can mount a /graphql endpoint on our back-end:</p><pre>// Mount GraphQL on /graphql const schema = makeExecutableSchema({ typeDefs, // Our RootQuery and RootMutation schema resolvers: resolvers() // Our resolvers }); app.use(&#39;/graphql&#39;, graphqlExpress({ schema }));</pre><p>And we can have a <a href="https://graphql-example.herokuapp.com/graphiql">nice-looking GraphiQL interface</a> on our back-end. To make a request without GraphiQL, simply copy <a href="https://graphql-example.herokuapp.com/graphql?query=query%20%7B%0A%20%20user(id%3A%202)%20%7B%0A%20%20%20%20firstname%0A%20%20%20%20lastname%0A%20%20%20%20projects%20%7B%0A%20%20%20%20%20%20name%0A%20%20%20%20%20%20tasks%20%7B%0A%20%20%20%20%20%20%20%20description%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D">the URL of the request</a>, and run it with cURL, AJAX, or directly in the browser. Of course, there are some GraphQL clients to help you build these queries. See below for some examples.</p><h3>What’s Next?</h3><p>This article’s aim is to give you a taste of what GraphQL looks like and show you that it’s definitely possible to try GraphQL without throwing away your REST infrastructure. The best way to know if GraphQL suits your needs is to try it yourself. I hope that this article will make you take the dive.</p><p>There are a lot of features we haven’t discussed about in this article, such as real-time updates, server-side batching, authentication, authorization, client-side caching, file uploading, etc. An excellent resource to learn about these features is <a href="https://www.howtographql.com/">How to GraphQL</a>.</p><p>Below are some other useful resources:</p><p>In conclusion, I believe that GraphQL is more than hype. It won’t replace REST tomorrow just yet, but it does offer a performant solution to a genuine problem. It is relatively new, and best practices are still developing, but it is definitely a technology that we will hear about in the next couple of years.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ce7ec9523f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solana Main Concepts]]></title>
            <link>https://medium.com/@smile0307/solana-programming-concepts-d231495361d?source=rss-3f6da6942a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/d231495361d</guid>
            <dc:creator><![CDATA[Sol Tech]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 08:06:02 GMT</pubDate>
            <atom:updated>2022-06-06T08:09:08.588Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s been helpful for me to think of Solana as an Operating System that runs on multiple computers (validators).</p><ul><li><em>Cluster</em>: A cluster is a network of validators that make up an instance of the Solana blockchain. Testnet, Devnet and Mainnet Beta are the clusters primarily recognized by the Solana community. Testnet and Devnet are used for testing and development. Mainnet Beta is the instance where tokens are recognized to have monetary value. But there is no reason other clusters could not exist.</li><li><em>Epoch</em>: Currently ~3 days. This period exists primarily to schedule validators but also times other events such as rent collection and rewards distribution.</li><li><em>Accounts</em>: An account is essentially a file with an address (pubkey) that lives on the Solana blockchain. If you need to store data on chain it gets stored in an account. Accounts live in the memory of the network of validators. An account must pay rent (see below) in order to persist on chain.</li><li><em>Sealevel</em>: The solana network runtime that enables the parallel execution of instructions and transactions. Though very different in ,implementation and modeling, it is equivalent to Ethereum VM (EVM).</li><li><em>Programs</em>: On Solana smart contracts are called programs. A program is just an account that has been marked executable. Once a program has been deployed on chain it can be read and interacted with via instructions (see below).</li><li><em>Program ID</em>: The public key of the program.</li><li><em>Account Ownership</em>: Accounts are owned by programs which are indicated by a Program id in the metadata “owner” field.</li><li><em>Native Programs</em>: “Special” programs that are required to run the network.</li><li><em>System Program</em>: The system program is responsible for creating new accounts, and assigning account ownership.</li><li><em>BPF Loader</em>: The BPF Loader program is responsible for deployment, upgrades and instruction execution of solana programs.</li><li>There are other native programs but these are the more relevant programs for solana programming.</li><li><em>Token Programs</em>: A kind of program that implements a fungible or non fungible token other than the native $SOL token.</li><li><em>Associated Token Accounts</em>: If an account holds any token other than the native Solana token it will have an associated token account for each type of token it holds.</li><li><em>Instructions</em>: What is called in order to execute a function of a program.</li><li><em>Sysvar</em>: An account which enforces certain variables of the network such as epoch, rent, validator rewards, etc…</li><li><em>Rent</em>: The network charges rent (in $SOL) for data held in accounts, since this takes up validator network resources. An account can be exempt from rent collection if it has 2 years of rent in it’s balance. Rent is collected every epoch. If an account is unable to rent it will no longer load.</li><li><em>Program Derived Addresses (PDAs)</em>: PDAs enable the transfer of an account’s ownership from one program to another. This is useful for situations that require an escrow account such as auctions, DEXs, swaps, etc…</li><li><em>Cross Program Invocation</em>: Calling a program from another program. This is helpful for more complex on chain actions. Such as executing an instruction of an associated token account program during a token swap.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d231495361d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a REST API with Rust and MongoDB — Actix web Version]]></title>
            <link>https://medium.com/@smile0307/build-a-rest-api-with-rust-and-mongodb-actix-web-version-307f6176ccbe?source=rss-3f6da6942a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/307f6176ccbe</guid>
            <dc:creator><![CDATA[Sol Tech]]></dc:creator>
            <pubDate>Sun, 29 May 2022 11:20:59 GMT</pubDate>
            <atom:updated>2022-05-29T11:20:59.696Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a REST API with Rust and MongoDB — Actix web Version</h3><p>REST API has become the De Facto for connecting and transferring data from one source to another. It offers a set of guidelines and architectural patterns for designing and developing web services.</p><p>This post will discuss building a user management application with Rust using the <a href="https://actix.rs/">Actix web</a> framework and <a href="https://www.mongodb.com/">MongoDB</a>. At the end of this tutorial, we will learn how to structure a Rust application, build a REST API and persist our data using MongoDB.</p><p>Actix web is an HTTP web framework written in Rust with performance and productivity support. Actix web ships with features like type-safety, reusability, logging, static file serving and much more that developers can leverage to build scalable applications.</p><p>MongoDB is a document-based database management program used as an alternative to relational databases. MongoDB supports working with large sets of distributed data with options to store or retrieve information seamlessly.</p><p>The complete source code is available in this <a href="https://github.com/smile930307/actix-mongo-api">repository</a>.</p><h3>Prerequisites</h3><p>To fully grasp the concepts presented in this tutorial, experience with Rust is required. Experience with MongoDB isn’t a requirement, but it’s nice to have.</p><p>We will also be needing the following:</p><ul><li>A <a href="https://www.mongodb.com/">MongoDB account</a> to host database. <a href="https://www.mongodb.com/cloud/atlas/register"><strong>Signup</strong></a> <strong>is completely free</strong>.</li><li><a href="https://www.postman.com/downloads/">Postman</a> or any API testing application # Let’s code ## Getting Started</li></ul><p>To get started, we need to navigate to the desired directory and run the command below in our terminal</p><pre>cargo new actix-mongo-api &amp;&amp; cd actix-mongo-api</pre><p>This command creates a Rust project called actix-mongo-api and navigates into the project directory.</p><p>Next, we proceed to install the required dependencies by modifying the [dependencies] section of the Cargo.toml file as shown below:</p><pre>//other code section goes here</pre><pre>    [dependencies]<br>    actix-web = &quot;4&quot;<br>    serde = &quot;1.0.136&quot;<br>    dotenv = &quot;0.15.0&quot;</pre><pre>    [dependencies.mongodb]<br>    version = &quot;2.2.0&quot;<br>    default-features = false<br>    features = [&quot;sync&quot;]</pre><p>actix-web = &quot;4&quot; is a Rust-based framework for building web applications.</p><p>serde = &quot;1.0.136&quot; is a framework for serializing and deserializing Rust data structures. E.g. convert Rust structs to JSON.</p><p>dotenv = &quot;0.15.0&quot; is a library for managing environment variables.</p><p>[dependencies.mongodb] is a driver for connecting to MongoDB. It also specifies the required version and the feature type(Sync API).</p><p>We need to run the command below to install the dependencies:</p><pre>cargo build</pre><h3>Application Entry Point</h3><p>With the project dependencies installed, modify the main.rs file in the src folder to the following:</p><pre>use actix_web::{get, App, HttpResponse, HttpServer, Responder};</pre><pre>    #[get(&quot;/&quot;)]<br>    async fn hello() -&gt; impl Responder {<br>        HttpResponse::Ok().json(&quot;Hello from rust and mongoDB&quot;)<br>    }</pre><pre>    #[actix_web::main]<br>    async fn main() -&gt; std::io::Result&lt;()&gt; {<br>        HttpServer::new(|| App::new().service(hello))<br>            .bind((&quot;localhost&quot;, 8080))?<br>            .run()<br>            .await<br>    }</pre><p>The snippet above does the following:</p><ul><li>Imports the required dependencies</li><li>Creates a hello handler that uses the Rust macro to specify the HTTP method, the route path /, and returns a JSON of Hello from rust and mongoDB.</li><li>Uses the #[actix_web::main] macro to run the main function asynchronously within the actix runtime. The main function does the following:</li><li>Creates a new server using HttpServer struct that uses a closure to serve incoming requests using the App instance. The App also registers the hello handler. HttpServer is the backbone of our application; it takes care of request handling, the maximum number of connections allowed, layered security, e.t.c, while App handles application logic like request handlers, middlewares, routing, e.t.c.</li><li>Configures the server to run asynchronously and process HTTP requests on localhost:8080.</li></ul><p>Next, we can test our application by running the command below in our terminal.</p><pre>cargo run</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*3U1f_IQNk_1fS0dcfzCSyQ.png" /></figure><h3>Module system in Rust</h3><p>A module in Rust is a mechanism for splitting code into reusable components and managing visibility between them. Modules help us maintain a good project structure for our project.</p><p>To do this, we need to navigate to the src folder and create api, models, and repository folder with the corresponding mod.rs file to manage visibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*_omJoAtXlsIu7E-Lalyq2g.png" /></figure><p>api is for modularizing API handlers.</p><p>models is for modularizing data logics.</p><p>repository is for modularizing database logics.</p><p><strong>Adding reference to the Modules</strong><br>To use the code in the modules, we need to declare them as a module and import them into the main.rs file.</p><pre>//add the modules<br>    mod api; <br>    mod models;<br>    mod repository;</pre><pre>    use actix_web::{get, App, HttpResponse, HttpServer, Responder};</pre><pre>    // the remaining part of our code goes here</pre><h3>Setting up MongoDB</h3><p>With that done, we need to log in or sign up into our <a href="https://dev.tohttp//">MongoDB</a> account. Click the project dropdown menu and click on the <strong>New Project</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*rGJjLdm5s5ArCoA5USALDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*sc1xILqBkVBfE9lHe6VzEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Q-22BfPFVp80lbFyQD_wOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*s__iSYlSQV0W6TO4Wz-wGQ.jpeg" /></figure><p>Click on <strong>Create</strong> to setup a cluster. This might take sometime to setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*pKMSGnxdBiANP1QDUErthw.png" /></figure><p>Next, we need to create a user to access the database externally by inputting the <strong>Username</strong>, <strong>Password</strong> and then clicking on <strong>Create User</strong>. We also need to add our IP address to safely connect to the database by clicking on the <strong>Add My Current IP Address</strong> button. Then click on <strong>Finish and Close</strong> to save changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*otSZvDCjAVDgKX5KEeFoaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*jTbw2dxy6m2ET-Mz9wLVAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*iltsDpiuCdqMdPrdWsw1_A.png" /></figure><h3>Connecting our application to MongoDB</h3><p>With the configuration done, we need to connect our application with the database created. To do this, click on the <strong>Connect</strong> button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*wNh1wNIkVOK1c0Ljsq2DNw.png" /></figure><p>Click on <strong>Connect your application</strong>, change the <strong>Driver</strong> to Rust and the <strong>Version</strong> as shown below. Then click on the copy <strong>icon</strong> to copy the connection string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Towi3_2x3gMTZmoBJTCuKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*K7Sem4DT9E14beBUb4FZQA.png" /></figure><p><strong>Setup Environment Variable</strong><br>Next, we must modify the copied connection string with the user’s password we created earlier and change the database name. To do this, first, we need to create a .env file in the root directory, and in this file, add the snippet copied:</p><pre>MONGOURI=mongodb+srv://&lt;YOUR USERNAME HERE&gt;:&lt;YOUR PASSWORD HERE&gt;@cluster0.e5akf.mongodb.net/myFirstDatabese?retryWrites=true&amp;w=majority </pre><p>Sample of a properly filled connection string below:</p><pre>MONGOURI=mongodb+srv://malomz:malomzPassword@cluster0.e5akf.mongodb.net/golangDB?retryWrites=true&amp;w=majority</pre><h3>Creating REST APIs</h3><p>With the setup done, we need to create a model to represent our application data. To do this, we need to navigate to the models folder, and in this folder, create a user_model.rs file and add the snippet below:</p><pre>use mongodb::bson::oid::ObjectId;<br>    use serde::{Serialize, Deserialize};<br><br>    #[derive(Debug, Serialize, Deserialize)]<br>    pub struct User {<br>        #[serde(rename = &quot;_id&quot;, skip_serializing_if = &quot;Option::is_none&quot;)]<br>        pub id: Option&lt;ObjectId&gt;,<br>        pub name: String,<br>        pub location: String,<br>        pub title: String,<br>    }</pre><p>The snippet above does the following:</p><ul><li>Imports the required dependencies</li><li>Uses the derive macro to generate implementation support for formatting the output, serializing, and deserializing the data structure.</li><li>Creates a User struct with required properties. We also added field attributes to the id property to rename and ignore the field if it is empty.</li></ul><p><strong>PS</strong>: <em>The </em><em>pub modifier makes the struct and its property public and can be accessed from other files/modules.</em></p><p>Next, we must register the user_model.rs file as part of the models module. To do this, open the mod.rs in the models folder and add the snippet below:</p><pre>pub mod user_model;</pre><p><strong>Create a User Endpoint</strong><br>With the model fully set up and made available to be consumed, we can now create our database logic to create a user. To do this, First, we need to navigate to the repository folder, and in this folder, create a mongodb_repo.rs file and add the snippet below:</p><pre>use std::env;<br>    extern crate dotenv;<br>    use dotenv::dotenv;</pre><pre>    use mongodb::{<br>        bson::{extjson::de::Error},<br>        results::{ InsertOneResult},<br>        sync::{Client, Collection},<br>    };<br>    use crate::models::user_model::User;</pre><pre>    pub struct MongoRepo {<br>        col: Collection&lt;User&gt;,<br>    }</pre><pre>    impl MongoRepo {<br>        pub fn init() -&gt; Self {<br>            dotenv().ok();<br>            let uri = match env::var(&quot;MONGOURI&quot;) {<br>                Ok(v) =&gt; v.to_string(),<br>                Err(_) =&gt; format!(&quot;Error loading env variable&quot;),<br>            };<br>            let client = Client::with_uri_str(uri).unwrap();<br>            let db = client.database(&quot;rustDB&quot;);<br>            let col: Collection&lt;User&gt; = db.collection(&quot;User&quot;);<br>            MongoRepo { col }<br>        }</pre><pre>        pub fn create_user(&amp;self, new_user: User) -&gt; Result&lt;InsertOneResult, Error&gt; {<br>            let new_doc = User {<br>                id: None,<br>                name: new_user.name,<br>                location: new_user.location,<br>                title: new_user.title,<br>            };<br>            let user = self<br>                .col<br>                .insert_one(new_doc, None)<br>                .ok()<br>                .expect(&quot;Error creating user&quot;);<br>            Ok(user)<br>        }<br>    }</pre><p>The snippet above does the following:</p><ul><li>Imports the required dependencies</li><li>Creates a MongoRepo struct with a col field to access MongoDB collection</li><li>Creates an implementation block that adds methods to the MongoRepo struct</li><li>Adds an init method to the implementation block to load the environment variable, creates a connection to the database, and returns an instance of the MongoRepo struct</li><li>Adds a create_user method that takes in a self and new_user as parameters and returns the created user or an error. Inside the method, we created a new document using the User struct. Then we use the self referencing the MongoRepo struct to access the insert_one function from the collection to create a new user and handle errors. Finally, we returned the created user information.</li></ul><p><strong>PS:</strong> <em>The </em><em>None specified when creating a new document tells MongoDB to automatically generate the user’s</em> <strong><em>id</em></strong><em>.</em></p><p>Next, we must register the mongodb_repo.rs file as part of the repository module. To do this, open the mod.rs in the repository folder and add the snippet below:</p><pre>pub mod mongodb_repos;</pre><p>Secondly, we need to create a handler that uses the create_user method from the repository to create a user. To do this, we need to navigate to the api folder, and in this folder, create a user_api.rs file and add the snippet below:</p><pre>use crate::{models::user_model::User, repository::mongodb_repo::MongoRepo};<br>    use actix_web::{<br>        post,<br>        web::{Data, Json},<br>        HttpResponse,<br>    };</pre><pre>    #[post(&quot;/user&quot;)]<br>    pub async fn create_user(db: Data&lt;MongoRepo&gt;, new_user: Json&lt;User&gt;) -&gt; HttpResponse {<br>        let data = User {<br>            id: None,<br>            name: new_user.name.to_owned(),<br>            location: new_user.location.to_owned(),<br>            title: new_user.title.to_owned(),<br>        };<br>        let user_detail = db.create_user(data);<br>        match user_detail {<br>            Ok(user) =&gt; HttpResponse::Ok().json(user),<br>            Err(err) =&gt; HttpResponse::InternalServerError().body(err.to_string()),<br>        }<br>    }</pre><p>The snippet above does the following:</p><ul><li>Imports the required dependencies</li><li>Uses the routing macro to specify HTTP method and corresponding route</li><li>Creates a create_user handler that takes in the db, a type to the MongoRepo and a new_user as parameters. Inside the handler, we created a data variable for creating a user, inserted it into the database using the db.create_user method, and returned the correct response if the insert was successful or error if any.</li></ul><p><strong>PS:</strong> <em>The </em><em>Data and </em><em>Json struct used in defining the parameter is for managing application state shared across routes and extracting JSON data from request payloads, respectively.</em></p><p>Finally, we need to modify our application entry point to include the create_user handler. To do this, we need to navigate to the main.rs file and modify it as shown below:</p><pre>mod api;<br>    mod models;<br>    mod repository;</pre><pre>    //modify imports below<br>    use actix_web::{web::Data, App, HttpServer};<br>    use api::user_api::{create_user};<br>    use repository::mongodb_repo::MongoRepo;</pre><pre>    #[actix_web::main]<br>    async fn main() -&gt; std::io::Result&lt;()&gt; {<br>        let db = MongoRepo::init();<br>        let db_data = Data::new(db);<br>        HttpServer::new(move || {<br>            App::new()<br>                .app_data(db_data.clone())<br>                .service(create_user)<br>        })<br>        .bind((&quot;127.0.0.1&quot;, 8080))?<br>        .run()<br>        .await<br>    }</pre><p>The snippet above does the following:</p><ul><li>Imports the required dependencies</li><li>Creates a db variable to establish a connection to MongoDB by calling the init() method and adds it to a new instance of the Data struct so that the database state can be available across the application scope.</li><li>Uses the app_data and service function to add the application data and the handler to the App instance.</li></ul><p><strong>PS:</strong> <em>The </em><em>move keyword attached to the closure gives it ownership of the MongoDB configuration.</em></p><p><strong>Get a User Endpoint</strong><br>To get the details of a user, we must first modify the mongodb_repo.rs file by adding a get_user method to the implementation block.</p><pre>use std::env;<br>    extern crate dotenv;<br>    use dotenv::dotenv;</pre><pre>    use mongodb::{<br>        bson::{extjson::de::Error, oid::ObjectId, doc}, //modify here<br>        results::{ InsertOneResult},<br>        sync::{Client, Collection},<br>    };<br>    use crate::models::user_model::User;</pre><pre>    pub struct MongoRepo {<br>        col: Collection&lt;User&gt;,<br>    }</pre><pre>    impl MongoRepo {<br>        pub fn init() -&gt; Self {<br>            //init code goes here<br>        }</pre><pre>        pub fn create_user(&amp;self, new_user: User) -&gt; Result&lt;InsertOneResult, Error&gt; {<br>            //create_user code goes here<br>        }</pre><pre>        pub fn get_user(&amp;self, id: &amp;String) -&gt; Result&lt;User, Error&gt; {<br>            let obj_id = ObjectId::parse_str(id).unwrap();<br>            let filter = doc! {&quot;_id&quot;: obj_id};<br>            let user_detail = self<br>                .col<br>                .find_one(filter, None)<br>                .ok()<br>                .expect(&quot;Error getting user&#39;s detail&quot;);<br>            Ok(user_detail.unwrap())<br>        }<br>    }</pre><p>The snippet above does the following:</p><ul><li>Modifies the dependencies to include oid::ObjectId and doc</li><li>Adds a get_user method that takes in a self and id as parameters and returns the user detail or an error. Inside the method, we converted the id to an ObjectId and used it as a filter to get matching document. Then we use the self referencing the MongoRepo struct to access the find_one function from the collection to get the details of the user and handle errors. Finally, we returned the created user information.</li></ul><p>Secondly, we need to modify user_api.rs by creating a handler that uses the get_user method from the repository to get a user.</p><pre>use crate::{models::user_model::User, repository::mongodb_repo::MongoRepo};<br>    use actix_web::{<br>        post, get, //modify here<br>        web::{Data, Json, Path}, //modify here<br>        HttpResponse,<br>    };</pre><pre>    #[post(&quot;/user&quot;)]<br>    pub async fn create_user(db: Data&lt;MongoRepo&gt;, new_user: Json&lt;User&gt;) -&gt; HttpResponse {<br>        //create_user code goes here<br>    }</pre><pre>    #[get(&quot;/user/{id}&quot;)]<br>    pub async fn get_user(db: Data&lt;MongoRepo&gt;, path: Path&lt;String&gt;) -&gt; HttpResponse {<br>        let id = path.into_inner();<br>        if id.is_empty() {<br>            return HttpResponse::BadRequest().body(&quot;invalid ID&quot;);<br>        }<br>        let user_detail = db.get_user(&amp;id);<br>        match user_detail {<br>            Ok(user) =&gt; HttpResponse::Ok().json(user),<br>            Err(err) =&gt; HttpResponse::InternalServerError().body(err.to_string()),<br>        }<br>    }</pre><p>The snippet above does the following:</p><ul><li>Modifies the dependencies to include get and Path</li><li>Uses the routing macro to specify HTTP method, corresponding route and route parameter</li><li>Creates a get_user handler that takes in the db, a type to the MongoRepo and a path for accessing route path as parameters. Inside the handler, we created an id variable to get the user’s <strong>id</strong>, get the user’s details from the database using the db.get_user method. We returned the correct response if the request was successful or error if any.</li></ul><p>Finally, we need to modify our application entry point(main.rs)to include the get_user handler by importing the handler and adding a new service for it.</p><pre>mod api;<br>    mod models;<br>    mod repository;</pre><pre>    //modify imports below<br>    use actix_web::{web::Data, App, HttpServer};<br>    use api::user_api::{create_user, get_user}; //import the handler here<br>    use repository::mongodb_repo::MongoRepo;</pre><pre>    #[actix_web::main]<br>    async fn main() -&gt; std::io::Result&lt;()&gt; {<br>        let db = MongoRepo::init();<br>        let db_data = Data::new(db);<br>        HttpServer::new(move || {<br>            App::new()<br>                .app_data(db_data.clone())<br>                .service(create_user)<br>                .service(get_user) //add this<br>        })<br>        .bind((&quot;127.0.0.1&quot;, 8080))?<br>        .run()<br>        .await<br>    }</pre><p><strong>Edit a User Endpoint</strong><br>To edit a user, we must first modify the mongodb_repo.rs file by adding an edit_user method to the implementation block.</p><pre>use std::env;<br>    extern crate dotenv;<br>    use dotenv::dotenv;</pre><pre>    use mongodb::{<br>        bson::{extjson::de::Error, oid::ObjectId, doc}, <br>        results::{ InsertOneResult, UpdateResult}, //modify here<br>        sync::{Client, Collection},<br>    };<br>    use crate::models::user_model::User;</pre><pre>    pub struct MongoRepo {<br>        col: Collection&lt;User&gt;,<br>    }</pre><pre>    impl MongoRepo {<br>        pub fn init() -&gt; Self {<br>            //init code goes here<br>        }</pre><pre>        pub fn create_user(&amp;self, new_user: User) -&gt; Result&lt;InsertOneResult, Error&gt; {<br>            //create_user code goes here<br>        }</pre><pre>        pub fn get_user(&amp;self, id: &amp;String) -&gt; Result&lt;User, Error&gt; {<br>            //get_user code goes here<br>        }</pre><pre>        pub fn update_user(&amp;self, id: &amp;String, new_user: User) -&gt; Result&lt;UpdateResult, Error&gt; {<br>            let obj_id = ObjectId::parse_str(id).unwrap();<br>            let filter = doc! {&quot;_id&quot;: obj_id};<br>            let new_doc = doc! {<br>                &quot;$set&quot;:<br>                    {<br>                        &quot;id&quot;: new_user.id,<br>                        &quot;name&quot;: new_user.name,<br>                        &quot;location&quot;: new_user.location,<br>                        &quot;title&quot;: new_user.title<br>                    },<br>            };<br>            let updated_doc = self<br>                .col<br>                .update_one(filter, new_doc, None)<br>                .ok()<br>                .expect(&quot;Error updating user&quot;);<br>            Ok(updated_doc)<br>        }<br>    }</pre><p>The snippet above does the following:</p><ul><li>Modifies the dependencies to include UpdateResult</li><li>Adds an update_user method that takes in a self, id, and new_user parameters and returns the updated user detail or an error. Inside the method, we converted the id to an ObjectId, created a filter variable to get the matching document we wanted to update and used the doc macro to update the document fields. Then we use the self referencing the MongoRepo struct to access the update_one function from the collection to update the user matching the filter specified and handle errors. Finally, we returned the updated user information.</li></ul><p>Secondly, we need to modify user_api.rs by creating a handler that uses the update_user method from the repository to update a user.</p><pre>use crate::{models::user_model::User, repository::mongodb_repo::MongoRepo};<br>    use actix_web::{<br>        post, get, put, //modify here<br>        web::{Data, Json, Path},<br>        HttpResponse,<br>    };<br>    use mongodb::bson::oid::ObjectId; //add this</pre><pre>    #[post(&quot;/user&quot;)]<br>    pub async fn create_user(db: Data&lt;MongoRepo&gt;, new_user: Json&lt;User&gt;) -&gt; HttpResponse {<br>        //create_user code goes here<br>    }</pre><pre>    #[get(&quot;/user/{id}&quot;)]<br>    pub async fn get_user(db: Data&lt;MongoRepo&gt;, path: Path&lt;String&gt;) -&gt; HttpResponse {<br>        //get_user code goes here<br>    }</pre><pre>    #[put(&quot;/user/{id}&quot;)]<br>    pub async fn update_user(<br>        db: Data&lt;MongoRepo&gt;,<br>        path: Path&lt;String&gt;,<br>        new_user: Json&lt;User&gt;,<br>    ) -&gt; HttpResponse {<br>        let id = path.into_inner();<br>        if id.is_empty() {<br>            return HttpResponse::BadRequest().body(&quot;invalid ID&quot;);<br>        };<br>        let data = User {<br>            id: Some(ObjectId::parse_str(&amp;id).unwrap()),<br>            name: new_user.name.to_owned(),<br>            location: new_user.location.to_owned(),<br>            title: new_user.title.to_owned(),<br>        };<br>        let update_result = db.update_user(&amp;id, data);<br>        match update_result {<br>            Ok(update) =&gt; {<br>                if update.matched_count == 1 {<br>                    let updated_user_info = db.get_user(&amp;id);<br>                    return match updated_user_info {<br>                        Ok(user) =&gt; HttpResponse::Ok().json(user),<br>                        Err(err) =&gt; HttpResponse::InternalServerError().body(err.to_string()),<br>                    };<br>                } else {<br>                    return HttpResponse::NotFound().body(&quot;No user found with specified ID&quot;);<br>                }<br>            }<br>            Err(err) =&gt; HttpResponse::InternalServerError().body(err.to_string()),<br>        }<br>    }</pre><p>The snippet above does the following:</p><ul><li>Modifies the dependencies to include put and ObjectId</li><li>Uses the routing macro to specify HTTP method, corresponding route and route parameter</li><li>Creates an update_user handler that takes in the db, a type to the MongoRepo, path, and new_user as parameters. Inside the handler, we created an id variable to get the user’s <strong>id</strong>, update the user’s details from the database using the db.update_user method by passing in the updated user’s information. Finally, we checked if the update was successful and returned the updated user or error if any.</li></ul><p>Finally, we need to modify our application entry point(main.rs)to include the update_user handler by importing the handler and adding a new service for it.</p><pre>mod api;<br>    mod models;<br>    mod repository;</pre><pre>    //modify imports below<br>    use actix_web::{web::Data, App, HttpServer};<br>    use api::user_api::{create_user, get_user, update_user}; //import the handler here<br>    use repository::mongodb_repo::MongoRepo;</pre><pre>    #[actix_web::main]<br>    async fn main() -&gt; std::io::Result&lt;()&gt; {<br>        let db = MongoRepo::init();<br>        let db_data = Data::new(db);<br>        HttpServer::new(move || {<br>            App::new()<br>                .app_data(db_data.clone())<br>                .service(create_user)<br>                .service(get_user)<br>                .service(update_user) //add this<br>        })<br>        .bind((&quot;127.0.0.1&quot;, 8080))?<br>        .run()<br>        .await<br>    }</pre><p><strong>Delete a User Endpoint</strong><br>To delete a user, we must first modify the mongodb_repo.rs file by adding an delete_user method to the implementation block.</p><pre>use std::env;<br>    extern crate dotenv;<br>    use dotenv::dotenv;</pre><pre>    use mongodb::{<br>        bson::{extjson::de::Error, oid::ObjectId, doc}, <br>        results::{ InsertOneResult, UpdateResult, DeleteResult}, //modify here<br>        sync::{Client, Collection},<br>    };<br>    use crate::models::user_model::User;</pre><pre>    pub struct MongoRepo {<br>        col: Collection&lt;User&gt;,<br>    }</pre><pre>    impl MongoRepo {<br>        pub fn init() -&gt; Self {<br>            //init code goes here<br>        }</pre><pre>        pub fn create_user(&amp;self, new_user: User) -&gt; Result&lt;InsertOneResult, Error&gt; {<br>            //create_user code goes here<br>        }</pre><pre>        pub fn get_user(&amp;self, id: &amp;String) -&gt; Result&lt;User, Error&gt; {<br>            //get_user code goes here<br>        }</pre><pre>        pub fn update_user(&amp;self, id: &amp;String, new_user: User) -&gt; Result&lt;UpdateResult, Error&gt; {<br>            //update_user code goes here<br>        }</pre><pre>        pub fn delete_user(&amp;self, id: &amp;String) -&gt; Result&lt;DeleteResult, Error&gt; {<br>            let obj_id = ObjectId::parse_str(id).unwrap();<br>            let filter = doc! {&quot;_id&quot;: obj_id};<br>            let user_detail = self<br>                .col<br>                .delete_one(filter, None)<br>                .ok()<br>                .expect(&quot;Error deleting user&quot;);<br>            Ok(user_detail)<br>        }<br>    }</pre><p>The snippet above does the following:</p><ul><li>Modifies the dependencies to include DeleteResult</li><li>Adds a delete_user method that takes in a self and id as parameters and returns the deleted user detail or an error. Inside the method, we converted the id to an ObjectId and created a filter variable to get the matching document we wanted to delete. Then we use the self referencing the MongoRepo struct to access the delete_one function from the collection to delete the user matching the filter specified and handle errors. Finally, we returned the deleted user information.</li></ul><p>Secondly, we need to modify user_api.rs by creating a handler that uses the delete_user method from the repository to delete a user.</p><pre>use crate::{models::user_model::User, repository::mongodb_repo::MongoRepo};<br>    use actix_web::{<br>        post, get, put, delete, //modify here<br>        web::{Data, Json, Path},<br>        HttpResponse,<br>    };<br>    use mongodb::bson::oid::ObjectId; //add this</pre><pre>    #[post(&quot;/user&quot;)]<br>    pub async fn create_user(db: Data&lt;MongoRepo&gt;, new_user: Json&lt;User&gt;) -&gt; HttpResponse {<br>        //create_user code goes here<br>    }</pre><pre>    #[get(&quot;/user/{id}&quot;)]<br>    pub async fn get_user(db: Data&lt;MongoRepo&gt;, path: Path&lt;String&gt;) -&gt; HttpResponse {<br>        //get_user code goes here<br>    }</pre><pre>    #[put(&quot;/user/{id}&quot;)]<br>    pub async fn update_user(<br>        db: Data&lt;MongoRepo&gt;,<br>        path: Path&lt;String&gt;,<br>        new_user: Json&lt;User&gt;,<br>    ) -&gt; HttpResponse {<br>        //update_user code goes here<br>    }</pre><pre>    #[delete(&quot;/user/{id}&quot;)]<br>    pub async fn delete_user(db: Data&lt;MongoRepo&gt;, path: Path&lt;String&gt;) -&gt; HttpResponse {<br>        let id = path.into_inner();<br>        if id.is_empty() {<br>            return HttpResponse::BadRequest().body(&quot;invalid ID&quot;);<br>        };<br>        let result = db.delete_user(&amp;id);<br>        match result {<br>            Ok(res) =&gt; {<br>                if res.deleted_count == 1 {<br>                    return HttpResponse::Ok().json(&quot;User successfully deleted!&quot;);<br>                } else {<br>                    return HttpResponse::NotFound().json(&quot;User with specified ID not found!&quot;);<br>                }<br>            }<br>            Err(err) =&gt; HttpResponse::InternalServerError().body(err.to_string()),<br>        }<br>    }</pre><p>The snippet above does the following:</p><ul><li>Modifies the dependencies to include delete</li><li>Uses the routing macro to specify HTTP method, corresponding route and route parameter</li><li>Creates a delete_user handler that takes in the db, a type to the MongoRepo and path as parameters. Inside the handler, we created an id variable to get the user’s <strong>id</strong> and ****delete the user from the database using the db.delete_user method by passing in the id. Finally, we returned the appropriate response or error if any.</li></ul><p>Finally, we need to modify our application entry point(main.rs)to include the delete_user handler by importing the handler and adding a new service for it.</p><pre>mod api;<br>    mod models;<br>    mod repository;</pre><pre>    //modify imports below<br>    use actix_web::{web::Data, App, HttpServer};<br>    use api::user_api::{create_user, get_user, update_user, delete_user}; //import the handler here<br>    use repository::mongodb_repo::MongoRepo;</pre><pre>    #[actix_web::main]<br>    async fn main() -&gt; std::io::Result&lt;()&gt; {<br>        let db = MongoRepo::init();<br>        let db_data = Data::new(db);<br>        HttpServer::new(move || {<br>            App::new()<br>                .app_data(db_data.clone())<br>                .service(create_user)<br>                .service(get_user)<br>                .service(update_user) <br>                .service(delete_user) //add this<br>        })<br>        .bind((&quot;127.0.0.1&quot;, 8080))?<br>        .run()<br>        .await<br>    }</pre><p><strong>Get all Users Endpoint</strong><br>To get the list of users, we must first modify the mongodb_repo.rs file by adding a get_all_users method to the implementation block.</p><pre>use std::env;<br>    extern crate dotenv;<br>    use dotenv::dotenv;</pre><pre>    use mongodb::{<br>        bson::{extjson::de::Error, oid::ObjectId, doc}, <br>        results::{ InsertOneResult, UpdateResult, DeleteResult},<br>        sync::{Client, Collection},<br>    };<br>    use crate::models::user_model::User;</pre><pre>    pub struct MongoRepo {<br>        col: Collection&lt;User&gt;,<br>    }</pre><pre>    impl MongoRepo {<br>        pub fn init() -&gt; Self {<br>            //init code goes here<br>        }</pre><pre>        pub fn create_user(&amp;self, new_user: User) -&gt; Result&lt;InsertOneResult, Error&gt; {<br>            //create_user code goes here<br>        }</pre><pre>        pub fn get_user(&amp;self, id: &amp;String) -&gt; Result&lt;User, Error&gt; {<br>            //get_user code goes here<br>        }</pre><pre>        pub fn update_user(&amp;self, id: &amp;String, new_user: User) -&gt; Result&lt;UpdateResult, Error&gt; {<br>            //update_user code goes here<br>        }</pre><pre>        pub fn delete_user(&amp;self, id: &amp;String) -&gt; Result&lt;DeleteResult, Error&gt; {<br>            //delete_user code goes here<br>        }</pre><pre>        pub fn get_all_users(&amp;self) -&gt; Result&lt;Vec&lt;User&gt;, Error&gt; {<br>            let cursors = self<br>                .col<br>                .find(None, None)<br>                .ok()<br>                .expect(&quot;Error getting list of users&quot;);<br>            let users = cursors.map(|doc| doc.unwrap()).collect();<br>            Ok(users)<br>        }<br>    }</pre><p>The snippet above adds a get_all_users method that takes in a self as a parameter and returns the list of users or an error. Inside the method, we use the self referencing the MongoRepo struct to access the find function from the collection without any filter so that it can match all the documents inside the database and handle errors. Finally, we returned the list of users.</p><p>Secondly, we need to modify user_api.rs by creating a handler that uses the get_all_users method from the repository to get list of users.</p><pre>use crate::{models::user_model::User, repository::mongodb_repo::MongoRepo};<br>    use actix_web::{<br>        post, get, put, delete, <br>        web::{Data, Json, Path},<br>        HttpResponse,<br>    };<br>    use mongodb::bson::oid::ObjectId; </pre><pre>    #[post(&quot;/user&quot;)]<br>    pub async fn create_user(db: Data&lt;MongoRepo&gt;, new_user: Json&lt;User&gt;) -&gt; HttpResponse {<br>        //create_user code goes here<br>    }</pre><pre>    #[get(&quot;/user/{id}&quot;)]<br>    pub async fn get_user(db: Data&lt;MongoRepo&gt;, path: Path&lt;String&gt;) -&gt; HttpResponse {<br>        //get_user code goes here<br>    }</pre><pre>    #[put(&quot;/user/{id}&quot;)]<br>    pub async fn update_user(<br>        db: Data&lt;MongoRepo&gt;,<br>        path: Path&lt;String&gt;,<br>        new_user: Json&lt;User&gt;,<br>    ) -&gt; HttpResponse {<br>        //update_user code goes here<br>    }</pre><pre>    #[delete(&quot;/user/{id}&quot;)]<br>    pub async fn delete_user(db: Data&lt;MongoRepo&gt;, path: Path&lt;String&gt;) -&gt; HttpResponse {<br>        //delet_user code goes here<br>    }</pre><pre>    #[get(&quot;/users&quot;)]<br>    pub async fn get_all_users(db: Data&lt;MongoRepo&gt;) -&gt; HttpResponse {<br>        let users = db.get_all_users();<br>        match users {<br>            Ok(users) =&gt; HttpResponse::Ok().json(users),<br>            Err(err) =&gt; HttpResponse::InternalServerError().body(err.to_string()),<br>        }<br>    }</pre><p>The snippet above does the following:</p><ul><li>Uses the routing macro to specify HTTP method and corresponding route</li><li>Creates a get_all_users handler that uses the db.delete_user method to get the list of users. Then, we returned the list of users or error if any.</li></ul><p>Finally, we need to modify our application entry point(main.rs)to include the get_all_users handler by importing the handler and adding a new service for it.</p><pre>mod api;<br>    mod models;<br>    mod repository;</pre><pre>    //modify imports below<br>    use actix_web::{web::Data, App, HttpServer};<br>    use api::user_api::{create_user, get_user, update_user, delete_user, get_all_users}; //import the handler here<br>    use repository::mongodb_repo::MongoRepo;</pre><pre>    #[actix_web::main]<br>    async fn main() -&gt; std::io::Result&lt;()&gt; {<br>        let db = MongoRepo::init();<br>        let db_data = Data::new(db);<br>        HttpServer::new(move || {<br>            App::new()<br>                .app_data(db_data.clone())<br>                .service(create_user)<br>                .service(get_user)<br>                .service(update_user) <br>                .service(delete_user) <br>               .service(get_all_users)//add this<br>        })<br>        .bind((&quot;127.0.0.1&quot;, 8080))?<br>        .run()<br>        .await<br>    }</pre><p>With that done, we can test our application by running the command below in our terminal.</p><pre>cargo run</pre><h3>Conclusion</h3><p>This post discussed how to modularize a Rust application, build a REST API, and persist our data using MongoDB.</p><p>You may find these resources helpful:</p><ul><li><a href="https://actix.rs/">Actix web</a></li><li><a href="https://github.com/mongodb/mongo-rust-driver">MongoDB Rust Driver</a></li><li><a href="https://serde.rs/">Serde (Serializing and Deserializing library)</a></li><li><a href="https://crates.io/crates/dotenv">Rust Environment Loader</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=307f6176ccbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to mint Solana NFTs using Candy Machine V2 [includes code]]]></title>
            <link>https://medium.com/@smile0307/how-to-mint-solana-nfts-using-candy-machine-v2-includes-code-5d4b501a7c0b?source=rss-3f6da6942a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d4b501a7c0b</guid>
            <dc:creator><![CDATA[Sol Tech]]></dc:creator>
            <pubDate>Sat, 28 May 2022 15:37:11 GMT</pubDate>
            <atom:updated>2022-05-28T15:38:03.636Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scripts and code to make you a pro ape NFT maker in the Solana ecosystem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5MMhWzozsWDkA7v1wO87Q.png" /></figure><p>n this tutorial, we will mint NFTs on Solana using the Candy Machine v0.0.2.</p><h3>Prerequisites</h3><p>Minting an NFT is the process of creating a token, freezing its maximum supply to 1 and attaching Metaplex NFT standard JSON to it, so a wallet can render it. This process requires you to have:</p><ul><li>some understanding of bash scripts, and a terminal</li><li>some knowledge of Git and Node</li><li>Solana CLI tools [<a href="https://docs.solana.com/cli/install-solana-cli-tools">installation guide</a>]</li></ul><h3>End results</h3><p>By the end of this tutorial, you will have 5 NFTs on the Solana devnet and a website to run a sale. We will also add a script to mint NFTs to your wallet via the CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*Ax3jd4_M1iCyilSm-6bNjA.png" /></figure><p><em>The cover image of this article was created using graphics from </em><a href="https://www.vecteezy.com/free-vector/candy-machine"><em>Candy Machine Vectors by Vecteezy</em></a><em> and </em><a href="https://www.freepik.com/vectors/heart"><em>Monkeys Vector by Brgfx on Freepik</em></a><em>.</em></p><h3>Step 1: Prep your images</h3><p>We are going to build an upgradable NFT project on top of the Meta Blocks protocol. We have created these 5 images that can be joined together. This collection will be called “Tara”.</p><p>You use this guide, even if don’t plan to be upgradable via Meta Blocks protocol. The process for minting a Meta Blocks compatible collection is the same as minting a normal NFT collection.</p><p>You can download these images <a href="https://gist.github.com/shivekkhurana/69b7dd768fefa6781bf4833dbd61527c#file-image-files-md">here</a>.</p><h3>Step 2: Setup Metaplex locally</h3><p>Metaplex offers a suite of tools and smart contracts (programs) that will ease the process of creating NFTs. We will use the official CLI to mint our collection.</p><h3>Step 2.1: Pull CLI from Github</h3><p>Open the terminal app on your computer. cd into a directory where you want to store the Metaplex related code. In my case this will be ~/Desktop. Then clone the repository:</p><pre>cd ~/Desktop<br>git clone git@github.com:metaplex-foundation/metaplex.git</pre><p>You should see the following files in the newly created metaplex folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ua1bE7GcCqsl0dfsoiWK5g.png" /></figure><p><em>Screenshot of the files inside the Metaplex folder</em></p><h3>Step 2.2: Build Metaplex CLI code</h3><p>We have the code but it’s not usable yet. We need to fetch its dependancies and compile it. The Metaplex package comes with multiple packages, but we only care about cli. To do this, goto the js/packages/cli folder inside metaplex, and execute the following commands:</p><pre>cd packages/cli # we only need to work with CLI<br>yarn # installs all dependencies<br>yarn build # compile typescript code to node</pre><p>This will create a folder named build in the cli folder. If you run node ./build/candy-machine-v2-cli.js, you should see the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5SYHNhhCh-aXyKB2xp9GXg.png" /></figure><p><em>Successfully built Candy Machine CLI output</em></p><h3>Step 3: Prep Metaplex NFT config</h3><p>Each asset (image/video etc) that you want to publish as an NFT needs an accompanying Metaplex config. This config is built to comply with Metaplex’s <a href="https://docs.metaplex.com/token-metadata/v1.1.0/specification">Token Metadata Standard</a>. In less technical terms, Metaplex designed a standard that to store NFTs on Solana, an everyone in the ecosystem adopted the standard.</p><p>From the point of view of the creator, you can think of this config as a way to specify the attributes, commissions and aspects of your NFT.</p><p>Since we have five assets, we need five configuration files. According to Metaplex, the numbering of the files start at 0. So for our 5 NFTs in the “Tara” collection, we will have the following files (total 10):</p><ul><li>0.png, 0.json for Tara Base</li><li>1.png, 1.json for Tara Right Blue</li><li>2.png, 2.json for Tara Right Red</li><li>3.png, 3.json for Tara Top Green and</li><li>4.png , 4.json for Tara Top Purple</li></ul><h3>Step 3.1: Create a folder for Tara project</h3><p>We will create two folders called tara and tara/assets in metaplex/js/packages/cli:</p><pre>cd ~/Desktop/metaplex/js/packages/cli<br>mkdir tara<br>cd tara<br>mkdir assets</pre><p>assets folder stores on-chain assets and the tara folder will be used to store keys and config. This is just our personal preference. These folder names can be anything.</p><h3>Step 3.2: Move 5 “Tara” images to the tara/assets folder</h3><p>Make sure that you name then 0.png, 1.png and so on.</p><h3>Step 3.3: Create the file 0.json for the first NFT</h3><p>This file will have the following content:</p><pre>{<br>    <em>&quot;name&quot;</em>: &quot;Tara Base Card&quot;,<br>    <em>&quot;description&quot;</em>: &quot;Tara universe is a demo project to showcase the power of Meta Blocks Protocol. This base card is where the story begins.&quot;,<br>    <em>&quot;image&quot;</em>: &quot;0.png&quot;,<br>    <em>&quot;attributes&quot;</em>:<br>    [<br>        {<br>            <em>&quot;trait_type&quot;</em>: &quot;texture&quot;,<br>            <em>&quot;value&quot;</em>: &quot;futuristic&quot;<br>        },<br>        {<br>            <em>&quot;trait_type&quot;</em>: &quot;slots&quot;,<br>            <em>&quot;value&quot;</em>: 4<br>        }<br>    ],<br>    <em>&quot;symbol&quot;</em>: &quot;TaraBase&quot;,<br>    <em>&quot;seller_fee_basis_points&quot;</em>: 1000,<br>    <em>&quot;collection&quot;</em>:<br>    {<br>        <em>&quot;name&quot;</em>: &quot;Tara Universe&quot;,<br>        <em>&quot;family&quot;</em>: &quot;Meta Blocks Samples&quot;<br>    },<br>    <em>&quot;properties&quot;</em>:<br>    {<br>        <em>&quot;files&quot;</em>:<br>        [<br>            {<br>                <em>&quot;uri&quot;</em>: &quot;0.png&quot;,<br>                <em>&quot;type&quot;</em>: &quot;image/png&quot;<br>            }<br>        ],<br>        <em>&quot;category&quot;</em>: &quot;image&quot;,<br>        <em>&quot;creators&quot;</em>:<br>        [<br>            {<br>                <em>&quot;address&quot;</em>: &quot;8J4tQgSifp1ibwXbMVBBKjry1YoSaoSLSMTkYQjsyzUA&quot;,<br>                <em>&quot;share&quot;</em>: 100<br>            }<br>        ]<br>    }<br>}</pre><p>In this configuration:</p><ul><li>You can add as many attributes as you want in attributes array</li><li>Alternate file types (like video) in the files array</li><li>For additional files, make sure you use the correct files.type</li><li>The royalty you get per trade in seller_fee_basis_points (1000 basis = 10% royalty, 10000 basis = 100% royalty)</li><li>Add your wallet address in creators.address</li><li>If there are multiple creators, you can specify the share split of royalties</li><li>Share = 100 signifies that 100% of the royalties for goto this creator</li></ul><h3>Step 3.4: Create configuration for all NFTs</h3><p>You can create a script to generate the configuration for you. If you are following along with the example, you can find the 5 json files and images <a href="https://gist.github.com/shivekkhurana/69b7dd768fefa6781bf4833dbd61527c">here</a>.</p><p>After this, your assets are ready (assuming you didn’t make any typos). The next step is to prepare the candy machine.</p><h3>Step 4: Prep Candy Machine Config</h3><p>The candy machine config lets you set the price, mint date and other attributes of the collection. To configure this, create a file called config.json in js/packages/tara:</p><pre>{<br>    <em>&quot;price&quot;</em>: 0.001,<br>    <em>&quot;number&quot;</em>: 5,<br>    <em>&quot;gatekeeper&quot;</em>: null,<br>    <em>&quot;solTreasuryAccount&quot;</em>: &quot;8J4tQgSifp1ibwXbMVBBKjry1YoSaoSLSMTkYQjsyzUA&quot;,<br>    <em>&quot;splTokenAccount&quot;</em>: null,<br>    <em>&quot;splToken&quot;</em>: null,<br>    <em>&quot;goLiveDate&quot;</em>: &quot;25 Dec 2021 00:00:00 GMT&quot;,<br>    <em>&quot;endSettings&quot;</em>: null,<br>    <em>&quot;whitelistMintSettings&quot;</em>: null,<br>    <em>&quot;hiddenSettings&quot;</em>: null,<br>    <em>&quot;storage&quot;</em>: &quot;arweave&quot;,<br>    <em>&quot;ipfsInfuraProjectId&quot;</em>: null,<br>    <em>&quot;ipfsInfuraSecret&quot;</em>: null,<br>    <em>&quot;awsS3Bucket&quot;</em>: null,<br>    <em>&quot;noRetainAuthority&quot;</em>: false,<br>    <em>&quot;noMutable&quot;</em>: false<br>}</pre><p>The important keys to change are:</p><ul><li>price: price of each NFT in SOL</li><li>solTreasuryAccount: public address that receives the funds from sales</li></ul><p>To get more info about each key value pair, refer to the official Metaplex documen at <a href="https://docs.metaplex.com/candy-machine-v2/configuration">https://docs.metaplex.com/candy-machine-v2/configuration</a></p><h3>Step 5: Generate a keypair for uploading these assets</h3><p>We need a Solana wallet to make contract calls to create these NFTs. Let’s create one in js/packages/cli/tara:</p><pre>solana-keygen new --outfile keypair.json</pre><p>We are working on the devnet at the moment, so make sure that your network is set to devnet</p><pre>solana config set --url https://api.devnet.solana.com<br>solana config get # will show the current config</pre><p>Finally, you need some SOL to pay gas. You can request some using airdrop:</p><pre>solana airdrop 2 -k ./keypair.json</pre><p>The above command will give an output similar to:</p><pre>Requesting airdrop of 2 SOL</pre><pre>Signature: Kme6a2HjbiWCi3hVcqa8qAPcZHmC6kCQhNSVHKT9NyNacpKZ12uxE3GjDVsDHj8TbXtAGdh4An2qSYa9uKe8Hzt</pre><pre>2 SOL</pre><p>It’s a good idea to test your collection on Devnet first. When done, you can change the network to Mainnet-Beta.</p><h3>Step 6: Upload the assets</h3><p>In the js/packages/cli/tara directory, run the following command to upload the assets to Arweave:</p><pre>node ../build/candy-machine-v2-cli.js upload \<br>    --env devnet \<br>    --keypair keypair.json \<br>    --config-path config.json \<br>    --cache-name taracache \<br>    ./assets</pre><p>On successful completion, you will get an output that looks like this:</p><pre>Beginning the upload for 5 (img+json) pairs<br>started at: 1643379208383<br>Size 5 { mediaExt: &#39;.png&#39;, index: &#39;0&#39; }<br>Processing asset: 0<br>initializing candy machine<br>initialized config for a candy machine with publickey: AuuLoYV9kx8HKWrpnJCT5whgURqd5MwxckWesL5arqh<br>Processing asset: 0<br>Processing asset: 1<br>Processing asset: 2<br>Processing asset: 3<br>Processing asset: 4<br>Writing indices 0-4<br>Done. Successful = true.<br>ended at: 2022-01-28T14:14:26.735Z. time taken: 00:00:58</pre><p>Take a not of the candy machine public key. For us, it is <strong>AuuLoYV9kx8HKWrpnJCT5whgURqd5MwxckWesL5arqh</strong></p><p>At this point, you can check the .cache folder to see the urls of the NFTs on Arweave.</p><p>If the command fails, you can run it again. The command is smart enough to resume uploads. If you are uploading a lot of images, you might need more than 2 SOL.</p><p>NOTE: If you are not able to upload at all, you can try to clear the cache and try again. The cache folder is hidden and called .cache</p><h3>Step 7: Verify uploads (optional)</h3><p>To ensure that the upload process, you can run the verify command as follows:</p><pre>node ../build/candy-machine-v2-cli.js verify_upload \<br>    --env devnet \<br>    --keypair ./keypair.json \<br>    --cache-name taracache \</pre><pre>wallet public key: 9WS1ezpcxDVfA8cWGzDswCxfXWPtc6xcrkEk9gN6PWh8<br>Key size 5<br>uploaded (5) out of (5)<br>ready to deploy!</pre><p>It’s recommended to run the verify command, but it’s possible that you like taking risks. Maybe you live life on the edge. In that case you can skip this step.</p><h3>Step 8: Choose a delivery mechanism</h3><p>At this point, your NFTs are ready on the chain. Now you can decide to:</p><ul><li>Mint them to your wallet via the command line or</li><li>Generate a candy machine website where users can mint their own</li></ul><p>The advantage of the latter approach is that the gas fee of the mint is paid by the user.</p><p>If you decide to create a website, you can follow the steps outlined here: <a href="https://docs.metaplex.com/candy-machine-v2/mint-frontend">https://docs.metaplex.com/candy-machine-v2/mint-frontend</a>. The value of the variable REACT_APP_CANDY_MACHINE_PROGRAM_ID is the public key of the candy machine computed in Step 6 (AuuLoYV9kx8HKWrpnJCT5whgURqd5MwxckWesL5arqh).</p><p>If you decide to mint the NFTs to your own wallet, you can do it via the CLI:</p><pre>node ../build/candy-machine-v2-cli.js mint_multiple_tokens\<br>    --env devnet \<br>    --keypair ./keypair.json \<br>    --cache-name taracache \<br>    --number 5</pre><p>The above command will try to mint 5 NFTs by reading the taracache. This cache was created in the upload process. You can pass any number in place of 5.</p><p>The NFTs will be stored in the wallet related to keypair.json. You can add this keypair to Phantom to check the NFTs.</p><p>A successful output will look something like:</p><pre>Minting 5 tokens...<br>wallet public key: 9WS1ezpcxDVfA8cWGzDswCxfXWPtc6xcrkEk9gN6PWh8<br>No instructions provided<br>No instructions provided<br>transaction 1 complete 61H3Ai5UPqDzLQ8fobZbN3zAnXycSKgt5vyqMB9eXuVWotH6hodwyCj1HnKNe3ynRybxdUiLZeCuwYs98V15WRV3</pre><pre>...</pre><pre>minting another token...<br>wallet public key: 9WS1ezpcxDVfA8cWGzDswCxfXWPtc6xcrkEk9gN6PWh8<br>No instructions provided<br>No instructions provided<br>transaction 5 complete 4yBqTztycEPqRMZTZTQadRC4DBkdcBgUhSFvkrmHhcg8LsiGx1NrxtUTJjVjcSsPu42Vwe5Bhxh5B8GKrE3YE1PS</pre><pre>minted 5 tokens<br>mint_multiple_tokens finished</pre><p>After running this command, you should see 5 NFTs in your wallet. Make sure you switch the network to devnet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuxA-Lv6eb1zUxGQ__wIag.png" /></figure><p><em>NFTs show up in Slope wallet</em></p><h3>Next steps</h3><p>Now you have minted your awesome NFT collection. You can sell them, build a community around them, or keep them in your wallet forever.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d4b501a7c0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Sense of the NFT Marketplace]]></title>
            <link>https://medium.com/@smile0307/making-sense-of-the-nft-marketplace-852c2c8bc1b9?source=rss-3f6da6942a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/852c2c8bc1b9</guid>
            <dc:creator><![CDATA[Sol Tech]]></dc:creator>
            <pubDate>Sat, 28 May 2022 01:24:47 GMT</pubDate>
            <atom:updated>2022-05-28T01:24:47.051Z</atom:updated>
            <content:encoded><![CDATA[<p>Non-fungible tokens (NFTs) may seem like a <a href="https://hbr.org/podcast/2021/03/the-nft-craze-and-the-future-of-spotify-and-streaming-music">passing craze</a>, but with over <a href="https://www.cnbc.com/2021/10/06/nft-trading-volume-hit-10-billion-2-reasons-why-people-are-buying.html">$10 billion</a> traded in the third quarter of 2021 alone, it’s become clear that this emerging technology — a blockchain-based tool that enables anyone to monetize digital content — is growing into a major industry. In March of this year, musician 3LAU collaborated with crypto startup Origin Protocol to create a specialized platform to sell his new album as an NFT, where it ultimately sold for <a href="https://www.businessinsider.com/nft-ultraviolet-3lau-first-ever-crypto-albums-sales-11-million-2021-3">$11.6 million</a>. Visual artist Beeple <a href="https://www.theverge.com/2021/3/11/22325054/beeple-christies-nft-sale-cost-everydays-69-million">famously sold</a> a tokenized digital artwork for $69 million through Christie’s auction house, and the NBA’s Top Shot, which is owned by crypto platform Dapper Labs and enables fans to buy and sell tokenized video clips of basketball game highlights, has generated over <a href="https://dappradar.com/flow/collectibles/nba-topshot">$715 million</a> in transaction volume.</p><p>In response to this massive growth, both individual creators and firms as wide-ranging as retail, music, entertainment, consumer products, fashion, and more have begun actively exploring ways to engage with the world of NFTs. Specifically, while some sellers have opted to build their own NFT marketplaces, most have found that a partnership with a third-party platform is more feasible, as it can reduce upfront costs, offer access to a larger existing customer base, and provide valuable add-on services such as marketing, legal, and technical support.</p><h3>What is an NFT marketplace?</h3><p>In contrast to platforms such as Spotify and Netflix, which provide unlimited digital content for a subscription fee, NFT platforms are built around the idea that just like physical content, digital content too can be scarce — that is, limited in quantity — and can therefore be meaningfully owned and traded. These platforms leverage blockchain technology to verify the provenance of digital content, similar to how a traditional auction house might verify that a given work of art is in fact the original and not a replica, and some platforms even offer the ability to “burn” items, further reinforcing the concept of scarcity for these digital products. Blockchain-based transaction logs can also facilitate royalty attribution, automatically sharing a percentage of revenue from second-hand sales with the original creator every time the NFT is traded.</p><p>Of course, as with any investment into a new capability, while partnering with the right marketplace can unlock entirely new markets and revenue streams, partnering with the wrong platform can seriously backfire — and when it comes to leveraging a rapidly-evolving new technology like NFTs, it’s not always obvious what the right choice is. To avoid making costly mistakes, it’s critical to understand the landscape of platforms that are currently available and determine which will be the best fit for your NFT offerings.</p><h3>What kinds of marketplaces are out there?</h3><p>While there are a number of factors to consider, we’ve found that it can be particularly helpful to characterize NFT marketplaces on a spectrum from <em>streamlined</em> to <em>augmented</em>. Streamlined marketplaces support a broader range of NFTs and offer more limited, generic services to sellers, while augmented marketplaces are highly specialized and provide a more full-service experience.</p><p>Streamlined platforms include services such as OpenSea and Rarible, which host both auctions and fixed-price sales for a wide variety of NFTs, and more closely resemble traditional platforms such as eBay, Esty, or Mercari. These marketplaces focus predominantly on enabling efficient transactions, often providing payment infrastructure to accept both credit cards and crypto payments in Bitcoin, Ethereum, and occasionally other specialty tokens. They offer minimal additional services, and because of their breadth, these platforms generally have fairly large and varied user bases.</p><p>Augmented marketplaces, on the other hand, tend to focus on narrower niches, and offer numerous value-added services such as minting (creating the NFT itself), marketing, curation, pricing recommendations, portfolio trackers, and even full-blown games built on top of the NFTs. For example, the NBA’s Top Shop focuses exclusively on basketball collectibles that the platform packages and markets, SuperRare focuses on visual art and provides extensive curation and recommendation services, and Sorare, which focuses on digital sports cards, hosts fantasy soccer competitions that incorporate the cards users buy on the platform.</p><p>These specialty services can add a lot of value, but of course, they come at a cost. To account for the resources required to build out, integrate, and support an array of customized tools and experiences, augmented platforms generally have a higher “take rate,” or transaction fee, as well as higher upfront setup costs. Streamlined marketplaces typically have lower initial and ongoing costs, but may require sellers to invest their own resources or hire external experts to design, mint, and market their NFTs.</p><h3>How can I engage with the market?</h3><p>So, how can you determine which type of platform is the best fit for your business? Companies with a large pool of intellectual property and a target audience within a specific domain may find it beneficial to partner with an augmented platform. A larger quantity of monetizable content generally means a larger upfront investment is more likely to pay off, and these specialized platforms can draw on their niche experience to ensure a successful launch and drive additional value through secondary tools and services.</p><p>If you’re not sure what kinds of specialized services might be a good fit for your business, it’s worth looking to other creators’ NFT experiments for inspiration. For example, artists may leverage these platforms to offer exclusive video content, or sports teams might include a free meet-and-greet or VIP upgrade with NFT purchases. McLaren Racing <a href="https://www.mclaren.com/racing/partners/tezos/mclaren-racing-creates-mclaren-racing-collective/">recently launched</a> a program where fans can collect various components of a Formula 1 race car in digital form, and the first fan to collect all 22 of the NFTs required to assemble a complete digital version of the car will win an all-expenses-paid trip to a Formula 1 race.</p><p>In addition, some augmented platforms offer detailed data analytics around when other NFTs on the market were minted, how many NFTs competitors are minting, average prices, sales numbers, and more. Firms can then use this data to make informed choices about how they mint and price their own digital offerings. For example, NBA Top Shot offers a detailed <a href="https://nbatopshot.com/listings/p2p/9a009433-a0f7-4f02-80a1-59c2837b7384+337b3188-77be-4109-8819-fb771534bffb">analytics page</a> for each NFT that includes a breakdown of related market activity, ownership history, and other information about the video highlight. Similarly, electronic music marketplace <a href="https://mkt.rcrdshp.com/">RCRDSHP</a> presents users with extensive analytics on both individual NFTs and on the overall state of the market. Although these industry-specific platforms may have narrower reach, they can be extremely effective within a given market — Sorare, for example, generated nearly <a href="https://cryptoslam.io/sorare/sales/summary">$20 million</a> in transaction volume last month and over <a href="https://cryptoslam.io/">$100 million</a> in the past year.</p><p>For products with broader appeal, however, companies and creators may be better off partnering with a streamlined marketplace. For example, Coca-Cola partnered with OpenSea to auction off a <a href="https://opensea.io/assets/0x455f04c9c54fffa699e9f6b1271e857a1f2bddfa/1">“Loot Box” NFT</a> that included digital versions of a vintage Coca-Cola cooler, jacket, and logo, as well as a real, fully-stock Coca-Cola refrigerator delivered to the winner’s home. It was a simple enough offering that didn’t require much in the way of custom, industry-specific specialization, and so OpenSea’s streamlined platform was a good fit. (The NFT collection ultimately sold for over <a href="https://www.coca-colacompany.com/news/coca-cola-nft-auction-fetches-more-than-575000">$575,000</a>, which Coca-Cola donated to Special Olympics International.)</p><h3>What will the future hold?</h3><p>At this point, you may be asking yourself which of these many platforms is likely to emerge as the Amazon-like industry standard. Traditional marketplaces tend to exhibit winner-takes-all dynamics, meaning that once a single platform achieves scale, it becomes nearly impossible for competitors to overtake it — and so, it’s only natural to be concerned about investing in a platform that won’t be made obsolete. However, in contrast to traditional markets, we believe that no single NFT platform is likely to assume such a dominant position. There are two key reasons for this:</p><p>First, NFT markets are inherently more open than their traditional counterparts. Since NFTs are built on fully public blockchain infrastructure, most transaction data is publicly available, limiting the extent to which these platforms can build the kinds of data moats that lead to monopolies.</p><p>In addition, the success of augmented platforms suggests that differentiation is highly valuable to both buyers and sellers. We’re already seeing that there’s strong demand for multiple coexisting NFT marketplaces, each focused on a different domain and offering specialized tools to help their partners succeed. Even within industries, multiple platforms can coexist, as long as they differentiate in the tools and experiences that they provide. For example, one NFT art platform might specialize in minting functionality, while another might focus on gaming experiences built on top of art NFTs.</p><p>While winner-take-all dynamics may be more likely among streamlined platforms, where the marketplace that provides the lowest cost transactions will likely attract a majority of both buyers and sellers, these platforms will never offer the degree of customization and industry-specific support made possible by a wide array of augmented platforms. And investors seem to agree: While streamlined platforms have certainly <a href="https://venturebeat.com/2021/07/20/opensea-raises-100m-at-1-5b-valuation-for-nft-marketplace/">done well</a>, augmented platforms have also had no trouble attracting funding, with Dapper Labs securing a <a href="https://www.coindesk.com/business/2021/09/22/dapper-labs-said-to-reach-76b-valuation-in-250m-funding-round/">$7.6 billion valuation</a> and Sorare raising a record-breaking <a href="https://techcrunch.com/2021/09/20/sorare-raises-680-million-for-its-fantasy-sports-nft-game/">$680 million</a> at a $4.3 billion valuation.</p><p>So, if you’re a creator, don’t feel like you have to wait for the “Amazon of NFTs” to emerge. Evaluate the marketplaces that are currently available based on how well they fit with your unique offerings and business needs, and if you find one that seems well-suited for you, go ahead and dip in a toe.</p><p>While NFTs are still a burgeoning industry, they have demonstrated the potential to be highly lucrative, creating real value for both buyers and sellers. They may have started out as a science project driven largely by crypto enthusiasts and risk-loving, tech-savvy artists, but NFTs are now rapidly entering the mainstream. Whether you’re a major brand like the NBA or an up-and-coming independent artist, partnering with the right platform is the critical first step to drive customer engagement and secure your position in this new digital economy.</p><p>Thanks for reading my post. I am providing service of building NFT market place. If you are interested in please contact me.</p><p>telegram : <a href="https://t.me/smile0307">https://t.me/smile0307</a></p><p>email : <a href="/service/mailto:ImamEugenaU2K@gmail.com">ImamEugenaU2K@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=852c2c8bc1b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Guide to Full Stack Solana Development with React, Anchor, Rust, and Phantom]]></title>
            <link>https://medium.com/@smile0307/the-complete-guide-to-full-stack-solana-development-with-react-anchor-rust-and-phantom-1f37bdd23ac?source=rss-3f6da6942a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f37bdd23ac</guid>
            <dc:creator><![CDATA[Sol Tech]]></dc:creator>
            <pubDate>Wed, 25 May 2022 08:53:14 GMT</pubDate>
            <atom:updated>2022-05-25T08:53:14.994Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Full Stack dapps with React, Solana, Anchor, and Phantom wallet.</h3><p>In this guide, I want to dive into Solana to show you how to build a full stack dapp. I also want to introduce the the ecosystem and the developer tooling to you to hopefully help you get up and running building your own ideas and applications going forward.</p><p>The code for the project is located <a href="https://github.com/smile930307/complete-guide-to-full-stack-solana-development">here</a></p><h3>Solana developer overview</h3><p>As someone who just started learning Solidity and its ecosystem about 6 months ago, I kind of assumed it couldn’t be that much harder to get up and running with. I was wrong.</p><p>Parts of the developer tooling are really nice and polished (the Solana CLI and Anchor), while the rest of the ecosystem, and even the documentation for Anchor (which to be fair, is very new), leaves a decent amount to be desired.</p><p>That being said, once you get the hang of everything it quickly becomes much easier to understand how to start implementing your own ideas and begin experimenting.</p><p>One of the keys to finding answers is to be vigilant about searching across all of Google, Github, and especially the various Discord servers for <a href="https://discord.gg/ZCHmqvXgDw">Anchor</a> and Solana. The developers in those channels have been extremely helpful, especially <a href="https://twitter.com/armaniferrante">Armani Ferrante</a> who created the Anchor framework. Get familiar with the search feature, you can often find answers to your questions in past discussions in Discord.</p><h3>Project overview</h3><p>The tooling we’ll be using today includes:</p><p><a href="https://docs.solana.com/cli/install-solana-cli-tools">Solana Tool Suite</a> — This includes a really polished and well documented CLI for interacting with the Solana network.</p><p><a href="https://project-serum.github.io/anchor/getting-started/introduction.html">Anchor Framework</a> — Anchor is actually a life saver for me, and I’m almost certain I would not have been able to get over the hump of building anything without it. It is the <a href="https://hardhat.org/">Hardhat</a> of Solana development and more, and I love it. It also offers a DSL on top of Rust so that you do not need a deep understanding of the language to get started, though I am still trying to learn Rust as it will probably be useful to build anything non-trivial, even with the DSL. A good free place to learn Rust is <a href="https://doc.rust-lang.org/book/title-page.html">The Rust Book</a>.</p><p><a href="https://solana-labs.github.io/solana-web3.js/">solana/web3.js</a> — A Solana version of <a href="https://web3js.readthedocs.io/">web3.js</a> that seems to work pretty well, but the documentation was almost unusable for me</p><p><a href="https://reactjs.org/">React</a> — The client-side framework</p><p>I will leave off all of the in depth details around how Solana itself works, as other people can cover this better than me. Instead I’ll try to just focus on building something and sharing the details that you need to be know to accomplish this, along with things I think are of utmost importance.</p><p>If you want to learn more about Solana and how it works, here are a few good pieces:</p><ul><li><a href="https://docs.solana.com/introduction">Solana Docs Introduction</a></li><li><a href="https://2501babe.github.io/posts/solana101.html">ok so what the fuck is the deal with solana anyway</a></li><li><a href="https://www.notboring.co/p/solana-summer">Solana Summer</a></li></ul><p>In this guide we’ll focus mainly on project setup, testing, and front end client integration for building out a couple of types of applications, mainly focused on CRUD operations (without the delete of course), which I found to be somewhat undocumented (integration with client applications).</p><p>We’ll also learn how to airdrop tokens to our own development accounts using the Solana CLI, and deploy our apps to both a local network as well as a live test network.</p><p>We won’t be focusing on NFTs in this guide, but maybe I will focus on doing that in a future guide. For now, if you’re interested in building an NFT marketplace on Solana, I recommend checking out <a href="https://www.metaplex.com/">Metaplex</a>.</p><h3>Prerequisites</h3><p>This tutorial covers how to build a full stack app on Solana, but does not go into how to install all of the individual dependencies.</p><p>Instead, I will list the dependencies and link to the documentation for how to install them, as each project will be able to explain and document these things better than I ever could, as well as keep them up to date.</p><ol><li>Node.js — I recommend installing Node using either <a href="https://github.com/nvm-sh/nvm">nvm</a> or <a href="https://github.com/Schniz/fnm">fnm</a></li><li>Solana Tool Suite — You can see the installation instructions <a href="https://docs.solana.com/cli/install-solana-cli-tools">here</a>. <em>note — If you have any issues installing Solana on an M1 Mac, try </em><a href="https://docs.solana.com/cli/install-solana-cli-tools#build-from-source"><em>building from source</em></a><em> and check out </em><a href="https://dev.to/nickgarfield/how-to-install-solana-dev-tools-on-an-m1-mac-kfn"><em>this guide</em></a><em>.</em></li><li>Anchor (including the <a href="https://project-serum.github.io/anchor/getting-started/installation.html#install-mocha">Mocha</a> installation) — Anchor installation was pretty straight-forward for me. You can find the installation instructions <a href="https://project-serum.github.io/anchor/getting-started/installation.html">here</a>.</li><li>Solana browser wallet — I recommend <a href="https://phantom.app/">Phantom</a>, which is what I have tested this app with.</li></ol><h3>Getting Started</h3><p>Before we get started building, let’s take a look at the Solana CLI.</p><h3>Solana CLI</h3><p>The main things we’ll be doing with the Solana CLI will be configuring our network (between localhost and a developer testnet) as well as airdropping tokens into our wallets, pretty much everything else we’ll be doing with the Anchor CLI.</p><p>For instance, we can check the current network (and other) configuration with this command:</p><pre>solana config get<br><br># output<br>Config File: /Users/user/.config/solana/cli/config.yml<br>RPC URL: https://api.devnet.solana.com<br>WebSocket URL: wss://api.devnet.solana.com/ (computed)<br>Keypair Path: /Users/user/.config/solana/id.json<br>Commitment: confirmed</pre><blockquote><em>If you do not have a </em><em>Keypair path, set one up by following the instructions </em><a href="https://docs.solana.com/wallet-guide/paper-wallet#seed-phrase-generation"><em>here</em></a></blockquote><p>We can change the network like so:</p><pre># set to localhost<br>solana config set --url localhost</pre><pre># set to devnet<br>solana config set --url devnet</pre><p>This is important as you will need to be aware of which network you are using as you’re building, testing, and deploying your programs. You also need to be sure your wallet is using the same network that your local environment is using when testing, something I’ll cover.</p><p>We’ll be starting by developing on a localhost network, then switching to the devnet network.</p><p>We can also use the CLI to see our current local wallet address:</p><pre>solana address</pre><p>And then get the full details about an account:</p><pre>solana account &lt;address from above&gt;</pre><p>Next let’s airdrop some tokens. To do so, first switch to the local network, as this is where we will be working to start off with:</p><pre>solana config set --url localhost</pre><p>Next, start the local network. This is going to be a local Solana node that we can deploy to for testing:</p><pre>solana-test-validator</pre><p>Once the local network is running, you can airdrop tokens to your account. With the network running, open a separate window and run the following command:</p><pre>solana airdrop 100</pre><p>You can the check the balance of your wallet:</p><pre>solana balance</pre><pre># or</pre><pre>solana balance &lt;address&gt;</pre><p>You should now have a balance 100 SOL in your wallet. With that, we can get started building.</p><h3>Let’s start building</h3><p>To get started, initialize a new anchor project and change into the new directory:</p><pre>anchor init mysolanaapp --javascript</pre><pre>cd mysolanaapp</pre><blockquote><em>Be sure to use Anchor version 0.16.0 or later.</em></blockquote><p>In this project, you’ll see four main folders (in addition to the <strong>node_modules</strong>):</p><p><strong>app</strong> — Where our frontend code will go</p><p><strong>programs</strong> — This is where the Rust code lives for the Solana program</p><p><strong>test</strong> — Where the JavaScript tests for the program live</p><p><strong>migrations</strong> — A basic deploy script</p><p>Let’s take a look at the program that was created for us.</p><p>Anchor uses, and enables us to write, an eDSL (<a href="https://en.wikipedia.org/wiki/Domain-specific_language#:~:text=embedded%20domain%2Dspecific%20language%20(eDSL,methods%2C%20macros%20etc.).">embedded DSL</a>) that abstracts away many of the more complex low level operations you’d typically need to do if you were using Solana &amp; Rust without it, making it more approachable for me.</p><pre>// programs/src/lib.rs<br>use anchor_lang::prelude::*;<br><br>declare_id!(&quot;Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS&quot;);<br><br>#[program]<br>pub mod mysolanaapp {<br>    use super::*;<br>    pub fn initialize(ctx: Context&lt;Initialize&gt;) -&gt; ProgramResult {<br>        Ok(())<br>    }<br>}<br><br>#[derive(Accounts)]<br>pub struct Initialize {}</pre><p>This is probably the most basic program you can write. The only thing happening here is we are defining a function called initialize, which when invoked just exits the program successfully. There is no data manipulation at all.</p><p>The Initialize struct defines the context as being empty of any arguments. We&#39;ll learn more about the function context later.</p><p>To compile this program, we can run the Anchor build command:</p><pre>anchor build</pre><p>Once a build is completed, you should see a new folder named <strong>target</strong>.</p><p>One of the artifacts created is an <a href="https://en.wikipedia.org/wiki/Interface_description_language">IDL</a> located at <strong>target/idl/mysolanaapp.json</strong>.</p><p>IDLs are very similar to an <a href="https://docs.soliditylang.org/en/v0.5.3/abi-spec.html">ABI</a> in Solidity (or a query definition in GraphQL), and we will be using them in a similar way in our JavaScript tests and frontends to communicate with our Solana program via RPC.</p><p>We can also test out our program. If you open <strong>tests/mysolanaapp.js</strong>, you will see that there is a test written in JavaScript that allows us to test out the program.</p><p>The test should look like this:</p><pre>const anchor = require(&#39;@project-serum/anchor&#39;);<br><br>describe(&#39;mysolanaapp&#39;, () =&gt; {<br>  // Configure the client to use the local cluster.<br>  anchor.setProvider(anchor.Provider.env());<br><br>  it(&#39;Is initialized!&#39;, async () =&gt; {<br>    const program = anchor.workspace.Mysolanaapp;<br>    const tx = await program.rpc.initialize();<br>    console.log(&quot;Your transaction signature&quot;, tx);<br>  });<br>});</pre><p>There are a couple of things to learn from this test that are important and we’ll be using in the future, both in our tests as well as in the front end JavaScript clients.</p><p>To call a Solana program using Anchor, we typically need two main things:</p><p><strong>1. </strong><strong>Provider</strong> - The Provider is an abstraction of a connection to the Solana network, typically consisting of a <a href="https://solana-labs.github.io/solana-web3.js/classes/Connection.html">Connection</a>, Wallet, and a <a href="https://solana-labs.github.io/solana-web3.js/modules.html#Commitment">preflight commitment</a>.</p><p>In the test, the Anchor framework will create the provider for us based on the environment (anchor.Provider.env()), but on the client we will need to construct the Provider ourselves using the user&#39;s Solana wallet.</p><p><strong>2. </strong><strong>program</strong> - The program is an abstraction that combines the Provider, idl, and the programID (which is generated when the program is built) and allows us to call RPC methods against our program.</p><p>Again, like with the Provider, Anchor offers a convenient way to access the program, but when building out the front end we&#39;ll need to construct this provider ourselves.</p><p>Once we have these two things, we can start calling functions in our program. For example, in our program we have an initialize function. In our test, you&#39;ll see we can invoke that function directly using program.rpc.functionName:</p><pre>const tx = await program.rpc.initialize();</pre><p>This is a very common pattern that you’ll use a lot when working with Anchor, and once you get the hang of understanding how it works, makes it really easy to connect to and interact with a Solana program.</p><p>We can now test the program by running the test script:</p><pre>anchor test</pre><h3>Building Hello World</h3><p>Now that we have our project setup, let’s create something a little more interesting.</p><p>I know that, as a full stack developer, most of the time I’m wondering how to do <a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> types of operations, so that’s what we’ll look at next.</p><p>The first program we’ll create will allow us to create a counter that increments every time we call it from a client application.</p><p>The first thing we need to do is open <strong>programs/mysolanaapp/src/lib.rs</strong> and update it with the following code:</p><pre>use anchor_lang::prelude::*;<br><br>declare_id!(&quot;Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS&quot;);<br><br>#[program]<br>mod mysolanaapp {<br>    use super::*;<br><br>    pub fn create(ctx: Context&lt;Create&gt;) -&gt; ProgramResult {<br>        let base_account = &amp;mut ctx.accounts.base_account;<br>        base_account.count = 0;<br>        Ok(())<br>    }<br><br>    pub fn increment(ctx: Context&lt;Increment&gt;) -&gt; ProgramResult {<br>        let base_account = &amp;mut ctx.accounts.base_account;<br>        base_account.count += 1;<br>        Ok(())<br>    }<br>}<br><br>// Transaction instructions<br>#[derive(Accounts)]<br>pub struct Create&lt;&#39;info&gt; {<br>    #[account(init, payer = user, space = 16 + 16)]<br>    pub base_account: Account&lt;&#39;info, BaseAccount&gt;,<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,<br>    pub system_program: Program &lt;&#39;info, System&gt;,<br>}<br><br>// Transaction instructions<br>#[derive(Accounts)]<br>pub struct Increment&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub base_account: Account&lt;&#39;info, BaseAccount&gt;,<br>}<br><br>// An account that goes inside a transaction instruction<br>#[account]<br>pub struct BaseAccount {<br>    pub count: u64,<br>}</pre><p>In this program we have two functions — create and increment. These two functions are the RPC request handlers that we will be able to call from a client application to interact with the program.</p><p>The first parameter of an RPC handler is the Context struct, which describes the context that will be passed in when the function is called and how to handle it. In the case of Create, we are expecting three parameters: base_account, user, and system_program.</p><p>The #[account(...)] attributes define constraints and instructions that are related to the proceeding account where declared. If any of these constraints do not hold, then the instruction will never execute.</p><p>Any client calling this program with the proper base_account can call these RPC methods.</p><p>The way that Solana deals with data is much different than anything I’ve ever worked with. There is no persisted state within the program, everything is attached to what are known as accounts. An account essentially holds all of the state of a program. Because of this, all data is passed by reference from the outside.</p><p>There are also no read operations. This is because all you need to do to read the contents of a program is to request the account, from there you are able to view all of the program’s state. To read more about how accounts work, check out <a href="https://2501babe.github.io/posts/solana101.html#programs-and-accounts">this post</a>.</p><p>To build the program:</p><pre>anchor build</pre><p>Next, let’s write a test that uses this counter program. To do so, open <strong>tests/mysolanaapp.js</strong> and update with the following code:</p><pre>const assert = require(&quot;assert&quot;);<br>const anchor = require(&quot;@project-serum/anchor&quot;);<br>const { SystemProgram } = anchor.web3;<br><br>describe(&quot;mysolanaapp&quot;, () =&gt; {<br>  /* create and set a Provider */<br>  const provider = anchor.Provider.env();<br>  anchor.setProvider(provider);<br>  const program = anchor.workspace.Mysolanaapp;<br>  it(&quot;Creates a counter)&quot;, async () =&gt; {<br>    /* Call the create function via RPC */<br>    const baseAccount = anchor.web3.Keypair.generate();<br>    await program.rpc.create({<br>      accounts: {<br>        baseAccount: baseAccount.publicKey,<br>        user: provider.wallet.publicKey,<br>        systemProgram: SystemProgram.programId,<br>      },<br>      signers: [baseAccount],<br>    });<br><br>    /* Fetch the account and check the value of count */<br>    const account = await program.account.baseAccount.fetch(baseAccount.publicKey);<br>    console.log(&#39;Count 0: &#39;, account.count.toString())<br>    assert.ok(account.count.toString() == 0);<br>    _baseAccount = baseAccount;<br><br>  });<br><br>  it(&quot;Increments the counter&quot;, async () =&gt; {<br>    const baseAccount = _baseAccount;<br><br>    await program.rpc.increment({<br>      accounts: {<br>        baseAccount: baseAccount.publicKey,<br>      },<br>    });<br><br>    const account = await program.account.baseAccount.fetch(baseAccount.publicKey);<br>    console.log(&#39;Count 1: &#39;, account.count.toString())<br>    assert.ok(account.count.toString() == 1);<br>  });<br>});</pre><p>Before we continue to test and deploy the program, we want to get the dynamically generated Program ID that was generated by the build. We need this ID to use in the Rust program to replace the placeholder ID we set up when we created the project. To get this ID, we can run the following command:</p><pre>solana address -k target/deploy/mysolanaapp-keypair.json</pre><p>We can now update the program IDs in <strong>lib.rs</strong>:</p><pre>// mysolanaapp/src/lib.rs</pre><pre>declare_id!(&quot;your-program-id&quot;);</pre><p>And in <strong>Anchor.toml</strong>:</p><pre># Anchor.toml<br>[programs.localnet]<br>mysolanaapp = &quot;your-program-id&quot;</pre><p>Next, run the test:</p><pre>anchor test</pre><p>Once the test passes, we can now deploy.</p><p>We can now deploy the program. Be sure that solana-test-validator is running:</p><pre>anchor deploy</pre><blockquote><em>You can also view the validator logging by opening a separate window and running </em><em>solana logs</em></blockquote><p>Now we’re ready to build out the front end.</p><h3>Building the React app</h3><p>In the root of the Anchor project, create a new react app to overwrite the existing <strong>app</strong> directory:</p><pre>npx create-react-app app</pre><p>Next, install the dependencies we’ll need for Anchor and Solana Web3:</p><pre>cd app</pre><pre>npm install @project-serum/anchor @solana/web3.js</pre><p>We’ll also be using <a href="https://github.com/solana-labs/wallet-adapter">Solana Wallet Adapter</a> to handle connecting the user’s Solana wallet. Let’s install those dependencies as well:</p><pre>npm install @solana/wallet-adapter-react \<br>@solana/wallet-adapter-react-ui @solana/wallet-adapter-wallets \<br>@solana/wallet-adapter-base</pre><p>Next, in the <strong>src</strong> directory, create a new file named <strong>idl.json</strong>. Here, copy the IDL JSON that was created for you in the main project folder, located at <strong>target/idl/mysolanaapp.json</strong>.</p><p>It would be nice if we could copy this <strong>idl</strong> file automatically to our client application <strong>src</strong> folder, but as of now I have not found a way to do this natively. You can of course create your own script that does this if you’d like, or else you need to copy and paste over the IDL after every change to your main program.</p><p>If you want a script like this, you can do it in just a couple of lines of code:</p><pre>// copyIdl.js<br>const fs = require(&#39;fs&#39;);<br>const idl = require(&#39;./target/idl/mysolanaapp.json&#39;);</pre><pre>fs.writeFileSync(&#39;./app/src/idl.json&#39;, JSON.stringify(idl));</pre><p>Next, open <strong>app/src/App.js</strong> and update it with the following:</p><pre>import &#39;./App.css&#39;;<br>import { useState } from &#39;react&#39;;<br>import { Connection, PublicKey } from &#39;@solana/web3.js&#39;;<br>import {<br>  Program, Provider, web3<br>} from &#39;@project-serum/anchor&#39;;<br>import idl from &#39;./idl.json&#39;;</pre><pre>import { PhantomWalletAdapter } from &#39;@solana/wallet-adapter-wallets&#39;;<br>import { useWallet, WalletProvider, ConnectionProvider } from &#39;@solana/wallet-adapter-react&#39;;<br>import { WalletModalProvider, WalletMultiButton } from &#39;@solana/wallet-adapter-react-ui&#39;;<br>require(&#39;@solana/wallet-adapter-react-ui/styles.css&#39;);</pre><pre>const wallets = [<br>  /* view list of available wallets at https://github.com/solana-labs/wallet-adapter#wallets */<br>  new PhantomWalletAdapter()<br>]</pre><pre>const { SystemProgram, Keypair } = web3;<br>/* create an account  */<br>const baseAccount = Keypair.generate();<br>const opts = {<br>  preflightCommitment: &quot;processed&quot;<br>}<br>const programID = new PublicKey(idl.metadata.address);</pre><pre>function App() {<br>  const [value, setValue] = useState(null);<br>  const wallet = useWallet();</pre><pre>  async function getProvider() {<br>    /* create the provider and return it to the caller */<br>    /* network set to local network for now */<br>    const network = &quot;http://127.0.0.1:8899&quot;;<br>    const connection = new Connection(network, opts.preflightCommitment);</pre><pre>    const provider = new Provider(<br>      connection, wallet, opts.preflightCommitment,<br>    );<br>    return provider;<br>  }</pre><pre>  async function createCounter() {    <br>    const provider = await getProvider()<br>    /* create the program interface combining the idl, program ID, and provider */<br>    const program = new Program(idl, programID, provider);<br>    try {<br>      /* interact with the program via rpc */<br>      await program.rpc.create({<br>        accounts: {<br>          baseAccount: baseAccount.publicKey,<br>          user: provider.wallet.publicKey,<br>          systemProgram: SystemProgram.programId,<br>        },<br>        signers: [baseAccount]<br>      });</pre><pre>      const account = await program.account.baseAccount.fetch(baseAccount.publicKey);<br>      console.log(&#39;account: &#39;, account);<br>      setValue(account.count.toString());<br>    } catch (err) {<br>      console.log(&quot;Transaction error: &quot;, err);<br>    }<br>  }</pre><pre>  async function increment() {<br>    const provider = await getProvider();<br>    const program = new Program(idl, programID, provider);<br>    await program.rpc.increment({<br>      accounts: {<br>        baseAccount: baseAccount.publicKey<br>      }<br>    });</pre><pre>    const account = await program.account.baseAccount.fetch(baseAccount.publicKey);<br>    console.log(&#39;account: &#39;, account);<br>    setValue(account.count.toString());<br>  }</pre><pre>  if (!wallet.connected) {<br>    /* If the user&#39;s wallet is not connected, display connect wallet button. */<br>    return (<br>      &lt;div style={{ display: &#39;flex&#39;, justifyContent: &#39;center&#39;, marginTop:&#39;100px&#39; }}&gt;<br>        &lt;WalletMultiButton /&gt;<br>      &lt;/div&gt;<br>    )<br>  } else {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;div&gt;<br>          {<br>            !value &amp;&amp; (&lt;button onClick={createCounter}&gt;Create counter&lt;/button&gt;)<br>          }<br>          {<br>            value &amp;&amp; &lt;button onClick={increment}&gt;Increment counter&lt;/button&gt;<br>          }</pre><pre>          {<br>            value &amp;&amp; value &gt;= Number(0) ? (<br>              &lt;h2&gt;{value}&lt;/h2&gt;<br>            ) : (<br>              &lt;h3&gt;Please create the counter.&lt;/h3&gt;<br>            )<br>          }<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>/* wallet configuration as specified here: https://github.com/solana-labs/wallet-adapter#setup */<br>const AppWithProvider = () =&gt; (<br>  &lt;ConnectionProvider endpoint=&quot;http://127.0.0.1:8899&quot;&gt;<br>    &lt;WalletProvider wallets={wallets} autoConnect&gt;<br>      &lt;WalletModalProvider&gt;<br>        &lt;App /&gt;<br>      &lt;/WalletModalProvider&gt;<br>    &lt;/WalletProvider&gt;<br>  &lt;/ConnectionProvider&gt;<br>)</pre><pre>export default AppWithProvider;</pre><h3>Hello World part 2</h3><p>Let’s create a variation of this program that, instead of dealing with a counter, allows us to create a message and keep track of all of the previously created messages.</p><p>To do so, let’s update our Rust program to look like this:</p><pre>/* programs/mysolanaapp/src/lib.rs */<br>use anchor_lang::prelude::*;<br><br>declare_id!(&quot;your-program-id&quot;);<br><br>#[program]<br>mod mysolanaapp {<br>    use super::*;<br><br>    pub fn initialize(ctx: Context&lt;Initialize&gt;, data: String) -&gt; ProgramResult {<br>        let base_account = &amp;mut ctx.accounts.base_account;<br>        let copy = data.clone();<br>        base_account.data = data;<br>        base_account.data_list.push(copy);<br>        Ok(())<br>    }<br><br>    pub fn update(ctx: Context&lt;Update&gt;, data: String) -&gt; ProgramResult {<br>        let base_account = &amp;mut ctx.accounts.base_account;<br>        let copy = data.clone();<br>        base_account.data = data;<br>        base_account.data_list.push(copy);<br>        Ok(())<br>    }<br>}<br><br>#[derive(Accounts)]<br>pub struct Initialize&lt;&#39;info&gt; {<br>    #[account(init, payer = user, space = 64 + 64)]<br>    pub base_account: Account&lt;&#39;info, BaseAccount&gt;,<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}<br><br>#[derive(Accounts)]<br>pub struct Update&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub base_account: Account&lt;&#39;info, BaseAccount&gt;,<br>}<br><br>#[account]<br>pub struct BaseAccount {<br>    pub data: String,<br>    pub data_list: Vec&lt;String&gt;,<br>}</pre><p>In this program we have two main pieces of data we’re keeping track of, a String named data and a Vector that holds a list of all data ever added to the program named data_list.</p><p>You’ll notice that the memory allocation here is higher (128 + 128) than the previous program in order to account for the Vector. I don&#39;t know how many updates you&#39;d be able to store in this program as is, but may be something to investigate more or experiment with, as this example in and of itself is experimental and just to give you an understanding of how things work.</p><p>Next, we can update the test for this new program:</p><pre>const assert = require(&quot;assert&quot;);<br>const anchor = require(&quot;@project-serum/anchor&quot;);<br>const { SystemProgram } = anchor.web3;<br><br>describe(&quot;Mysolanaapp&quot;, () =&gt; {<br>  const provider = anchor.Provider.env();<br>  anchor.setProvider(provider);<br>  const program = anchor.workspace.Mysolanaapp;<br>  it(&quot;It initializes the account&quot;, async () =&gt; {<br>    const baseAccount = anchor.web3.Keypair.generate();<br>    await program.rpc.initialize(&quot;Hello World&quot;, {<br>      accounts: {<br>        baseAccount: baseAccount.publicKey,<br>        user: provider.wallet.publicKey,<br>        systemProgram: SystemProgram.programId,<br>      },<br>      signers: [baseAccount],<br>    });<br><br>    const account = await program.account.baseAccount.fetch(baseAccount.publicKey);<br>    console.log(&#39;Data: &#39;, account.data);<br>    assert.ok(account.data === &quot;Hello World&quot;);<br>    _baseAccount = baseAccount;<br><br>  });<br><br>  it(&quot;Updates a previously created account&quot;, async () =&gt; {<br>    const baseAccount = _baseAccount;<br><br>    await program.rpc.update(&quot;Some new data&quot;, {<br>      accounts: {<br>        baseAccount: baseAccount.publicKey,<br>      },<br>    });<br><br>    const account = await program.account.baseAccount.fetch(baseAccount.publicKey);<br>    console.log(&#39;Updated data: &#39;, account.data)<br>    assert.ok(account.data === &quot;Some new data&quot;);<br>    console.log(&#39;all account data:&#39;, account)<br>    console.log(&#39;All data: &#39;, account.dataList);<br>    assert.ok(account.dataList.length === 2);<br>  });<br>});</pre><p>To test it out:</p><pre>anchor test</pre><blockquote><em>If the test fails, try turning off the validator and then running again.</em></blockquote><p>Next, let’s update the client.</p><pre>/* app/src/App.js */<br>import &#39;./App.css&#39;;<br>import { useState } from &#39;react&#39;;<br>import { Connection, PublicKey } from &#39;@solana/web3.js&#39;;<br>import { Program, Provider, web3 } from &#39;@project-serum/anchor&#39;;<br>import idl from &#39;./idl.json&#39;;</pre><pre>import { PhantomWalletAdapter } from &#39;@solana/wallet-adapter-wallets&#39;;<br>import { useWallet, WalletProvider, ConnectionProvider } from &#39;@solana/wallet-adapter-react&#39;;<br>import { WalletModalProvider, WalletMultiButton } from &#39;@solana/wallet-adapter-react-ui&#39;;<br>require(&#39;@solana/wallet-adapter-react-ui/styles.css&#39;);</pre><pre>const wallets = [ new PhantomWalletAdapter() ]</pre><pre>const { SystemProgram, Keypair } = web3;<br>const baseAccount = Keypair.generate();<br>const opts = {<br>  preflightCommitment: &quot;processed&quot;<br>}<br>const programID = new PublicKey(idl.metadata.address);</pre><pre>function App() {<br>  const [value, setValue] = useState(&#39;&#39;);<br>  const [dataList, setDataList] = useState([]);<br>  const [input, setInput] = useState(&#39;&#39;);<br>  const wallet = useWallet()</pre><pre>  async function getProvider() {<br>    /* create the provider and return it to the caller */<br>    /* network set to local network for now */<br>    const network = &quot;http://127.0.0.1:8899&quot;;<br>    const connection = new Connection(network, opts.preflightCommitment);</pre><pre>    const provider = new Provider(<br>      connection, wallet, opts.preflightCommitment,<br>    );<br>    return provider;<br>  }</pre><pre>  async function initialize() {    <br>    const provider = await getProvider();<br>    /* create the program interface combining the idl, program ID, and provider */<br>    const program = new Program(idl, programID, provider);<br>    try {<br>      /* interact with the program via rpc */<br>      await program.rpc.initialize(&quot;Hello World&quot;, {<br>        accounts: {<br>          baseAccount: baseAccount.publicKey,<br>          user: provider.wallet.publicKey,<br>          systemProgram: SystemProgram.programId,<br>        },<br>        signers: [baseAccount]<br>      });</pre><pre>      const account = await program.account.baseAccount.fetch(baseAccount.publicKey);<br>      console.log(&#39;account: &#39;, account);<br>      setValue(account.data.toString());<br>      setDataList(account.dataList);<br>    } catch (err) {<br>      console.log(&quot;Transaction error: &quot;, err);<br>    }<br>  }</pre><pre>  async function update() {<br>    if (!input) return<br>    const provider = await getProvider();<br>    const program = new Program(idl, programID, provider);<br>    await program.rpc.update(input, {<br>      accounts: {<br>        baseAccount: baseAccount.publicKey<br>      }<br>    });</pre><pre>    const account = await program.account.baseAccount.fetch(baseAccount.publicKey);<br>    console.log(&#39;account: &#39;, account);<br>    setValue(account.data.toString());<br>    setDataList(account.dataList);<br>    setInput(&#39;&#39;);<br>  }</pre><pre>  if (!wallet.connected) {<br>    return (<br>      &lt;div style={{ display: &#39;flex&#39;, justifyContent: &#39;center&#39;, marginTop:&#39;100px&#39; }}&gt;<br>        &lt;WalletMultiButton /&gt;<br>      &lt;/div&gt;<br>    )<br>  } else {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;div&gt;<br>          {<br>            !value &amp;&amp; (&lt;button onClick={initialize}&gt;Initialize&lt;/button&gt;)<br>          }</pre><pre>          {<br>            value ? (<br>              &lt;div&gt;<br>                &lt;h2&gt;Current value: {value}&lt;/h2&gt;<br>                &lt;input<br>                  placeholder=&quot;Add new data&quot;<br>                  onChange={e =&gt; setInput(e.target.value)}<br>                  value={input}<br>                /&gt;<br>                &lt;button onClick={update}&gt;Add data&lt;/button&gt;<br>              &lt;/div&gt;<br>            ) : (<br>              &lt;h3&gt;Please Inialize.&lt;/h3&gt;<br>            )<br>          }<br>          {<br>            dataList.map((d, i) =&gt; &lt;h4 key={i}&gt;{d}&lt;/h4&gt;)<br>          }<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>const AppWithProvider = () =&gt; (<br>  &lt;ConnectionProvider endpoint=&quot;http://127.0.0.1:8899&quot;&gt;<br>    &lt;WalletProvider wallets={wallets} autoConnect&gt;<br>      &lt;WalletModalProvider&gt;<br>        &lt;App /&gt;<br>      &lt;/WalletModalProvider&gt;<br>    &lt;/WalletProvider&gt;<br>  &lt;/ConnectionProvider&gt;<br>)</pre><pre>export default AppWithProvider;</pre><p>Next, build and deploy the program (be sure that solana-test-validator is running):</p><pre>anchor build</pre><pre>anchor deploy</pre><p>With the new build you’ll have a new <strong>IDL</strong> that you’ll need to update for your client. Either copy over the new IDL to <strong>app/src/idl.json</strong> or run your <strong>copyIdl.js</strong> script.</p><h3>Testing it out</h3><p>When testing out the new program, be sure to update the <strong>idl.json</strong> file that was created by the build.</p><p>Change into the <strong>app</strong> directory and run the start command:</p><pre>npm start</pre><h3>Deploying to Devnet</h3><p>Deploying to a live network is pretty straightforward from here. The main things we need to do are:</p><p><strong>1.</strong> Update the Solana CLI to use devnet:</p><pre>solana config set --url devnet</pre><p><strong>2.</strong> Update Phantom wallet to use devnet</p><p><strong>3.</strong> Open <strong>Anchor.toml</strong> and update the cluster from localnet to devnet.</p><p><strong>4.</strong> Rebuild the program. Be sure the program ID in <strong>Anchor.toml</strong> matches the current program ID.</p><p><strong>5.</strong> Deploy the program again, this time it will be deployed to devnet</p><p><strong>6.</strong> In <strong>app/src/App.js</strong>, we need to also update the network, this time using the clusterApiUrl from @solana/web3, like this:</p><pre>/* before */<br>&lt;ConnectionProvider endpoint=&quot;http://127.0.0.1:8899&quot;&gt;</pre><pre>/* after */<br>import {<br>  ...,<br>  clusterApiUrl<br>} from &#39;@solana/web3.js&#39;;</pre><pre>const network = clusterApiUrl(&#39;devnet&#39;);</pre><pre>&lt;ConnectionProvider endpoint={network}&gt;</pre><p>From here, you should be able to deploy and test as we have done the the previous steps.</p><blockquote><em>The code for this project is located </em><a href="https://github.com/dabit3/complete-guide-to-full-stack-solana-development"><em>here</em></a></blockquote><h3>Next steps</h3><p>Another in depth tutorial I’d suggest checking out next is <a href="https://lorisleiva.com/create-a-solana-dapp-from-scratch">Create a Solana dApp from scratch</a> which implements a simplified version of Twitter as a Solana dapp.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f37bdd23ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to select the correct blockchain fork for launching your own cryptocurrency.]]></title>
            <link>https://medium.com/@smile0307/which-blockchain-to-fork-to-start-your-own-cryptocurrency-16c6cc8a79fd?source=rss-3f6da6942a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/16c6cc8a79fd</guid>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Sol Tech]]></dc:creator>
            <pubDate>Mon, 23 May 2022 13:00:09 GMT</pubDate>
            <atom:updated>2024-05-23T20:42:06.198Z</atom:updated>
            <content:encoded><![CDATA[<p>How many blockchain platforms are there? And which one serves the best for your project implementation? Those are the main questions crossing blockchain entrepreneurs’ minds.</p><p>The need for forking in blockchain growing along with technology adaptation to the various business industries. That is why we want to turn your attention to the question of how to create your own cryptocurrency by forking an existing blockchain. We will analyze a few current successful solutions to help you understand where to start your own cryptocurrency.</p><h3>WHAT IS BLOCKCHAIN FORKING?</h3><p>Blockchain fork is essentially a split of any existing blockchain. Basically, there are two types of forks we can define: soft and hard forks.</p><p>The <strong>soft forks</strong> are those that are aimed to insert functional changes within the network so that the system will remain the same, yet all current nodes should be updated to the new rules.</p><p>The<strong> hard fork usually results in the </strong>creation of new, customized cryptocurrency. An example of such a fork may be BitcoinCash, Dash, EthereumClassic.</p><p>As far as the blockchain codes are open-sourced, anyone can <em>clone git repository</em> and build a similar blockchain environment. This approach is very common for <strong>custom blockchain development</strong> which is aimed to empower the current business solution.</p><p>Yet before I start describing the fundamental criteria for choosing a blockchain platform to fork, let’s define why you need to fork in the first place?</p><h3>WHEN DO YOU NEED A FORK?</h3><p>Answering the question, making a fork of an existing solution is a good choice if you want to get the power of an already existing blockchain but make it more simple or adjust just a couple of your own custom features.</p><p>In addition, blockchain forking is a popular decision if you want to get access to Ethereum EVM technology. To make such, one needs to fork Geth or Parity nodes and then further adjust it according to requirements.</p><p><strong><em>Also making a fork of an existing blockchain fairly saves development costs, as far as the process is not that time-consuming in comparison to starting your own custom cryptocurrency from scratch.</em></strong></p><p>When thinking of any crypto payments adoption there is another important question that occurs: how to choose a blockchain platform to fork?</p><h3>WHICH IS THE BEST BLOCKCHAIN PLATFORM TO MAKE A FORK?</h3><p>We often use Bitcoin or Bitcoin-based as well as Ethereum-based blockchain technologies in order to create a custom cryptocurrency.</p><h3>BITCOIN FORKS</h3><p>Bitcoin technology has the biggest amount of forks simply because it was the first sample of crypto payments. So everyone who wants to create cryptocurrency has at least taken a look at this code.</p><p>I suggest implementing Bitcoin technology in case your business case requires simple payments and ordinary system’s tasks. For the more complex solutions, I recommend considering other Bitcoin or Ethereum-based cryptocurrencies as a foundation to start your own cryptocurrency.</p><h3>DASH BLOCKCHAIN</h3><p><a href="https://www.dash.org/"><strong>Dash</strong></a> is a direct fork of Bitcoin but it has implemented numerous advantages to the initial technology. One of such is an enhancement to the Bitcoin consensus such as usage of X11 hashing algorithms for a low energy consuming PoW and adjustment of masterodes. The use of last allows for a wider list of operational features, for instance, <strong>DAO creation</strong> for protocol governing.</p><p>Also, masternodes are seen as a much secure solution. As far as one should deposit a considerable amount of native cryptocurrency to be able to process a node. This prevents the network from the attacks of potential malicious members.</p><p>Dash uses InstantSend and PivateSend services to ensure secure and fast transactions. The protocol is easy upgradable and adaptable to the node software updates due to usage of SPORKs mechanism.</p><h3>PIVX BLOCKCHAIN</h3><p><a href="https://pivx.org/?hl=en"><strong>PIVX</strong></a> (Private Instant Verified Transactions) is a younger blockchain and represents a fork of Dash with a mix of additional adjustments taken from other solutions.</p><p>PIVIX has taken Bitcoin wallet technology and format along with Dash masternode models. Yet, unlike traditional Bitcoin forks, PIVX uses a proof-of-stake consensus model to enhance transaction speed and blockchain operability.</p><p>Thanks to the usage of SwiftX service PIVX also allows for instant and secure transactions along with adoption of SPORKs mechanism for the better upgradability of nodes.</p><h3>QTUM BLOCKCHAIN</h3><p><a href="https://qtum.org/en"><strong>Qtum</strong></a> is a Bitcoin fork which supports Ethereum EVM and therefore enables smart contract creation. The DGP management integrated into Qtum system allows for adjusting of new blockchain settings with the help of smart contracts reducing the amount of hard forks.</p><p>Unlike previous examples, Qtum uses neither masternodes nor DAO governing for protocol operation. It is based on PoS consensus which allows any user to stake and process a node. Furthermore, Qtum has a very large community that maintains the network, it takes third place after Bitcoin and Ethereum.</p><h3>ETHEREUM FORKS</h3><p>Ethereum blockchain is considered as another best technology to fork to start your own cryptocurrency. Mainly due to the possibility of Solidity smart contracts support.</p><p>In terms of Ethereum blockchain forking, the best and commonly used practice is to fork Geth or Parity nodes. Then, to start your own cryptocurrency, you can customize it as you wish, add required features like custom wallet cryptography and implement the needed consensus model.</p><h3>QUORUM BLOCKCHAIN</h3><p>Consensys <a href="https://consensys.net/quorum/enterprise"><strong>Quorum</strong></a> is the Ethereum-based blockchain fork of the <a href="https://geth.ethereum.org/docs/getting-started"><strong>Geth node</strong></a>. The main aim of Quorum creation is to enable successful blockchain adoption for businesses.</p><p>Unlike traditional Ethereum, Quorum blockchain does not base on PoW. It allows for several consensus models that are more suitable for permissioned consortium chains. It adopted PoA, Raft-based, and Istanbul BTF consensus models running.</p><p>In advance, Quorum also runs its own services for additional transaction encryption. <a href="https://github.com/ConsenSys/quorum"><strong>Tessera and Constellation</strong></a> are in-built systems that allow for generating, encryption, decryption, and distribution of private transactions with additional self-management of all discovered nodes.</p><p><strong><em>In the case of Quorum you can see how the Ethereum blockchain fork can be changed and customized to the unique requirements like adjustment of a few consensus models while eliminating PoW. We can define Avalanche case as the other example of a successful Ethereum fork implementation with further adoption to the network ecosystem.</em></strong></p><h3>AVALANCHE NETWORK</h3><p><a href="https://www.avalabs.org/"><strong>Avalanche</strong></a> is one of the most prominent Ethereum forks while creating not just a single blockchain, but a heterogeneous blockchain protocol for hosting multiple blockchains.</p><p>The Avalanche network is aiming to deal with the biggest Ethereum problem — scalability. The issue is solved due to stepping by the casual Ethereum PoW and using a new version of Proof-of-Stake consensus. The new model allows for an incredible level of finality (around 3 sec per transaction) and an unlimited amount of validators taking part in the consensus.</p><p>In the case of Avalanche, the project adopted the full EVM toolkit from <a href="https://geth.ethereum.org/docs/getting-started"><strong>Ethereum Geth node</strong></a>, so such tools as MetaMask or Truffle are easily accessible. The PoS adoption enables a high-speeded smart contract creation and enormous throughput.</p><h3>MAIN POINTS WHEN CHOOSING THE BEST BLOCKCHAIN FOR FORKING</h3><p>While choosing which blockchain to fork to start your own cryptocurrency, there are a few crucial points to pay attention to. Answering them will help to define which blockchain platform to choose for your <strong>custom cryptocurrency integration</strong>.</p><ol><li><strong><em>Consensus model</em></strong></li><li><strong><em>DAO</em></strong></li><li><strong><em>Masternodes</em></strong></li><li><strong><em>Smart contracts</em></strong></li><li><strong><em>Private transaction services</em></strong></li></ol><p>Let’s take a look at each of them and define the network which fits the best to each of those requirements.</p><h3>CONSENSUS MODEL</h3><p>Previously described blockchain used two types of consensus: PoW (Bitcoin, Dash) and PoS (PIVX, Qtum, Avalanche). This is one of the fundamental things you should choose while making a fork. PoS is considered being a faster and less costly solution as well as providing more energy efficiency.</p><p>Though, you can spend additional efforts on development and adjust consensus to your needs. For example — change Ethereum PoW in Parity node to PoA(proof-of-authority) or PoS to speed up your system.</p><h3>DAO</h3><p>The creation of DAO is crucial in terms of protocol governing. This is also time-consuming and costly if you decide to integrate it into the already existing solution. That is why, if you feel like your project will need a governing layer, it is better to keep an eye on the solutions that have this in-built feature (PIVX, Dash).</p><h3>MASTERNODES</h3><p>Masternodes empower protocol security and provide additional operational features. Moreover, it helps to create a greater incentive mechanism for network members.</p><p>While making a fork, there is a possibility of adjusting masternodes to the client’s requirement and set all needed features (for instance establishing or eliminating masternode fees). So if your business model requires masternodes running consider PIVX or Dash fork implementation.</p><h3>SMART CONTRACTS</h3><p>When you need to run smart contracts for your project it is better to utilize Qtum or make an Ethereum fork. You will get a reliable and verified solution within a short period of time.</p><p>As you can see on the Avalanche example, forking and integration of EVM is fully possible as well as its adaptation to other programming languages. The same is applicable to WASM, x86 or similar virtual machines.</p><h3>PRIVATE TRANSACTION SERVICES</h3><p>The PrivateSend service from Dash allows for coin mixing which helps to make them untraceable and anonymous. The service mixes user’s coins with Dash coins in such a way that the real receiver address will never meet the authentic sender address. The maximum times of mixing is eight; the more rounds it does the more security your transaction gets.</p><p>You can check for PIVX SwiftX and Quorum Tessera services as an alternative to PrivateSend. Thus, if you need to enable such a feature for your project, consider one of those forks implementations.</p><h3>CONCLUSION</h3><p>I have reviewed some of the well-known examples which can help you to start your own cryptocurrency. Yet it is worth mentioning that you can take any open-sourced blockchain node, fork it, adjust features for your needs, and launch your own network. So you are not limited to the mentioned above ledgers and can fork any blockchain code: EOS, Polkadot, Tron, etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16c6cc8a79fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>