<?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 Federico Magnani on Medium]]></title>
        <description><![CDATA[Stories by Federico Magnani on Medium]]></description>
        <link>https://medium.com/@drunnnn?source=rss-5b77f59a6593------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uBs4ZXtNt59YFdKt9Xc9Og.jpeg</url>
            <title>Stories by Federico Magnani on Medium</title>
            <link>https://medium.com/@drunnnn?source=rss-5b77f59a6593------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:40:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@drunnnn/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 to create a full working website from scratch (no coding, almost)]]></title>
            <link>https://medium.com/design-bootcamp/how-to-create-a-full-working-website-from-scratch-no-coding-almost-d35fcb97429f?source=rss-5b77f59a6593------2</link>
            <guid isPermaLink="false">https://medium.com/p/d35fcb97429f</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Federico Magnani]]></dc:creator>
            <pubDate>Thu, 19 May 2022 22:53:37 GMT</pubDate>
            <atom:updated>2022-05-21T17:30:30.878Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone,<br>I promised myself that most of the posts I’ll publish here will be crypto-related, but I thought that it could be useful for someone learning how to create a website from scratch for whatever reason.</p><p>Here is a beginner guide for creating a full working website from scratch without <em>initially</em> putting a penny on the table (after UST collapse we are all poor lmao).<br>Since you will be using google cloud trial, at the end of the trial period (3 months) you’ll have to start paying the subscription or you will need to shut down your website :(.</p><p>Let’s play some background music: hopefully you’ll be able to have your fresh new website ready to be customized by the end of the new Gemitaiz’s album</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fopen.spotify.com%2Fembed%2Falbum%2F0VliboIrLzdC2Qgjdm5V4S%3Futm_source%3Doembed&amp;display_name=Spotify&amp;url=https%3A%2F%2Fopen.spotify.com%2Falbum%2F0VliboIrLzdC2Qgjdm5V4S&amp;image=https%3A%2F%2Fi.scdn.co%2Fimage%2Fab67616d00001e029bc0f2396a3033896410b63c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=spotify" width="456" height="380" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad96343c6db2a8671ddebe66ce7f1338/href">https://medium.com/media/ad96343c6db2a8671ddebe66ce7f1338/href</a></iframe><p>Let’s start!</p><figure><img alt="Tom Holland is the worst Spider-Man" src="https://cdn-images-1.medium.com/max/350/0*KEooMRJCIHpespyo" /><figcaption>Tom Holland is the worst Spider-Man ever</figcaption></figure><p>What are our ingredients?<br>• <strong>Google cloud credit </strong>(trial period of 3 months) → consider upgrading the plan at the end of the trial period<br>• <strong>Wordpress</strong> (the best CMS out there if you don’t want to code)<br>• <strong>Register.it</strong> (for registering our domain and DNS stuff)<br>• <strong>Certbot</strong> (for obtaining SSL certificates)</p><p>In a nutshell: we’re going to use google cloud credit for creating a VM instance where we’re going to install wordpress. Then, we will register our domain for free and we will put the IP address of our VM in the DNS configuration of the domain. Finally, we will install SSL certificates via certbot</p><p>This process can be done in the following 3 steps (+bonus):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*4EwDGWjAXQIhcbnNBK06xg.jpeg" /><figcaption>Your face when the website will be online</figcaption></figure><p><strong>Step 1: Google Cloud VM + Wordpress</strong></p><p>Go to the <a href="https://console.cloud.google.com/freetrial/signup/tos">Google Cloud registration page </a>and register for a trial period. It will ask you to register a credit card as a form of identity check, it won’t charge you anything, consider using a virtual Revolut card. <br>IMPORTANT: this will allow you to benefit of google cloud services for 90 days then, if you want your website to be online, you’ll need to start paying the subscription. Otherwhise, if you’re just doing it for fun consider to disable the billing <em>some days before</em> the expiration date of the trial by going to <strong>Billing &gt; Account Management &gt; Disable billing</strong></p><p>Having completed your registration, start <strong>creating a new project: </strong>I’ll call it “Medium article”. So far so good, your dashboard should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3cWz-6ZPHU2o2eyHcfJuw.png" /><figcaption>Google Cloud dashboard of your project</figcaption></figure><p>Now open the burger menu at the top left and scroll to <br><strong>Compute Engine &gt; VM Instances &gt; Enable<br></strong>It will take a while, after some time try to refresh the page.<br>Now, click at the bottom left on “<strong>Marketplace</strong>” and type “wordpress” on the search bar that will have appeared. Choose the wordpress result with the black logo, click on it, and then click on “<strong>Launch</strong>”.<br>In the window that will pop-up, click on “<strong>Enable</strong>”, this will download the Cloud APIs that it needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xY1akhrkojPdtzkNbrkqxA.png" /><figcaption>Searching wordpress on the marketplace</figcaption></figure><p>Now choose the VM instance that you want. We’ll go cautious and we will choose the <strong>e2-small </strong>(default one). It charges near 10 bucks per month, we are allowed to be rich for 90 days so let’s use it. Type your mail, accept the terms of service and run “<strong>Deploy</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwGhfWm75ic2dAVIHMTQSg.png" /></figure><p>In order to see your baby-website, click on the <strong>https://ipAddress…</strong> that will be on your current page, here is a caption:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhN7KBpQ8PdQOgWGe_4xfQ.png" /></figure><p>Indeed, the IP address shown belongs to the VM you’ve just deployed. By clicking on it, your browser may ask you if you’re super-sure to proceed in the navigation since the link would look not secure: just click on <strong>Advanced &gt; Continue.<br></strong> You can access to the wordpress dashboard by logging in with the “<strong>Wordpress Admin</strong>” credentials present in this page and start your editings create pages, posts and whatever you like</p><p>Cheers, your virtual machine is running with Wordpress on it! Let’s move to the second step</p><p><strong>Step 2: Domain registration + DNS configuration</strong></p><p>Now it’s time to reach <a href="https://controlpanel.register.it/"><strong>register.it</strong></a> and register your domain, hoping that it hasn’t been registered by someone else yet. In my case I’m going to register “<strong>supercoolwebsitexd.com</strong>”. In the registration procedure you will be asked to put your credit card information also if the domain you’re purchasing is free: just do the same that you did on the Google Cloud registration step. Notice that register.it will charge you<strong> </strong>€0.01 just for identity verification (it will reimburse you instantaneously). <br>In some cases you’ll be required to confirm the registration via mail.</p><p>Notice that the registration expires in <strong>one year</strong>: in some cases the renewal might not be free</p><p>Now go to your profile page and select the domain you’ve just registered. From the dashboard, click on <strong>DNS &gt; DNS Configuration</strong> (Configurazione DNS) <strong>&gt; Advanced </strong>(Gestione Avanzata) and next to your domain <strong>paste the IP address of your Google Cloud VM </strong>(the address that came out at the end of Step 1).<br>Save the changes (Applica).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*d0IEoKuliGdIU9WEQLQICg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*-fnDXvlngm2bnuruErHocA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*c1T7nmkp-7PaSJtiEpQ2kQ.png" /><figcaption>Before</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*3NKWxTDkwPO66hMigxThOQ.png" /><figcaption>After</figcaption></figure><p>It will take some time for your DNS edits to propagate, take some coffee and scroll your Instagram feed no rush. <br>After some time you will be able to access to your baby-website directly through your new domain, yay!</p><p>What we do now is editing directly the wordpress configuration so that it points directly the domain instead of the VM IP address: <br>access to your website via the admin route ( www.yourdomain.com/wp-admin ), access via the credentials Google Cloud provided you at the end of step 1 and go to <strong>Settings &gt; General</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*d-nL5djowWk0fTAD3PtuGQ.png" /></figure><p>Now, remove the IP address where you see it and substitute it with your new domain (in my case https://www.supercoolwebsitexd.com ): notice that we put “https” instead of “http” even if we still don’t have SSL on, but we will cover it in the next step.<br>In this section you can edit also the site title and the tagline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvpmZmef4PHCub-jLrWa7Q.png" /><figcaption>Update Site Address</figcaption></figure><p><strong>Step 3</strong>: <strong>Register SSL certificates</strong></p><p>Now, if you get scared easily by the view a nice empty command line, here is the tricky part. For the more veterans instead, this will be a cup of tea. <br>Return to the <strong>Compute Engine dashboard</strong> on Google Cloud (<strong>Compute Engine &gt; VM Instances</strong> remember?) and, selecting your current VM, click on <strong>SSH</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVPFbAUkwZQ7hagmQditZw.png" /><figcaption>Communicating with the VM via SSH</figcaption></figure><p>On a new browser instance, a Linux based command-line will appear. This command-line will allow you to interact with the VM: we will use it in order to install the SSL certificates (that is what allows your website to be preceeded by “https” instead of “http”: there is a lot of security stuff behind that “s” of difference).</p><p>We will install the certificates via Certbot. Just copy each of the following lines and paste it on the command line. Notice that when you use the install command, it will ask you Do you want to continue? [Y/n] : just type Y and press enter</p><p>sudo apt update</p><p>sudo apt install snapd → type Y and press enter</p><p>sudo snap install core; sudo snap refresh core</p><p>sudo snap install --classic certbot</p><p>sudo ln -s /snap/bin/certbot /usr/bin/certbot</p><p>sudo certbot --apache <br>→ enter your email, press Enter;<br>→ type Y, press Enter;<br>→ type N, press Enter;<br>→ type your domain, press enter: <br><strong>in my case </strong>supercoolwebsitexd.com, www.supercoolwebsitexd.com</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*eQ0I_PZQcttlfw7yCG4UOQ.png" /></figure><p>→ It may ask you to select a virtual host among two options, select the option associated to “HTTPS”: and type enter (in my case it was the first one, twice)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*ayVqgN01UQTwgHY-_lMY2w.png" /></figure><p>sudo certbot renew --dry-run</p><p>If you didn’t encouter troubles, congrats! Now your website is not flagged anymore as not secure and you’re ready to go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vRXngyJfxjNBI88q4RbhPw.png" /><figcaption>The lock symbol means that the certificate is valid</figcaption></figure><p><strong>Bonus: Indexing on Google</strong></p><p>By covering all the three steps you’re ready to mess around with your website, I suggest you to download a free theme and to gain confidence with Wordpress native site builder (it’s super intuitive tho).</p><p>Once that you’ve defined more or less the final structure and appearence of your website, I would suggest you to care about indexing.</p><p>SEO can give some headache but it is essential for your website to be reachable from external users. In order to save some time (we are lazy aren’t we?) I suggest you to download the Wordpress plugin “<strong>All in One SEO</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3DM5eZ4JvhS7rWii3ja3Q.png" /><figcaption>AIO SEO (seems Sardinian lmao)</figcaption></figure><p>In the configuration, disable the PRO options (unless you want to pay for them) and, once that you’ve set up everything, you should see the dashbord page.<br>Now go to the <a href="https://search.google.com/search-console/welcome?utm_source=about-page">Google Search Console</a> and insert the URL of your website, click on “<strong>Continue</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGSgDhDWjmp-gJ36SB0P1A.png" /><figcaption>Google Search Console</figcaption></figure><p>Now you should see a popup page: click on “<strong>Tag HTML</strong>” and then on “<strong>Copy</strong>”: this allows us to have the meta-tag that must be put in the &lt;head&gt; section of the HTML of our website: AIO SEO will do it for us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56wlopYw5SoZKP95zOT7Qw.png" /></figure><p>Go back to the dashboard of AIO SEO (on your wordpress website) and paste the tag under “<strong>General Settings</strong>”&gt;“<strong>Webmaster Tools</strong>”<strong> &gt; </strong>“<strong>Google</strong>” and then save the changes. This will allow to your google account to claim the property of the website and to access to the search console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-WY1yvIctZxoKN073gjE-Q.png" /></figure><p>Now go on <strong>“Settings</strong>” &gt; “<strong>Permalinks</strong>” and choose “<strong>Post name</strong>”: this allow users to reach the pages via their slug. Remeber to <strong>save changes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXg-Le5nWNLE-Eeb42K7wQ.png" /></figure><p>Finally (last step I promise) come back to AIO SEO dashboard and, by going to “<strong>Sitemaps</strong>” click on “<strong>Open Sitemap</strong>”. You will see a page where are located link defining the sitemap(according to the structure you gave to the websites): you need to copy and paste all of them in the sitemap section of the <a href="https://search.google.com/search-console/sitemaps?">google search console</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUlJahBBS5pJ1njikomLrQ.png" /><figcaption>Button for opening the sitemap</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*viQjtbLX-fBDT5lL0MwbrQ.png" /><figcaption>sitemap list (in my case)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9o0YhN3ei9gnIQYDuU64Rw.png" /></figure><p>Well, you’re done! It has been a little journey but if you reached this point congratulations, you deserve the website you’ve just created! 👏🏽👏🏽👏🏽👏🏽</p><p>Have fun and go crazy :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d35fcb97429f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/design-bootcamp/how-to-create-a-full-working-website-from-scratch-no-coding-almost-d35fcb97429f">How to create a full working website from scratch (no coding, almost)</a> was originally published in <a href="https://medium.com/design-bootcamp">Bootcamp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anatomy of a NFT auto-purchasing bot on Solana]]></title>
            <link>https://drunnnn.medium.com/anatomy-of-a-nft-auto-purchasing-bot-on-solana-ada47a458019?source=rss-5b77f59a6593------2</link>
            <guid isPermaLink="false">https://medium.com/p/ada47a458019</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[solana-nft-marketplace]]></category>
            <category><![CDATA[magic-eden]]></category>
            <category><![CDATA[nft]]></category>
            <dc:creator><![CDATA[Federico Magnani]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 13:09:17 GMT</pubDate>
            <atom:updated>2022-03-20T16:07:53.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzQWeWAfhoVbGpMoGX4FxQ.png" /></figure><p>EDIT (Deprecation Warning): Since the pubblication of this article, Magic Eden started using a different logic on the smart contract side.</p><p>This guide refers to the smart contract deployed at MEisE1HzehtrDpAAT8PnLHjpSSkRYakotTuJRPjTpo8<br>but currently Magic Eden is using a contract deployed at M2mx93ekt1fmXSVkTrUL9xVFHkmME8HTUi5Cyc5aF7K</p><p>NFTs! Without any doubt, The NFTs phenomenon has been one of the most popular trends of 2021 from an economical and social-behavioural perspective.</p><p>The reason behind their popularity, beyond the memes about it, must be sought in the new sensibility of people concerning the theme of “digital property” rather then digital possession, enlarged by the willness of belonging to a large, decentralized community of people interested in cool projects in development, endorsed sometimes by very well known personalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*5QoC2l1Xux0dZzDfWm-2yA.jpeg" /><figcaption>NFT sales on a daily perspective. Source: nonfungible.com</figcaption></figure><p>In this guide we take a step into coding an automated purchasing nft bot which snipes any listing below a certain threshold from the floor price on Magic Eden, one of the biggest nft marketplace on Solana. Let’s get into it!</p><p>Runtime:<br>• Node: v.16.7.0</p><p>Main dependencies:<br>• @project-serum/borsh: ^0.2.2,<br>• borsh: ^0.6.0,<br>• @solana/web3.js: ^1.24.1, <br>• request: ^2.88.2 (deprecated)</p><p>Toolbox: <br>• <strong>Global variables</strong><br>• <strong>Websocket</strong>: in order to retrieve the latest listings of any collection in the fastest way possible. <br>• <strong>Metaplex metadata decoder</strong>: you will need it in order to interpret nfts metadata<br>• <strong>Borsh-decoder</strong>: in order to interpet transaction data.<br>• <strong>Transaction builder</strong>: in order to set properly the transaction we will use to purchase our nfts.<br>• <strong>Floor-Updater</strong>: in order to retrieve the floors of every collection listed on magic eden (&gt;1600 collections) and auto-update the trigger threshold. <br>• <strong>RPC-endpoint</strong>: in order to turn on the websocket and fetch all the necessary data, you will need a provider to perform your JSON-RPC requests. Most of the RPC public endpoints are slow or rate-limited, so the best thing could be selecting a paid plan from a private provider. <br>• <strong>Patience and enthusiasm</strong></p><p>Ready? Let’s go!</p><ol><li><strong>Global variables</strong> (in main.js ):</li></ol><pre>const { Connection, PublicKey, TransactionInstruction, Transaction, Keypair, sendAndConfirmTransaction } = require(&#39;@solana/web3.js&#39;);</pre><pre>const WebSocket = require(&#39;ws&#39;);<br>const fs = require(&#39;fs&#39;)<br>const path = require(&quot;path&quot;)<br>const { decodeMetadata } = require(&quot;./structure&quot;);</pre><pre>const TOKEN_METADATA_PROGRAM_ID = new PublicKey(&#39;metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s&#39;);</pre><pre>const magicEdenAddress = &quot;MEisE1HzehtrDpAAT8PnLHjpSSkRYakotTuJRPjTpo8&quot;</pre><pre>const borsh = require(&#39;@project-serum/borsh&#39;)<br>const borshNpm = require(&#39;borsh&#39;)<br>const bs58 = require(&#39;bs58&#39;)<br>var request = require(&#39;request&#39;);<br>const arrayPvtKey = [*, *, *,...] //your private key in array-format<br>const wally = Keypair.fromSecretKey(new Uint8Array(arrayPvtKey))</pre><pre>var nftListSniping = JSON.parse(fs.readFileSync(path.join(__dirname, &quot;nftSuME.json&quot;)))<br>var sogliaPerc = 0.6<br>const wsConnection = `wss://${/*your endpoint goes here*/}`<br>const url = `https://${/*your endpoint goes here*/}`<br>const connection = new Connection(url)<br>var ws<br>var commitment = &quot;processed&quot;</pre><p>Moreover, we will handle the incoming data from the websocket in a heuristic single-thread way using EventEmitter</p><pre>const EventEmitter = require(&#39;events&#39;);<br>class MyEmitter extends EventEmitter { }<br>const myEmitter = new MyEmitter();</pre><p>2. <strong>Websocket</strong> (in main.js ):</p><pre>function monitor(){ <br>    ws = new WebSocket(wsConnection);<br>    ws.onopen = () =&gt; {<br>        ws.send(JSON.stringify({<br>            &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>            &quot;id&quot;: 1,<br>            &quot;method&quot;: &quot;programSubscribe&quot;,<br>            &quot;params&quot;: [<br>                magicEdenAddress,<br>                {<br>                    &quot;encoding&quot;: &quot;base64&quot;,<br>                    &quot;commitment&quot;: commitment,<br>                }<br>            ]<br>        }));<br>    }<br>    ws.on(&quot;message&quot;, (evt) =&gt; {<br>        try {<br>            var data = JSON.parse(evt).params.result.value<br>            data.slot = JSON.parse(evt).params.result.context.slot<br>            myEmitter.emit(&#39;task&#39;, data); //here we emit the event for retrieving information from the listing<br>        } catch (e) {<br>            console.log(e)<br>        }<br>    })<br>    ws.onclose = function() {<br>        setTimeout(monitor, 100); //sometimes the ws freezes, in this way we restart it <br>    };<br>    return ws<br>}</pre><pre>monitor()</pre><p>3. <strong>Metaplex metadata decoder</strong>: you will need to create a file structure.js where you will have the method to decode the metadata. The code is a bit ugly since it is built from a typescript code</p><pre>&quot;use strict&quot;;<br>exports.__esModule = true;<br>exports.decodeMetadata = exports.METADATA_SCHEMA = exports.Metadata = exports.Data = exports.Creator = exports.Edition = exports.EditionMarker = exports.MasterEditionV2 = exports.MasterEditionV1 = exports.MetadataCategory = exports.MetadataKey = exports.EDITION_MARKER_BIT_SIZE = exports.MAX_EDITION_LEN = exports.MAX_METADATA_LEN = exports.MAX_CREATOR_LEN = exports.MAX_CREATOR_LIMIT = exports.MAX_URI_LENGTH = exports.MAX_SYMBOL_LENGTH = exports.MAX_NAME_LENGTH = exports.RESERVATION = exports.EDITION = exports.METADATA_PREFIX = exports.extendBorsh = void 0;<br>var _a = require(&#39;<a href="http://twitter.com/solana/web3">@solana/web3</a>.js&#39;), SystemProgram = _a.SystemProgram, SYSVAR_RENT_PUBKEY = _a.SYSVAR_RENT_PUBKEY, TransactionInstruction = _a.TransactionInstruction;<br>var borsh_1 = require(&quot;borsh&quot;);<br>var web3_js_1 = require(&quot;<a href="http://twitter.com/solana/web3">@solana/web3</a>.js&quot;);<br>var base58 = require(&#39;bs58&#39;);<br>var extendBorsh = function () {<br>    borsh_1.BinaryReader.prototype.readPubkey = function () {<br>        var reader = this;<br>        var array = reader.readFixedArray(32);<br>        return new web3_js_1.PublicKey(array);<br>    };<br>    borsh_1.BinaryWriter.prototype.writePubkey = function (value) {<br>        var writer = this;<br>        writer.writeFixedArray(value.toBuffer());<br>    };<br>    borsh_1.BinaryReader.prototype.readPubkeyAsString = function () {<br>        var reader = this;<br>        var array = reader.readFixedArray(32);<br>        return base58.encode(array);<br>    };<br>    borsh_1.BinaryWriter.prototype.writePubkeyAsString = function (value) {<br>        var writer = this;<br>        writer.writeFixedArray(base58.decode(value));<br>    };<br>};<br>exports.extendBorsh = extendBorsh;<br>(0, exports.extendBorsh)();<br>exports.METADATA_PREFIX = &#39;metadata&#39;;<br>exports.EDITION = &#39;edition&#39;;<br>exports.RESERVATION = &#39;reservation&#39;;<br>exports.MAX_NAME_LENGTH = 32;<br>exports.MAX_SYMBOL_LENGTH = 10;<br>exports.MAX_URI_LENGTH = 200;<br>exports.MAX_CREATOR_LIMIT = 5;<br>exports.MAX_CREATOR_LEN = 32 + 1 + 1;<br>exports.MAX_METADATA_LEN = 1 +<br>    32 +<br>    32 +<br>    exports.MAX_NAME_LENGTH +<br>    exports.MAX_SYMBOL_LENGTH +<br>    exports.MAX_URI_LENGTH +<br>    exports.MAX_CREATOR_LIMIT * exports.MAX_CREATOR_LEN +<br>    2 +<br>    1 +<br>    1 +<br>    198;<br>exports.MAX_EDITION_LEN = 1 + 32 + 8 + 200;<br>exports.EDITION_MARKER_BIT_SIZE = 248;<br>var MetadataKey;<br>(function (MetadataKey) {<br>    MetadataKey[MetadataKey[&quot;Uninitialized&quot;] = 0] = &quot;Uninitialized&quot;;<br>    MetadataKey[MetadataKey[&quot;MetadataV1&quot;] = 4] = &quot;MetadataV1&quot;;<br>    MetadataKey[MetadataKey[&quot;EditionV1&quot;] = 1] = &quot;EditionV1&quot;;<br>    MetadataKey[MetadataKey[&quot;MasterEditionV1&quot;] = 2] = &quot;MasterEditionV1&quot;;<br>    MetadataKey[MetadataKey[&quot;MasterEditionV2&quot;] = 6] = &quot;MasterEditionV2&quot;;<br>    MetadataKey[MetadataKey[&quot;EditionMarker&quot;] = 7] = &quot;EditionMarker&quot;;<br>})(MetadataKey = exports.MetadataKey || (exports.MetadataKey = {}));<br>var MetadataCategory;<br>(function (MetadataCategory) {<br>    MetadataCategory[&quot;Audio&quot;] = &quot;audio&quot;;<br>    MetadataCategory[&quot;Video&quot;] = &quot;video&quot;;<br>    MetadataCategory[&quot;Image&quot;] = &quot;image&quot;;<br>    MetadataCategory[&quot;VR&quot;] = &quot;vr&quot;;<br>})(MetadataCategory = exports.MetadataCategory || (exports.MetadataCategory = {}));<br>var MasterEditionV1 = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>    function MasterEditionV1(args) {<br>        this.key = MetadataKey.MasterEditionV1;<br>        this.supply = args.supply;<br>        this.maxSupply = args.maxSupply;<br>        this.printingMint = args.printingMint;<br>        this.oneTimePrintingAuthorizationMint =<br>            args.oneTimePrintingAuthorizationMint;<br>    }<br>    return MasterEditionV1;<br>}());<br>exports.MasterEditionV1 = MasterEditionV1;<br>var MasterEditionV2 = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>    function MasterEditionV2(args) {<br>        this.key = MetadataKey.MasterEditionV2;<br>        this.supply = args.supply;<br>        this.maxSupply = args.maxSupply;<br>    }<br>    return MasterEditionV2;<br>}());<br>exports.MasterEditionV2 = MasterEditionV2;<br>var EditionMarker = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>    function EditionMarker(args) {<br>        this.key = MetadataKey.EditionMarker;<br>        this.ledger = args.ledger;<br>    }<br>    EditionMarker.prototype.editionTaken = function (edition) {<br>        var editionOffset = edition % exports.EDITION_MARKER_BIT_SIZE;<br>        var indexOffset = Math.floor(editionOffset / 8);<br>        if (indexOffset &gt; 30) {<br>            throw Error(&#39;bad index for edition&#39;);<br>        }<br>        var positionInBitsetFromRight = 7 - (editionOffset % 8);<br>        var mask = Math.pow(2, positionInBitsetFromRight);<br>        var appliedMask = this.ledger[indexOffset] &amp; mask;<br>        return appliedMask != 0;<br>    };<br>    return EditionMarker;<br>}());<br>exports.EditionMarker = EditionMarker;<br>var Edition = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>    function Edition(args) {<br>        this.key = MetadataKey.EditionV1;<br>        this.parent = args.parent;<br>        this.edition = args.edition;<br>    }<br>    return Edition;<br>}());<br>exports.Edition = Edition;<br>var Creator = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>    function Creator(args) {<br>        this.address = args.address;<br>        this.verified = args.verified;<br>        this.share = args.share;<br>    }<br>    return Creator;<br>}());<br>exports.Creator = Creator;<br>var Data = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>    function Data(args) {<br>        this.name = args.name;<br>        this.symbol = args.symbol;<br>        this.uri = args.uri;<br>        this.sellerFeeBasisPoints = args.sellerFeeBasisPoints;<br>        this.creators = args.creators;<br>    }<br>    return Data;<br>}());<br>exports.Data = Data;<br>var Metadata = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>    function Metadata(args) {<br>        this.key = MetadataKey.MetadataV1;<br>        this.updateAuthority = args.updateAuthority;<br>        this.mint = args.mint;<br>        this.data = args.data;<br>        this.primarySaleHappened = args.primarySaleHappened;<br>        this.isMutable = args.isMutable;<br>        this.editionNonce = args.editionNonce;<br>    }<br>    return Metadata;<br>}());<br>exports.Metadata = Metadata;<br>var CreateMetadataArgs = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>    function CreateMetadataArgs(args) {<br>        this.instruction = 0;<br>        this.data = args.data;<br>        this.isMutable = args.isMutable;<br>    }<br>    return CreateMetadataArgs;<br>}());<br>var UpdateMetadataArgs = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>    function UpdateMetadataArgs(args) {<br>        this.instruction = 1;<br>        this.data = args.data ? args.data : null;<br>        this.updateAuthority = args.updateAuthority ? args.updateAuthority : null;<br>        this.primarySaleHappened = args.primarySaleHappened;<br>    }<br>    return UpdateMetadataArgs;<br>}());<br>var CreateMasterEditionArgs = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>    function CreateMasterEditionArgs(args) {<br>        this.instruction = 10;<br>        this.maxSupply = args.maxSupply;<br>    }<br>    return CreateMasterEditionArgs;<br>}());<br>var MintPrintingTokensArgs = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>    function MintPrintingTokensArgs(args) {<br>        this.instruction = 9;<br>        this.supply = args.supply;<br>    }<br>    return MintPrintingTokensArgs;<br>}());<br>exports.METADATA_SCHEMA = new Map([<br>    [<br>        CreateMetadataArgs,<br>        {<br>            kind: &#39;struct&#39;,<br>            fields: [<br>                [&#39;instruction&#39;, &#39;u8&#39;],<br>                [&#39;data&#39;, Data],<br>                [&#39;isMutable&#39;, &#39;u8&#39;], // bool<br>            ]<br>        },<br>    ],<br>    [<br>        UpdateMetadataArgs,<br>        {<br>            kind: &#39;struct&#39;,<br>            fields: [<br>                [&#39;instruction&#39;, &#39;u8&#39;],<br>                [&#39;data&#39;, { kind: &#39;option&#39;, type: Data }],<br>                [&#39;updateAuthority&#39;, { kind: &#39;option&#39;, type: &#39;pubkeyAsString&#39; }],<br>                [&#39;primarySaleHappened&#39;, { kind: &#39;option&#39;, type: &#39;u8&#39; }],<br>            ]<br>        },<br>    ],<br>    [<br>        CreateMasterEditionArgs,<br>        {<br>            kind: &#39;struct&#39;,<br>            fields: [<br>                [&#39;instruction&#39;, &#39;u8&#39;],<br>                [&#39;maxSupply&#39;, { kind: &#39;option&#39;, type: &#39;u64&#39; }],<br>            ]<br>        },<br>    ],<br>    [<br>        MintPrintingTokensArgs,<br>        {<br>            kind: &#39;struct&#39;,<br>            fields: [<br>                [&#39;instruction&#39;, &#39;u8&#39;],<br>                [&#39;supply&#39;, &#39;u64&#39;],<br>            ]<br>        },<br>    ],<br>    [<br>        MasterEditionV1,<br>        {<br>            kind: &#39;struct&#39;,<br>            fields: [<br>                [&#39;key&#39;, &#39;u8&#39;],<br>                [&#39;supply&#39;, &#39;u64&#39;],<br>                [&#39;maxSupply&#39;, { kind: &#39;option&#39;, type: &#39;u64&#39; }],<br>                [&#39;printingMint&#39;, &#39;pubkeyAsString&#39;],<br>                [&#39;oneTimePrintingAuthorizationMint&#39;, &#39;pubkeyAsString&#39;],<br>            ]<br>        },<br>    ],<br>    [<br>        MasterEditionV2,<br>        {<br>            kind: &#39;struct&#39;,<br>            fields: [<br>                [&#39;key&#39;, &#39;u8&#39;],<br>                [&#39;supply&#39;, &#39;u64&#39;],<br>                [&#39;maxSupply&#39;, { kind: &#39;option&#39;, type: &#39;u64&#39; }],<br>            ]<br>        },<br>    ],<br>    [<br>        Edition,<br>        {<br>            kind: &#39;struct&#39;,<br>            fields: [<br>                [&#39;key&#39;, &#39;u8&#39;],<br>                [&#39;parent&#39;, &#39;pubkeyAsString&#39;],<br>                [&#39;edition&#39;, &#39;u64&#39;],<br>            ]<br>        },<br>    ],<br>    [<br>        Data,<br>        {<br>            kind: &#39;struct&#39;,<br>            fields: [<br>                [&#39;name&#39;, &#39;string&#39;],<br>                [&#39;symbol&#39;, &#39;string&#39;],<br>                [&#39;uri&#39;, &#39;string&#39;],<br>                [&#39;sellerFeeBasisPoints&#39;, &#39;u16&#39;],<br>                [&#39;creators&#39;, { kind: &#39;option&#39;, type: [Creator] }],<br>            ]<br>        },<br>    ],<br>    [<br>        Creator,<br>        {<br>            kind: &#39;struct&#39;,<br>            fields: [<br>                [&#39;address&#39;, &#39;pubkeyAsString&#39;],<br>                [&#39;verified&#39;, &#39;u8&#39;],<br>                [&#39;share&#39;, &#39;u8&#39;],<br>            ]<br>        },<br>    ],<br>    [<br>        Metadata,<br>        {<br>            kind: &#39;struct&#39;,<br>            fields: [<br>                [&#39;key&#39;, &#39;u8&#39;],<br>                [&#39;updateAuthority&#39;, &#39;pubkeyAsString&#39;],<br>                [&#39;mint&#39;, &#39;pubkeyAsString&#39;],<br>                [&#39;data&#39;, Data],<br>                [&#39;primarySaleHappened&#39;, &#39;u8&#39;],<br>                [&#39;isMutable&#39;, &#39;u8&#39;], // bool<br>            ]<br>        },<br>    ],<br>    [<br>        EditionMarker,<br>        {<br>            kind: &#39;struct&#39;,<br>            fields: [<br>                [&#39;key&#39;, &#39;u8&#39;],<br>                [&#39;ledger&#39;, [31]],<br>            ]<br>        },<br>    ],<br>]);<br>// eslint-disable-next-line no-control-regex<br>var METADATA_REPLACE = new RegExp(&#39;\u0000&#39;, &#39;g&#39;);<br>var decodeMetadata = function (buffer) {<br>    var metadata = (0, borsh_1.deserializeUnchecked)(exports.METADATA_SCHEMA, Metadata, buffer);<br>    metadata.data.name = metadata.data.name.replace(METADATA_REPLACE, &#39;&#39;);<br>    metadata.data.uri = metadata.data.uri.replace(METADATA_REPLACE, &#39;&#39;);<br>    metadata.data.symbol = metadata.data.symbol.replace(METADATA_REPLACE, &#39;&#39;);<br>    return metadata;<br>};<br>exports.decodeMetadata = decodeMetadata;</pre><p>On the other hand, on main.js , you write these two functions in order to handle with the metadata account and the metadata itself</p><pre>async function getMetadataAccount(nftAddress) {<br>    var address = (await PublicKey.findProgramAddress([Buffer.from(&quot;metadata&quot;), TOKEN_METADATA_PROGRAM_ID.toBuffer(), nftAddress.toBuffer()], TOKEN_METADATA_PROGRAM_ID))[0]<br>    return address<br>}</pre><pre>async function getParsedMetadata(connection, nftAddress) {<br>    var metaAddress = await getMetadataAccount(nftAddress)<br>    var data = (await connection.getAccountInfo(metaAddress)).data<br>    const metadata = decodeMetadata(data)<br>    return metadata<br>}</pre><p>4. <strong>Borsh-decoder</strong> (in main.js ): we will need these decoders to retrieve the nft address from the escrow account data, to decode the price from the listing transaction and to encode the price for the purchasing transaction</p><pre>async function decodeEscrowAccountData(escrowPubkey) { <br>    const dataLayout = borsh.struct([<br>        borsh.publicKey(&quot;initializerKey&quot;),<br>        borsh.publicKey(&quot;initializerDepositTokenAccount&quot;),<br>        borsh.u64(&quot;takerAmount&quot;)<br>    ]);<br>    const t = dataLayout.decode(data)<br>    for (var i = 0; i &lt; Object.keys(t).length; i++) {<br>        t[Object.keys(t)[i]] = Object.values(t)[i].toString()<br>    }<br>    var nftAddress = t.initializerKey<br>    return nftAddress<br>}</pre><pre>async function getPriceFromBase64Data(base64Data) {<br>    var data_layout = borsh.struct([<br>        borsh.u64(&quot;nonSoCheE&quot;),<br>        borsh.publicKey(&quot;owner&quot;),<br>        borsh.publicKey(&quot;escrowID&quot;),<br>        borsh.u64(&quot;price&quot;),<br>    ])<br>    var escrowPubkeyEncodedData = Buffer.from(base64Data,&quot;base64&quot;)<br>    const t = data_layout.decode(escrowPubkeyEncodedData)<br>    for (var i = 0; i &lt; Object.keys(t).length; i++) {<br>        t[Object.keys(t)[i]] = Object.values(t)[i].toString()<br>    }<br>    var escrowPubkey = t.escrowID<br>    var walletVenditore = t.owner<br>    var encodedPrice = Number(t.price)<br>    return [walletVenditore,escrowPubkey,encodedPrice]<br>}</pre><pre>function encodePrice(cifraIntera){<br>    var g = { x: &#39;8179382949091792022&#39;, y: String(cifraIntera) }<br>    class Assignable {<br>        constructor(properties) {<br>            Object.keys(properties).map((key) =&gt; {<br>                this[key] = properties[key];<br>            });<br>        }<br>    }<br>    const value = new Assignable(g);<br>    const schema = new Map([[Assignable, { kind: &#39;struct&#39;, fields: [[&#39;x&#39;, &#39;u64&#39;], [&#39;y&#39;, &#39;u64&#39;],] }]]);<br>    const encodedPrice = borshNpm.serialize(schema, value).toString(&quot;hex&quot;);<br>    return encodedPrice<br>}</pre><pre>function costruisciDataAcquisto(encodedPrice, indirizzoNFT) {<br>    try {<br>        var a = &quot;438e36d81f1d1b5c&quot;<br>        var dataInHex = encodedPrice.replace(&quot;96d480ba74018371&quot;, &quot;&quot;)<br>        // dataInHex = dataInHex.substr(0, dataInHex.length - 2)<br>        var b = dataInHex<br>        var c = new PublicKey(indirizzoNFT).toBuffer().toString(&quot;hex&quot;)<br>        var dataAcquisto = a + b + c<br>        return dataAcquisto<br>    } catch (e) {<br>        return null<br>    }<br>}</pre><p>5. <strong>Transaction builder</strong>: now we have in main.js the functions for building the purchasing transaction. We split this step into intermediate steps for <br>1) arraging all the essential information <br>2) adding the instructions to the transaction <br>3) sending the transaction</p><pre>async function MEaddInstructionsForBuyingNFT(transaction, walletAcquirente, escrowID, walletVenditore, escrowPubkey, indirizzoMetadati, indirizziCreatori, dataAcquisto) {<br>    var indirizzoSconosciuto1 = &quot;GUfCR9mK6azb9vcpsxgXyj7XRPAKJd4KMHTTVvtncGgp&quot;<br>    var systemProgram = &quot;11111111111111111111111111111111&quot;<br>    var tokenProgram = &quot;TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA&quot;<br>    var indirizzoSconosciuto2 = &quot;2NZukH2TXpcuZP4htiuT8CFxcaQSWzkkR6kepSWnZ24Q&quot;<br>    var dataInstrutionInHex = dataAcquisto<br>    var programId = &quot;MEisE1HzehtrDpAAT8PnLHjpSSkRYakotTuJRPjTpo8&quot;<br>    var dataInstruction2Buffered = Buffer.from(dataInstrutionInHex, &#39;hex&#39;)<br>    var instructions = new TransactionInstruction({<br>        data: dataInstruction2Buffered,<br>        keys: [<br>            {<br>                pubkey: new PublicKey(walletAcquirente),<br>                isSigner: true,<br>                isWritable: true<br>            },<br>            {<br>                pubkey: new PublicKey(escrowPubkey),<br>                isSigner: false,<br>                isWritable: true<br>            },<br>            {<br>                pubkey: new PublicKey(walletVenditore),<br>                isSigner: false,<br>                isWritable: true<br>            },<br>            {<br>                pubkey: new PublicKey(escrowID),<br>                isSigner: false,<br>                isWritable: true<br>            },<br>            {<br>                pubkey: new PublicKey(indirizzoSconosciuto1),<br>                isSigner: false,<br>                isWritable: false<br>            },<br>            {<br>                pubkey: new PublicKey(systemProgram),<br>                isSigner: false,<br>                isWritable: false<br>            },<br>            {<br>                pubkey: new PublicKey(tokenProgram),<br>                isSigner: false,<br>                isWritable: false<br>            },<br>            {<br>                pubkey: new PublicKey(indirizzoSconosciuto2),<br>                isSigner: false,<br>                isWritable: true<br>            },<br>            {<br>                pubkey: new PublicKey(indirizzoMetadati),<br>                isSigner: false,<br>                isWritable: false<br>            }<br>        ],<br>        programId: new PublicKey(programId)<br>    })<br>    for (var i = 0; i &lt; indirizziCreatori.length; i++) {<br>        var w = {<br>            pubkey: new PublicKey(indirizziCreatori[i]),<br>            isSigner: false,<br>            isWritable: true<br>        }<br>        instructions.keys.push(w)<br>    }<br>    return transaction.add(instructions)<br>}</pre><pre>async function MEbuyOnChainPt1(arrayPvtKey, inserzione) {<br>    const privateKeyuint8 = new Uint8Array(arrayPvtKey)<br>    const mioWallet = Keypair.fromSecretKey(privateKeyuint8)<br>    console.log(mioWallet.publicKey.toString())<br>    const walletAcquirente = mioWallet.publicKey.toString()<br>    var transaction = new Transaction()<br>    var escrowID = inserzione.escrowID<br>    var walletVenditore = inserzione.walletVenditore<br>    var escrowPubkey = inserzione.escrowPubkey<br>    var indirizzoMetadati = inserzione.indirizzoMetadati<br>    var dataAcquisto = inserzione.dataAcquisto<br>    var indirizziCreatori = inserzione.dettagliCollezione.creators.map((x) =&gt; {<br>        return x.address<br>    })<br>    transaction = await MEaddInstructionsForBuyingNFT(transaction, walletAcquirente, escrowID, walletVenditore, escrowPubkey, indirizzoMetadati, indirizziCreatori, dataAcquisto)<br>    return transaction<br>}</pre><pre>async function MEbuyOnChainPt2(arrayPvtKey, transaction) {<br>    const privateKeyuint8 = new Uint8Array(arrayPvtKey)<br>    const mioWallet = Keypair.fromSecretKey(privateKeyuint8)<br>    try {<br>        console.dir(transaction, { depth: null })<br>        var c = connection<br>        const signature = await sendAndConfirmTransaction(c, transaction, [mioWallet])<br>        console.log(signature)<br>        return signature<br>    } catch (e) {<br>        console.log(e)<br>    }<br>}</pre><p>Now, we are left to arrange everything we’ve written so far into the callback of the event “task” emitted whenever a new listing transaction arrives</p><pre>myEmitter.on(&#39;task&#39;,async(data)=&gt;{<br>    var escrowID = data.pubkey<br>    try{<br>        var base64Data = data.account.data[0]<br>        var isPotentialSaleInsertion = base64Data.includes(&quot;JEUwEoDhf&quot;)<br>        if (!isPotentialSaleInsertion) {<br>            return<br>        }<br>        var [walletVenditore,escrowPubkey,encodedPrice] = await getPriceFromBase64Data(base64Data)<br>        var prezzo = encodedPrice* 0.000000001<br>        encodedPrice=encodePrice(encodedPrice)<br>        var nftAddress = await decodeEscrowAccountData(escrowPubkey)<br>        var metadata = await getParsedMetadata(connection, new PublicKey(nftAddress))<br>        if (!metadata) {<br>            return<br>        }<br>        var dettagliCollezione = {<br>            nomeNftInCollezione: metadata.data.name,<br>            collezione: metadata.data.symbol,<br>            sellerFeeBasisPoint: metadata.data.sellerFeeBasisPoints,<br>            creators: metadata.data.creators,<br>        }<br>        var indirizzoMetadati = await getMetadataAccount(new PublicKey(nftAddress))<br>        var inserzione = {<br>            nome: metadata.data.name,<br>            prezzo: prezzo,<br>            encodedPrice: encodedPrice,<br>            indirizzoNFT: metadata.mint,<br>            indirizzoMetadati: indirizzoMetadati.toString(),<br>            walletVenditore: walletVenditore,<br>            escrowPubkey: escrowPubkey,<br>            escrowID: escrowID,<br>            dettagliCollezione: dettagliCollezione,<br>            slot:data.slot<br>        }<br>        if (!inserzione.dettagliCollezione.creators) {<br>            return<br>        }<br>        var buildCollezioneString = `${inserzione.dettagliCollezione.collezione}_&amp;_${inserzione.dettagliCollezione.creators[0].address}`<br>        inserzione.buildCollezioneString = buildCollezioneString<br>        inserzione.dataAcquisto = costruisciDataAcquisto(inserzione.encodedPrice, inserzione.indirizzoNFT)<br>        var nelMirino = _.sortBy(nftListSniping.filter(x =&gt; x.collezione === inserzione.buildCollezioneString), [&quot;floorPrice&quot;])[0]<br>        if(nelMirino){<br>            inserzione.soglia=nelMirino.soglia<br>        }<br>        console.log(inserzione)<br>        if(!nelMirino||Number(inserzione.prezzo) &gt;= nelMirino.soglia){<br>            return<br>        }<br>        try{<br>            myEmitter.emit(&#39;compracompra&#39;, inserzione);<br>        }catch(e){}<br>    }catch(e){<br>        console.log(e)<br>    }<br>})</pre><p>if the listing had survived after all the quality checks, we’re ready to emit the event for buying the listed nft</p><pre>myEmitter.on(&quot;compracompra&quot;,async(inserzione)=&gt;{<br>    try {<br>        var transact = await MEbuyOnChainPt1(arrayPvtKey, inserzione) <br>        var sign = await MEbuyOnChainPt2(arrayPvtKey, transact)<br>        if (sign) {<br>            console.log(`Purchasing TX: ${sign}`)<br>        }<br>    } catch (e) {<br>        console.log(e)<br>    }<br>})</pre><p>6. <strong>Floor-Updater</strong>: So, this was the last step to build a working bot, but in order to know the proper trigger prices, we need to have a list of the collections we’re targeting and we need to update periodically the floor prices. The on-chain solution would be scraping each escrow account on magiceden , but it is super inefficient in terms of time and resource wasting. The off-chain method is still super inefficient but at least is useable: it is about fetching all collections via magiceden api. It would be better integrating the followingcode in a separated process. The updated information will be saved in nftSuMe.json</p><pre>const { Connection, PublicKey} = require(&#39;<a href="http://twitter.com/solana/web3">@solana/web3</a>.js&#39;);<br>const fs = require(&#39;fs&#39;)<br>const path = require(&quot;path&quot;)<br>const { decodeMetadata } = require(&quot;./structure&quot;);<br>const TOKEN_METADATA_PROGRAM_ID = new PublicKey(&#39;metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s&#39;);<br>var request = require(&#39;request&#39;);</pre><pre>var nftListSniping = JSON.parse(fs.readFileSync(path.join(__dirname, &quot;nftSuME.json&quot;)))<br>var coolDownPeriodRequest = 0 <br>var sogliaPerc = 0.6</pre><pre>var coolDownPeriod = 250<br>const url = `<a href="https://${/*">https://${/*</a> your endpoint here */}`<br>var connection = new Connection(url)</pre><pre>async function getMetadataAccount(nftAddress) {<br>    var address = (await PublicKey.findProgramAddress([Buffer.from(&quot;metadata&quot;), TOKEN_METADATA_PROGRAM_ID.toBuffer(), nftAddress.toBuffer()], TOKEN_METADATA_PROGRAM_ID))[0]<br>    return address<br>}</pre><pre>function coolDown(coolDownPeriod) {<br>    return new Promise((resolve) =&gt; {<br>        setTimeout(() =&gt; {<br>            resolve()<br>        }, coolDownPeriod)<br>    })<br>}</pre><pre>async function escrowStatsRPC(collectionName) {<br>    return new Promise((resolve) =&gt; {<br>        var options = {<br>            &#39;method&#39;: &#39;GET&#39;,<br>            &#39;url&#39;: `<a href="https://api-mainnet.magiceden.io/rpc/getCollectionEscrowStats/$%7BcollectionName%7D?nowait=true`">https://api-mainnet.magiceden.io/rpc/getCollectionEscrowStats/${collectionName}?nowait=true`</a>,<br>            &#39;headers&#39;: {<br>                &#39;authority&#39;: &#39;api-mainnet.magiceden.io&#39;,<br>                &#39;user-agent&#39;: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36&#39;<br>            }<br>        };<br>        request(options, function (error, response) {<br>            try {<br>                if (error) throw new Error(error);<br>                var result = JSON.parse(response.body).results<br>                // console.log(response.headers[&#39;x-ratelimit-remaining&#39;])<br>                if (response.statusCode != 200) {<br>                    console.log(response.statusCode)<br>                }<br>                var w = {<br>                    symbol: result.symbol,<br>                    name: result.name,<br>                    listedCount: result.listedCount,<br>                    floorPrice: result.floorPrice * 0.000000001,<br>                    avgPrice24hr: result.avgPrice24hr * 0.000000001,<br>                    volume24hr: Number(result.volume24hr) * 0.000000001,<br>                    volumeAll: result.volumeAll * 0.000000001<br>                }<br>                w.soglia = w.floorPrice * sogliaPerc<br>                resolve(w)<br>            } catch (e) {<br>                resolve(null)<br>            }<br>        });<br>    })</pre><pre>}</pre><pre>async function getMintAndFirstCreatorRPC(collectionName) {<br>    var encodedData = encodeURIComponent(`{&quot;$match&quot;:{&quot;collectionSymbol&quot;:&quot;${collectionName}&quot;},&quot;$sort&quot;:{&quot;takerAmount&quot;:1,&quot;createdAt&quot;:-1},&quot;$skip&quot;:0,&quot;$limit&quot;:20}`)<br>    return new Promise((resolve) =&gt; {<br>        var options = {<br>            &#39;method&#39;: &#39;GET&#39;,<br>            &#39;url&#39;: `<a href="https://api-mainnet.magiceden.io/rpc/getListedNFTsByQuery?nowait=true&amp;q=${encodedData}`">https://api-mainnet.magiceden.io/rpc/getListedNFTsByQuery?nowait=true&amp;q=${encodedData}`</a>,<br>            &#39;headers&#39;: {<br>                &#39;authority&#39;: &#39;api-mainnet.magiceden.io&#39;,<br>                &#39;accept&#39;: &#39;application/json, text/plain, */*&#39;,<br>                &#39;user-agent&#39;: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36&#39;,<br>                &#39;origin&#39;: &#39;<a href="https://magiceden.io&/#39;">https://magiceden.io&#39;</a>,<br>                &#39;referer&#39;: &#39;<a href="https://magiceden.io/&#39;">https://magiceden.io/&#39;</a><br>            }<br>        };<br>        request(options, function (error, response) {<br>            try {<br>                if (error) throw new Error(error);<br>                if (response.statusCode != 200) {<br>                    console.log(response.statusCode)<br>                }<br>                var nft = JSON.parse(response.body).results.shift()<br>                if (!nft) throw new Error(error);<br>                var address = nft.mintAddress<br>                var firstcreator = nft.creators.shift().address<br>                resolve([address, firstcreator])<br>            } catch (e) {<br>                resolve([null, null])<br>            }<br>        });<br>    })<br>}</pre><pre>async function massivePriceCheckEndpoint(show) {<br>    try {<br>        var richiesteTotali = 0<br>        var start = performance.now()<br>        return new Promise((resolve, reject) =&gt; {<br>            var options = {<br>                &#39;method&#39;: &#39;GET&#39;,<br>                &#39;url&#39;: &#39;<a href="https://api-mainnet.magiceden.io/all_collections?nowait=true&#39;">https://api-mainnet.magiceden.io/all_collections?nowait=true&#39;</a>,<br>                &#39;headers&#39;: {<br>                }<br>            };<br>            request(options, function (error, response) {<br>                try {<br>                    if (error) throw new Error(error);<br>                    var nomiCollezione = JSON.parse(response.body).collections.map((x) =&gt; { <br>                        if(!x.isFlagged){<br>                            return x.symbol<br>                        } <br>                    }).filter((x) =&gt; { if (x) return x })<br>                    resolve(nomiCollezione)<br>                } catch (e) { reject(e) }<br>            });<br>        })<br>            .then((nomiCollezione) =&gt; {<br>                return new Promise(async (resolve) =&gt; {<br>                    var allData = []//floors, avgP 24h, vol 2h<br>                    async function push(i) {<br>                        var d = await escrowStatsRPC(nomiCollezione[i])<br>                        if (d) {<br>                            var [address, firstcreator] = await getMintAndFirstCreatorRPC(nomiCollezione[i])<br>                            if (address &amp;&amp; firstcreator) {<br>                                d.address = address<br>                                d.metadataAccount = await getMetadataAccount(new PublicKey(address))<br>                                d.firstcreator = firstcreator<br>                                if (show) {<br>                                    console.log(`${i + 1}/${nomiCollezione.length}`)<br>                                }<br>                                allData.push(d)<br>                            }<br>                        }<br>                    }<br>                    for (var i = 0; i &lt; nomiCollezione.length; i++) {<br>                        try {<br>                            await push(i)<br>                            await coolDown(coolDownPeriodRequest)<br>                        } catch (e) { }<br>                    }<br>                    allData = allData.filter((x) =&gt; { if (x) return x })<br>                    var limit = 100<br>                    var finalBigData = []<br>                    for (var i = 0; i &lt; allData.length; i += Math.min(limit, Math.max(Math.abs(allData.length - i - 1), 1))) {<br>                        try{<br>                            richiesteTotali += 1<br>                            // console.log(`${i+1}/${allData.length}`)<br>                            var cap = Math.min(i + limit, allData.length - 1)<br>                            var Accs = allData.slice(i, cap)<br>                            var metadataAccounts = Accs.map((x) =&gt; { return new PublicKey(x.metadataAccount) })<br>                            var bunchData = (await connection.getMultipleAccountsInfo(metadataAccounts))<br>                            for (var z = 0; z &lt; bunchData.length; z++) {<br>                                try {<br>                                    var x = bunchData[z]<br>                                    var data = decodeMetadata(x.data)<br>                                    if (data.data.creators) {<br>                                        // Accs[z].metadata = data<br>                                        Accs[z].collezione = `${data.data.symbol}_&amp;_${data.data.creators[0].address}` //`_&amp;_${data.data.creators[0].address}`//<br>                                        Accs[z].timestamp = new Date(Date.now()).toTimeString()<br>                                        finalBigData.push(Accs[z])<br>                                    }<br>                                    // allData[indexOf(Accs, Accs[z])].metadata = data<br>                                } catch (e) {<br>                                    console.log(e)<br>                                    console.dir(Accs[z], { depth: null })<br>                                }<br>                            }<br>                            await coolDown(coolDownPeriod)    <br>                        }catch(e){}<br>                    }<br>                    try {<br>                        fs.writeFileSync(path.join(__dirname, &quot;nftSuME.json&quot;), JSON.stringify(finalBigData))<br>                    } catch (e) { }<br>                    resolve(finalBigData)<br>                })<br>            })<br>            .catch((e) =&gt; {<br>                console.log(e)<br>                return null<br>            })<br>    } catch (e) {<br>        console.log(e)<br>    }<br>}</pre><pre>massivePriceCheckEndpoint(true)<br>setInterval(async () =&gt; {<br>    try {<br>        var lista = await massivePriceCheckEndpoint(true)<br>        if (lista) {<br>            nftListSniping = lista<br>        }<br>    } catch (e) {<br>        console.log(e)<br>    }<br>}, 50000)</pre><p>while on main.js :</p><pre>setInterval(async () =&gt; {<br>  try {<br>    var file = &quot;nftSuME.json&quot;<br>    var lista1 = await readFile(path.join(__dirname, file))<br>    if (lista1) {<br>      nftListSniping = JSON.parse(lista1)<br>    }<br>  } catch (e) {<br>    console.log(e)<br>  }<br>}, 50000)</pre><p>We reached the end of this guide, congrats! <br>If you make some bucks out of this please consider donating some SOL to this address: EtfgPnXhF2WNjmAdBCoD8VCMfPskw96yDXMV2NPnCxZX</p><p>All the best! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ada47a458019" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>