<?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 Jacob on Medium]]></title>
        <description><![CDATA[Stories by Jacob on Medium]]></description>
        <link>https://medium.com/@jacob_62353?source=rss-bde5a14925a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0HMvy1MmWH7P0M4H</url>
            <title>Stories by Jacob on Medium</title>
            <link>https://medium.com/@jacob_62353?source=rss-bde5a14925a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:42:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jacob_62353/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[Solana Metaplex NFT Mutability and Provenance]]></title>
            <link>https://medium.com/@jacob_62353/solana-metaplex-nft-mutability-and-provenance-29b810ad06aa?source=rss-bde5a14925a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b810ad06aa</guid>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[anchor]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Jacob]]></dc:creator>
            <pubDate>Mon, 24 Oct 2022 09:06:09 GMT</pubDate>
            <atom:updated>2022-10-24T09:06:09.004Z</atom:updated>
            <content:encoded><![CDATA[<p>(This article is also available as a <a href="https://www.youtube.com/channel/UC2X5uaF23zt32siwSkOyxVQ">YouTube tutorial</a>, and is part of a series by <a href="https://mlabs.city/">MLabs</a>, a Haskell and Rust consultancy specializing in mission-critical software development and cross-team collaboration. For future articles and other MLabs news, you can also follow us on Twitter <a href="https://twitter.com/MLabs10">@Mlabs10</a>).</p><p>In one of my previous tutorials, I gave <a href="https://medium.com/@jacob_62353/introduction-365296716979">a beginner’s guide to Solana NFTS in the Rust language</a>. Check that out if you want a primer on what NFTs are, or how to create and inspect NFTs on the Solana blockchain in Rust. In this tutorial, I’m going to expand on that concept a little more, and explain some of the important features of NFTs on the Solana blockchain that I didn’t cover before. In particular, this article will describe which things to inspect to see if your NFT is legitimate and secure. Then we’ll go through a small bit of Rust code that you can run to allow you to check any NFT on the Solana blockchain for yourself.</p><p>Picture the scene: you’ve been surfing the interwebs, and blockchain bros on Reddit have revealed to you the wonderful world of NFT art. Eager for a taste of the action, you rush to your favourite NFT marketplace and buy yourself your very own digital work of art. You hand over your Sol and are now the proud owner of one of the popular <a href="https://www.degods.com/">DeGods</a>, perhaps <a href="https://solana.fm/address/Gn9jqWBSc83Mmcmr1bYmY62b1jmjYykDgskaYt3m4rAv">DeGod #7899 </a>(account address Gn9jqWBSc83Mmcmr1bYmY62b1jmjYykDgskaYt3m4rAv).</p><p>But how can you be sure that this is really a DeGods original and not a forgery? Perhaps more insidiously, how can you be sure that the NFT can’t just be changed by the creator after you buy it, the rug pulled out from under you, and the NFT you own is now completely different from the one that you bought? Read on to find out!</p><h3>The NFT Structure</h3><p>Before we get started, let’s reorient ourselves with what our NFT looks like on the Solana blockchain. This is a bit of a hefty diagram so brace yourselves, I promise I’ll explain what it all means. Ready?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1BbH87vK9jgV4fo7WbWUw.png" /><figcaption>Simplified Solana NFT structure (some fields omitted for clarity)</figcaption></figure><p>Let’s break it down. Each of the coloured boxes represents an account or a file. The orange boxes are normal user wallets, and in this case we have two; one each for the creator of the NFT (at the bottom) and the user who owns the NFT. The red boxes are Solana smart contract program accounts, which own accounts so that they can only be altered by authorized instructions. The blue boxes are <a href="https://solanacookbook.com/core-concepts/pdas.html">PDA</a> accounts that hold important information about the NFT. And finally, the green boxes are normal web files outside of the Solana blockchain.</p><p>The dashed lines denote ownership by program accounts. They make sure that only authorized instructions can change accounts that they own. The solid arrows just highlight where fields contain the addresses of other accounts.</p><p>The red box on the left is the <a href="https://spl.solana.com/token">Token Program</a>, part of the Solana Program Library, which defines a common implementation for fungible and non-fungible tokens. The red box on the right is the Metaplex <a href="https://docs.metaplex.com/programs/token-metadata/overview">Token Metadata Program</a>, which is the widely used as a way to attach metadata to tokens.</p><p>The two blue PDA accounts on the left are both owned by the Token program account. The top one is the token mint, used to define the “type” of the token, and required to create the NFT in the first place. The lowermost one is the token account, which describes who owns the NFT.</p><p>The two blue PDA accounts on the right are both owned by the Metaplex program account. The leftmost one in the centre is the <a href="https://docs.metaplex.com/guides/archived/architecture/deep_dive/overview#master-edition">Master Edition</a> account, which is used if the creator wants to make multiple editions of an NFT. The rightmost one is the <a href="https://docs.metaplex.com/guides/archived/architecture/deep_dive/overview#metadata">Metadata</a> account, which stores most of the information about what the NFT actually represents. It contains a link to the off-chain metadata file.</p><p>The green boxes to the right are the off-chain metadata file, containing more information about the NFT including a link to an image file.</p><p>Phew! That is a lot of different accounts just for one NFT. Now we know roughly what the structure is, let’s dig into some of those metadata account fields in more detail.</p><h3>Provenance</h3><p>The first thing we’ll cover is provenance, or in other words, if this NFT is a forgery. The simplest way to check that is to see if it is part of the DeGods collection. Part of the metadata stored on the chain records what collection the NFT is part of. Heading over to a <a href="https://solana.fm/address/Gn9jqWBSc83Mmcmr1bYmY62b1jmjYykDgskaYt3m4rAv">Solana explorer</a>, and typing in the NFT address, you can see a summary of all the information that’s publicly available about that NFT. There we can see that the address of the collection is 6XxjKYFbcndh2gDcsUrmZgVEsoDxXMnfsaGY6fpTJzNr, which you know from other trusted sources is the address of the DeGods collection.</p><p>But that’s not all. More importantly, it will tell you if this collection has been <em>verified</em>. That means that the owner of the collection has signed the transaction that made this NFT. Otherwise, any Tom Dick or Harry could slap the collection address onto their NFT and claim it’s part of the collection. Only the verified ones are legitimately part of that collection, as enforced by the Metaplex token smart contract.</p><h3>On-Chain Mutability</h3><p>The next thing to check is mutability. If an NFT is marked as mutable, then the creator (or more accurately the “update authority”) of the NFT can change almost everything about it, including its name, its description, even its image and attributes. There’s nothing stopping the creator from swapping your DeGod image with another one, or even removing the image altogether, and leaving you with nothing. And they can do this after you have paid for it!</p><p>If we revisit our <a href="https://solana.fm/address/Gn9jqWBSc83Mmcmr1bYmY62b1jmjYykDgskaYt3m4rAv">DeGodd NFT</a> we can see (at the time of writing) it is indeed marked as “Mutable”. Effectively there’s only a “handshake” agreement with the owner of the NFT for the creator not to alter the NFT, kept in place for fear of public outcry. That doesn’t seem very blockchain to me, where the whole idea is that we don’t have to trust anyone, just the underlying maths!</p><p>So why is this mutability even an option? It does open the door to some interesting creative possibilities. Perhaps your NFT is a picture of a seed of some fantastical imaginary plant. Each day, the creator replaces the image file with a slightly older version of your seedling, and each time you visit your NFT you can see it grow from seedling to sapling to mature plant. Changing the image like that is only possible by marking it mutable. And the important thing is that those changes can still only be made by the creator, not by some random third party.</p><p>But if you want assurances that your NFT is not open to any sort of foul play, you’ll want to make sure that it is immutable by default. Unfortunately at the moment (using the Metaplex system), there’s no way to do that as a customer after purchasing an NFT. But it’s something to look out for while shopping.</p><h3>Off-Chain Mutability</h3><p>Let’s say that you do want an NFT that’s completely locked down and unchangeable. You do your due diligence and purchase one that is marked as immutable. That means that all the <em>on-chain</em> information (in the various Metaplex metadata accounts) is now immutable. But some of the metadata about your NFT is not stored on the chain, it’s stored elsewhere on the internet! All Metaplex metadata accounts have the field “uri”, which by convention points to a JSON file that holds additional information. This includes very important fields like the description and the link to the image file.</p><p>This means that even if your token is marked as immutable, whoever controls where that JSON file is hosted can freely edit it, replace it, or completely remove it! In the case of our <a href="https://solana.fm/address/Gn9jqWBSc83Mmcmr1bYmY62b1jmjYykDgskaYt3m4rAv/metadata">DeGods image from before</a>, we can see in the metadata (taken from the blockchain) that this file is hosted at <a href="https://metadata.degods.com/g/7898.json">https://metadata.degods.com/g/7898.json</a>. And that JSON in turn contains the link to our image, hosted at <a href="https://metadata.degods.com/g/7898-dead.png">https://metadata.degods.com/g/7898-dead.png</a>. So that means whoever controls degods.com has complete control over what our DeGod actually looks like, even after we’ve bought the NFT, and even if it’s marked as immutable. In fact, the eagle-eyed might have noticed that this file is called 7898, even though it’s the metadata for 7899? Foul play! Or, more likely, an off-by-one miss-labelling. But you never know…</p><p>Why is so much important stuff about our NFT stored off the chain? Again, the same argument as before applies: this allows artists to modify the NFT for legitimate purposes. But it’s also because storing things on the blockchain is expensive and rigid. You pay a much higher price per bit to store information on the Solana blockchain than on a traditional server. Also, you can’t dynamically allocate space in accounts, so if you wanted to store additional fields for your NFT (such as the <a href="https://solana.fm/address/Gn9jqWBSc83Mmcmr1bYmY62b1jmjYykDgskaYt3m4rAv">attributes of our DeGod</a>), you can’t do that on the chain.</p><p>If you have a problem in the blockchain, the solution is always more blockchain. The JSON can also be hosted on-chain, just not on Solana. Blockchains like <a href="https://www.arweave.org/">Arweave</a> provide an immutable place to store data so that the file can be hosted with assurances that it cannot be changed by anyone. It also has the added benefit that (in theory) the file will always be available, and avoids situations like your NFT creator going bust and stopping hosting his website altogether. Once again though, this is a solution that only the creator of an NFT can do at creation time, and unfortunately there is no way to retrofit this onto existing NFTs.</p><h3>Rust NFT Explorer</h3><p>There’s one more step we could take in this paranoid line of inquiry. How do we know that we can trust the marketplace we’re buying this NFT from? Or the <a href="https://solana.fm/">https://solana.fm</a> Solana explorer itself? Let’s write our own small Rust program that sidesteps them entirely and gets the information from a trusted source: directly from the mainnet RPC nodes. Paranoid inclinations aside, this also provides us a nice way to consolidate what we’ve learned about the Metaplex system of mutability and provenance!</p><p>(The following code is also available on <a href="https://github.com/JacobAraiza/provenance">GitHub</a> if you’d like to run it yourself or follow along in your own code editor of choice).</p><p>So what we’re looking to write is a small command line program, which takes an NFT address as its input, and outputs all the interesting metadata to the console for us to read. To keep the example simple, I’m going to assume this NFT has Metaplex metadata and also Master Edition information. I’m also going to keep error handling simple and just exit with an error message if anything goes wrong. Handily we can use the address of our DeGod from before as our example, as it fits that criteria. It’s almost like I planned it that way!</p><p>The first thing we’ll need to do (if you’re writing this in tandem), is cargo init ourselves a new repository to work with. Then we can edit the Cargo.toml to include all the crates we’ll need for later (spoilers):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4337e48f23b96137978cc8fc12a20a4/href">https://medium.com/media/c4337e48f23b96137978cc8fc12a20a4/href</a></iframe><p>Then in our pristine empty main.rs we’ll add in all our imports and typedefs now to save time later:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/044efed553ec0144d3a28ecd5e6e1fc4/href">https://medium.com/media/044efed553ec0144d3a28ecd5e6e1fc4/href</a></iframe><p>Any command line Rust program worth its salt needs a nice way to parse command line arguments. My go-to too for that is the excellent structopt library. In a couple of lines we can declare our arguments with some sensible defaults:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fe64a572ae5844bc995704936c76f77/href">https://medium.com/media/9fe64a572ae5844bc995704936c76f77/href</a></iframe><p>And then get started on our fn main() :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f289c2bb4b6d5854f4483494eea360c/href">https://medium.com/media/4f289c2bb4b6d5854f4483494eea360c/href</a></iframe><p>Now we can run the program with cargo run -- MINT_ADDRESS_HERE and voila! It does nothing. Yet.</p><p>(From now on all of the code that isn’t a struct definition is being added into the main function, with the rest of the function omitted for brevity.</p><p>Next up we need to connect to the Solana network to request information. For that, we need an address to connect an <a href="https://www.alchemy.com/overviews/solana-rpc">RPC node</a> on, the logical one being the mainnet so we can get the details of real NFTs and not just “fake” ones on the test or dev nets. That’s the default address we added in the structopt definition above. Access the network is as simple as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84d283e5fd4b4671fef5802610dca4e1/href">https://medium.com/media/84d283e5fd4b4671fef5802610dca4e1/href</a></iframe><p>The first account to access is the mint address itself. This is the address that identifies the NFT (Gn9jqWBSc83Mmcmr1bYmY62b1jmjYykDgskaYt3m4rAv for our old friend DeGod #7899). If we fetch that account from the block-chain, then we can print out the mint owner, the supply and the decimal places (hopefully 1 and 0 respectively, to make it a unique, singular, and non-fungible NFT):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3546e76fa1d6cea8289b854f3826f699/href">https://medium.com/media/3546e76fa1d6cea8289b854f3826f699/href</a></iframe><p>Running that against our NFT you should get something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9a7f9fa81af46fe564311c51cc4af1d/href">https://medium.com/media/e9a7f9fa81af46fe564311c51cc4af1d/href</a></iframe><p>There we can see we’ve already proven a few things:</p><ul><li>The account is owned by the Token smart contract (with the distinctive Token prefix to its address), so this is a token of some kind.</li><li>The supply is 1 and the decimals are 0. That means we can only ever have 1 of these tokens, and that a person can only ever own 0 or 1 of it at any one time (in other words, you can’t own 0.5 or 0.333 of it). That means it’s not fungible so this is indeed an NFT.</li><li>The mint authority matches the one displayed on <a href="https://solana.fm/address/Gn9jqWBSc83Mmcmr1bYmY62b1jmjYykDgskaYt3m4rAv/">https://solana.fm</a></li></ul><p>For a bit more information, we can dig into the Master Edition metadata account:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebaa9be45250b7ac308508a6d3709ea5/href">https://medium.com/media/ebaa9be45250b7ac308508a6d3709ea5/href</a></iframe><p>Running the program again gets us some new output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ffaa202032ce0945d0704c60482c6c9/href">https://medium.com/media/5ffaa202032ce0945d0704c60482c6c9/href</a></iframe><p>Nothing too exciting there, it just confirms that this is the only edition of this NFT, there aren’t any other “prints” or editions.</p><p>The juicy bit comes next, when we access the on-chain metadata account:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe6e007dade24cb6f37906a0acd4f158/href">https://medium.com/media/fe6e007dade24cb6f37906a0acd4f158/href</a></iframe><p>That gives us a lot more output to look at:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b671a03701bee21f01c88755b9ee18c/href">https://medium.com/media/4b671a03701bee21f01c88755b9ee18c/href</a></iframe><p>A few interesting things to note there:</p><ul><li>We’ve got the name and the symbol of this NFT (but not the actual image or description yet).</li><li>The primary sale has happened, so if you buy this NFT now it’s on the secondary market and not from the original creator.</li><li>The NFT is mutable (uh-oh…) so it could in theory change at any time at the update Authority’s whim.</li><li>This is verified (by the Metaplex program) as being part of the <a href="https://solana.fm/address/6XxjKYFbcndh2gDcsUrmZgVEsoDxXMnfsaGY6fpTJzNr">6XxjK… collection</a>, which is definitely the DeGods collection that we expected.</li><li>We’ve got the link to the off-chain metadata that we can inspect for more information.</li></ul><p>Then we need to pull down that off-chain metadata JSON file. First, we’ll need a struct to deserialize the JSON easily, using the excellent serde crate (if you’re following along at home, put these definitions outside of the main function where the rest of the code is going):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c036d133d6c32635cc80e73188136748/href">https://medium.com/media/c036d133d6c32635cc80e73188136748/href</a></iframe><p>After that, we can fetch the file (using reqwest instead of the RPCClient as it’s on the boring old normal web):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b0e2f0c0c0d90d8c0ecf77b5ede2ed3/href">https://medium.com/media/4b0e2f0c0c0d90d8c0ecf77b5ede2ed3/href</a></iframe><p>This gives us another raft of extra information:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a3be8eb1994ff913b71059332ababf2/href">https://medium.com/media/7a3be8eb1994ff913b71059332ababf2/href</a></iframe><p>Most importantly, we finally have the link to the image itself. This seemed to me like a great opportunity for a delightful tangent, so to spice things up I added a little code to print the image as ASCII art into the terminal using the lovely asciify crate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e44f28af1d4d2372943f2ca3ffe1c4dd/href">https://medium.com/media/e44f28af1d4d2372943f2ca3ffe1c4dd/href</a></iframe><p>Which produces this output that’s <a href="https://metadata.degods.com/g/7898-dead.png">vaguely similar to the original</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97e5815b4b8caa57d540553a83a49e04/href">https://medium.com/media/97e5815b4b8caa57d540553a83a49e04/href</a></iframe><h3>Conclusion</h3><p>As we have seen, proving the provenance of an NFT on the Solana blockchain is straightforward. But we have also seen how the mutability of a Solana NFT is complex and misleading. It’s all too easy to have an NFT which is not as immutable as you would expect, and which is potentially open to manipulation by nefarious creators. Forewarned and forearmed with this example code, you can avoid scams and unwanted behaviour in your NFTs going forward.</p><h3>MLabs</h3><p>New technologies like blockchain offer great promise, but creating secure and reliable products is no easy feat. <a href="https://mlabs.city/">MLabs</a> provides essential services to smart contract projects, particularly in the Cardano, Polkadot, and Solana spaces. Our tailored support helps some clients overcome internal hurdles while others rely on MLabs completely for development.</p><p>Startups often lack clear launch strategies. Others have promising product ideas with no ability to execute. MLabs can fill in where needed, reducing both time to launch and overall development cost. With complete DevOps solutions and tailored offerings available, our services are flexible and comprehensive. A software engineering consultancy specializing in Haskell and Rust, MLabs has successfully assisted numerous teams like yours to develop diverse products, many first of their kind to market.</p><p>Connect with <a href="https://mlabs.city/">MLabs</a> today and <a href="https://mlabs.city/contact">schedule your free consultation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b810ad06aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginners guide to Solana NFTs in Rust.]]></title>
            <link>https://medium.com/@jacob_62353/introduction-365296716979?source=rss-bde5a14925a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/365296716979</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Jacob]]></dc:creator>
            <pubDate>Wed, 07 Sep 2022 08:42:40 GMT</pubDate>
            <atom:updated>2022-10-24T09:12:53.051Z</atom:updated>
            <content:encoded><![CDATA[<p>(This article is also available as a <a href="https://www.youtube.com/channel/UC2X5uaF23zt32siwSkOyxVQ">YouTube tutorial</a>, and is part of a series by <a href="https://mlabs.city/">MLabs</a>, a Haskell and Rust consultancy specializing in mission-critical software development and cross-team collaboration. For future articles and other MLabs news, you can also follow us on Twitter <a href="https://twitter.com/MLabs10">@Mlabs10</a>).</p><p><a href="https://solana.com/">Solana</a> is a blockchain that’s all about speed. Like many blockchains, it’s also possible to mint NFTs on the Solana blockchain. But what is an NFT, I hear you ask? How do they work on Solana? How do I make my own? Read on to find out!</p><h3>What is an NFT?</h3><p>A Non Fungible Token or NFT might sound like a complex concept, but it’s pretty straightforward. It’s an entry on the blockchain, owned by a blockchain account, which is associated with a particular asset. That asset could be anything, digital or physical, such as a digital movie poster, a piece of music, or a physical painting. They are “Non Fungible” because any one NFT is not the same as the next NFT, unlike fungible dollars where any one dollar note is interchangeable with any other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*KjI1ROLQ_fVhbk_JYxandA.png" /><figcaption>Very simplistic diagram of a generic blockchain NFT.</figcaption></figure><p>The important (and controversial) thing to remember is that even though a blockchain account can prove that it owns an NFT, that NFT is only <em>associated</em> with the asset itself. While it can be considered a kind of proof of ownership, it has no legal standing. Buying an NFT doesn’t stop anyone else from copying, sharing, or recreating its associated asset. That means if I use my blockchain account to buy an NFT of a cute cat picture (which usually the NFT will just contain a link to), anyone else can still follow that link, download the image, and set it as their phone wallpaper.</p><p>So far NFTs have been popularised largely as a way to buy “bragging rights” over digital art. But some more practical applications are being explored, such as using NFTs as tickets to music venues, which allows artists to get a percentage of resale costs.</p><h3>NFTs in Solana</h3><p>To understand exactly how NFTs you need to understand a few things about the Solana <a href="https://docs.solana.com/developing/programming-model/overview">programming model</a> and <a href="https://docs.solana.com/terminology">terminology</a>. Smart contracts on the Solana blockchain are called programs, and store their state in accounts:</p><blockquote><em>If the program needs to store state between transactions, it does so using </em>accounts<em>. Accounts are similar to files in operating systems such as Linux in that they may hold arbitrary data that persists beyond the lifetime of a program. Also like a file, an account includes metadata that tells the runtime who is allowed to access the data and how.</em></blockquote><p>One of the programs that already exist on the Solana ecosystem is <a href="https://spl.solana.com/token">the Token program</a>. It’s a ready-made program for creating your own fungible or non-fungible tokens. The documentation linked there does a good job of explaining how to create tokens using the command line, so instead of repeating that I’ll show you how to do similar things in Rust code.</p><p>If you’re writing Rust code that handles Solana NFTs, you’re probably going to be using the spl-token crate. Using this library we can mint new NFT tokens, create Accounts to hold those NFTs and move NFTs between accounts. Having a look at the code on <a href="https://docs.rs/spl-token/latest/spl_token/state/struct.Account.html">the crate docs</a>, we can understand a little more clearly what data a token Account contains:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4551189e4df1499bb1210e96ad601c77/href">https://medium.com/media/4551189e4df1499bb1210e96ad601c77/href</a></iframe><p>Some of those fields we don’t need to worry about now, but the important ones are:</p><ol><li>mint: the address of the account this token was minted from. You can think of this as the token’s “type”, which describes which token is owned by this account.</li><li>owner: the address of the owner of this token account, for an NFT this is the person who owns the NFT.</li><li>amount: how much of the given token this account holds. For an NFT, this will be either 0 or 1, but for a fungible currency, this could be any value.</li></ol><p>There’s also an existing program and crate mpl-token-metadata which we can use to associated assets with our NFT. I’ll go into that in more detail later on, but it represents assets on the chain with this structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eedc88cb3053d098d709767999ffb59f/href">https://medium.com/media/eedc88cb3053d098d709767999ffb59f/href</a></iframe><p>That allows you to name your NFT, and give a link to whatever digital asset it represents.</p><p>So we end up with a collection of accounts and relationships that can be represented like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*jfNVWDYNAWvGOVrMhpS_9w.png" /><figcaption>Diagram of the accounts involved in a Solana NFT.</figcaption></figure><p>The red boxes represent the program accounts. They already exist on the chain and own other accounts so only authorized changes can be made to them. The orange boxes are the wallets of the accounts that create the NFT and own the NFT. These are just “normal” wallet accounts, and could even be the same account if you were minting an NFT to keep for yourself. The blue boxes are the accounts that we’ll create in the next section: the mint to create and identify the “type” of the NFT, the token account to hold the NFT in, and the metadata account to store the link to the asset and other metadata.</p><h3>How to make your own NFTs</h3><p>Let’s get our hands dirty with some actual Rust code. I find this is always the best way to properly understand something. All the code written here is available on <a href="https://github.com/JacobAraiza/nft">GitHub</a> if you want to see it in full. The first thing to do, if you haven’t already done so, is to install <a href="https://rustup.rs/">Rust</a> and the <a href="https://docs.solana.com/cli/install-solana-cli-tools">Solana tool suite</a>. Then we can make a repo:</p><pre>cargo init nft</pre><p>Before we run any code, we need to make sure we’re using the testnet, <a href="https://docs.solana.com/clusters">otherwise things could get expensive</a>!</p><pre>solana config set --url &quot;https://api.testnet.solana.com&quot;</pre><p>We’ll also need two throwaway accounts, which we can airdrop some funds into for free because we’re on the testnet. One to represent the authority who creates the NFT, and the other to represent a user to own the NFT. The rest of the code will assume that the files are in the nft folder we just created, so make sure you create them there:</p><pre>cd ./nft<br>solana-keygen new -o user.keypair<br>solana airdrop 1 -k user.keypair<br>solana-keygen new -o authority.keypair<br>solana airdrop 1 -k authority.keypair</pre><p>I’ll be writing our code in tests/test.rs, so we can run and check that it’s working as we go along. The first thing we’ll need is a big pile of includes and a test stub so we have something to run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1e6451ff5363285f83c89e0326721a8/href">https://medium.com/media/b1e6451ff5363285f83c89e0326721a8/href</a></iframe><p>And of course, some includes in Cargo.toml so all those imports work:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c3810e1906ee1a781f96c376f8b38f0/href">https://medium.com/media/6c3810e1906ee1a781f96c376f8b38f0/href</a></iframe><p>Then if we do cargo test we should see…</p><pre>running 1 tests</pre><pre>test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s</pre><p>Success! Unsurprisingly. Let&#39;s get some meat on those bones. To help us with the next step we’ll need a little helper function to execute commands on the testnet, using the RpcClient we just imported to execute instructions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c1bf31ea746040fd9c6e6a13245ddd7/href">https://medium.com/media/7c1bf31ea746040fd9c6e6a13245ddd7/href</a></iframe><h3>Creating a Mint</h3><p>Then we can use that to start writing our first real bit of functionality. The first thing we’re going to need to do is create a token mint. As I mentioned before, you can think of this as sort of the “type” of the token, and it’s also needed to create (or “mint” in Solana terminology) new tokens. Let’s add a function that creates a new account, and then initializes it as a token mint account:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc0547b6e0e643a62967931f491485c1/href">https://medium.com/media/dc0547b6e0e643a62967931f491485c1/href</a></iframe><p>One thing to note there is the decimals argument. This is describing how many decimal places our new token should have available. If you were making CyberDollars™ for example, you might put this as 2 so that a user could own $1.23. As we’re making an NFT, we’ll be setting this to 0, so that a user can only own exactly 1 or 0 of our token. It wouldn’t make sense if a user could own half of an NFT.</p><p>Now we can pull this all together inside our test stub and see if it works! A bit of initialization:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2437bee2b3f7d25c57876957cbafce94/href">https://medium.com/media/2437bee2b3f7d25c57876957cbafce94/href</a></iframe><p>Then we create the mint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6489f29f00a7ccda83db858696dbaa8c/href">https://medium.com/media/6489f29f00a7ccda83db858696dbaa8c/href</a></iframe><p>And then we can fetch the newly created account from the blockchain to check it exists:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1289f63a1979652fd8e969c0bd057df/href">https://medium.com/media/e1289f63a1979652fd8e969c0bd057df/href</a></iframe><p>Running cargo test again shows the test still passing: a very promising sign!</p><h3>Creating a Token Account</h3><p>Now that we have a mint account, we can mint our NFT. But first, we need a token account to own the NFT, in the same way that you need a bank account to hold traditional money. A nice way to do that is by using <a href="https://spl.solana.com/associated-token-account">associated token accounts</a>. That way instead of having to remember another account address, the token account can be automatically derived from just the user’s main account address and the mint address. Once we have that address, we can make another function to create it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a3d750462975e7cd26f0626c216fcc6/href">https://medium.com/media/8a3d750462975e7cd26f0626c216fcc6/href</a></iframe><p>Then once again we can add that to our test function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37a53fca87b06bf2ed92aceb1933baa5/href">https://medium.com/media/37a53fca87b06bf2ed92aceb1933baa5/href</a></iframe><p>And check that it works by fetching the account from the chain and inspecting it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f60bc2ef7c4676e5b4c0eef4a0a425d/href">https://medium.com/media/6f60bc2ef7c4676e5b4c0eef4a0a425d/href</a></iframe><p>As you can see, the Solana account itself is owned by the token program, this is to make sure that no one can tamper with the data without authorization. Internally it is marked as having the user as its owner as well (slightly confusing as it&#39;s re-using the word “owner” for a slightly different meaning), which in this context means the person who actually has control over the token account. And we can see that the mint “type” is the one that we created in the first step.</p><h3>Minting</h3><p>Armed with a mint and an account to mint into, we can now create a function to mint our NFT:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/419aa1d304d81798fc60b780eb752d25/href">https://medium.com/media/419aa1d304d81798fc60b780eb752d25/href</a></iframe><p>And add that to our test, making sure to set the amount to 1 so that our NFT is unique:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1d774bf22609152d27c06bf73cbbf18/href">https://medium.com/media/b1d774bf22609152d27c06bf73cbbf18/href</a></iframe><p>Now when we re-fetch the account, it should contain our newly minted token:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb7338143bc37120bba60a092a7a98b5/href">https://medium.com/media/bb7338143bc37120bba60a092a7a98b5/href</a></iframe><h3>Adding Assets</h3><p>Running cargo test once again is once again a success! So now we have an NFT, mission accomplished right? Wrong. At the moment our NFT is pretty boring: it’s just an address on the blockchain that proves we own it, but it doesn’t have any assets associated with it. To fix that, we can create an associated metadata account using the mpl-token-metadata crate. If you’re interested in more detail about the on-chain structure of the Metaplex metadata system <a href="https://docs.metaplex.com/guides/archived/architecture/deep_dive/overview">here</a>. We’ll need a structure to temporarily store our metadata before we write it to the blockchain:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52e6f3869735406085aa6316b46757a1/href">https://medium.com/media/52e6f3869735406085aa6316b46757a1/href</a></iframe><p>There we can have a link to the digital asset that our NFT has “ownership” over. We’ll also need an associated account address, in the same way that we had an associated token address, so that we can find the metadata with just the mint address and the user&#39;s wallet address:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/137410c0f77a8226f4d5a70064142fb4/href">https://medium.com/media/137410c0f77a8226f4d5a70064142fb4/href</a></iframe><p>Combining those two functions we can make a function to create our metadata account:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e45b6ea8c4cca408380155bc7c558ff/href">https://medium.com/media/9e45b6ea8c4cca408380155bc7c558ff/href</a></iframe><p>Then we can call that from our test function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86eaf5338f090eda6e4e378f91948404/href">https://medium.com/media/86eaf5338f090eda6e4e378f91948404/href</a></iframe><p>And now our NFT represents a lovely gold star. Let&#39;s check that that’s worked as expected and that that metadata is now available on the chain:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cda7829e2916bc87ca87180c5f04aa0/href">https://medium.com/media/3cda7829e2916bc87ca87180c5f04aa0/href</a></iframe><h3>Creating a Master Edition</h3><p>The Metaplex token metadata system also has a concept of a <a href="https://docs.metaplex.com/guides/archived/architecture/deep_dive/overview#master-edition">Master Edition</a>. This is an extra account to add a few additional metadata fields. This is designed for if you plan on making editions of your NFT. For example, if you had a piece of art as your Master Edition, you could then mint official “prints” of the original as new editions.</p><p>Creating the Master Edition metadata also has one very useful side effect: What’s to stop the authority from minting a copy of our NFT, reducing it to a worthless FT? Nothing at the moment. The Master Edition puts a stop to that by disabling the mint from creating any more copies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10242241708f04487e76d214f57ac1a2/href">https://medium.com/media/10242241708f04487e76d214f57ac1a2/href</a></iframe><p>Then we can add that code to our test, and check that the account has been created as expected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa6380689b0ef42425cf9e06235ce7fe/href">https://medium.com/media/fa6380689b0ef42425cf9e06235ce7fe/href</a></iframe><p>Now the mint should be unable to create any more tokens, leaving the sole supply as a single NFT:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82fc7682432cb9c46aaadaf8b87f4bc7/href">https://medium.com/media/82fc7682432cb9c46aaadaf8b87f4bc7/href</a></iframe><h3>Conclusion</h3><p>There you have it, a whistle-stop tour of NFTs, NFTs in Solana, and how to mint your own NFTs in a few lines of Rust code. I hope you found it informative and enjoyable 🙂.</p><p>As I mentioned, all the code above is available on <a href="https://github.com/JacobAraiza/nft">GitHub</a> if you want to see it in full.</p><h3>MLabs</h3><p>New technologies like blockchain offer great promise, but creating secure and reliable products is no easy feat. <a href="https://mlabs.city/">MLabs</a> provides essential services to smart contract projects, particularly in the Cardano, Polkadot, and Solana spaces. Our tailored support helps some clients overcome internal hurdles while others rely on MLabs completely for development.</p><p>Startups often lack clear launch strategies. Others have promising product ideas with no ability to execute. MLabs can fill in where needed, reducing both time to launch and overall development cost. With complete DevOps solutions and tailored offerings available, our services are flexible and comprehensive. A software engineering consultancy specializing in Haskell and Rust, MLabs has successfully assisted numerous teams like yours to develop diverse products, many first of their kind to market.</p><p>Connect with <a href="https://mlabs.city/">MLabs</a> today and <a href="https://mlabs.city/contact">schedule your free consultation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=365296716979" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing an Anchor Solana program in Rust]]></title>
            <link>https://medium.com/@jacob_62353/testing-an-anchor-solana-program-in-rust-65144b0cc5ce?source=rss-bde5a14925a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/65144b0cc5ce</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[solanas]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[anchor]]></category>
            <dc:creator><![CDATA[Jacob]]></dc:creator>
            <pubDate>Tue, 30 Aug 2022 11:05:55 GMT</pubDate>
            <atom:updated>2022-10-24T09:12:25.143Z</atom:updated>
            <content:encoded><![CDATA[<p>(This article is also available as a <a href="https://www.youtube.com/channel/UC2X5uaF23zt32siwSkOyxVQ">YouTube tutorial</a>, and is part of a series by <a href="https://mlabs.city/">MLabs</a>, a Haskell and Rust consultancy specializing in mission-critical software development and cross-team collaboration. For future articles and other MLabs news, you can also follow us on Twitter <a href="https://twitter.com/MLabs10">@Mlabs10</a>).</p><h3>Introduction</h3><p>For those who haven’t come across it, <a href="https://book.anchor-lang.com/introduction/what_is_anchor.html">Anchor</a> is a framework for writing <a href="https://solana.com/">Solana</a> programs (smart contracts) in the Rust programming language. It’s designed to reduce the amount of boilerplate that you need to write code that can run on the Solana blockchain, while also handling some of the common security pitfalls for you automatically.</p><p>Unfortunately, by its very nature, it can sometimes be a little hard to understand exactly what Anchor code does under the hood. I’d certainly recommend that new starters in Solana write code without Anchor, at least to begin with, in order to better understand some of its design decisions and structure.</p><p>At the time of writing, there also isn’t much documentation available that focuses on how to properly unit tests Anchor code in Rust — all of the blogs I’ve found focus on <a href="https://imfeld.dev/writing/starting_with_solana_part03">testing in JavaScript</a>. This blog is here to correct that!</p><p>Here I’ll lay out everything you need to know to test your Solana programs without leaving the safety of the Rust language.</p><p>All the code outlined below is available in full on <a href="https://github.com/JacobAraiza/messenger">GitHub</a>, if you want to see it in all its glory.</p><h3>A Solana Program</h3><p>First things first: we’ll need an idea for a program to write in Anchor so that we have something to test. I had an idea I wanted to write about that seemed a perfect fit: an on-chain email service. Specifically, it’s a Solana program that lets you send “emails” to anyone for whom you have a public account key.</p><p>Doing this in Solana gives us a couple of benefits over an off-chain solution:</p><ul><li>Messages cannot be deleted: so there’s a permanent public record of who emailed who.</li><li>It’s a trusted medium: messages can’t be tampered with by any third parties.</li></ul><p>So what does the implementation look like? Something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*DwimNTZeGG9wpFP4mmBQ9Q.png" /></figure><p>The main structure is a linked list of Messages, with each Message pointing to the previous message (except the last Message, which points to nothing). By “pointing” I just mean it will have the public key of the next message stored within it. Then each User will control a Mailbox, which points to the most recent message to come into the inbox.</p><p>The final important part is that the program itself will own the Mailbox and all the Messages (using <a href="https://solanacookbook.com/core-concepts/pdas.html">Program Derived Addresses or PDAs</a>) so that we can control all changes to those structures. PDAs are a complex thing to get your head around, so don’t worry if you find them hard to grasp. I know I did when I first came across them!</p><p>So here’s a brief outline of what we need to write:</p><ul><li>Two account data structures: one for a user’s Mailbox and one for an individual Message</li><li>A method for finding a Solana account’s Mailbox from their public key</li><li>A Solana program with a single “send message” instruction which creates a new Message (and a new Mailbox if the receiving user has never received a message) and then adds the Message to their Mailbox.</li></ul><p>One thing that I won’t be showing here is encrypting the messages themselves, which you would want to do to avoid all your messages being easily read by anyone with access to the blockchain. I have added an implementation in the codebase on GitHub if it piques your interest.</p><h3>An Anchor Implementation</h3><p>Here’s the part you’ve been looking forward to; writing some actual code! First off we’re going to need some files to put things in (I’m going to keep mine simple and just use the one file as it’s not too much code):</p><pre>src/<br>  lib.rs<br>Cargo.toml</pre><p>And we’ll need to fill Cargo.toml with a few dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f815ddd4bfc3df7664e4fd91d9edb7ac/href">https://medium.com/media/f815ddd4bfc3df7664e4fd91d9edb7ac/href</a></iframe><p>(For the eagle-eyed: I’ll explain that features=[&quot;init-if-needed&quot;] in a moment).</p><p>Now let’s populate that lib.rs. At the top we need some imports from Anchor and Solana:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad1fbff8b827b828a09e1c882ad43380/href">https://medium.com/media/ad1fbff8b827b828a09e1c882ad43380/href</a></iframe><p>Then we start off with the data structures that we’ll need, a Mailbox and a Message:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae8597602d2f4ca69d3086739167f94b/href">https://medium.com/media/ae8597602d2f4ca69d3086739167f94b/href</a></iframe><p>The #[account] is an Anchor macro that is adding some useful boilerplate code for us.</p><p>We’ll also need to know the space requirements for these structs later: unfortunately, you have to manually calculate these, but there’s a good reference <a href="https://book.anchor-lang.com/anchor_references/space.html">here</a> to tell you how that works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4619eb0e3c24c8b739b1a7bfbd980e6/href">https://medium.com/media/e4619eb0e3c24c8b739b1a7bfbd980e6/href</a></iframe><p>I’m setting the message size to always be 255 bytes max just as an arbitrary limit to make the code a bit simpler here.</p><p>Next up, we need the list of accounts that we’re going to need for our “send message” instruction:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2006495f644bc83eb35764ead85bf66/href">https://medium.com/media/b2006495f644bc83eb35764ead85bf66/href</a></iframe><p>That’s a complex block of code, so let me break it down. High level, we’ve got five accounts that we need:</p><ol><li>from: the account of the person sending the message, this is a Signer because they’re paying for the transaction so it needs to have been signed by them to authorize the payments.</li><li>to: the account of the person to send the message to.</li><li>mailbox: the account which holds the Mailbox struct data (holds the address of the latest message in the inbox).</li><li>message: the account which holds the Message struct (with the message text and the address of the previous message in the inbox).</li><li>system_program: this is the global system program account, which we need in order to initialize the mailbox and message accounts.</li></ol><p>There are a lot of Anchor macros to understand here too, so let’s go through those:</p><ol><li>#[derive(Accounts)]: this adds all the boilerplate code to de-serialize the structure when calling the instruction</li><li>#[instruction(message_seed: Vec&lt;u8&gt;)]: this allows us to access a field from arguments passed into the instruction, in this case, the message_seed which lets us create the message PDA.</li><li>#[account(...)]: this is an even more complex one, and I encourage you to have a look at the <a href="https://docs.rs/anchor-lang/latest/anchor_lang/derive.Accounts.html#constraints">Anchor Lang Book section on constraints</a> if you want to understand it more. In a nutshell, it will create a PDA for us if it doesn’t already exist. The key part to note is that the seed for the mailbox PDA address is to account’s public key: so it makes it very easy to find any user’s mailbox address. This is where the init_if_needed feature from before makes its appearance: so that we can initialize this structure only on the first message, and reuse the existing one for all subsequent messages.</li></ol><p>And then we come to the meat of the code, the actual program instruction to send a message:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b9b219dd8ee08a1bf26bf3431efcece/href">https://medium.com/media/4b9b219dd8ee08a1bf26bf3431efcece/href</a></iframe><p>Once again the Anchor macros are doing all the heavy lifting here, this time its #[program], which is expanding everything out into the functions you need for a Solana program. Then all the code does is three things: check that the message isn’t too long, initialize all the Message fields in message, and then add the message to the end of the inbox linked list.</p><p>To make that code above compile, we’ll need an error structure too:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b2c33911b1c96f2294ea1219df55904/href">https://medium.com/media/9b2c33911b1c96f2294ea1219df55904/href</a></iframe><p>Then we’re almost done, there are just a few more useful functions we can sprinkle in. A helper function for calculating the mailbox PDA address:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df16965b6b358889ecfaa84423c84fdd/href">https://medium.com/media/df16965b6b358889ecfaa84423c84fdd/href</a></iframe><p>And a helper function for creating the send_direct_message instruction:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5af07143ab05720bfa27cc8c5bd764d4/href">https://medium.com/media/5af07143ab05720bfa27cc8c5bd764d4/href</a></iframe><p>Here you can see we’re filling out the vec! in the same order as the fields in SendDirectMessage, the Anchor macros will de-serialize that for us when the instruction is actually executed. You also might notice that we reference instruction::SendDirectMessage: that’s defined for us by the #[program] macro we used earlier. And last of all we use our mailbox_pda function to calculate the address of the mailbox account for us.</p><p>Just one final thing we need for a working program, and that’s defining the program identifier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1caadc190eeb7579125d9874504d99a/href">https://medium.com/media/a1caadc190eeb7579125d9874504d99a/href</a></iframe><p>Phew that’s a lot of code! Let’s take a break shall we?</p><h3>Expanding Macros with cargo expand</h3><p>This is a bit of an aside, but I found the cargo expand command very useful when debugging some problems. In a nutshell, it expands out all the macros in a file so that you can see the actual Rust code that it becomes just before it is fully compiled. Especially with a system such as Anchor that adds a lot of boilerplate code for you, this can be quite handy for debugging issues.</p><p>If you want to give it a go, you can install it with cargo install cargo-expand . You’ll also need to be using the latest nightly version (rustup install nightly if you don’t already have it, then you can run cargo +nightly expand).</p><p>I won’t show the whole output (as unsurprisingly its rather large), but here’s a snippet that shows what the declare_id! macro expands to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04a97ecafe17649858859fec0049ceec/href">https://medium.com/media/04a97ecafe17649858859fec0049ceec/href</a></iframe><h3>Writing Tests</h3><p>Now comes the important bit: actually writing some unit tests. For those who aren’t aware, rust has an excellent built-in <a href="https://doc.rust-lang.org/book/ch11-01-writing-tests.html">testing framework</a>, which I encourage you to investigate if you haven’t used it already. First of all, we’ll make a test stub at tests/integration.rs where it will automatically be detected by cargo :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59f203bf3f49c22f485c517133a47ff8/href">https://medium.com/media/59f203bf3f49c22f485c517133a47ff8/href</a></iframe><p>As you might notice, here I’m using the async keyword to make this an async test, with the excellent <a href="https://tokio.rs/">tokio</a> crate as the async runner. If you’re not familiar with async then I recommend taking a look at the <a href="https://rust-lang.github.io/async-book/">Async Book</a>, but it shouldn’t affect your understanding of the rest of the code much: they’ll be a few errant await keywords sprinkled around that you can safely ignore.</p><p>You might also notice we’re also re-importing tokio from solana_program_test rather than as a stand-alone crate: that makes it easier to keep the version numbers aligned. Don’t forget to add those imports to program/Cargo.toml:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97ef94aacb0727f7d8aea9d6a9611029/href">https://medium.com/media/97ef94aacb0727f7d8aea9d6a9611029/href</a></iframe><p>The next step is to set up a virtual in-memory Solana validator that can execute the program, and load the program onto it. For this we’ll be using the solana-program-test crate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26ce66356cecca6bb685e816b4a09832/href">https://medium.com/media/26ce66356cecca6bb685e816b4a09832/href</a></iframe><p>Couple of things to note here: first the Solana program (Solana’s term for a smart contract) crate is being made automatically available here under the program namespace. From there it is automatically available the program unique identifier we defined in the declare_id! macro call.</p><p>Also automatically defined for us is the entry function: this is created from the #[program] macro attribute we used earlier. This is where the code will start running from; sort of the Solana equivalent of a fn main.</p><p>Next up we’ll need to add some accounts to test with, and give them a little pocket money to pay for their transactions (using a few imports from the solana-sdk crate):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/747f00e1ba1d3bd888a4e1fee104fd31/href">https://medium.com/media/747f00e1ba1d3bd888a4e1fee104fd31/href</a></iframe><p>Then we can start up the validator and get testing (most of the following code is in test_program, but I’ll save repeating myself from now on by just putting the new lines by themselves):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bfa03819f70fb349d1b3e352e879cc0/href">https://medium.com/media/1bfa03819f70fb349d1b3e352e879cc0/href</a></iframe><p>The first thing to test is that the mailboxes don’t exist yet, we should have a nice clean starting position:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/674544c76c93ea2c7004dc55275b17d7/href">https://medium.com/media/674544c76c93ea2c7004dc55275b17d7/href</a></iframe><p>The context.banks_client is the interface we can use to query the validator to get things like accounts and balances.</p><p>After that, we can send our first message, but before we do we’ll need some helper functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c51083cb92b5c46abd57ceaa33551af/href">https://medium.com/media/4c51083cb92b5c46abd57ceaa33551af/href</a></iframe><p>This function calls the helper function we created in [lib.rs](&lt;http://lib.rs&gt;) send_direct_message to create the instruction we need, then send it off to the context client as a new transaction (signed by the sender to authorize payment).</p><p>One thing to note here is that we’re using a random seed for a message PDA. You cant use something like the sender or the message body as the seed, because the user might send the same message twice!</p><p>With those done, we can start sending messages in our test function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c93cd377fd4b220af06cab82de290a25/href">https://medium.com/media/c93cd377fd4b220af06cab82de290a25/href</a></iframe><p>(I’ve called the message ciphertext because it should really be encrypted, but as I mentioned above I’ve left that out to simplify things).</p><p>And now we can test that the message worked as expected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75c0a6df0ee41cfe6a5807d7f9956889/href">https://medium.com/media/75c0a6df0ee41cfe6a5807d7f9956889/href</a></iframe><p>We’re using the client to get the accounts data, and then we can de-serialize that (with functions created for us by the #[account] macro), and check the contents are what we expected.</p><p>And that&#39;s about it! One more message just to check its all working as expected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5c1041d8d37153c37d174324dc9536d/href">https://medium.com/media/c5c1041d8d37153c37d174324dc9536d/href</a></iframe><p>Aaaand we’re finally finished writing code. Thank goodness! Only one task remains: let’s run these tests.</p><h3>Running the Tests</h3><p>Normally you’d run cargo test at this point, but to test this properly we need to run cargo test-bpf (if this is your first time using Solana in Rust, you’ll need to install <a href="https://docs.solana.com/cli/install-solana-cli-tools">the Solana tool suite</a>).</p><p>And that should be it! Hopefully, you’ll get output something like this:</p><pre>test test_program ... ok</pre><pre>test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.26s</pre><h3>Conclusion</h3><p>If you’ve stuck with me this far: thanks! And hopefully I’ve been able to show you how to write a small Anchor Solana program, and more importantly how to test it in Rust. As I mentioned in the intro, you can see all the code I’ve outline in full on the <a href="https://github.com/JacobAraiza/messenger">GitHub</a>, feel free to visit that to get a better idea of the full picture.</p><h3>MLabs</h3><p>New technologies like blockchain offer great promise, but creating secure and reliable products is no easy feat. <a href="https://mlabs.city/">MLabs</a> provides essential services to smart contract projects, particularly in the Cardano, Polkadot, and Solana spaces. Our tailored support helps some clients overcome internal hurdles while others rely on MLabs completely for development.</p><p>Startups often lack clear launch strategies. Others have promising product ideas with no ability to execute. MLabs can fill in where needed, reducing both time to launch and overall development cost. With complete DevOps solutions and tailored offerings available, our services are flexible and comprehensive. A software engineering consultancy specializing in Haskell and Rust, MLabs has successfully assisted numerous teams like yours to develop diverse products, many first of their kind to market.</p><p>Connect with <a href="https://mlabs.city/">MLabs</a> today and <a href="https://mlabs.city/contact">schedule your free consultation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65144b0cc5ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>