<?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 Nick Stebbs on Medium]]></title>
        <description><![CDATA[Stories by Nick Stebbs on Medium]]></description>
        <link>https://medium.com/@n-stebbings?source=rss-9224a7e051eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xJgQCCkqAJFJr_UhETPWbA.jpeg</url>
            <title>Stories by Nick Stebbs on Medium</title>
            <link>https://medium.com/@n-stebbings?source=rss-9224a7e051eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:35:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@n-stebbings/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[Building a kitty utopia with Rust (and Solidity): III — The Math(s) of Herding Cats]]></title>
            <link>https://n-stebbings.medium.com/building-a-kitty-utopia-with-rust-and-solidity-iii-the-math-s-of-herding-cats-7bd66e6a5d27?source=rss-9224a7e051eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bd66e6a5d27</guid>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[cryptography-for-dummies]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[zero-knowledge]]></category>
            <dc:creator><![CDATA[Nick Stebbs]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 06:00:27 GMT</pubDate>
            <atom:updated>2025-03-25T00:17:59.306Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a kitty utopia with Rust (and Solidity): III — The Math(s) of Herding Cats</h3><p><em>To catch up with this series, start here:<br></em><a href="https://n-stebbings.medium.com/building-a-kitty-utopia-in-rust-i-kitception-330b12455f9e"><em>Part 1</em></a><em> </em><a href="https://n-stebbings.medium.com/building-a-kitty-utopia-with-rust-and-solidity-ii-we-build-in-stages-0b07133d2288"><em>Part 2</em></a></p><p>Brace yourselves. No trip through the world of zero-knowledge was going to avoid a prowl down Math(s)* alley. I’ve tried my best to make it digestible!</p><p><em>*If you are perhaps an American who likes to drop the ‘s’ here: be grateful I’ve humored you this far. I’m a Brit, so there are some things I just cannot do. </em>🎩</p><h3>Let’s Be Discrete</h3><p>So far, we’ve touched on the magic of elliptic curves (generating a useful public key that we can share, and letting us keep our private key… private).</p><p>Let’s dig a little deeper and find out <em>how </em>they are so useful in encryption. As it turns out, the reason is related to another classical encryption problem; one that provides some some pretty handy mathematical difficulties. Namely, the difficulty of solving the <strong>discrete logarithm problem.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*peovAHNUEyEkxRrs-fuY6g.png" /><figcaption>Classical discrete logarithm problem in a finite field (yawn)</figcaption></figure><p>If your eyes are glazing over, let me use an analogy. Let’s say you started with a <em>time</em> on a traditional two-handed clock 🕰 that only you knew exactly (a, above, which is analogous to our private key). Say that you wanted to share a different time A with a friend, which was related to yours by a certain number of complete rotations around the clock (this new time is analogous to our public key). As we know, when you go around the clock, it will wrap around and start back at 0. In the discrete logarithm problem, we&#39;re dealing with modular exponentiation, where we compute A = g^a mod p. Here, g is a special number (a generator) that everyone knows, and raising it to the power of a (your private key) gives us A (your public key) when we consider everything modulo p (with clock arithmetic).</p><p>In the clock analogy, p is 12. But in cryptographic systems, we take p to be a very large prime number. So, the mod p part above means we wrap around when we get to this big prime number p.</p><p>The discrete logarithm problem states that — if we use big enough numbers here — even when we give away the public value A (and everyone already knows g), it will take an infeasibly long time for anyone to work out a (our private key), because there are so many possible values and we&#39;d essentially have to try them all.</p><h3>How does this relate to crypto?</h3><p><em>*serious Maths warning</em></p><p>When we move to elliptic curve cryptography (the form that’s primarily used for public/private key generation in blockchain), we adapt this concept.</p><p>Instead of modular exponentiation, we use point addition on one of our magical elliptic curves (a special way of adding points, ensuring the result is also on the curve). In elliptic curve systems, we compute A = a·G, where G is a generator point on the curve (known to everyone), a is our private key (a scalar), and A is our public key (another point on the curve).</p><p>In other words, in elliptic curve systems, instead of raising numbers to powers in a finite field (a set of numbers that go up to our prime, p, with operations that wrap around at p, i.e., mod p), we instead perform repeated addition of points on an elliptic curve defined over the field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhACIcFxoqEzxfx6pynaRg.png" /><figcaption>Elliptic Curve Discrete Logarithm Problem (ECDLP - an acronym I would rank as quite average in its potential for humor)</figcaption></figure><p>For a great visual representation of this stuff, which was key to my understanding, I highly recommend <a href="https://curves.xargs.org/">this site</a>!</p><p>Some of these curves support <em>bilinear pairings -</em> which allow certain structured operations that are difficult to reverse. These pairings are critical in zero-knowledge proofs, enabling our magical privacy sauce. In our case: the Semaphore protocol we will soon be enacting uses a BN254 curve, which I will let you <a href="https://hackmd.io/@jpw/bn254">geek out on</a> in your own time. Thankfully it also uses the fun-sounding BabyJubJub, as mentioned in the <a href="https://semaphore.pse.dev/whitepaper-v1.pdf">whitepaper</a>. In case you are wondering what the recipe for these curves are…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZQGi4n4-iUcsL0GY5B--A.png" /><figcaption>Baby Jubjub,(Not actually an acronym, but I’ll take it)</figcaption></figure><h3>The Cool Cats Club: A story to understand Zero-Knowledge Proofs (Maths warnings now retracted)</h3><p><em>If you’re vaguely with me so far, that’s amazing — you’ve made one big conceptual leap into our kitty utopia’s inner workings. Let’s take another, much easier one. Let me tell you a story…</em></p><p>In the sun-soaked living room of a quiet suburban house, a group of cats lounged lazily on a Sunday afternoon. All except for one — Whiskers, a sleek black cat with unusually bright green eyes, who had recently developed a passion for magic.</p><p>“I have something to show you all,” Whiskers announced, standing on his hind legs and adjusting an invisible bow tie with his paw.</p><p>The other cats perked up their ears with mild interest. Even Mittens, the skeptical tabby, opened one eye.</p><p>“I need a volunteer,” Whiskers continued. “Someone who will verify my trick.”</p><p>After some coaxing, Felix, an orange tabby known for his fairness, grudgingly stood up.</p><p>“I am going to prove to all of you that I’m a member of the Cool Cats Club,” Whiskers declared proudly.</p><p>This statement caused a stir among the felines. The Cool Cats Club was an exclusive society that met every Friday night at the clubhouse down by the abandoned fish market. Membership was highly coveted.</p><p>“But here’s the challenge,” Whiskers continued, with a dramatic pause. “I will prove my membership without revealing my secret clubhouse password, or even which member I am in the club registry!”</p><h4>The Magical Setup</h4><p>Before we dive into Whiskers’ impressive feat, let’s understand what he had in his magic toolkit:</p><ol><li><strong>A Secret Password</strong>: Each Cool Cats Club member has a unique secret password for getting into the clubhouse, that they keep to themselves (their private key).</li><li><strong>A Membership Card</strong>: Derived from the secret password using special mathematical formulae (that we delved into up above) — this is a public way of showing they’re a member without revealing the secret.</li><li><strong>The Club’s Registry</strong>: A special structure (we’ll call a Merkle tree.. for now) that contains all membership cards used each night.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwDHs-rdOftuJhhZWRHSiQ.jpeg" /><figcaption>Petition to change the name to Meerkat tree is currently under assessment</figcaption></figure><p>4. <strong>The Registry Seal</strong>: A single magical number (we’ll call this the Merkle root) that represents the entire state of the club’s membership that night.</p><p>Felix, as a representative of the audience (and the verifier of our proof), has access to the public Club Registry Seal that was published after last Friday’s meeting. This seal was a mathematical fingerprint of everyone who attended the meeting, but it didn’t reveal who specifically was there.</p><h4>The Magic Show Begins</h4><p>Whiskers started his performance by setting up a small table with a black cloth. On it, he placed three items:</p><ol><li>A sealed envelope (representing his private inputs)</li><li>The official Cool Cats Club Seal (the public Merkle root)</li><li>A blank piece of paper and a pen, for working out</li></ol><p>“Inside this envelope,” Whiskers explained, “are two things only I know: my secret password and the special path that connects my Membership Card Number to the official Club Seal.”</p><p>Felix nodded, understanding his role. “I have here the official Cool Cats Club Registry Seal from last Friday’s meeting,” he confirmed, holding up a card with a complex number on it.</p><p>On the blank paper, Whiskers scrawled out a mathematical proof — a series of numbers and relationships that would convince Felix of his membership without revealing any secrets.</p><h3>The Zero-Knowledge Magic Trick</h3><p>The Zero-Knowledge magic is that, all the while, he never opened the envelope or revealed its contents.</p><p>Instead, he used a special protocol (a zero-knowledge proof circuit) that allowed Felix to verify Whiskers’ claim without seeing any secrets:</p><ol><li><strong>Creating a Binding Identity Commitment</strong>: First, Whiskers used his secret password to calculate his membership card number. Since the way this is done is with a one way hashing function, this has the effect of committing to the secret password’s value so it can’t later be changed (like choosing a card from a deck).</li><li><strong>Proving the Path</strong>: Next, Whiskers proved he knew a valid path from his membership card number to the official Club Registry Seal. Since the Registry Seal (Merkle root) is deterministically calculated from everyone’s membership card numbers (public keys), the <strong>path</strong> is just the exact way that Whisker’s card was combined with others to determine the Registry Seal.</li><li><strong>Verification Without Revelation</strong>: Most importantly, this entire process was designed so Felix could verify everything without learning which member Whiskers was or what his password might be.</li></ol><p>Felix was presented with a shorter (<strong>succinct)</strong> summary of the verifiable checklist of mathematical relationships (constraints) that had to be satisfied to prove Whiskers’ secret knowledge. If they were all ticked off, it would prove Whiskers was telling the truth. In computational terms, it was an <strong>argument system —</strong> and what it argued was Whiskers’ <strong>knowledge</strong> of the Secret Password attached to the Membership Card that was used to generate the Cool Cats Club Seal for that night. This could all be done without Felix asking any extra questions (it was <strong>non-interactive</strong>).</p><p><em>Tadaaaaa! </em>It was a <strong>Z</strong>ero-<strong>K</strong>nowledge, <strong>S</strong>uccinct, <strong>N</strong>on-interactive <strong>AR</strong>gument of <strong>K</strong>nowledge. A <strong>zk-SNARK</strong>! What an incredible (somewhat long-winded) trick! And an acronym for the ages!</p><h3>The Mathematical Sleight of Paw (and the cryptographic details)</h3><p>Behind Whiskers’ engaging performance was some serious mathematical magic:</p><h4>The Pedersen Hash: Transforming Secrets into Public Values</h4><p>The first piece of magic was how Whiskers converted his secret password into a public membership card. This used a special function called a <em>Pedersen hash</em> that:</p><ul><li>Takes any input (the password)</li><li>Maps it to points on an elliptic curve</li><li>Combines those points to create a unique, irreversible output (the membership card number)</li></ul><p>This hash function has a special property: even if you see the output (membership card), you can’t figure out the input (password) that created it. In other words, it has the property we mentioned in our previous article, it is <strong>hiding. </strong>By using this to <em>commit </em>their identity, we can also say this stage was <strong>binding.</strong></p><h4>The Merkle Tree: Organizing Club Membership</h4><p>The Cool Cats Club organized all membership cards into a special structure called a Merkle tree. Imagine a tree where:</p><ul><li>Each leaf is a membership card number</li><li>Each branch combines two cards below it (again, using a hashing function)</li><li>The process continues until reaching a single deterministic value at the top (the root)</li></ul><p>This structure allows anyone to verify membership without exposing the entire membership list!</p><p><em>For an interesting implementation of this in Rust, look </em><a href="https://github.com/arkworks-rs/r1cs-tutorial/tree/main/merkle-tree-example"><em>here</em></a><em> (but it’s not for the faint-hearted!)</em></p><p><em>Further watching, reading:</em></p><blockquote><a href="https://www.youtube.com/watch?v=gcKCW7CNu_M">What is a zkSNARK?</a> (Berkeley RDI Center Lecture)<br><a href="https://www.youtube.com/watch?v=G38G2sfZwB0&amp;t=5460s">Master Essential Math for zk Proofs</a> (extropy Live Session)</blockquote><blockquote><a href="http://chriseth.github.io/notes/articles/zksnarks/zksnarks.pdf">zkSNARKS in a Nutshell </a>(by Christian Reitwießner)<br><a href="https://crypto.stackexchange.com/questions/112545/why-do-snarks-operate-on-arithmetic-circuits">Why do SNARKs operate on arithmetic circuits?</a> (StackExchange post)<br><a href="https://jtriley.substack.com/p/constructing-zk-snark-circuits">PLONKish(!) arithmetic circuits for zkSNARKS in Rust</a> (by jtriley)<br><a href="https://zcash.github.io/halo2/concepts/proofs.html">The Halo2 Book</a> (zCash)</blockquote><h4>If you followed along with this, that’s amazing - you will understand what’s going on behind the scenes of our next build stage. If not, hopefully the attempt was at least a little amusing!</h4><p><strong>Coming soon…</strong></p><h3>Build Stage 2: Keeping kitty privacy with Zero Knowledge proofs using Semaphore</h3><p><em>When not falling down cryptography rabbit-holes, I can be found working on another side project that got out of hand, </em><a href="https://planitt.io/"><em>https://planitt.io</em></a><em> — looking for alpha testers now.</em></p><p><em>I am also actively looking for new contracts, get in touch at </em><a href="https://nickstebbings.com/"><em>https://nickstebbings.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bd66e6a5d27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a kitty utopia with Rust (and Solidity): II — We Build In Stages]]></title>
            <link>https://n-stebbings.medium.com/building-a-kitty-utopia-with-rust-and-solidity-ii-we-build-in-stages-0b07133d2288?source=rss-9224a7e051eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b07133d2288</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Nick Stebbs]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 03:22:33 GMT</pubDate>
            <atom:updated>2025-03-18T03:23:27.617Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a kitty utopia with Rust (and Solidity): II — We Build In Stages</h3><p>(I advise that you read the first post <a href="https://medium.com/@n-stebbings/building-a-kitty-utopia-in-rust-i-kitception-330b12455f9e">here</a> to have the faintest clue what I am going on about.)</p><p>Have a look here if you want to read the code so far for this stage:<br><a href="https://github.com/nick-stebbings/zkCATS/commits/medium/stage-2/">https://github.com/nick-stebbings/zkCATS/</a> *</p><p><em>*Rust warning…</em></p><p>By this point, you may be forgiven for not taking this seriously. And in a way, you’re right. But if I’m known for one thing, it’s that I never fail to follow through on a good acronym. We’re building this thing (albeit a relatively <em>light approximation</em> of this thing).</p><p><strong>Let’s go!</strong></p><h4>Stage 1: Minimal Rust web app for our Agora, and initial Smart Contracts</h4><ul><li>The Architect (some practical allowances)</li><li>Securing private kitty space — encryption in the voting booth</li><li>A simple pseudonymous tax system</li></ul><p><strong>A note on The Architect:</strong></p><p>In order to narrow the scope of these articles to be mainly about encryption, we assume a creator in our kitty-verse. They helpfully went ahead and built a simple web API and Vue.js app for our Agora, <a href="https://github.com/nick-stebbings/zkCATS/blob/medium/stage-2/sql/dev_initial/02-dev-seed.sql">seeded</a> the database with 3 Cool Cats (Alf, Bella, and Charles) - being already part of a <a href="https://github.com/nick-stebbings/zkCATS/blob/6267acbb542c9ba2d34d18e84767f597c390e759/crates/lib/lib-core/src/model/community.rs#L11">Community</a>. The Architect may also set up a basic taxation system to be used in the demo, just to speed things along.</p><h3>Securing private kitty-space</h3><p>We’re going to get our paws wet with some simple encryption, and show how we use Web 2.0 patterns for the Agora/app space, before we layer on some decentralized goodness.</p><p>What we do later with zero knowledge proofs is really following on from work done in the 70’s/80’s — encryption that is the very lifeblood of the internet — so we’re using that stuff as a jumping off point to understand things easier later on.</p><p>We start by building a private digital meeting place for our kitizens. After all, even the most independent of felines need a place to gather and collectively decide the fate of their milk funds. Our Agora needs to be secure, efficient, and — most importantly — free from canine interference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*sdxCnDbNt6Cj2kTl" /><figcaption>The door policy: Cool cats only</figcaption></figure><p><strong>Identity</strong><br>Our kitizens need identity. They need to be able to log in securely, vote, and have their contributions tracked without compromising their privacy. We’re going with a simple yet effective token-based authentication system.</p><p>We’re not implementing any role based permissions — kitizens will be on the same level. As a result, our tokens will consist of just three parts: an identifier (our kitizen’s username), an expiration time, and a signature — to make sure nobody’s been tampering with the first two components.</p><p>Here’s the core of our token generation system. We take an identifier, a duration to calculate the expiration, and a salt (which adds randomness — we generated it for the user and stored in the database as a UUID). Since the server will both issue and validate the token, and is the only one holding the encryption key, we will <a href="https://security.stackexchange.com/questions/220185/jwt-choosing-between-hmac-and-rsa">choose HMAC</a>: a form of symmetric encryption (using one key).</p><pre>fn _generate_token(ident: &amp;str, duration_sec: f64, salt: &amp;str, key: &amp;[u8]) -&gt; Result&lt;Token&gt; {<br>    // Compute first two components<br>    let ident = ident.to_string();<br>    let exp = now_utc_plus_sec_str(duration_sec);// Sign first two components<br>    let sign_b64u = _token_sign_into_b64u(&amp;ident, &amp;exp, salt, key)?;<br><br>    Ok(Token {<br>        ident,<br>        exp,<br>        sign_b64u,<br>    })<br>}</pre><p>We will generate the token, store it as a http-only cookie, and kitizens will have their session authenticated by including it in their HTTP requests to the server.</p><p>This HMAC token system (<a href="https://github.com/nick-stebbings/zkCATS/commit/6267acbb542c9ba2d34d18e84767f597c390e759">code here</a>) represents the most basic form of trust in our kitizen ecosystem — a simple way of saying “yes, you are who you claim to be.” It’s a classic Web 2.0 pattern, where a central authority (our server) issues and validates credentials. We could later phase out the need for a centralized server from our app-space using some peer-to-peer dApp framework like Holochain. For now, it serves as a first layer of privacy.</p><p>Before we move on let’s touch upon some properties of the hashing algorithm we used for our HMAC token (SHA512). It is both <strong>hiding — </strong>it’s difficult to find the original input given only the hash, and it is <strong>binding </strong>— it ensures that any change to the input will result in a different hash. These properties will turn out to be mighty useful in upping our accounting privacy, later on.</p><h3>The Bridge to Web3: From HMAC to Elliptic Curve Cryptography</h3><p>While our Agora uses these simple HMAC tokens to secure our kitizens’ identities, the blockchain world (which we’ll venture into with our taxation system) operates on different principles of trust.</p><p>Our HMAC tokens rely on a central server holding a secret key. What if we didn’t want to trust any single entity? What if kitizens wanted to operate in a trust-less environment? This is where Ethereum and smart contracts enter our narrative.</p><p>In Ethereum, and blockchain in general, identity works differently. Instead of server-issued tokens, users have cryptographic key pairs. The private key (which only they possess) is used to sign transactions, while the public key (or more accurately, an address derived from it) is visible to everyone.</p><p>We generate the public key from the private key by finding a point on a special curve called <em>secp256k1</em>, which, although it may be very useful, I’m sure you’ll agree won’t win any acronym awards.</p><p>Here’s a <a href="https://fitsaleem.medium.com/ethereums-elliptic-curve-digital-signature-algorithm-ecdsa-88e1659f4879">great article</a> that goes into the weeds about this.</p><p>As it turns out, these elliptic curves are not just fundamental to blockchain identity — they also play a crucial role in the zero-knowledge proofs we’ll implement to secure our kitizens’ tax privacy.</p><p>The same cryptographic principles that allow for trust-less identity verification in Web3 can be extended to create mathematical proofs where kitizens can demonstrate they have certain information (like they have made contributions to a Cat Community’s Milk Fund) without revealing anything else about themselves (like their voting preferences). This balance of transparency and privacy is exactly what our independent-minded felines need in their digital Agora.</p><h3>Pseudonymous Cats</h3><p>A necessary step to creating our zkCATS is to create a set of smart contracts for holding a verifiable record of our community membership, tax scheme, and list of recipients. You can see the initial smart contracts <a href="https://github.com/nick-stebbings/zkCATS/tree/medium/stage-2/eth/contracts">here</a></p><p>In their wisdom, the Architect decided to deploy to zkSync, which is a scalable Layer 2 protocol built on Ethereum. We will leverage some of its’ features to make our taxation system run much quicker, cheaper, and with more privacy. Under the hood it too leverages zero knowledge proofs (but maybe you worked that out already).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8PEEdV4qltIbBZZWZIlImQ.png" /></figure><p>Here we can see the first deployment of our MilkFund contract. Using the block explorer here, we can highlight the main problem we still need to solve…</p><p>Sure, we can make an accounting layer, but if just any old snoop can look up the contract like this, what’s to preserve our kitty’s privacy? We have managed to achieve <em>pseudonymity</em>, but with modern encryption, we can do better!</p><p>This is the problem we’ll solve in the next build stage. <strong>Coming soon…</strong></p><h4>Stage 2: Keeping kitty privacy with Zero Knowledge proofs using Semaphore</h4><h4>Stage 3: Generating NF-kitty badges to be displayed in the Agora</h4><p><em>When not falling down cryptography rabbit-holes, I can be found working on another side project that got out of hand, </em><a href="https://planitt.io/"><em>https://planitt.io</em></a><em> — looking for alpha testers now.</em></p><p><em>I am also actively looking for new contracts, get in touch at </em><a href="https://nickstebbings.com/"><em>https://nickstebbings.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b07133d2288" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a kitty utopia in Rust: I — Kitception]]></title>
            <link>https://n-stebbings.medium.com/building-a-kitty-utopia-in-rust-i-kitception-330b12455f9e?source=rss-9224a7e051eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/330b12455f9e</guid>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Nick Stebbs]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 21:40:36 GMT</pubDate>
            <atom:updated>2025-03-12T01:50:04.425Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a kitty utopia with Rust &amp; Solidity: I — Kitception</h3><h4>If I leave the world one thing, I’d like it to be this</h4><p>How did it come to this? My contribution to the world must surely reach further? But one must be humble. “Start with what you can do”.</p><p>Sure, I wanted to join the all time greats and have a lasting contribution to the world of encryption, but I also wanted to meme. The meme must be strong.</p><h3>Birth of the zero-knowledge Community Autonomous Taxation System</h3><p>It started innocently enough. I was researching this interesting maths/software problem, as one does when they fall down a new tech rabbit hole. Suddenly there they were — the titans of the zero-knowledge proof* world with their hilariously named systems: STARKs, SNARKs, and PLONKs. I swear I am not making this up.</p><p><em>*if you’re lost already, don’t worry, we’ll make it make sense</em></p><p>And I thought: “These people will be remembered for generations. Not for their groundbreaking cryptographic innovations, but for their absolutely top-tier acronym game.”</p><p>That’s when I knew my calling. If I wanted cryptographic immortality, I needed an acronym that would make people take notice. Something memorable, something… meme-able.</p><h4>Enter zkCATS</h4><p>Zero Knowledge Community Autonomous Taxation System. Is it revolutionary? Maybe. Is it another excuse to put more cats into distributed systems? Absolutely.</p><p>First, relieve yourself of any preconceived notions of how the world works *<em>right now</em>*. We need to let our imaginations run free for a moment.</p><p>Imagine a future where we don’t have an over-arching powerful sovereign state taking half of our money, but instead we have a system whereby society members voluntarily funnel resources into those areas most needed by their community, based on a system of direct democracy, leveraging distributed ledger technologies and encryption.</p><p>You might say we could imagine further, and build a world where we have no taxation at all. Sounds like a dream, but one that might quickly devolve into a Hobbesian state of nature. One in which all domestic cats would have to fend for themselves. It cannot be. Kitizens, unite!</p><p>Let’s think of a way we can provide a template for establishing a minimal social contract for monetary contributions — to keep things ticking over, but allow different (kitizen-proposed) percentage distributions to different community causes to be agreed upon, transacted, and then <strong><em>proven</em></strong> cryptographically, while retaining high levels of privacy (<strong><em>zero-knowledge</em></strong> of individual transaction history and balances).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/57/0*2r-qQc8mYaE4edSu.gif" /><figcaption>Already bored.</figcaption></figure><p>This is the idea I will play with in a fun ongoing project I am using to learn more about zero-knowledge proving systems and smart contract development. These are topics which can be… a little dry. Hopefully my playful analogies will make following along feel a bit less like chewing on dried catnip - but I will admit sometimes they will become a l-iittle stretched.</p><h3>The problems of centralization</h3><p>As with all system design problems, we should probably start by having a look at an existing system. Let’s (very reductively) summarize the way the current system is supposed to work with a fun diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dnxyCmtUJPSFSGcngkPFiw.png" /><figcaption>A system leading to a potential breakdown of inter-feline relations</figcaption></figure><p>Humans (in all their wisdom), have managed to devise a system, which most are born into, whereby they allow a certain percentage — dictated by some much wiser economists and politicians — to be removed from their monetary rewards for labor. Under this system, kitizens would not get to vote on the specifics of the distribution system, but they would cast their vote for a set of delegates and… <strong>trust</strong> them to do the right thing. As a reward, certain public goods and services would be made made available (security, healthcare, emergency services etc.). Not everyone, not even a majority of the population, would need to agree to the set of delegates, although all should contribute. We won’t go into the weeds with regards to different levels of taxation — for now, this simple model will do.</p><h4>Points of failure &amp; points for improvement</h4><p>We can identify several points of failure in this system:</p><ul><li>Firstly, if a kitizen managed to avoid the centralized enforcement of their contribution, they would have an unfair advantage in life over their peers (see the fatcat, top-right). They would still benefit from the public goods, but without contributing.</li><li>Secondly, if certain kitizens did not agree to the set of delegates chosen, or were not there on the day of choosing (like Deb, who was of course sleeping), they would nevertheless be forced to contribute, with the distribution of funds chosen in a way that they didn’t agree with. However they would still benefit from the public goods.</li><li>Thirdly, even if kitizens got their choice of delegates, some of the delegates might not act in their best interest (!), and might distribute the funds in a way that was not fair or representative of the kitizenry (not optimized for public good).</li><li>Finally, although individual balances remain private, they sometimes need to be made transparent to the centralized authority that enforces (👮) and accounts (🧐) for the system. Such audits are the stuff of kitty nightmares and we would prefer to avoid them, while still proving compliance to the other kitizens.</li></ul><p>Let’s see if we can replace or improve upon some of these points of failure through decentralization. For now we aren’t going to worry about aspects such as contribution enforcement (kitties generally like a quiet life, anyway), but we will be concerned with accounting.</p><p>Our main aims are to keep/improve upon the existing levels of <strong>privacy</strong> — and see if we can introduce <strong>devolution, voluntarism and autonomy</strong>, and see if that brings more fairness (social justice) or efficiency into the system.</p><h3>Introducing voluntarism/devolution, leveraging DLT</h3><p>Let’s start with the accounting system. Since the invention of Bitcoin and as a consequence the developments in the field of distributed ledger technology (DLT) that allow a public ledger of monetary transactions (a form of <a href="https://www.emerald.com/insight/content/doi/10.1108/s1569-37592023000111b008/full/html">triple-entry book-keeping</a>) to be enforced with cryptography, we can posit that (a) the use of a public ledger for accounting and (b) the use of <a href="https://www.google.com/url?sa=t&amp;source=web&amp;rct=j&amp;opi=89978449&amp;url=https://www.coinbase.com/learn/crypto-basics/what-is-a-smart-contract&amp;ved=2ahUKEwjFhdPaof6LAxWazDgGHTwYLYMQFnoECE8QAQ&amp;usg=AOvVaw31JupDzJ_lFyD8tD506Q9E">smart contracts</a> to automate certain aspects of monetary re-distribution might produce a fairer system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ViXQ8i5Mg3l0wnLH_qQelg.png" /><figcaption>Using direct democracy and DLT accounting to increase feline voluntarism, removing third parties and fatcats</figcaption></figure><p>Here we introduce <em>devolution</em> of power from the centralized enforcement/accounting services, by routing funds directly to the accounts of those managing the services.</p><p>One could argue that, what with the widespread privatization of a lot of public services in the last few decades, this is not a huge leap. We could remove the third party enforcers/accountants from the system and optimize for value to the end-users. This requires the introduction of a trust-less system (although, it’s only really trust-less on the <a href="https://www.quora.com/Does-Ethereum-really-give-us-trustless-transactions">record-keeping level</a>). To address trust at the human level, we would need some kind of reputation system.</p><p>We hereby also introduce <em>voluntarism </em>via the use of a public space or <a href="https://en.wikipedia.org/wiki/Agora">Agora</a> for the discussion of, and agreement on, a shared social contract. The space also acts as a way of showing <em>reputation </em>via some kind of badge system (to be worked out later) that lets other kitizens (a) See if you have voted and (b) See if you have contributed to the shared fund.</p><p><em>This Agora could also become a centralized point of failure if it does not also become decentralized in its’ operation and maintenance. However — for all practical purposes - we will use a centrally hosted web application for this, knowing full well that it could be hosted in a more decentralized/communally organized way later on, using a DAO, or technologies such as </em><a href="https://www.holochain.org/"><em>Holochain</em></a><em>.</em></p><p>The other voluntary aspect in this system is that although not everyone necessarily contributes to the common fund, those who chose not to vote or contribute are not guaranteed the provision of public services (see Deb, who now gets to snooze with full responsibility).</p><h4>How to retain privacy?</h4><p>You might notice from the diagram we have introduced a new problem that wasn’t there in the previous system. Given the public nature of the public keys (which also act as addresses for sending funds) in the Ethereum blockchain, we now have a potential privacy violation.</p><p>Given that many kitizens will not just be making their contributions to the milk fund using Ethereum, but will also have other on-chain transactions — that they don’t want to share with any old snoopy cat — how do we prevent the ability to track these other transactions by simply tracing them from the public service accounts? We need some way of validating that transactions <em>have</em> been made without actually revealing the <em>addresses</em> of the transactions in the Agora.</p><h4>This is the ZK part</h4><p>This is the field of mathematics/cryptography that we alluded to earlier — which we are going to thoroughly explore in later blog posts — and can help us here. We’ll be constructing a PLONKish arithmetic circuit (naturally), but for now we’ll just assume this is secret privacy sauce.</p><p>That’s it — for the moment. We’ll start the build in the next post. I’ll leave you to mull over the prospects of such an utopian future for our furry friends. If you’d like to contribute on the finer points of the system design, or whether the feline character even has the capacity for such co-operation — go at it in the comments.</p><p><em>When not falling down cryptography rabbit-holes, I can be found working on another side project that got out of hand, </em><a href="https://planitt.io/"><em>https://planitt.io</em></a><em> — looking for alpha testers now.</em></p><p><em>I am also actively looking for new contracts, get in touch at </em><a href="https://nickstebbingsportfolio.netlify.app/">https://nickstebbingsportfolio.netlify.app/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=330b12455f9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From local storage To-do list to Fractal, Peer-to-Peer Habit Tracker (refrain)]]></title>
            <link>https://n-stebbings.medium.com/from-local-storage-to-do-list-to-fractal-peer-to-peer-habit-tracker-refrain-5fe747131d45?source=rss-9224a7e051eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fe747131d45</guid>
            <category><![CDATA[peer-to-peer]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[holochain]]></category>
            <category><![CDATA[personal-habits]]></category>
            <dc:creator><![CDATA[Nick Stebbs]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 08:39:59 GMT</pubDate>
            <atom:updated>2024-08-08T08:39:59.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*0BLNak07ls-ZBwle9-AxRg.png" /><figcaption>Houston, we have a logo</figcaption></figure><h3>Part 4: Building for a target that… doesn’t exist</h3><p>(Start with <a href="https://n-stebbings.medium.com/from-session-cookie-to-do-list-to-fractal-distributed-listmania-part-1-645911140e53">part 1</a> , <a href="https://n-stebbings.medium.com/from-session-cookie-to-do-list-to-fractal-distributed-listmania-2da3e33728a">part 2</a> or <a href="https://n-stebbings.medium.com/from-local-storage-to-do-list-to-fractal-peer-to-peer-habit-tracker-3be56214c6ee">part 3</a> for the earlier development story)</p><p>A lot has happened in the Holochain ecosystem since my last writings on this project. It has become less of a moving target for development since the initial Beta release candidate dropped in December 2022, leading us all the way to today’s most <a href="https://blog.holochain.org/holochain-0-3-a-new-launcher-and-hc-on-mobile/">stable release</a> (0.3.2).</p><p>That isn’t to say we’re without growing pains, but development (even… deployment!) on the platform is becoming much less fraught with blockages. Even the possibility of a mobile peer-to-peer version of my habit tracker has now started to appear on the horizon. Which is great, because I have spent most of the last year designing a new version of the app to run primarily on that target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qK47ghyRs_PGMTV3dgp8hA.jpeg" /><figcaption>Initial UI testing of the mobile-first design</figcaption></figure><h3>Tips for Holochain front-end devs who value sanity</h3><p>I’d like to think I have learnt something about software in the last few years (wouldn’t we all…) so, in order to avoid ever rebuilding the UI from the scratch, I’ve made the front-end almost entirely Holochain agnostic. If you can <a href="https://www.apollographql.com/docs/react/development-testing/testing/">mock out</a> all of your zome calls in this way, you don’t even need a back-end and you can go home early (maybe?).</p><p>Here’s the new stack:</p><ul><li>GraphQL layer for fetching data, which resolves queries and mutations to my Holochain <a href="https://n-stebbings.medium.com/from-local-storage-to-do-list-to-fractal-peer-to-peer-habit-tracker-3be56214c6ee">zome functions</a> (p2p network calls) and delivers the payload back, all via a nicely typed/validated schema.</li><li>React, <a href="https://the-guild.dev/graphql/codegen">GraphQL Codegen</a> &amp; Apollo Client for developer tools/ergonomics out the wazoo (I get automatic typed React hook generation whenever the schema is updated - meaning I actually forget I am using Holochain data types so long as I keep my schema in line).</li><li><a href="https://jotai.org/">Jotai</a> and a bit of React context for state-management. I just couldn’t justify Redux any more, especially given there is so much boiler-plate from the GraphQL layer already.</li><li>Apollo Client and <a href="https://github.com/11bit/jotai-minidb">jotai-minidb</a> are used to cache responses and create an indexed data store to rapidly retrieve extra details on my interactive data visualisations. Later I will use Apollo Client to add pagination of the JSON data such that the habit hierarchy can pre-load along multiple dimensions (key for a seamless experience).</li><li>React Testing Library. I decided never again to try to make something this complex without some front-end testing. Ever!</li><li>Deployment via Tauri: <a href="https://darksoil.studio/p2p-shipyard/">p2p Shipyard</a> are bringing the Android mobile target into view via <a href="https://v2.tauri.app/">Tauri 2.0</a>. Great! Although it’s <a href="https://tauri.app/v1/references/webview-versions/">not</a> the easiest trying to target all the different Webview versions at once.</li><li>Github Actions to automatically build for MacOS, Windows and Linux with every release, and to run my test suite with every push to my develop branch.</li></ul><h3>It still just a To-do list?</h3><p>No, of course not. It’s a hierarchical data-viz you can tick o… yes - OK for the moment it’s still a To-do list.</p><p>But! The heavy lifting (dynamically generating JSON to power the visualizations from a load of Holochain entries) has largely been done. The next minor release will be adding back in the temporal dimension — the daily calendar — that I first got working in the <a href="https://habfract.online/">proof of concept</a>, so that it is actually a habit tracker again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLJ5hj4OHsVhMtWJotDxLg.png" /><figcaption>Even astronauts have To-do lists</figcaption></figure><h3>But it’s peer-to-peer?</h3><p>It’s the personal version of the app (solo), but we have the *potential* for peers! By persisting all data by default on the local encrypted ledger (not the DHT) we allow a more local-first, privacy-first approach to your behavioral data.</p><p>The social dimension will be added, via a lobby, at a later date. In the lobby you’ll be able to share templates, share subsets of your personal data, import data shared by others into your own personal app (to mimic!), and create private accountability channels.</p><p>For now, we have reached what I call <strong>minimum viable dog-food.</strong></p><h3>Sounds… disgusting!</h3><p>Sure, but it ought to be useful. I wanted to start <a href="https://en.wikipedia.org/wiki/Eating_your_own_dog_food#:~:text=Eating%20your%20own%20dog%20food%20or%20%22dogfooding%22%20is%20the%20practice,usage%20using%20product%20management%20techniques.">dog-fooding</a> as soon as I could in order to (a) get the delivery pipeline flowing and (b) help me iron out bugs, and test out the foundations that all the exciting p2p stuff will rely on for a good user experience.</p><p>Habit/Fract (that’s right, this project even has a name by this point) has a <a href="https://habitfract.net/">new home on the web</a>, and I will be planning out a roadmap of the app’s future using the first early releases of the app on Holochain.</p><p>Now that I’ve suitably lowered your expectations, please feel free to join me! You can currently download a MacOS, Windows or Debian version to play around with <a href="https://github.com/HabFract/monorepo/releases">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fe747131d45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a cool thing: Step 2 (Make it performant)]]></title>
            <link>https://n-stebbings.medium.com/making-a-cool-thing-step-2-make-it-performant-738cf43ec233?source=rss-9224a7e051eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/738cf43ec233</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Nick Stebbs]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 05:16:15 GMT</pubDate>
            <atom:updated>2024-07-31T08:01:03.332Z</atom:updated>
            <content:encoded><![CDATA[<p>After a week of the clawing feeling and a distraction with some other tasks, I got back to the drawing board and admitted I had to make a mobile site too.</p><p>People love their phones, and they certainly wouldn’t love me if I took up a load of their data allowance just to show them a cheeky modal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJVC2nbWH-LONdVxQRbvrw.png" /><figcaption>The cheeky modal of doom</figcaption></figure><p>I can avoid the contempt. The question is: how?</p><p>I had already discovered that (due to too much re-painting by the browser) the only way to make this SVG animation perform on devices with a lower capacity for rendering was to decrease the number of elements, or use CSS animation.</p><p>All of this sounded like way too much work. And it might rip the heart out of the cool thing. This was not supposed to be a mega-keep-you-up-at-night-and-be-totally-consumed-by-it project, either (I had tried that approach <a href="https://habfract.online/">with another cool thing</a> and I don’t recommend the development experience).</p><p>Then I had an idea that probably should have been obvious from the start:</p><p>If they can’t handle the content, don’t serve them the content. Server-side rendering and static site generation have become widespread for a good reason — we shouldn’t be loading up the user’s browser with work that we could do for them ahead of time.</p><p>I did a fairly major refactor to make the code more reasonable, and add a bit of mobile-first CSS to pave the way for what was coming. Then I looked into <em>Nuxt.js</em> — as I knew it was the <em>Next</em> to <em>Vue</em>’s <em>React</em>, if you… err, get what I’m saying. And it might just be the answer to my problems — server side rendering and code-splitting right out of the box.</p><p>I transplanted the whole site into a <a href="https://github.com/nick-stebbings/ssr-my-portfolio-2">scaffolded Nuxt app</a>, messed around with plugins for a few hours, and voila! By using the <a href="https://nuxt.com/modules/device">device module</a> I was able to conditionally render the animation based on a flag that was assigned differently (on the server) for different devices.</p><p>For a little extra boost I optimized and lazy-loaded all of my static images. Take a look at the newly optimized site on mobile or desktop, <a href="https://seashell-app-zf6of.ondigitalocean.app/">HERE</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52IVhkfYY5IMDV6FUuh3Hw.png" /><figcaption>Mobile optimization: by serving specific content to mobile devices I saved their data (and bacon?)</figcaption></figure><p>There are still some issues to address (alas, tablets are somewhat caught in no-man’s land), but I feel like I salvaged an essence of coolness whilst still serving the important thing to all users — the actual written content.</p><p>You could call it cheating, delaying the inevitable (<em>hello</em> WebGL), device discrimination, whatever. I’m calling it fixed</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=738cf43ec233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a cool thing: Step 1 (Make it)]]></title>
            <link>https://n-stebbings.medium.com/making-a-cool-thing-step-1-make-it-eed5ae887cc9?source=rss-9224a7e051eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/eed5ae887cc9</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[creativity]]></category>
            <dc:creator><![CDATA[Nick Stebbs]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 04:49:13 GMT</pubDate>
            <atom:updated>2023-11-08T00:16:17.342Z</atom:updated>
            <content:encoded><![CDATA[<p>One day recently I decided to try and make a cool thing.<br>(<em>DISCLAIMER: The author acknowledges the total subjectivity of cool and doesn’t care</em>)</p><p>I looked for some inspiration.</p><p>I found some.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hVm3juixZ4rc5D_iwEpqA.png" /><figcaption>A spark of inspiration</figcaption></figure><p>I have always considered myself a bit of a generalist — a Jack of All Trades. This seemed when I was younger to be a disadvantage, but I have found since becoming a developer that it’s useful to be a dab hand at a lot of things (across the whole stack is a good start). Then you can pick the right tool for the job.</p><p>“This’ll be cool… I’ll make that image into a website”, I thought.</p><p>This is the point at which, if I was working in a team, somebody might’ve said something like: “ That’s a creative idea, Nick. Why don’t we talk about trying to incorporate it along-side some established design conventions…”</p><p>So I just built the thing, to discourage the idea from living rent-free in my mind. A bit of Figma here, a bit of Vue there (for the first time), and a big dollop of SVGator since I didn’t want to learn some new animation library just to make this one thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*pFXwtZ7IX0-33D1ldXoeFw.png" /><figcaption>A look at the early design stages</figcaption></figure><p>And it worked great… <a href="http://nickstebbings.com/">kinda</a>.</p><p>I had <a href="https://www.crmarsh.com/svg-performance/">already realised</a> it wouldn’t perform on a mobile device/tablet, so I put up a cheeky modal to recommend to people on those devices not to view it yet.</p><p>I deployed it on Netlify and sent the link to a few trusty colleagues.</p><p>I got back some positive and… honest… feedback, along the lines of:</p><p>“ That’s a creative idea, Nick. It’d be better if you tried to incorporate it along-side some established design conventions.”</p><p>Blast. I didn’t sign up for this. I just wanted to make a cool thing. Well, at least I had made it. Just had to live with the clawing interior feeling that there may be a good reason people design mobile-first.</p><p>Wait… there’s an idea!<br><a href="https://medium.com/@n-stebbings/making-a-cool-thing-step-2-make-it-performant-738cf43ec233">Part two</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eed5ae887cc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From local storage To-do list to Fractal, Peer-to-Peer Habit Tracker]]></title>
            <link>https://n-stebbings.medium.com/from-local-storage-to-do-list-to-fractal-peer-to-peer-habit-tracker-3be56214c6ee?source=rss-9224a7e051eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3be56214c6ee</guid>
            <dc:creator><![CDATA[Nick Stebbs]]></dc:creator>
            <pubDate>Mon, 15 Nov 2021 04:39:05 GMT</pubDate>
            <atom:updated>2021-11-15T04:39:05.819Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Part 3: Storing on the DHT</strong></h4><p>In <a href="https://n-stebbings.medium.com/from-session-cookie-to-do-list-to-fractal-distributed-listmania-2da3e33728a?source=user_profile---------0-------------------------------">part 2</a> I described how I experimented with a single paged application for persisting and visualising personal habit information. In this post I will bring you up to date with the state of the project.</p><h3><strong>How much did SOLID help to salvage?</strong></h3><p>I spent some time learning about the distributed p2p architecture as implemented by Holochain (including starting to learn the Rust programming language). Although, ultimately, hApps (Holochain apps) will be able to be written in any language that compiles down to WebAssembly, currently Rust is the only option. My web API would be useless with the new p2p architecture at any rate.</p><p>I would have to rebuild the backend completely. Since the frontend was written in Mithril, using JSX, I could reuse much of the UI. I first decided to address the state management issues by using Redux and <a href="https://github.com/piotrwitek/typesafe-actions">typesafe-actions</a> to allow easy management of loading and error states, while aiding organisation in the reducer. Since learning Rust, moving to Typescript on the front end made sense as I am then able to match interfaces.</p><h3>I feel a List coming on</h3><p>Since the bottom of each fractal habit structure <em>could </em>potentially be a list (which I omitted from the last version), I thought it would be a good place to start… yes… another Todo list.</p><p>This time the whole process was driven by tests (following the canonical TodoMVC examples), using Jest as a test runner and React Testing library. One of the main lessons I learnt from the previous version was that I never want to experience not testing again! Too much time was spent chasing bugs in the UI.</p><p>After setting up local models on the frontend and testing everything upto the ‘Save’ button (i.e. I was <em>ready to persist </em>once more), I reached this error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHUYPhj4Q5zr0RwruKlamg.png" /><figcaption>“Attempted to call a zome function that doesn’t exist”</figcaption></figure><p>It was time to learn about Distributed Hash Tables, anchors, and all things Holochain.</p><h3><strong>Persisting on Holochain</strong></h3><p>First, a litte background:</p><ul><li>A zome (short for chromosome) is like a microservice that makes up part of a hApp. User profiles, for example.</li><li>An hApp’s code is made up of zomes, compiled into WebAssembly, packaged into a DNA. DNA is like “the rules of the game” when it comes to app logic and validation.</li><li>A DNA instance runs on a ‘conductor’, a process that runs — on your machine or on Holoports (which act as distributed hosts for hApps, proxying for other user agents on the network and allowing p2p connections even from behind firewalls/routers).</li><li>A conductor <em>conducts, </em>both in the sense that it orchestrates the installation/running/validating of different hApp DNA instances, and that it allows calls to public zome functions to pass through it via the conductor API.</li><li>Each hApp instance runs in a Cell on the conductor, and creates a private network for all other peers on Holochain that are using the exact same DNA (the same set of rules).</li><li>Data for each agent on the private network is stored privately on their ‘source chain’ — a hashed sequence of ‘elements’ containing a header and possibly an entry (the content).</li><li>Public/private key encryption is used to sign the elements and verify the authenticity of the data to other peers.</li><li>Public data can be made and shared with other agents on the network.</li><li>Public data is stored in a Validating DHT (<a href="https://developer.holochain.org/concepts/4_dht/#the-distributed-hash-table-a-public-data-store">Distributed Hash Table</a>).</li></ul><h4>Why I Care</h4><p>It’s a pretty different way of doing things. That’s why.</p><p>As somebody creating an application where an objective is to share personal data, I would like to empower users to take sovereignty of that data and share it as much or as little as they like, with whomever they like, without having a third party intervene.</p><h4>What This Means for My Design</h4><p>This means I have to store my data on a DHT. As mentioned in the Holochain docs, one issue with having a DHT is it is trickier than finding data than in a relational database.</p><blockquote>This creates a chicken-and-egg problem. In order to retrieve a piece of data that matters to you, you need to know its address. But you can only know the address if you can calculate it from the data<br><a href="https://developer.holochain.org/concepts/5_links_anchors/">https://developer.holochain.org/concepts/5_links_anchors</a></blockquote><p>Thankfully, having used Shopify’s GraphQL API in the past, I am not new to the idea of a graph database. It also makes my design descision for how to store hierarchies of habits very straightforward. <a href="http://lab.kochlein.com/FertileForest/models/PathEnumeration">Path enumeration</a> is the obvious option…</p><h3>Comparing Hierarchy Storage Models</h3><p>Because I need to create a graph of <em>Anchors (</em>an entry point to the graph)<em> </em>and <em>Links </em>(edges between entry nodes), to access the data in the DHT. How does this model help to store hierarchies? How does it compare with the model I was using with a <em>relational </em>persistence layer — <a href="http://lab.kochlein.com/FertileForest/models/NestedSet">Nested Sets</a>?</p><h4>Nested Sets, or “Modified Pre-Order Tree Traversal”</h4><p><a href="https://en.wikipedia.org/wiki/Nested_set_model#Example">This example</a> illustrates how the first version of my app stored its habit hierarchies. To query a subtree, e.g. to find all descendants, is as easy as selecting nodes that have ‘LFT’ and ‘RGT’ attribute values <strong>between </strong>those of my target ancestor node’s.</p><p>The main drawback is that insertions are expensive operations, as you <em>may</em> have to update all of the LFT/RGT values of all tuples (e.g. if you are adding a new parent to the top of the tree).</p><h4>Path Enumeration, or “Materialized Paths”</h4><p>This image shows how Holochain allows organisation and retrieval of data from the DHT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*-oDx2KVmFpzoS7S7t5YFpw.png" /><figcaption>Holochain’s Distributed Graph Database — <a href="https://developer.holochain.org/concepts/5_links_anchors">https://developer.holochain.org/concepts/5_links_anchors</a>/</figcaption></figure><p>We can pick out a simple hierarchy to demonstrate path enumeration: Each <em>genre </em>comes under the umbrella <em>all genres</em>.</p><p>Here, an <em>anchor</em> to link to musical genres has been made — a simple string “<strong>_all_genres</strong>_”, which can be stored as an entry in the DHT. It can easily be remembered and its <a href="https://en.wikipedia.org/wiki/Hash">hash </a>used to connect to other entries.</p><p>By creating <em>links </em>between elements of hashed data in the DHT, and using an optional tag (e.g. using the string “#folk”) then I can allow filtering of elements when I come to fetch data.</p><p>Since we can access anything tagged <em>folk</em>, <em>hawaiian </em>or <em>ukelele </em>from the “<strong>_all_genres</strong>_” anchor, by making a link and filtering with a tag, we have an easy <strong>path </strong>to each genre which can respectively be defined as:</p><ul><li>_all_genres_/#folk</li><li>_all_genres_/#hawaiian</li><li>_all_genres_/#ukelele</li></ul><p>If I were then to add a more specific sub-genre and create a link to it as a child of one of the existing tagged genres — such as <em>baritone ukelele —</em> it would have the path “<strong>_all_genres_/#ukelele/baritone_ukelele</strong>”.</p><h3>Design Efficiencies</h3><p>One of the benefits of a graph database is that a query is designed to return only the information that is actually needed. Anyone who has used a GraphQL API will know the knock on effect for constructing a request — instead of asking for whole tables of data you ask for specific attributes (properties of the nodes you are interested in).</p><p>By redesigning the data persistence layer to fit a graph model, I noticed a (now glaring) inefficiency in my original version of HabitFract. When querying my web API, I would ask for a table of “HabitDates” — records in a relation that uses two foreign keys to create a many-many relationship between “Habits” and “Dates” — the yellow, orange and purple relations in the entity relationship diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UJESnOjJhojiDvSQT_bFQ.png" /></figure><p>After every calendar day completed, when a user accessed the app, I would trigger a lifecycle hook to insert records into the ‘<em>date</em>’ and ‘<em>habit_date_completed</em>’ relations seen above. The ‘<em>habit_date_completed</em>’ <strong>completed </strong>value defaulted to ‘<strong>false</strong>’. It was a naive approach:</p><p>Imagine if the user has data stored for 100 different habits, and they wait a month before accessing the app again. The page reload will be waiting on about 31 + 3100 new records to be inserted, just to record the fact that they haven’t done anything!</p><p>The important thing to realise is that there is no need to record a <strong>false </strong>value for an action being completed on a date. That is the obvious default position of all actions before we do them, and so ‘gaps’ in the calendar can be inferred from the ‘<strong>completed = true</strong>’ days.</p><h3>Simplifying the Schema</h3><p>The above realisation, combined with the more modular microservice based architecture of Holochain has influenced me to concentrate on the general concept of recording *When* something happened.</p><p>There is already another hApp under development called ‘Where’, to do with locating where people are (not just geographically, but, for example, emotionally too). You can see it being trialled and discussed <a href="https://www.youtube.com/watch?v=DJiA25WuDzU">here</a>.</p><p>To make my habit tracking logic reusable, I will break it up into a smaller project called ‘When’: See the <a href="https://github.com/nick-stebbings/hc-react-redux-shared-todo-feed/tree/red-dots">github repo</a> with the <a href="https://github.com/nick-stebbings/hc-react-redux-shared-todo-feed/blob/red-dots/DESIGN.md">design document</a> which includes specifics about the implementation of the concepts discussed in this article.</p><p>This means I can cut down the schema to 3 basic models: a thing that is done, (like a Todo list being completed), a Habit (a record of that action over time), and the specific instances in time when the action was completed (Red Dots).</p><p>Part 4 of this series will go into more detail about implementing “When”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3be56214c6ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From local storage To-do list to Fractal, Peer-to-Peer Habit Tracker]]></title>
            <link>https://n-stebbings.medium.com/from-session-cookie-to-do-list-to-fractal-distributed-listmania-2da3e33728a?source=rss-9224a7e051eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2da3e33728a</guid>
            <category><![CDATA[habit-building]]></category>
            <category><![CDATA[sinatra]]></category>
            <category><![CDATA[mithriljs]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nick Stebbs]]></dc:creator>
            <pubDate>Tue, 09 Nov 2021 00:43:19 GMT</pubDate>
            <atom:updated>2022-12-20T23:56:54.020Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: Multilayered architecture</h4><h4>(<a href="https://n-stebbings.medium.com/from-session-cookie-to-do-list-to-fractal-distributed-listmania-part-1-645911140e53?source=your_stories_page----------------------------------------">Part </a>1)</h4><p>While I was studying the LS185 course in the <a href="https://launchschool.com/">Launch School</a> curriculum, I had the idea for my own web app — <a href="https://habit-triangles.herokuapp.com/">a habit tracker</a> that would allow you to dissect patterns of behavior into their smallest constituent parts. I thought of the inital idea after being exposed to the book ‘Atomic Habits’ by James Clear, and using the WorkFlowy application.</p><p>The difference with my application compared to other linear habit trackers like HabitBull, or the simple crossing off of calendar days, was that I was going to make a *fractal* way of visualizing behaviour (the concept is <a href="https://medium.com/@hello_69361/habits-and-fractals-36b35c156560">succinctly explained</a> here by a fellow Medium writer).</p><p>I also had ideas about changing the core architecture to a decentralised ‘community network’ allowing learning from each others’ habits but with sovereignty of personal data. The discovery of <a href="https://www.holochain.org/">Holochain</a> — an emerging decentralised framework &amp; cloud computing infrastructure — was what got me into serious backend coding from the start. For me this would be the long term goal — make my first Holochain app. But first I would explore client-server architecture in-depth and make a single paged application.</p><h3><strong>Learning from the first attempt</strong></h3><p>The local storage version I had already made was based quite closely around the Todo list app that I had followed along with in the LS curriculum. We were advised to experiment and make our own simple applications in this fashion.</p><p>I showed the app in its prototype state to a fellow student on the course, Steve. He had more JavaScript experience than me and saw some of the limitations of my design. I had become somewhat attached to using the jQuery Swiper component and it was leading me to write lots of hard-to-maintain code.</p><p>Now I was starting to learn that there are tools out there for almost every job, and thankfully Steve pointed me towards the library D3js. I was still somewhat new at modular design and not used to incorporating anything other than jQuery into my approach to manipulating the DOM.</p><h3>Planning a new UI</h3><p>I spent some time getting to grips with the basics of the D3 data join, different layouts, and how I could visualise my fractal structure in the browser. When developing the frontend visualisations:<br> 1. I would need to incorporate d3-zoom.<br> 2. The closest layout that I could envisage my data structure working with was a <a href="https://observablehq.com/@d3/zoomable-icicle">zoomable icicle diagram</a> where only 3 levels are displayed at any one point.<br> 3. This is based on a hierarchical data structure so I needed to explore the way that d3 works with hierarchical data.<br> 4. To try and load a full tree of data for each user at once would cause issues rendering, once the tree reached a certain size.<br> 5. I could instead populate the data join with the level of the hierarchy that I wanted to visualise at any one moment (a subtree), and query the ‘edges of my data’ (the leaves of the currently displayed tree) at the specific level I was viewing. The idea of pagination data being fetched in increments seemed to be the closest approximation.</p><h3>Backend SOLID principles</h3><p>In the period between first design and sketching the above path to a MVP, I also studied relational databases using PostgreSQL. I had always known that local storage would be good for nothing other than a personal prototype of the interface and concept, but now I was faced with the task of choosing a persistent data store. My main challenge from <a href="https://n-stebbings.medium.com/from-session-cookie-to-do-list-to-fractal-distributed-listmania-part-1-645911140e53?source=your_stories_page----------------------------------------">Part </a>1was how to separate concerns —as Uncle Bob had said — to delay making that decision final for as long as possible.</p><p>It took me a little time to get my head around dependency injection &amp; inversion of control, as well as separating out all responsibilities for Object Relational Mapping. I spent time learning the <a href="https://dry-rb.org/">dry-rb libraries</a> and their uses. The libraries make Uncle Bob’s vision easier to implement!</p><h3>Choosing a stack</h3><p>I used a <a href="https://kopilov-vlad.medium.com/sinatra-webpack-vue-js-spa-template-project-333d44fcdc54">starter</a> for a <em>spike</em>, just to explore the multi-layered SPA structure.</p><p>I had been reading about the ‘Build First’ philosophy of development workflow, asset bundling in JS, and modular design. All of this would need to be incorporated going forward. I had started to learn about the use of reactive JS frameworks but not wanting to deviate too far from the Launch School philosophy of ‘<em>mastery of fundamentals’</em>, I decided not to learn any big framework, but picked up MithrilJS (it’s lightweight and easy to get started with).</p><p>BACKEND:<br>- Sinatra for routing<br>- Sequel and ROM-rb for ORM<br>- dry-rb, a set of modern Ruby libraries, for code organisation and DI<br>- PostgreSQL</p><p>FRONTEND:<br>- MithrilJS<br>- D3 for visualisation<br>- Axios to query the backend<br>- Webpack</p><p>I would set up both layers as individual Docker containers and allow continuous intergration/development with Github actions by pushing new versions of the images to Docker Hub with each push to the Main git branch.</p><h3><strong>What I came up with</strong></h3><p>I made a <a href="https://api.habfract.online/">web API</a> for storing and <a href="https://github.com/nick-stebbings/fractal-habits-SPA-tailwind-mithril/blob/main/src/api/system/hht/api.rb">serving hierarchically structured (JSON)</a> serialised habit data. The design choices I took enable rapid interaction between the application layer and the data persistence layer, and the ability to ‘switch out’ the ‘<em>Source of Ultimate Truth</em>’ from a database to a file of serialised data, simply by passing a query string <strong>`?demo=true</strong>` to the frontend. I managed to do this while retaining most of the core functionality of the app (vs. when it was using the PostgreSQL persistence layer).</p><p>My initial objective was to demonstrate Uncle Bob’s premise of SOLID design allowing you to make the database ‘an implementation detail’. I was hoping that this would allow adaptability towards decentralised architecture in the future.</p><p>The library ROM-rb (Ruby Object Mapper), with its YAML adapter, was crucial to this, but the adapter does not allow writing to files. This meant that I could only make a ‘read-only’ version that would not persist changes to the serialised data for longer than the session. For demonstration purposes, this is fine, and leaves the option for easily <em>swapping back the persistence layer</em> to a database after playing around with the structure of the web scraped data: an adapter in the true sense. This will in turn make the app more immediately accessible as people will be able to ‘import’ web-scraped habit structures and then make them their own by persisting to the database.</p><p>EDIT: After migrating the UI to React, the demo of this feature is no longer live. I have instead implemented a UI <a href="https://habfract.online/">demo</a> with pre-built templates to play around with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OA38pAmyco-e6MpgPDwjDA.png" /></figure><h3>Areas for Improvement</h3><p>Due to the fact that I had yet to discover React &amp; Redux at the time, I didn’t come up with a cohesive state management pattern for the frontend. By the time I was using multiple levels of component state this become a real issue. I later learnt that the <a href="https://kevinfiol.com/blog/simple-state-management-in-mithriljs/">Meiosis</a> pattern would have gone very well with MithrilJS’s lightweight approach and it is a good introduction to Redux’s patterns.</p><p>Since starting to build the Holochain-backend version I have focused on Redux from the start and expect to rewrite many of the frontend components to work with React, which will make the fractal view much more responsive and smooth out the state management bugs mentioned above.</p><p>How many of my 5 UI points did I manage to hit? It is currently a zoomable tree diagram, without the buffered ‘pagination’ type feed of data. The React version should hit all 5 to make the visualisation fractal.</p><p>I am pleased with the amount I learnt through this primarily backend coding journey. How far can we take the Todo list?</p><p>Find out in part 3!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2da3e33728a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From local storage To-do list to Fractal, Peer-to-Peer Habit Tracker]]></title>
            <link>https://n-stebbings.medium.com/from-session-cookie-to-do-list-to-fractal-distributed-listmania-part-1-645911140e53?source=rss-9224a7e051eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/645911140e53</guid>
            <dc:creator><![CDATA[Nick Stebbs]]></dc:creator>
            <pubDate>Wed, 27 Oct 2021 09:11:07 GMT</pubDate>
            <atom:updated>2021-11-10T00:50:35.065Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: Beginnings</h4><h3>“It started with a liiiist”</h3><p>It started with a To-do list. The word(s?) lost all meaning…</p><p>‘Add To-do item’</p><p>‘Delete To-do’</p><p>‘Add new To-do list’</p><p>‘To-do or not To-do…’</p><p>We’ve all been there; after all, it’s a canonical CRUD example. As somebody who was drilling code problems all day, it was a step up to something a little more cohesive. For me it was also an introduction to Sinatra and Rack-based frameworks in general.</p><p>I <em>persisted </em>as long as I needed to and moved on — exploring what else Sinatra was capable of. It led me to develop a multi-page app that would store data on tracking personal habits — exercise, meditation, diet etc. I stored an array of linked lists (habits) which had a boolean value (completed/not completed) for each day of tracking.</p><p>Most of my time was spent prettying the front-end with Bootstrap and more JavaScript than was strictly necessary, appropriating SwiperJS so that I could swipe back and forth between consecutive tracked days. I stored each habit as a node in linked list, visualised by a triangle, and tried extending Flexbox (gasp) to allow an inverted ‘stacking’ of the triangles into a ‘Habit Pyramid’.</p><p>I was pleased with <a href="https://habit-triangles.herokuapp.com/">my progress</a>, but not pleased enough to draw a line under it. There was a bigger, more scalable project lurking underneath the cluttered codebase.</p><h3>Enter Uncle Bob</h3><p>They say Mastery involves mentorship. I feel lucky to have studied (and currently finishing) the Launch School curriculum where they put a total focus on these principles. I have to admit having deviated from strictly following the course in sequence, deciding to get lost my fair share of rabbit-holes throughout the last 2 years of study, but always returning to their trusted and valued community.</p><p>One of the more recent but inevitable diversions was a video by Robert (‘Uncle Bob’) Martin: <a href="https://www.youtube.com/watch?v=WpkDN78P884">Architecture, the Lost Years</a>. I had hear about SOLID principles of design but it seemed a bit too advanced for me, still mastering the basics of HTTP requests and JavaScript object creation.</p><p>This video stretched, or should I say expanded, my comprehension of what I could build. It got me thinking about how I can de-couple the application layer from the persistence layer. I had heard of Uncle Bob before, but seeing his presentation made me understand why he was so valued to the industry… and now separation of concerns makes so much sense!</p><p>With a mind to develop decentralised applications later on down the line, I suddenly saw the possibility of extending Habit Triangles to be a social app, where we could encourage each other to develop self-actualising habit patterns and retain sovereignty over our private data. Holochain is what inspired this; fall into that rabbit hole if you choose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*CSM37vCO7-YPYQ2zPgyYZQ.png" /><figcaption>Where can we go from here?</figcaption></figure><p>A new goal: create a version of Habit Pyramids that can take any type of data store. ‘<strong>Defer important decisions as long as possible</strong>’.</p><p>Whether to use traditional client-server architecture or decentralised/distributed architecture seemed like a suitably huge decision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=645911140e53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking the MagiJSian’s Code: JavaScript Object Creation Patterns, Revealed!]]></title>
            <link>https://n-stebbings.medium.com/breaking-the-magijsians-code-javascript-object-creation-patterns-revealed-7eeffe791c3d?source=rss-9224a7e051eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eeffe791c3d</guid>
            <dc:creator><![CDATA[Nick Stebbs]]></dc:creator>
            <pubDate>Wed, 17 Mar 2021 20:43:01 GMT</pubDate>
            <atom:updated>2021-03-17T20:43:01.232Z</atom:updated>
            <content:encoded><![CDATA[<p>A famous American illusionist recently floated into the sky.</p><p>It was an impressive feat, but let us not forget how much (ahem..) groundwork was put in over the years prior. Standing (or hovering) on street corners, year-on-year, he focused on his fundamentals: creating objects from thin air.</p><p>Let us become magician programmers and explore the mighty powers available to us for making new JavaScript objects.</p><h4>Basic Sleight of Hand: `Object.create`</h4><p>The trick to trump all tricks: Create a brand new object; link it to another object. Behaviour delegation is what JavaScript ‘inheritance’ is <em>really</em> all about. <br> When the property cannot be found on the object in question, it delegates to the next object up the <em>prototype chain.</em></p><p><em>Watch and learn:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d1e2ac6e46e0830821cb167108620fc/href">https://medium.com/media/8d1e2ac6e46e0830821cb167108620fc/href</a></iframe><p>There <em>is</em> a catch (although it’s really a feature). Sometimes your new objects will have hidden properties that you forgot were lurking in the background. To create a <em>truly </em>new, shiny object, you will need to pass null to Object.create (like so…)</p><p><em>For my next trick I will need a blank piece of paper:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/495e784c35f455354b7f6970b863bbc2/href">https://medium.com/media/495e784c35f455354b7f6970b863bbc2/href</a></iframe><p>Having built in methods that all objects can access turns out to be a useful feature, and so in JavaScript objects typically delegate, in the last instance, to Object.prototype. This is a special object that we could call ‘the <em>prototype of prototypes</em>’.</p><p>What is Object.prototype&#39;s prototype? null :</p><p>Object.getPrototypeOf(Object.prototype) === null // true</p><h4>ES6 Classes</h4><p>Of course, to be a modern magician, you’ve got to have <em>class. </em>Since ECMAScript 2015, we’ve had access to a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">new kind of syntax</a> for constructing objects: the class keyword. We also were given the extends keyword, for emulating traditional class inheritance and creating a superclass/subclass relationship.</p><p>Except… in JavaScript there aren’t really any classes! But there <em>is </em>now a way to dress up the basic sleight of hand object creation into something a little more… classic. If it makes it easier to digest for you, then use this syntax, but to know what it’s really doing under the hood we need to hark back to pre-ES6 object creation patterns…</p><h4>Pseudo-Classical</h4><p><em>Harry Houdini is trying to prepare his next illusion. He’s getting tired of repeating the same props, but he also doesn’t want to make everything from scratch.</em></p><p>In steps the new keyword! We can use it with a function that was made specifically to create new objects, a constructor function (we capitalise the name of this function, by convention).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33e0f141b27c73bda0c71d3be8e48e45/href">https://medium.com/media/33e0f141b27c73bda0c71d3be8e48e45/href</a></iframe><p>If we instead don’t want to bother with resetting constructor property, the pattern breaks down as:</p><pre>function Constructor() { <br> // Add properties you want to be unique to an object<br>}</pre><pre>Constructor.prototype.propertyName = // a shared property;</pre><pre>Constructor.prototype.methodName = function() { // a shared method }</pre><p>But we could also add properties to the prototype from within the constructor function, using conditional branches to prevent duplication of code:</p><pre>function Constructor() { <br> // Add properties you want to be unique to an object</pre><pre>if(!this.propertyName) {<br>  Constructor.prototype.propertyName = // shared property;<br>}<br>if(typeof this.methodName !== &#39;function&#39;) {<br>  Constructor.prototype.methodName = function() { // shared method }<br>}<br>// We checked if the properties/methods existed on &#39;this&#39;, (or a prototype in &#39;this&#39;s prototype chain).<br>}</pre><p>But what is this? You might be wondering. Let’s delve deeper into the secrets of the constructor function:</p><p>When a function is called with new, it:<br>a) Creates a new object<br>b) Creates a prototype linkage from the new object to the object referenced by the prototype property of the function.<br><em>(So far, it’s done what </em><em>Object.create does, but it also…)</em></p><p>c) Binds the object to the this keyword (which changes the execution context of the function)<br>d) Implicitly returns the object from the function call</p><p>One last point… how do we know if the properties of our object come from its prototype?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/463a817ca42d2feb8b0fbedbac52a1ab/href">https://medium.com/media/463a817ca42d2feb8b0fbedbac52a1ab/href</a></iframe><h4>Objects Linked to Other Objects (OLOO)</h4><p><em>Phew! Old Houdini had to put up with a lot of complexity. A modern </em><a href="https://frontendmasters.com/courses/advanced-javascript/oloo-questions/"><em>mage</em></a><em> realised this and came up with a new trick harnessing the power of </em><em>Object.create in a different way.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b82cbb8f0699a8d509da90c31d8985f0/href">https://medium.com/media/b82cbb8f0699a8d509da90c31d8985f0/href</a></iframe><p>The pro’s and cons of this pattern have been (and will continue to be) thoroughly <a href="https://stackoverflow.com/questions/29788181/kyle-simpsons-oloo-pattern-vs-prototype-design-pattern">debated</a>. One aspect that changes with this pattern is how to identify the prototypal inheritance (or behaviour delegation) at play:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1afeb922ec731106cbecd1f9d9a786e3/href">https://medium.com/media/1afeb922ec731106cbecd1f9d9a786e3/href</a></iframe><p>That does it for this edition of… <strong>‘Breaking the magiJSian’s code</strong>’</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eeffe791c3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>