<?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 Tim Edge on Medium]]></title>
        <description><![CDATA[Stories by Tim Edge on Medium]]></description>
        <link>https://medium.com/@tdedgx?source=rss-f40b51ecaf27------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pJ0GcaOYaxtZ-19B65M2WA.png</url>
            <title>Stories by Tim Edge on Medium</title>
            <link>https://medium.com/@tdedgx?source=rss-f40b51ecaf27------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:36:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tdedgx/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[The Conviction Graph]]></title>
            <link>https://tdedgx.medium.com/the-conviction-graph-0072b423f525?source=rss-f40b51ecaf27------2</link>
            <guid isPermaLink="false">https://medium.com/p/0072b423f525</guid>
            <category><![CDATA[wisdom]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[prediction-markets]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[social-media]]></category>
            <dc:creator><![CDATA[Tim Edge]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 01:07:42 GMT</pubDate>
            <atom:updated>2026-07-03T01:07:42.074Z</atom:updated>
            <content:encoded><![CDATA[<h4>Most of the internet measures attention. A conviction graph measures what people are willing to stand behind</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fI_yYBfS5YhDqCxuKY7gcw.png" /></figure><p>The software that increasingly reads, ranks, summarises and answers on our behalf learns from the open web. That’s the training corpus, the retrieval source, the thing a model reaches for when you ask it something hard. And the open web is not a record of what people believe. It’s a record of what got <em>attention</em> — what was published prolifically, tuned for a feed, repeated until it ranked. Volume stands in for importance, and volume is purchasable, farmable, and increasingly synthetic.</p><p>So we’re about to hand a great deal of judgement to systems whose picture of what humans value is shaped, in large part, by whoever was loudest. That’s a strange foundation, and it’s the problem this piece is about. Not the cartoon fear that “AI will lie to us” — something narrower and more tractable: the <em>inputs</em> have no notion of conviction.</p><p>So here’s the question we set ourselves. What would it take to have the other thing — a record of what people are genuinely willing to stand behind, weighted by something other than how often it was posted, and structured so a machine could read it? That record is what we’ve been building. We call it a conviction graph.</p><h3>What it actually is</h3><p>People post claims — especially the contested <em>normative</em> ones, the moral and policy questions that have no settlement date. Others back or contest those claims by staking or bonding real value behind them, on-chain. What accumulates isn’t a feed optimised for outrage, and it isn’t a pile of facts somebody simply asserted. It’s a persistent, machine-readable map of positions, weighted by how much people are actually willing to put behind each one.</p><p>The important word is <em>map</em>, not <em>verdict</em>. A conviction graph does not resolve <em>“a carbon tax is the fairest way to cut emissions”</em> to true or false — there is no oracle that could. What it produces is a <strong>distribution</strong>: who holds which position, how strongly, and how those positions cluster, support each other, and collide. The output is the shape of the disagreement, rendered honestly, instead of a single answer laundered through an algorithm. Conviction, not assertion — and conviction, not veracity.</p><h3>A claim becomes a weighted node</h3><p>Start with one claim. Someone writes it down and stakes behind it; others who hold the same position add their own stake. That accumulated backing gives the claim a weight, and the weight is what turns a sentence into a node in the graph.</p><p>An obvious objection is that economic backing is just <em>money</em>, so a graph weighted by it measures the deepest wallet, not the strongest conviction. That would re-create the exact “loudest voice” pathology we started out complaining about. So the weighting is deliberately not “sum of stake.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSrxzUqDe2VOBKaV-KGjbg.png" /><figcaption><em>Stake becomes influence only after it’s damped: a square root on the amount, a lift for diverse backing, and a filter of earned, un-buyable reputation.</em></figcaption></figure><p>Influence scales with the square root of stake, so a hundred times the capital buys roughly ten times the weight, not a hundred. Each stake is then weighted by its backer’s <em>reputation</em> — an earned, soulbound, non-transferable score (a 0.1× to 10× multiplier) that money can’t buy and that you lose by being wrong when a position is contested. A claim’s weight is lifted further by the diversity of the <em>sources</em> cited behind it, and by how broad and balanced its coalition of <em>backers</em> is, so many small, independent stakers count for more than one whale at the same total. None of that abolishes the tilt of capital. It narrows it.</p><h3>From nodes to a graph</h3><p>A pile of weighted claims is still just a pile. What makes it a <em>graph</em> is the edges — and those aren’t drawn by hand. As each claim arrives, a natural-language-inference model reads it against the claims already present and classifies the relationship: does this <strong>support</strong> that one, <strong>contradict</strong> it, or is it merely <strong>related</strong>? Support pulls claims together; contradiction records a genuine fault line without letting the two sides collapse into each other; related is the loose relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUX8Dj3iviSgxygiMqWMqg.png" /><figcaption><em>Nodes are claims, coloured by conviction; edges are the machine-classified relationships. Same-position claims gather into clusters; the edges between opposing clusters are the fault lines.</em></figcaption></figure><p>Run that over thousands of claims and structure precipitates out. Positions that say the same thing in different words gather into clusters — and each cluster surfaces its highest-conviction member as the one that speaks for it, so the strongest statement of a shared idea rises to represent the group rather than the position being scattered across a dozen near-duplicates. Clusters that argue with each other are joined by contradiction edges, which mark exactly where a society’s genuine disagreement sits rather than papering over it. This is the payoff of <em>distribution, not verdict</em>: you don’t get told who’s right, you get shown where the lines are drawn and how much weight stands on each side.</p><h3>The layers underneath</h3><p>None of that is a single clever trick; it’s a stack, and each layer sees something the one below it can’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MU1ikH181fHL9ooTRqkCTA.png" /><figcaption><em>Bottom to top, each layer is derived from the ones below it — and the whole stack is reconstructable from the on-chain record, so the map can be checked, not just trusted.</em></figcaption></figure><p>At the base is the thing the chain guarantees due to decentralisation: who backed what, how much, and when, recorded so it can’t be quietly edited. Above that, every claim is embedded — placed in a space where semantic nearness is measurable. On top of the embeddings sit the typed edges. Above the edges, two independent systems run: semantic categorisation sorts claims into topics and domains, while community detection finds the clusters that emerge from the edge structure itself. And at the top, centrality analysis surfaces the load-bearing claims — the ones everything else leans on — while a separate pass merges near-duplicate phrasings so a single idea expressed ten ways isn’t mistaken for ten ideas. Out of all of it falls the conviction graph: structured, queryable, and in principle reconstructable by anyone from the same on-chain data.</p><h3>Why the engagement model works this way</h3><p>Start with what we’re <em>not</em> claiming: that putting money behind a statement makes it true — it doesn’t, any more than a million retweets do. What backing a claim <em>does</em> is different, and more defensible: it turns engagement into a <em>transparency</em> signal. The signal isn’t “this is correct,” it’s “here’s where conviction actually concentrates, and here’s the receipt.”</p><p>That’s also why engagement here runs along a spectrum rather than forcing a single way in — graded by how much you’re willing to put at risk. At the light end is social signalling: liking or endorsing a claim costs nothing and feeds the ranking only as a soft signal. In the middle, and most characteristic, is principal-protected staking — skin in the game without the gamble: your principal comes back at unlock, and the only thing you ever trade is native staking yield for the protocol’s scored rewards. At the sharp end is bonding and its contests — closer to the old idea of a veracity bond — an adversarial layer where you genuinely <em>can</em> lose what you put up, and the closest thing here to the pull of a prediction market.</p><p>This engagement model and the output matters for the AI problem we opened with. A model grounded in a conviction graph isn’t being told which claims are true and which are false — we don’t have that, and neither does anyone else. It’s being given something the open web can’t offer: an <em>attributable, tamper-evident view of the distribution of human positions</em>, with the disagreements marked rather than smoothed over. The grounding value is the provenance and the visible spread of opinion, not a verdict handed down by whoever staked the most.</p><h3>Come and look</h3><p>The distinction the whole thing rests on is simple: most of the internet measures attention, and attention is loud, cheap, and game-able; a conviction graph measures what people are willing to stand behind, and writes it down where no one can quietly rewrite it. That gives you a map of human positions with its provenance intact — the kind of substrate the next generation of systems could actually ground themselves in, instead of whatever was loudest on the open web.</p><p>The idea stands on its own. The product is the early, unproven part — it’s an alpha, on testnet. So the best thing you can do isn’t to take our word for any of this. It’s to come and try to break it.</p><p><em>Rationall is a decentralised conviction-graph protocol on Cardano — alpha, on testnet.</em></p><ul><li>Try it (Google sign-in, faucet ADA, wallet optional): <a href="https://rationall.io/about">https://rationall.io/about</a></li><li>Docs: <a href="https://rationall.io/docs">https://rationall.io/docs</a></li><li>Join the Discord: <a href="https://discord.gg/ydWUh9834s">https://discord.gg/ydWUh9834s</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0072b423f525" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decentralised Ledger ≠ Distributed Ledger]]></title>
            <link>https://tdedgx.medium.com/decentralised-ledger-distributed-ledger-7e0d458abfaa?source=rss-f40b51ecaf27------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e0d458abfaa</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[dlt]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[decentralization]]></category>
            <dc:creator><![CDATA[Tim Edge]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 06:30:45 GMT</pubDate>
            <atom:updated>2026-06-30T06:30:45.502Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why true decentralisation — not just distribution — is the only foundation for trustworthy data in an AI world</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8aFkL3FmJRQCvhXMQjyPQ.png" /></figure><p>We treat “crypto,” “blockchain,” and “distributed ledger” as if they were the same thing. They get swapped interchangeably, usually shorthand for “the money stuff.” In doing so, we’ve quietly lost sight of the one property that actually determines whether any of it can be trusted: <strong>decentralisation</strong>.</p><p>Following <a href="https://medium.com/@VitalikButerin/the-meaning-of-decentralization-a0c92b76a274">Vitalik Buterin</a>, decentralisation breaks down into architectural (how many machines run it) and political (how many independent parties control it). Distribution and decentralisation are not the same. That distinction is the whole game.</p><h3><strong>The conflation problem</strong></h3><p>We use three words as if they were interchangeable: crypto, blockchain, and distributed ledger technology (DLT). In practice they are treated as synonyms, all carrying the same implied promise — “this data is trustworthy because it’s on a ledger.”</p><p>But a ledger being distributed tells you almost nothing about whether you can trust it. A bank can distribute its database across a hundred data centres and it remains one bank’s ledger. A consortium of five companies can run a “distributed” chain where any three of them can still rewrite history.</p><p>Distribution is about topology and uptime — many machines, no single point of failure. It is a real engineering property, but not a trust property. You can distribute a lie across a thousand servers and all you have is a well-replicated lie.</p><h3>The one property that matters for trust</h3><p>Decentralisation is a different claim entirely. It is not about how many copies exist — it is about how few weak points remain. How many independent parties would need to collude, be coerced, or be compromised before the record could be altered or the rules rewritten?</p><p>In a genuinely decentralised system, the answer is: an impractically large and diffuse set of actors with no shared point of control. You cannot fit them into one room.</p><p>This is the entire reason the technology matters. Distribution gives you resilience. Decentralisation gives you trust you do not have to extend to any particular person or institution. You no longer rely on a custodian’s reputation — you can verify the record yourself, knowing no small group can quietly change it.</p><p>The questions that actually matter for any chain are therefore simple: Who really secures it, and how concentrated is their power? Who runs the nodes, who can change the protocol, and how hard is it? How resistant is the system to one actor — or one government — pressuring a handful of others? Those answers are what separate a trust layer from a shared spreadsheet with good marketing.</p><h3>The one property that matters for trust</h3><p>Decentralisation is a different claim entirely. It’s not about how many copies exist — it’s about <strong>how few weak points there are.</strong> How many parties would have to collude, be coerced, or be compromised before the record could be changed or the rules quietly rewritten? In a genuinely decentralised system the answer is: an impractically large, diffuse set of independent actors with no shared point of control. You can’t fit the people who’d have to collude into one room.</p><p>That is the entire reason this technology is interesting. When you minimise the weak points, you no longer have to trust a custodian. You don’t take the record on faith because someone reputable vouches for it; you can verify it, and no small group can change it out from under you. <em>Distributed</em> gets you resilience. <em>Decentralised</em> gets you trust you don’t have to extend to anyone in particular.</p><p>So the questions worth asking about any chain aren’t “is it fast” or “is it distributed.” They’re: who actually secures it, and how concentrated are they? Who runs the software, and where do the nodes sit? Who can change the protocol, and how hard is it? How resistant is it to one actor — or one government — leaning on a handful of others? Those answers are what separate a trust layer from a shared spreadsheet with good marketing.</p><h3>Why trust beats finance when the world runs on AI</h3><p>For most of crypto’s history this distinction was academic, because the dominant use case was finance. People already trusted these systems with money — hundreds of billions flowed through them, often via centralised, custodial rails. Finance is unusually forgiving: losses are quantifiable, and tools like regulation, insurance, courts, and chargebacks can sometimes provide recourse. You can get away with “distributed, partly decentralised, and mostly honest.”</p><p>The world we’re entering is far less forgiving. We are building an information environment where AI systems read, summarise, rank, and decide — often at machine speed with minimal human oversight. These systems are only as good as their grounding data. The open internet, their primary training substrate, is optimised for engagement rather than truth: much of it is unattributed, hard to verify, and trivially editable.</p><p>A corrupted financial record costs money that can later be disputed. A corrupted belief fed into AI systems that shape decisions for millions propagates silently, with no chargeback and no court of appeal. When AI mediates what a billion people accept as reality, the integrity of its inputs becomes the central question — and the safety bar is higher, not lower.</p><p>This is why a focus on trust now beats a focus on finance. The scarcest resource in an AI-saturated world is not another financial instrument — it is data with verifiable provenance: attributable, tamper-evident, and resistant to quiet revision by any single party.</p><p>A decentralised ledger does not make claims true. It provides something more modest but powerful: a tamper-evident, attributable record of who committed to what, and when. The ledger is the incorruptible scoreboard. Everything else — the referee — must be built on top.</p><h3>Why we treat the chain as plumbing</h3><p>We chose Cardano primarily for one reason: it has one of the strongest overall decentralisation profiles across every dimension — not just block production, but node distribution, software clients, development funding, governance, and stake distribution. A system is only as decentralised as its weakest link, and Cardano scores highly on that minimum standard. That said, any other base chain, sidechain, or Layer 2 with comparable decentralization properties would serve the same purpose.</p><p>Having chosen the chain for this single critical property, we treat it as plumbing. Users should not need to think about epochs, UTxOs, or block producers — any more than they think about TCP handshakes when sending email. The chain’s job is to sit beneath the surface and guarantee an immutable, custodian-free trust layer.</p><p>Above it, we make the experience ordinary: sign in with existing accounts (currently Google), and receive a self-custodial, zero-knowledge smart wallet — no browser extensions or seed phrases required. Good plumbing should disappear.</p><h3>What we built on top: the conviction graph</h3><p>When “trustworthy data” is the goal rather than a side-effect of moving money, what do you build?</p><p>We built a <strong>conviction graph</strong>. People post claims — especially contested normative ones on morality and policy with no clear settlement date or outcome — and others support or challenge them by staking real value on-chain. What emerges is not an outrage feed or a pile of bare assertions, but a persistent, machine-readable map weighted by how much skin people are willing to put behind each idea. Conviction, not assertion.</p><p>A natural objection is that this simply hands power to the deepest wallets. To counter that, influence scales with the square root of stake (100× capital buys roughly 10× weight), is boosted by backer diversity, and is filtered through earned, soulbound reputation that can be lost in contests. Capital still tilts the system — we acknowledge that openly — but far less than raw wealth would.</p><p>The ledger serves as the tamper-evident scoreboard: it records who staked what, when, and by whom. The referee lives in the mechanism above it — staking, diversity weighting, reputation, and contests where wrong positions can be challenged and slashed. Truth-pressure comes from the social layer; the chain only ensures the record cannot be quietly altered.</p><p>We are equally candid about the limits. The chain guarantees the hard facts. Clustering, ranking, and display happen off-chain, but that layer is re-derivable from on-chain data using published algorithms, and the key parameters (weights, caps, multipliers) live on-chain and will be governed by on-chain vote. The goal is to move even the rules of judgement out of any small group’s control.</p><p>You can build the social mechanics on many platforms. But the combination of a tamper-evident, auditable record of economically backed conviction with on-chain governance of its rules requires a sufficiently decentralised ledger.</p><p>This brings us back to Buterin. He identified three axes of decentralisation: architectural, political, and logical. A conviction graph is deliberately logically centralised — one shared, canonical map, just as a blockchain maintains one shared ledger. That is not a contradiction; it is the point. You want a single coherent reference everyone can read from and contribute to. A thousand incompatible private maps would be useless.</p><p>The trick is to achieve this logical singularity without architectural or political centralisation — so no one owns the map, even though everyone shares it. Decentralise the infrastructure and control; keep the picture coherent. That is exactly what a truly decentralised ledger makes possible.</p><p>This is the kind of substrate an AI system could actually trust: a versioned, signed, auditable snapshot of what humans are willing to stake real value on — judged by provenance and weighted conviction, not raw volume. That is the bet.</p><p>The core distinction stands on its own: decentralised is not the same as distributed, and trust is the property worth chasing. The product itself is still early — exploratory alpha on testnet. The best thing you can do is join the conversation and come try to break it.</p><p><em>Rational Protocol is a decentralised conviction-graph protocol on Cardano — exploratory alpha, on testnet.</em></p><ul><li>Try it (Google sign-in, faucet free ADA, wallet optional): <a href="https://rationall.io/about">https://rationall.io/about</a></li><li>Docs: <a href="https://rationall.io/docs">https://rationall.io/docs</a></li><li>Join the Discord: <a href="https://discord.gg/ydWUh9834s">https://discord.gg/ydWUh9834s</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e0d458abfaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Private Data Management using Decentralised Ledgers]]></title>
            <link>https://itnext.io/private-data-management-using-decentralised-ledgers-b972c6855e48?source=rss-f40b51ecaf27------2</link>
            <guid isPermaLink="false">https://medium.com/p/b972c6855e48</guid>
            <category><![CDATA[trust]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[midnight-network]]></category>
            <dc:creator><![CDATA[Tim Edge]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 08:50:41 GMT</pubDate>
            <atom:updated>2026-01-23T02:30:40.106Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>A Midnight Blockchain Case Study</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwnBkcLJ6NSuk8PngdQqeQ.png" /></figure><h3>1. Introduction</h3><p>In today’s interconnected world, individuals face challenges in managing personal data securely and privately across digital boundaries. A Private Data Manager (PDM) leveraging privacy-focused Decentralised Ledgers or DLTs offers a solution. Building on my <a href="https://medium.com/itnext/data-flow-across-trust-boundaries-using-decentralised-ledgers-515203676ce5">previous article</a> on business to business data flow, this piece presents a reproducible demo for a consumer use-case, focusing on personal data control with enhanced privacy.</p><h3>2. The Problem</h3><p>For sensitive data like identity, medical records or location feeds, users generally rely on centralised services, which have privacy &amp; integration risks, and offer limited control or inability to verify and trust data. This can result in breaches or vendor lock-in. Decentralised systems promise user control and better interoperability, but traditional DLTs like public blockchains expose data to all participants, so they are unsuitable for many real-world use-cases without privacy preserving features. The broader issue is needing privacy at the same time as enabling seamless and secure exchange of data and facts.</p><h3>3. The Goal: Trustworthy, Interoperable and Secure Data Systems</h3><p>The goal is systems where private data flows securely across boundaries, even without inherent trust between the sender and receiver. This empowers users with data control, ensuring:</p><ul><li>Secure &amp; real-time flow of critical facts &amp; data between parties without relying on centralised systems</li><li>Balanced and dynamic confidentiality, integrity, and availability for different use-cases</li><li>Objective, transparent, auditable and verifiable records to facilitate trust between participants</li><li>Minimisation of friction in participation, facilitating simple integration with minimal technical or organisational barriers</li></ul><h3>4. Proposed Architecture for Trusted Secure Data Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQWZRnJHhAiNOHF2hh8JhA.png" /></figure><p>To address these challenges, an architecture based on Distributed Ledger Technologies (DLT) will be demonstrated here. This is designed around a consumer facing app with an on-device data vault and a bridge to a DLT via a custom smart contract enabling private and secure data exchanges.</p><h4>Distributed Ledger Technology (DLT)</h4><p>DLT provides the foundation. Legacy systems are centralised, siloed, and vulnerable, while DLTs offer:</p><ul><li><strong>Global Shared State</strong>: Permissionless nodes ensuring availability and resilience</li><li><strong>Verifiable Records</strong>: Consensus mechanisms for tamper-resistant data history</li><li><strong>Trusted Execution</strong>: Programmable logic that guarantees execution as written</li><li><strong>Self-Sovereignty</strong>: User-controlled identity and data ownership</li></ul><h4>The Midnight DLT</h4><p>Midnight, a Cardano partner-chain, is ideal:</p><ul><li><strong>Inherited Security</strong>: Part of the Cardano family, ensuring a decentralised, immutable, and auditable state</li><li><strong>Hybrid Model</strong>: Native support for both private and public operations</li><li><strong>Programmable Privacy</strong>: Smart contracts enable custom ZK workflows without bespoke infrastructure</li><li><strong>Scalable Utility</strong>: High throughput via Jolteon (5,000 TPS) with negligible fees, designed for transaction utility</li></ul><h4>Consumer App</h4><p>The <strong>Private Data Manager (PDM)</strong> is a standalone app serving as a secure, local data vault. It enables three key privacy-preserving sharing modes via Midnight integration:</p><ul><li><strong>ZK-Proven Facts</strong>: Data stays private on-device while facts are verified on-chain via ZK commitments</li><li><strong>P2P Data Exchange</strong>: Utilising the blockchain to securely broker direct channels between parties</li><li><strong>On-Chain Encrypted Storage</strong>: Wallet keys derive shared secrets for recipient-specific encryption and granular access control</li></ul><h4>Data Architecture</h4><p>A standard ontology is used to ensure semantic interoperability. This simplifies and enhances queries, validation, and cross-system data exchange. Crucially, this ontology permeates the data stored in all stages of exchange:</p><ul><li><strong>On-Device</strong>: Data in the user’s vault is stored as structured JSON-LD objects (e.g., Person, MedicalCondition)</li><li><strong>In-Transit</strong>: P2P exchanges use Message types to wrap payloads</li><li><strong>On-Chain</strong>: Payloads retain their schematic structure, meaning they are immediately usable by any system respecting the ontology</li></ul><p>Together, these form an interoperable, scaleable, privacy-enhanced architecture for seamless data exchange and management.</p><h3>5. The Demonstration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8n-Rv7Jjh7udUx4xZq-Gw.png" /></figure><p>This PDM implementation consists of a suite of demo scripts that leverage on-device storage and the <em>midnight-sdk</em> for blockchain interactions. A custom <em>“Privacy Bridge”</em> smart contract is deployed to handle on-chain mechanics, including verifying ZK commitments, managing access to ciphertext, and brokering point-to-point channels.</p><p>The application acts as a hybrid wallet and dApp, uses self-certifying <em>Decentralised Identifiers (DIDs)</em> for identity and managing credential verification. To ensure semantic interoperability, it adheres to a <em>Schema.org via JSON-LD</em> based ontology for all data structures.</p><p><strong><em>Note:</em></strong><em> Since the public </em>testnet<em> is currently undergoing rapid updates, this demo uses a local custom Midnight </em>devnet<em> running via </em>Docker<em>. This provides a stable environment for deploying the Privacy Bridge and interacting with the network.</em></p><h4>Clone the PDM Demo App</h4><p>Setup requires <em>Node.js</em> 18+ and <em>npm</em> as well as <em>docker</em> (only for running a local midnight dev network). See <a href="https://github.com/Edgxtech/pdm-demo-app/blob/main/README.md">README</a> for full setup instructions, checks and troubleshooting steps.</p><p>From your working directory, clone the PDM project:</p><pre>git clone https://github.com/Edgxtech/pdm-demo-app.git<br>cd pdm-demo-app</pre><h4>Start the Midnight Network</h4><p>Make sure <em>docker</em> and <em>docker compose</em> are installed, then start the required services:</p><pre>cd background/midnight-node<br>docker compose up -d<br>cd ../..</pre><p>Wait ~30 seconds for services to initialize, then verify all three are running:</p><pre>docker compose ps</pre><h4>Setup</h4><p>From the project root pdm-demo-app, install:</p><pre>npm install</pre><p>then run setup:</p><pre>cp .env.template .env<br>npm run setup</pre><p>This bootstraps the environment by creating funded wallets, deploying the PrivacyBridge contract, and issuing credentials. Success looks like this:</p><pre>🏁 Step 1: Wallet Creation<br>   ✅ Created wallet for Alice<br>   ✅ Created wallet for Bob<br>   ...<br><br>🏁 Step 2: Wallet Funding<br>   💰 Alice: 21308368 DUST<br>   💰 Bob: 47841596 DUST<br>   ✅ All wallets funded and verified!<br><br>🏁 Step 3: Contract Deployment<br>   Loading contract...<br>   ✅ Contract deployed! Address: 0200015b9cce...<br>   ✅ Updated PRIVACY_BRIDGE_CONTRACT in .env<br><br>🏁 Step 4: Credential Registration<br>   Trusted Issuers: ✅ Admin (did:pdm:gov:8b1c...)<br>   Issued Credentials: 🚒 Emergency Services: EMERGENCY_SERVICES<br><br>✅ PDM Demo - Full Setup Complete!</pre><blockquote><em>Each step can be run individually if needed (check the </em><a href="https://github.com/Edgxtech/pdm-demo-app/blob/main/README.md"><em>README</em></a><em> for details).</em></blockquote><h4>Verify Setup</h4><p>To verify your actor balances:</p><pre>npm run check-balance</pre><h4>Demo 1: ZK Age Proof</h4><p>Script: npm run demo:age (or npx tsx scripts/demo-01-zk-age-proof.ts)</p><p>Full script: <a href="https://github.com/Edgxtech/pdm-demo-app/blob/main/scripts/demo-01-zk-age-proof.ts">View on GitHub</a></p><p>Verifies age thresholds (18/21) using local ZK proofs and on-chain persistent commitments, without revealing the actual birthdate.</p><p>Key snippets (ZK proof generation and on-chain commitment):</p><pre>// 1. Create local ZK age proof claim (birthdate stays private)<br>const { claim, proof } = createAgeProofClaim(identityCredential.birthDate, threshold);<br><br>// 2. Generate persistent ZK commitment (cryptographic binding)<br>const claimHash = hashContent(claim);<br>const commitment = __compactRuntime.persistentCommit(descriptor, rawDataBytes, nonce);<br><br>// 3. Store commitment on Midnight DLT via Privacy Bridge<br>await (deployedContract as any).callTx.storeCommitment(<br>    dataId, commitment, alice.did, recipientDid, metadata<br>);</pre><p>Output Logs:</p><pre>[Step 1/4] Initialize actors and connect to contract<br>   alice       : mn_shield...hnz43uuqasm0, 21308368 DUST<br>   ✅ Connected to contract at 0200015b9cce2dd99efa9f177162ec032b722d6889937706adac844e6ff91b771650<br><br>[Step 2/4] Create identity credential with birthdate<br>   📋 Identity: Alice Smith<br>   📊 Current Age: 35 years<br><br>[Step 3/4] Store age proof commitments<br>   🔐 Age &gt;= 18: ✅ VERIFIED<br>   ✅ Proof stored. Block: 39757, Tx: d35c7b07...<br>   🔐 Age &gt;= 21: ✅ VERIFIED<br>   ✅ Proof stored. Block: 39764, Tx: 606e4b40...<br><br>[Step 4/4] Verify proofs on-chain<br>   🔍 [Verifier] Checking Alice&#39;s age proof...<br>   🧐 Checking commitment for age &gt;= 18...<br>   Status: ✅ CONFIRMED<br>   🧐 Checking commitment for age &gt;= 21...<br>   Status: ✅ CONFIRMED<br><br>════════════════════════════════════════════════════════════<br>📊 ZK AGE PROOF RESULTS<br>════════════════════════════════════════════════════════════<br>   👤 Subject:   Alice Smith<br>   🎂 Birth Date: HIDDEN (ZK Proof)<br>   📊 Age:        35<br>────────────────────────────────────────────────────────────<br>   Age &gt;= 18: ✅ PROVEN<br>   Age &gt;= 21: ✅ PROVEN<br>════════════════════════════════════════════════════════════</pre><h4>How it works: ZK Age Proof</h4><p>Alice proves her age (e.g., &gt;= 18) without revealing her birthdate:</p><ul><li><strong>Local Proof Generation</strong>: Alice generates a ZK proof locally on her device using the Midnight SDK. Her private birthdate never leaves her device</li><li><strong>Compact Circuit</strong>: The proof logic (Age &gt;= Threshold) is defined in a <strong>Compact</strong> smart contract, compiled into ZK circuits</li><li><strong>On-Chain Verification</strong>: The Midnight blockchain verifies the proof and stores a <strong>ZK Commitment</strong> on-chain</li><li><strong>Privacy Preserved</strong>: Verifiers check the on-chain status (e.g., “PROVEN”) without ever accessing the raw data</li></ul><h4>Demo 2: P2P Direct Data Share</h4><p>Script: npm run demo:p2p (or npx tsx scripts/demo-02-p2p-share.ts)</p><p>Full script: <a href="https://github.com/Edgxtech/pdm-demo-app/blob/main/scripts/demo-02-p2p-share.ts">View on GitHub</a></p><p>Establishes a direct P2P data channel using STUN for NAT traversal and the Midnight DLT as a secure, encrypted signalling layer.</p><p><em>Note that this and the following demo’s involve storing ciphertext </em><strong><em>on-chain</em></strong><em> which comes with a </em><strong><em>“harvest now, decrypt later”</em></strong><em> risk — this is discussed below.</em></p><p>Key snippets (ECDH key derivation and session signalling):</p><pre>// 1. Derive shared secret via ECDH from wallet keypairs (no pre-sharing needed)<br>const sharedSecretBytes = deriveSharedSecretECDH(<br>    alice.encryptionKeypair.privateKey,<br>    bob.encryptionKeypair.publicKey<br>);<br>const sharedSecret = bytesToHex(sharedSecretBytes);<br><br>// 2. Alice creates P2P session and stores encrypted WebRTC offer on-chain<br>const session = await createP2PSession(alice.did, bob.did, sharedSecret);<br>await (deployedContract as any).callTx.createP2PSession(<br>    session.sessionId,<br>    alice.did, bob.did,<br>    session.encryptedOffer<br>);<br><br>// 3. Bob discovers, decrypts offer, stores encrypted answer on-chain<br>await (deployedContract as any).callTx.answerP2PSession(<br>    session.sessionId,<br>    bob.did,<br>    bobSession.encryptedAnswer<br>);<br><br>// 4. Handshake complete: Real UDP data transfer (Schema.org/Message)<br>const secretData = JSON.stringify({<br>    &#39;@context&#39;: &#39;https://schema.org&#39;,<br>    &#39;@type&#39;: &#39;Message&#39;,<br>    &#39;text&#39;: &#39;This is a secret message sent directly...&#39;,<br>    &#39;sender&#39;: { &#39;@type&#39;: &#39;Person&#39;, &#39;name&#39;: &#39;Alice&#39; }<br>});<br>const transfer = await performRealDataTransfer(secretData, ...);</pre><p>Output Logs:</p><pre>[Step 1/6] Initialize actors and connect to contract<br>   alice       : mn_shield...hnz43uuqasm0, 23010395 DUST<br>   bob         : mn_shield...wlvkycsrl56r, 47841596 DUST<br>   ✅ Connected to contract at 0200015b9cce2dd99efa9f177162ec032b722d6889937706adac844e6ff91b771650<br>   👤 Alice (sender): wants to share data directly with Bob<br>   👤 Bob (recipient): will receive data via P2P channel<br><br>[Step 2/6] Alice creates P2P session and stores offer on-chain<br>   ✅ P2P session stored. Block: 39214, Tx: b39a3368...<br><br>[Step 3/6] Bob discovers session and reads encrypted offer<br>   📥 Retrieved encrypted offer from chain<br>   ✅ Bob retrieved session offer from blockchain<br><br>[Step 4/6] Bob processes offer and stores answer<br>   ✅ Bob created P2P answer<br>   ✅ Answer stored. Block: 39221, Tx: 08bc6582...<br><br>[Step 5/6] Alice completes handshake and transfers data<br>   🔓 Alice decrypted answer from Bob<br>   🤝 WebRTC handshake complete!<br>   📤 Alice sends: &quot;{&quot;@type&quot;:&quot;Message&quot;,&quot;text&quot;:&quot;This is a secret message...&quot;}&quot;<br>   📥 Bob receives: &quot;{&quot;@type&quot;:&quot;Message&quot;,&quot;text&quot;:&quot;This is a secret message...&quot;}&quot;<br>   ✅ Direct P2P data transfer successful!<br><br>[Step 6/6] Close P2P session<br>   ✅ Session closed. Block: 39228, Tx: c03a8ca7...<br><br>════════════════════════════════════════════════════════════<br>🎉 P2P DIRECT DATA SHARE SUMMARY<br>════════════════════════════════════════════════════════════<br>   ✅ Alice created P2P session<br>   ✅ Encrypted offer stored on Midnight blockchain<br>   ✅ Bob discovered and read session<br>   ✅ Bob created and stored encrypted answer<br>   ✅ WebRTC handshake completed<br>   ✅ Direct P2P data transfer successful<br>   ✅ Session closed on-chain<br>🔐 Privacy Guarantees:<br>   • ECDH-derived shared secret (no pre-sharing)<br>   • End-to-end encrypted signalling<br>   • No centralised relay server<br>   • Blockchain provides audit trail<br>   • Direct DTLS-encrypted data channel<br>════════════════════════════════════════════════════════════</pre><h4>How it works: P2P End-to-End Encrypted Transfer</h4><p>Direct P2P networking secured by blockchain signalling:</p><ul><li><strong>ECDH Key Exchange</strong>: Parties derive a shared secret from their wallet keypairs (X25519) without any pre-shared secrets</li><li><strong>Encrypted Signalling</strong>: WebRTC connection details are E2E encrypted and exchanged via the Midnight ledger, ensuring only the intended recipient can connect</li><li><strong>Direct Data Channel</strong>: Once connected, data flows directly between parties over encrypted <strong>UDP sockets</strong>, bypassing central servers</li><li><strong>STUN Discovery</strong>: Public STUN servers assist with NAT traversal (IP discovery) only; they cannot access the encrypted traffic</li></ul><h4>Demo 3: Sharing via Encrypted On-Chain Storage</h4><p>Script: npm run demo:storage (or npx tsx scripts/demo-03-onchain-storage.ts)</p><p>Full script: <a href="https://github.com/Edgxtech/pdm-demo-app/blob/main/scripts/demo-03-onchain-storage.ts">View on GitHub</a></p><p>Demonstrates End to End (E2E) encrypted data storage on the Midnight DLT with smart contract-enforced access control permissions.</p><p>Key snippets (ECDH envelope encryption and authorised storage):</p><pre>// 1. Encrypt FOR Bob using ECDH (Schema.org/Person)<br>const sensitiveContent = JSON.stringify({<br>    &#39;@context&#39;: &#39;https://schema.org&#39;,<br>    &#39;@type&#39;: &#39;Person&#39;,<br>    &#39;name&#39;: &#39;Alice Smith&#39;,<br>    &#39;medicalCondition&#39;: { &#39;@type&#39;: &#39;MedicalCondition&#39;, &#39;name&#39;: &#39;Blood Type O+&#39; }<br>});<br><br>const { encryptedPayload, metadata } = createEncryptionEnvelope(<br>    sensitiveContent,<br>    alice.seed,<br>    bob.encryptionKeypair.publicKeyHex<br>);<br><br>// 2. Generate a ZK Auth Commitment so only Alice can grant access later<br>const { secret: aliceSecret } = await getOwnerAuth(dataId, alice);<br>const authCommitment = await computeAuthCommitment(contract, aliceSecret, contractAddress);<br><br>// 3. Store encrypted ciphertext and auth commitment on-chain<br>await (deployedContract as any).callTx.storeEncryptedData(<br>    dataId, metadata, alice.did, encryptedPayload, &#39;&#39;, authCommitment<br>);</pre><p>Output Logs:</p><pre>[Step 1/8] Initialize actors and connect to contract<br>   alice       : mn_shield...hnz43uuqasm0, 22457642 DUST<br>   bob         : mn_shield...wlvkycsrl56r, 47841596 DUST<br>   charlie     : mn_shield...apxfpgvpd3tv, 44064642 DUST<br>   ✅ Connected to contract at 0200015b9cce2dd99efa9f177162ec032b722d6889937706adac844e6ff91b771650<br><br>[Step 2/8] Alice encrypts and stores sensitive data for Bob<br>   📝 Sensitive Data: &quot;{&quot;@type&quot;:&quot;Person&quot;,&quot;knows&quot;:{&quot;name&quot;:&quot;Bob&quot;,&quot;telephone&quot;:&quot;123...&quot;}...&quot;<br>   🔒 Encrypted Ciphertext: dZrdq/K477L9Bsvbu5ZosUTNmJv6v6H5...<br>   ✅ Alice&#39;s data stored. Block: 39300, Tx: a9e640bf...<br><br>[Step 3/8] Test: Owner access (Alice)<br>   ✅ Alice granted access to herself. Block: 39309, Tx: eba3fb52...<br>   🔓 Decrypted Content: &quot;{&quot;@type&quot;:&quot;Person&quot;,&quot;knows&quot;:{&quot;name&quot;:&quot;Bob&quot;}...&quot;<br>   ✅ Owner access: PASS.<br><br>[Step 4/8] Test: Bob access (pre-grant)<br>   ✅ Pre-grant denial: PASS.<br><br>[Step 5/8] Test: Bob access (post-grant)<br>   ✅ Alice granted access to Bob. Block: 39317, Tx: 283f8d8a...<br>   🔓 Decrypted Content: &quot;{&quot;@type&quot;:&quot;Person&quot;,&quot;knows&quot;:{&quot;name&quot;:&quot;Bob&quot;}...&quot;<br>   ✅ Post-grant access: PASS.<br><br>[Step 6/8] Test: Charlie access (never granted)<br>   ✅ Unauthorised denial: PASS.<br><br>[Step 7/8] Test: Charlie attempts unauthorised self-grant<br>   🎭 Charlie attempts to grant himself access to Alice&#39;s data...<br>   ❌ Transaction rejected by contract<br>   ✅ Self-grant attack prevented: PASS.<br><br>[Step 8/8] Test: Bob access (revoked)<br>   ✅ Alice revoked access from Bob. Block: 39325, Tx: 070343f5...<br>   ✅ Post-revoke denial: PASS.<br><br>════════════════════════════════════════════════════════════<br>ACCESS CONTROL MATRIX RESULTS<br>════════════════════════════════════════════════════════════<br>✅ PASS | Owner (Alice) can access own data | Expected: true, Actual: true<br>✅ PASS | Bob cannot access before grant | Expected: false, Actual: false<br>✅ PASS | Bob can access after grant | Expected: true, Actual: true<br>✅ PASS | Charlie cannot access (never granted) | Expected: false, Actual: false<br>✅ PASS | Charlie self-grant attack rejected | Expected: false, Actual: false<br>✅ PASS | Bob cannot access after revoke | Expected: false, Actual: false<br>────────────────────────────────────────────────────────────<br>Total: 6/6 tests passed<br>════════════════════════════════════════════════════════════</pre><h4>How it works: Encrypted On-Chain Storage</h4><p>Secure storage with granular access control:</p><ul><li><strong>E2E Encryption</strong>: Data is encrypted using an ECDH shared secret derived from the sender’s private key and recipient’s public key</li><li><strong>Encrypted State</strong>: Ciphertext is stored on the public ledger but is only decryptable by the intended recipient</li><li><strong>ZK Access Control</strong>: <strong>Compact circuits</strong> enforce that only the data owner can grant or revoke access permissions on-chain</li><li><strong>Confidentiality</strong>: Even on the public part of the blockchain, data remains private, protected by strong cryptography</li></ul><h4>Demo 4: Emergency Multi-Party Authorisation</h4><p>Script: npm run demo:emergency (or npx tsx scripts/demo-04-emergency-auth.ts)</p><p>Full script: <a href="https://github.com/Edgxtech/pdm-demo-app/blob/main/scripts/demo-04-emergency-auth.ts">View on GitHub</a></p><p>Simulates a multi-party emergency response where verified services require explicit family approval to access private location data.</p><p>Key snippets (ECDH location encryption and multi-party authorization):</p><pre>// 1. Alice encrypts location FOR family (Bob) using ECDH (Schema.org/Place)<br>const locEncrypted = encryptForRecipient(<br>    JSON.stringify({ <br>        &#39;@context&#39;: &#39;https://schema.org&#39;, <br>        &#39;@type&#39;: &#39;Place&#39;, <br>        &#39;geo&#39;: { &#39;@type&#39;: &#39;GeoCoordinates&#39;, &#39;latitude&#39;: locationData.lat, ... } <br>    }),<br>    alice.seed,<br>    bob.encryptionKeypair.publicKeyHex<br>);<br><br>// 2. Family (Bob) verifies emergency service&#39;s Midnight credential<br>const hasCredential = contract._hasValidCredential_0(ctx, ppd, emergencyDid, currentTs);<br><br>// 3. Bob grants access to verified service using owner&#39;s secret<br>await (bobContract as any).callTx.grantAccess(<br>    dataId, emergencyDid, alice.did, aliceSecret<br>);<br><br>// 4. Emergency service decrypts location using ECDH with sender&#39;s public key<br>const location = decryptFromSender(ciphertext, iv, senderPublicKey, bob.seed);</pre><p>Output Logs:</p><pre>[Step 1/7] Initialize actors and connect to contract<br>   alice       : mn_shield...hnz43uuqasm0, 21757907 DUST<br>   bob         : mn_shield...wlvkycsrl56r, 47841596 DUST<br>   charlie     : mn_shield...apxfpgvpd3tv, 44064642 DUST<br>   emergency   : mn_shield...nvx3xqtc624h, 45411917 DUST<br>   ✅ Connected to contract at 0200015b9cce2dd99efa9f177162ec032b722d6889937706adac844e6ff91b771650<br><br>[Step 2/7] Alice privately logs location data (background tracking before incident)<br>   📍 [T-2h] -33.8688, 151.2093 - Sydney CBD<br>      Block: 39336, Tx: 2592b1a7...<br>   📍 [T-1h] -33.752, 150.6875 - Blue Mountains trail<br>      Block: 39343, Tx: f15b5355...<br>   ✅ Location history stored on-chain (2 entries)<br><br>[Step 3/7] Unknown party (Charlie) requests access<br>   🎭 Request from: Rapid Response Medical Team (Impersonator)<br>   🔍 Bob verifies requestor&#39;s credentials...<br>   ❌ Credential check: NO CREDENTIAL FOUND<br>   ❌ Bob DENIES - unverified requestor<br>   ✅ Denial logged. Charlie&#39;s request rejected.<br><br>[Step 4/7] Verified emergency service attempts access (pre-authorization)<br>   🚒 Emergency Services (Fire &amp; Rescue) attempts to access location data...<br>   ❌ Access Denied: Unauthorised (no access grant found).<br>   ✅ Security Check: PASS (Emergency service cannot bypass authorization).<br><br>[Step 5/7] Verified emergency service requests access<br>   🚒 Request from: Emergency Services (Fire &amp; Rescue)<br>   ✅ Access request submitted. Block: 39359, Tx: 50d1a645...<br><br>[Step 6/7] Family member approves verified request<br>   📱 Bob receives notification...<br>   ✅ Credential check: VALID EMERGENCY_SERVICES credential<br>   ✅ Access granted. Block: 39367, Tx: 48a8d702...<br><br>[Step 7/7] Emergency service retrieves location data<br>   🚒 Emergency Services (Fire &amp; Rescue) receives decrypted location:<br>   📍 Coordinates: -33.752, 150.6875<br>   ✅ Emergency service has received valid location data<br><br>════════════════════════════════════════════════════════════<br>🏥 EMERGENCY RESPONSE SUMMARY<br>════════════════════════════════════════════════════════════<br>   📋 Timeline:<br>      1. Alice logged location (background tracking)<br>      2. Alice went missing<br>      3. Charlie (unverified) requested access - DENIED<br>      4. Emergency Services attempted access (pre-authorization) - DENIED<br>      5. Emergency Services (verified) requested access<br>      6. Bob approved the request<br>      7. Emergency Services retrieved location<br>   🔐 Security Demonstrations:<br>      • ECDH encryption - no pre-shared secrets<br>      • Unverified requestors denied<br>      • Only verified services with family approval get access<br>      • Full audit trail on-chain<br>════════════════════════════════════════════════════════════</pre><h4>How it works: Multi-Party Authorisation</h4><p>A governance workflow where access requires verified authorisation:</p><ul><li><strong>Role-Based Encryption</strong>: Data is encrypted for a trusted family member (Guardian) who controls downstream access</li><li><strong>Credential Verification</strong>: The smart contract validates <strong>Midnight Verified Credentials</strong> (e.g., “Emergency Services”) before processing access requests</li><li><strong>Conditional Logic</strong>: Access is only granted when a valid request corresponds with Guardian approval</li><li><strong>Audit Trail</strong>: The entire workflow — tracking, request, approval, and access — is immutably recorded on-chain</li></ul><h3>6. Discussion</h3><p><strong>Key Observations</strong></p><ol><li><strong>Seamless Decentralised Flow</strong>: Participants have seamless flow of meaningful data including content or proofs while maintaining security and privacy, without the need for centralised systems and the vulnerabilities they bring</li><li><strong>Balanced Security Options</strong>: Participants can opt for different methods depending on the use-case ranging from disclosing proofs rather than raw data, on-chain encrypted storage with access control, or direct P2P encrypted transfer via DLT signalling</li><li><strong>Verifiable Trust</strong>: Participants can be sure of the trust of the system and the data due to the natural audit trail provided by the blockchain as well as integrated credential verification capabilities</li><li><strong>Interoperable Architecture</strong>: Participants and systems can integrate seamlessly due to the interoperable data architecture, minimising friction in participation</li></ol><p><strong>Caveats</strong></p><ol><li><strong>Harvest Now, Decrypt Later Risk</strong>: Demos 2–4 carry this risk as they involve on-chain ciphertext. For <strong>time-decaying data</strong> or <strong>ephemeral secrets</strong> (e.g., historical location, past health readings, expired credentials) it may be acceptable to trade-off long-term confidentiality for better availability. For <strong>high-stakes, long-lived secrets</strong> (e.g., financial keys, permanent identity credentials), prefer ZK proofs that keep raw data off-chain entirely</li><li><strong>Standards Selection</strong>: I’m choosing standards for data formats and protocols for research and demo purposes here, there are many options to consider for a production system</li><li><strong>Test Network</strong>: Note we have used a test network which is not a permanent system, however has allowed the demonstration with less resources</li><li><strong>Research Status</strong>: This is research and is not a production ready system, more effort and validation of security and function is needed across all layers of the application — use externally at your own risk</li></ol><h3>7. Summing Up</h3><p>This demo extends <a href="https://medium.com/itnext/data-flow-across-trust-boundaries-using-decentralised-ledgers-515203676ce5">prior work</a>, showing how privacy-focused DLT’s like Midnight can make self-controlled data practical for consumers, while still supporting data exchange. By addressing privacy, scalability, ontologies, and verifiable credentials, we demonstrated a trustworthy, secure and data liquid system. DLT here is seen primarily as a data system, the other aspects are obviously money, finance and voting, together which realise the original blockchain dream.</p><h3>8. Future Work</h3><p>While this demo showcases powerful privacy and security enhancements, several missing pieces remain for even broader real-world adoption. These include, but are not limited to:</p><ul><li><strong>Web2-Style Account Flows</strong>: Eliminating crypto jargon with intuitive, web-like logins powered by zero-knowledge tech, making onboarding as simple as signing into a traditional app</li><li><strong>Legacy System Integration</strong>: Integration with systems such as CRM and ERP to connect private and liquid data to existing business functions</li><li><strong>Advanced Storage Modes</strong>: Options such as storage on private cloud for backup and recovery, and time-based sharing with proof of erasure</li><li><strong>Advanced Credential Systems</strong>: Exploring systems such as the Key Event Recipient Infrastructure (KERI) protocol</li><li><strong>Scalability Research</strong>: Investigation of throughput limits and scaling options for the DLT</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b972c6855e48" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/private-data-management-using-decentralised-ledgers-b972c6855e48">Private Data Management using Decentralised Ledgers</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Flow across Trust Boundaries using Decentralised Ledgers]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://itnext.io/data-flow-across-trust-boundaries-using-decentralised-ledgers-515203676ce5?source=rss-f40b51ecaf27------2"><img src="https://cdn-images-1.medium.com/max/1024/1*CVvmoNBy2TwwELTdSfJrkA.jpeg" width="1024"></a></p><p class="medium-feed-snippet">A Consignment Tracking Case Study</p><p class="medium-feed-link"><a href="https://itnext.io/data-flow-across-trust-boundaries-using-decentralised-ledgers-515203676ce5?source=rss-f40b51ecaf27------2">Continue reading on ITNEXT »</a></p></div>]]></description>
            <link>https://itnext.io/data-flow-across-trust-boundaries-using-decentralised-ledgers-515203676ce5?source=rss-f40b51ecaf27------2</link>
            <guid isPermaLink="false">https://medium.com/p/515203676ce5</guid>
            <category><![CDATA[data-liquidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[cardano]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[trust]]></category>
            <dc:creator><![CDATA[Tim Edge]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 09:30:35 GMT</pubDate>
            <atom:updated>2026-01-20T09:03:37.067Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Data Liquidity: The Key to Taming IT Complexity]]></title>
            <link>https://tdedgx.medium.com/towards-data-liquidity-3e35420885b4?source=rss-f40b51ecaf27------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e35420885b4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[complexity]]></category>
            <category><![CDATA[modernisation]]></category>
            <category><![CDATA[information-technology]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Tim Edge]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 09:17:41 GMT</pubDate>
            <atom:updated>2026-04-15T01:23:42.593Z</atom:updated>
            <content:encoded><![CDATA[<h4>Towards Data Liquidity as a Unified Goal for Information Technology (IT) Modernisation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDuLUZ2TKphOXmuim1PNlQ.jpeg" /></figure><blockquote><em>“We are facing a future of unbounded complexity, whether we harness it to prosper or careen off a cliff into mind-numbing junk is an open question” (Lucas et al., 2012)</em></blockquote><h3>1. Introduction</h3><p>Organisations face a grand challenge in managing complex IT systems, where diverse elements, protocols, and security constraints hinder modernisation, leading to unpredictable outcomes and wasted resources. Data Liquidity, defined as the seamless flow of data to its needed application context, is proposed as a unified metric to manage this <em>non-linear</em> complexity, guiding holistic IT modernisation.</p><p>The aim of this essay is to motivate development of a new evaluation method and focus for modernisation based on Data Liquidity which encompasses whole-system performance.</p><h3>2. Background and Problem</h3><p>A previous post <a href="https://medium.com/@tdedgx/the-complexity-of-evolving-complex-it-4f5d96769673">The Complexity of Evolving Complex IT</a>, discussed how the complexity of IT systems — driven by organic growth, infrastructure focus, and other barriers — means it is exceedingly difficult to modernise systems in a constructive way that benefits the whole system. IT modernisation exhibits <em>non-linear</em> complexity, where small changes yield unpredictable system-wide effects that hinder progress, leading to suboptimal performance and wasted resources.</p><h3>3. What is being done about it currently</h3><h4>Modernisation Goals are Clear Enough</h4><p>IT modernisation goals may differ per organisation, however here we’ll consider a general set of high level goals as accessibility, security, and sustainability (Vial, 2019; Al-Ruithe et al, 2018), which provides a clear enough framework for <em>what</em> to achieve.</p><ul><li><strong>Accessibility</strong>. Ensuring systems, tools, and data are available, user-friendly, interoperable and responsive with low latency. The ideal state being seamless access to tools which enhance productivity.</li><li><strong>Security</strong>. Providing robust confidentiality, integrity, and availability to protect users and data against evolving threats, including AI-driven attacks and insider threats. This ensures trust and resilience in dynamic IT environments.</li><li><strong>Sustainability</strong>. Designing systems that are scalable, maintainable, and adaptable, supporting continuous upgrades, energy efficiency, and rapid adoption of innovations to meet future needs.</li></ul><h4>There are Trade-Offs</h4><p>There are often trade-offs for any modernisation decisions though, for example:</p><ul><li>High-performance AI systems (accessibility, sustainability) often sacrifice security via centralised computing.</li><li>Over simplifying tools e.g. AI assisted data pipelines (accessibility) simplifies data processing but reduces understanding and maintainability of data architectures, limiting adaptability and increasing long-term costs (sustainability).</li><li>Zero-trust security models (security) restrict data access to prevent breaches, exacerbating data silos (accessibility) and increasing integration costs for scalable systems (sustainability).</li><li>Edge Computing subsystems using dedicated bandwidth (accessibility) limit adaptability for emergency communications (sustainability).</li></ul><p>Because of the trade-offs involved, an <em>approach to modernisation</em> is needed, containing a vision and design principles along with suitable evaluation methods. Next we’ll discuss one such approach, around the idea of transitioning to information-centric systems.</p><h4>Promising Approaches</h4><p>A promising approach is information-centric systems (Kraus et al, 2021) aiming to move to systems where information becomes the ‘managed unit’ for integration prioritising data-driven decision-making, connectivity, modularity and interoperability. This approach can inherently reduce complexity e.g. by standardising data formats and enabling modular architectures while addressing the whole of system requirement for integrated information.</p><p>There are a substantial amount of related emerging technologies, see: <a href="https://edgx.tech/articles/it-sota-report-2025">State-Of-The-Art Report 2025</a>. Perhaps most notably are Information Centric Networking (ICN), Software Defined Networking (SDN), Data Related innovations such as Data Fabric, Data Mesh &amp; Unified Data Architectures, Software Defined Computing (SDC), and Distributed Ledger Technologies (DLT). However, these and other approaches that may show promise are in their relative infancy (Qiao et al., 2019), meaning so are methods to evaluate them. In particular, a unified metric to evaluate their impact on whole-system performance is lacking.</p><h3>4. Still Missing a Critical Method of Evaluation</h3><p>Current IT evaluation methods, such as low-level metrics (Aslanpour et al., 2020; Duan, 2017; Orogat &amp; El-Roby, 2021; Talburt et al., 2019) or analytical modelling (Azodolmolky et al., 2013; Duan, 2017), focus on narrow workloads (Pedreira et al., 2023), small-scale systems or can only produce upper bounds of performance. They fail to address the dynamic data flows of emerging technologies like ICN and Data Mesh.</p><p>Without taking a step back and asking <em>‘how do we make constructive progress for the whole-system’</em> and <em>‘what trade-offs are reasonable’</em>, modernisation is likely to be attempted in a very exploratory <em>‘see what sticks’</em> approach at the risk of exacerbating complexity or sidelining good technologies due to ossification (Akhshabi &amp; Dovrolis, 2013). The challenge, however, lies in evaluating dynamic, context-driven data flows across distributed systems. A unified metric like Data Liquidity could encapsulate how technologies like ICN or Data Mesh contribute to this purpose.</p><h3>5. A New Focus on Data Liquidity</h3><p>I’m thinking about data — encoding of a signal representing some content or meaning — as like the <em>oil</em> which enables applications to operate. For those applications to operate most effectively, at least in terms of their accessibility to live data, is when data can be where it needs to be, when it needs to be there.</p><h4>Definition and Contrast</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*2iWsT85b5YuE_lGZlRUJVg.jpeg" /><figcaption>Figure 1: Data Liquidity prioritises dynamic, context-driven data flow</figcaption></figure><p>Data Liquidity, defined as <em>the ability of data to flow to the application context it is needed</em>, differs from related concepts like interoperability (technical compatibility), accessibility (user access), and velocity (data speed), as it prioritises seamless, context-driven flow of meaningful data. Unlike prior mostly qualitative definitions (Bosworth, 2009; Courtney, 2011; De Saulles, 2020; Penfield et al., 2009; Wixom &amp; Piccoli, 2021; Piccoli et al., 2022), such as “the ease of data asset reuse and recombination” (Wixom &amp; Piccoli, 2021), this focuses on meaningful content delivery to applications and users and representing data as the base unit of encoding content.</p><h4>Proposition</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8P2Zoy4YsFMGJUdWyK64ag.png" /><figcaption>Figure 2: System Performance Versus Optimisation Effort. When Data Liquidity is optimised independently, it could act as a rising performance floor, and together with Flow Engineering, enable more predictable improvements and shorter feedback loops for applications. Without these mechanics, application performance could plateau at lower levels and exhibit more erratic behaviour due to system interdependencies.</figcaption></figure><p>My claim is that if IT modernisation efforts optimise for Data Liquidity as defined, and use Flow Engineering (information-centric) instead of Network Engineering (infrastructure-centric), it is the best we can do to have an optimised <em>technical</em> core system, since the applications are, or can dynamically be, <em>‘oiled’</em> with the right data, which is data needed and authorised for a given use-case. That optimisation <em>encapsulates</em> the need for high value, authorised content to flow throughout distributed applications including routing, authentication, encryption and transport efficiency.</p><h3>6. Potential Impacts of Data Liquidity</h3><p>Optimising IT systems for Data Liquidity could fundamentally transform the approach to modernisation by providing a way to navigate complexity and enable more efficient, predictable, and scalable systems.</p><h4>Simplified Decision-Making</h4><p>Data Liquidity serves as a unifying metric to evaluate and prioritise technologies and approaches across system layers. By encapsulating the efficiency of data flow to its needed application context, it provides a clear, holistic measure to guide modernisation efforts. This provides a way to handle the <em>non-linearity</em> inherent in IT modernisation, where small changes often lead to unpredictable system-wide effects. With Data Liquidity as a focal point, decision-making becomes more streamlined, enabling IT leaders to assess trade-offs and select technologies like Information-Centric Networking (ICN) or Data Mesh that <em>may</em> align with whole-system performance goals.</p><h4>Enhanced DevOps Efficiency</h4><p>Focusing on Data Liquidity decouples the complexity of the core architecture from application-level innovation, creating a more <em>linear</em> challenge for operating and innovating applications and tools. While complex systems remain necessary for complex problems, this strategic separation shifts complexity to a domain with shorter user-correction loops. These loops involve users identifying needs, developers implementing data-driven systems and IT practitioners aligning data flows with leadership priorities. This process fosters iterative corrections (Kurtz et al., 2003) in both the core architecture (optimised for Data Liquidity) <em>and</em> user-facing applications. These corrections are easier to identify, occur in shorter cycles, and yield more predictable outcomes, reducing wasted resources and improving system responsiveness.</p><h4>Strategic Advantages in Time-Sensitive Domains</h4><p>Mastering Data Liquidity in distributed systems could provide competitive edges in time-sensitive domains such as logistics, healthcare, and defence. I think that’s why the race is on (Maslej et al., 2025) but no-one has really said it this way… It’s not a story about who can make the best AI but who can make the best live-data integrated human-machine teams over bandwidth constrained networks. For example, in logistics, real-time shipment tracking can be enhanced through decentralised ledgers with interoperable meta protocols. In healthcare, seamless data flows can improve patient monitoring and response times. In defence, dynamic data prioritisation ensures mission-critical information reaches the right context in a timely manner. This capability positions organisations to respond faster and more effectively in dynamic, high-stakes environments.</p><h4>Example Scenarios</h4><p>The following scenarios further illustrate the potential benefit of Data Liquidity.</p><ul><li><strong>Dynamic Data Prioritisation in Emergency Response</strong>. In a remote search-and-rescue operation, a team needs a mapping data update hosted at a strategic data center via software-defined radio. A Data Liquid system dynamically prioritises CAP theorem consistency (Brewer, 2000), using SDN to reconfigure a commercial network for secure, optimised transport. Post-emergency, it shifts to real-time alert monitoring over consistency, ensuring seamless data flow without manual intervention.</li><li><strong>Seamless Resource Sharing in Autonomous Vehicles</strong>. A self-driving car in a busy urban area requires a collision-avoidance prediction. In a Data Liquid system, Information-Centric Networking (ICN) and Software-Defined Computing (SDC) enable the car to access shared computing resources from a nearby edge node. Only essential data (e.g., sensor inputs, prediction outputs) is exchanged, secured by decentralised authorisation, ensuring efficient and secure data flow.</li><li><strong>Streamlined DevOps and Integration Workflows</strong>. A DevOps team integrates an AI-driven customer analytics tool in a large enterprise. Using a Data Mesh architecture with Data Fusion (Castanedo, 2013; Foo &amp; Ng, 2013), the tool accesses standardised, interoperable and meaningful data products. Data Liquidity ensures dynamic data flows to the tool’s context, supported by Software-Defined Computing for on-demand processing using high-performance computing. This reduces integration time from weeks to days, lowers costs, and enhances analytics with timely, semantically correct data.</li></ul><h4>Implementation Challenges</h4><p>Adopting Data Liquidity wouldn’t be without challenges though. Developing robust, quantifiable metrics for Data Liquidity will require nuanced research to measure dynamic, context-driven data flows. Additionally, implementation will likely demand change management for processes and cultures, upskilling for understanding how to leverage related technologies and collaborative governance to align data flows with organisational priorities. These are substantial challenges, however they are surmountable with targeted research and organisational commitment, paving the way for scalable and resilient IT systems.</p><h3>7. Summing Up</h3><p>IT complexity is a barrier to modernisation, preventing constructive progress and resulting in wasted resources. While there are clear goals for modernisation, some promising approaches and a substantial amount of related emerging technologies which could address the limitations, there is no effective way to assess whole-system performance of modern IT systems. Data Liquidity offers a path forward, enabling navigation towards scalable and efficient systems.</p><p>My claim is that by observing and optimising for Data Liquidity — enabling seamless, context-driven data flows — complexity could be managed and constructive progress could be made, akin to removing the <em>non-linearity</em> of modernisation. This is since a highly Data Liquid system is as good as the core architecture can be, so that along with Flow Engineering, the utility of applications can be optimised in a more <em>linear</em> and efficient way at a high layer of abstraction closer to users and their needs.</p><p>By prioritising Data Liquidity in a modernisation strategy, organisations could break the cycle of complexity, benefiting from high-utility systems into the future. Without such a metric to navigate from, organisations risk perpetuating costly, inefficient modernisation efforts.</p><h3>8. So how do we Measure and Observe Data Liquidity?</h3><p>Quantifying Data Liquidity likely requires novel metrics to measure dynamic, context-driven flows. Future research should explore metrics to guide IT modernisation, with pilot studies testing flow-based architectures in real-world scenarios along with organisational change requirements. I’m currently looking for collaborators for a formal research proposal to quantify Data Liquidity.</p><p>In the mean-time watch this space as I explore more concepts around this paradigm, I’m looking to build demonstrations and discuss findings such as;</p><ul><li>Integrating AI agents with live-data for e.g. <a href="https://tdedgx.medium.com/a-foray-into-price-prediction-with-ai-agents-67baa513cfee">making price predictions</a>, seeking trust without limiting potential of the agents</li><li>Using <a href="https://medium.com/@tdedgx/data-flow-across-trust-boundaries-using-decentralised-ledgers-515203676ce5">distributed ledgers for e.g. global consignment tracking</a>, seeking interoperability advantages in non-trusting relationships</li></ul><h3>References</h3><pre>Akhshabi, S., &amp; Dovrolis, C. (2013). The Evolution of Layered Protocol Stacks <br>    Leads to an Hourglass-Shaped Architecture (pp. 55–88). <br>    https://doi.org/10.1007/978-1-4614-6729-8_4<br>Al-Ruithe, M., Benkhelifa, E., &amp; Hameed, K. (2018). Key Issues for Embracing <br>    the Cloud Computing to Adopt a Digital Transformation: A study of Saudi <br>    Public Sector. Procedia Computer Science, 130, 1037–1043. <br>    https://doi.org/10.1016/j.procs.2018.04.145<br>Aslanpour, M. S., Gill, S. S., &amp; Toosi, A. N. (2020). Performance evaluation <br>    metrics for cloud, fog and edge computing: A review, taxonomy, benchmarks <br>    and standards for future research. Internet of Things, 12, 100273. <br>    https://doi.org/10.1016/J.IOT.2020.100273<br>Azodolmolky, S., Nejabati, R., Pazouki, M., Wieder, P., Yahyapour, R., &amp; Simeonidou, D. (2013). <br>    An analytical model for software defined networking: A network calculus-based <br>    approach. Proceedings - IEEE Global Communications Conference, GLOBECOM, <br>    1397–1402. https://doi.org/10.1109/GLOCOM.2013.6831269<br>Bosworth, A. (2009). Data Liquidity or how we can use ARRA’s $19 Billion wisely.<br>    Adam Bosworth’s Weblog.<br>Brewer, E. A. (2000). Towards robust distributed systems (abstract). <br>    Proceedings of the Nineteenth Annual ACM Symposium on Principles of <br>    Distributed Computing, 7. https://doi.org/10.1145/343477.343502<br>Castanedo, F. (2013). A Review of Data Fusion Techniques. The Scientific World<br>    Journal, 2013(1). https://doi.org/10.1155/2013/704504<br>Courtney, P. K. (2011). Data Liquidity in Health Information Systems. The <br>    Cancer Journal, 17(4), 219–221. <br>    https://doi.org/10.1097/PPO.0b013e3182270c83<br>De Saulles, M. (2020). Data Liquidity: Data Exchange Platforms as Drivers of <br>    Innovation. https://doi.org/10.13140/RG.2.2.20887.93603<br>Duan, Q. (2017). Cloud service performance evaluation: status, challenges, and<br>    opportunities – a survey from the system modeling perspective. Digital <br>    Communications and Networks, 3(2), 101–111. https://doi.org/10.1016/J.DCAN.2016.12.002<br>Foo, P. H., &amp; Ng, G. W. (2013). High-level Information Fusion: An Overview. <br>    J. Adv. Inf. Fusion, 8, 33–72. <br>    https://api.semanticscholar.org/CorpusID:3195541<br>Kraus, S., Jones, P., Kailer, N., Weinmann, A., Chaparro-Banegas, N., &amp; Roig-Tierno, N. (2021). <br>    Digital Transformation: An Overview of the Current State of the Art of <br>    Research. Sage Open, 11(3). https://doi.org/10.1177/21582440211047576<br>Kurtz, C. F., &amp; Snowden, D. J. (2003). The new dynamics of strategy: <br>    Sense-making in a complex and complicated world. IBM Systems Journal, 42(3),<br>    462–483. https://doi.org/10.1147/sj.423.0462<br>Lucas, P., Ballay, J., &amp; McManus, M. (2012). Trillions: Thriving in the <br>    Emerging Information Ecology (1st ed.). Wiley.<br>Maslej, N., Fattorini, L., Perrault, R., Gil, Y., Parli, V., Kariuki, <br>    N., Capstick, E., Reuel, A., Brynjolfsson, E., Etchemendy, J., Ligett, <br>    K., Lyons, T., Manyika, J., Niebles, J. C., Shoham, Y., Wald, R., Walsh, <br>    T., Hamrah, A., Santarlasci, L., … Oak, S. (2025). Artificial Intelligence<br>    Index Report 2025.<br>Orogat, A., &amp; El-Roby, A. (2021). Cbench: Demonstrating comprehensive <br>    evaluation of question answering systems over knowledge graphs through <br>    deep analysis of benchmarks. Proceedings of the VLDB Endowment, 14(12), <br>    2711–2714. https://doi.org/10.14778/3476311.3476326<br>Pedreira, P., Erling, O., Karanasos, K., Schneider, S., McKinney, W., Valluri, S. R., Zait, M., &amp; Nadeau, J. (2023). <br>    The Composable Data Management System Manifesto. Proceedings of the VLDB <br>    Endowment, 16(10), 2679–2685. https://doi.org/10.14778/3603581.3603604<br>Penfield, S., Martin Anderson, K., Edmunds, M., &amp; Belanger, M. (2009). Toward <br>    Health Information Liquidity: Realization of Better, More Efficient Care <br>    From the Free Flow of Health Information.<br>Piccoli, G., Rodriguez, J. A., Someh, I. A., &amp; Wixom, B. (2022). Data Liquidity: <br>    Conceptualization, Measurement and Determinants. International Conference <br>    on Interaction Sciences. https://api.semanticscholar.org/CorpusID:256848424<br>Qiao, X., Wang, H., Tan, W., Vasilakos, A. V., Chen, J., &amp; Blake, M. B. (2019). <br>    A survey of applications research on content-centric networking. China <br>    Communications, 16(9), 122–140. https://doi.org/10.23919/JCC.2019.09.009<br>Talburt, J. R., Pullen, D., &amp; Penning, M. (2019). Evaluating and Improving Data<br>    Fusion Accuracy (pp. 295–326). https://doi.org/10.1007/978-3-030-03643-0_14<br>Vial, G. (2019). Understanding digital transformation: A review and a research <br>    agenda. The Journal of Strategic Information Systems, 28(2), 118–144. <br>    https://doi.org/10.1016/j.jsis.2019.01.003<br>Wixom, B. H., &amp; Piccoli, G. (2021). Build Data Liquidity To Accelerate Data <br>    Monetization. https://cisr.mit.edu/publication/2021_0501_DataLiquidity_WixomPiccoli</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e35420885b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complexity of Evolving Complex IT]]></title>
            <link>https://tdedgx.medium.com/the-complexity-of-evolving-complex-it-4f5d96769673?source=rss-f40b51ecaf27------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f5d96769673</guid>
            <category><![CDATA[modernisation]]></category>
            <category><![CDATA[complexity]]></category>
            <category><![CDATA[information-technology]]></category>
            <dc:creator><![CDATA[Tim Edge]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 09:15:33 GMT</pubDate>
            <atom:updated>2025-07-02T09:15:33.350Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Short Essay on the Critical Barriers to Evolving Big Gnarly Information Technology (IT) Systems</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKzoFnGkJNbzO2hM1LDlUg.jpeg" /></figure><h3>1. Introduction</h3><p>Organisations are faced with a grand challenge to manage and optimise use of their Information Technology (IT) systems. They must optimise decision-making and operations across distributed IT environments. This is challenging due to the complexity of diverse elements, protocols, data formats, connectivity, security constraints, and the continual integration of new capabilities, such as live-data-enabled AI agents.</p><p>Modernisation of these systems is a problem of complexity where we can get stuck in a loop trying to make improvements but experience unexpected outcomes. Progress and utility can plateau, we can’t constructively evolve the utility of the whole system for everyday purposes or we have to make trade-offs or simplifications for short term benefits. I can see this repeating primarily because of how modernisation of sub-systems are not concerned enough about modernising the whole system.</p><p>The aim of this short essay is to raise awareness of the barriers to IT modernisation due to complexity and in a follow-on article, motivate development of a new evaluation method and focus for modernisation which considers whole-of-system performance.</p><h3>2. What is IT Complexity</h3><p>Complexity is used here in a duel way. Firstly, IT systems are inherently complex since they typically involve a numerosity of elements, connections, configuration options, topologies, techniques and interdependencies (Duan, 2017). These characteristics make it challenging to understand large-scale systems behaviour (Lloyd, 2001; Siegenfeld &amp; Bar-Yam, 2020).</p><p>Secondly, The modernisation of IT systems is a problem of complexity, meaning it is difficult to know which problems to solve and with what solutions, since outcomes are often unexpected, unpredictable and costly. This complexity is <em>non-linear</em>, meaning small changes in one subsystem can lead to disproportionate system-wide effects, complicating modernisation efforts. On the positive side, we know order can emerge from iteratively reinforcing constructive patterns (Kurtz et al., 2003), therefore whole of system, in addition to low level, evaluations become necessary.</p><p>These characteristics give rise to specific causes of complexity, which entrench barriers to modernisation, as explored below.</p><h3>3. Causes of IT Complexity</h3><p>The complexity of IT systems arises from interconnected causes.</p><h4>Historical Infrastructure-centric focus</h4><p>Historically, IT systems have prioritised infrastructure, tightly coupling applications to networking and data layers. Modifying applications demands rigorous assessment of resource usage (processor, storage, memory, bandwidth) and interactions with interconnected services or databases. Changes at one layer can unpredictably disrupt other services, introducing vulnerabilities, network congestion, or excessive resource consumption (Xia et al., 2015; Aslan et al., 2023). This vertical integration creates rigid architectures, complicating updates and increasing maintenance challenges.</p><h4>Organic Growth</h4><p>Organic growth, often driven by a ‘see what sticks’ approach and a systems thinking tendency to delegate design decisions to subsystems, results in bespoke selections for core components like data and network layers. While interoperable and open protocols can alleviate some issues, optimising subsystems frequently increases overall system complexity. This ad-hoc evolution leads to fragmented architectures, where components are tailored to specific needs but lack cohesion, complicating integration and scalability (Tan et al., 2024). For instance, custom data layers may enhance local performance but create interoperability challenges, amplifying maintenance overhead and risking system-wide inefficiencies.</p><h4>Difficulty Simplifying</h4><p>Over the years complex solutions for complex problems have been adopted, where specific trade-offs are needed for different benefits. A good example is the proliferation in database systems (Stonebraker &amp; Cetintemel, 2005), each suiting specific use-cases. Efforts to simplify IT systems often introduce trade-offs, such as increased complexity when limitations surface, requiring band-aid fixes. It can also result in obscuration of underlying architectures, complicating debugging and maintenance. If third-party services are adopted, to transfer the complexity, that comes with a cost and is usually with a centralised provider presenting security risks or vendor lock-in of an architecture.</p><h4>Monopolisation of Bandwidth</h4><p>Communication bearers, such as global telecommunications and internet networks, are often assumed to be stable and reliable, yet they face physical constraints like bandwidth and latency, which limit throughput, particularly in edge computing, IoT, and deployable secure radio networks (Raeisi-Varzaneh et al., 2023). Systems optimised for specific applications or purposes often monopolise available bandwidth, performing their functions well but using too much freedom of action wasting bandwidth. For example, redundant transmissions such as sending entire files instead of references, transferring documents with low-value content (e.g., blank spaces in PDFs), or resending full datasets despite minimal changes.</p><h4>Security Requirements</h4><p>Security mechanisms significantly contribute to IT system complexity. Modern IT environments rely on intricate security architectures — firewalls, centralised authentication systems, and encryption protocols — that are tightly coupled to infrastructure and applications. Security constraints can introduce dependencies and lock data into specific formats or repositories that complicate maintenance and upgrades (Cherdantseva &amp; Hilton, 2013). Organisations are often forced to make trade-offs, prioritising immediate security compliance over long-term system flexibility.</p><h4>Human Element</h4><p>The complexity of IT modernisation is not solely a technical challenge; it is intertwined with human and organisational factors. Siloed organisational structures foster disjointed technology stacks, as departments prioritise their own tools without regard for system-wide interoperability (Pedreira, 2023). Limited cross-functional collaboration between IT, business, and operations teams leads to subsystem-focused decisions that increase overall complexity. Resistance to change, upskilling demands, and fear of disrupting critical operations further hinder modernisation, perpetuating inefficient systems and complicating holistic progress (Ardıç, 2021; Ertmer et al., 2012).</p><h4>Trade-Offs in Modernisation</h4><p>Modernising IT systems often involves trade-offs that inadvertently increase complexity, as organisations prioritise short-term improvements over long-term system coherence. Budget constraints may lead to adopting low-cost, proprietary solutions that meet immediate needs but lack interoperability, creating integration challenges as systems scale (Triantafyllou et al., 2018). For example, a company might deploy a cheap database solution that cannot handle future data volumes, necessitating costly workarounds or replacements. Rapid deployment of new applications often bypasses thorough testing, leading to unforeseen interactions affecting stability. Subsystem optimisation, such as boosting a single application’s performance, can degrade whole-system performance by overtaxing shared resources like bandwidth or storage.</p><h3>4. Consequences of IT Complexity</h3><p>The resulting complexity has various first-order consequences, such as fragmented architectures and siloed data, which are discussed here.</p><h4>Fragmented technology stacks</h4><p>Modern IT systems blend standard and bespoke data formats, protocols, and services to support diverse applications. Legacy protocols, software, and middleware, retained out of necessity, underpin critical functions but hinder system reliability and scalability. Integrating new systems into these fragmented architectures escalates complexity, complicating maintenance and diagnostics across diverse networks and applications (Triantafyllou et al., 2018; Pedreira, 2023; Tan et al., 2024). For example, incompatible legacy APIs often require custom adapters, increasing costs and delaying upgrades.</p><h4>DevOps velocity</h4><p>Development teams are often burdened with managing servers, networks, firewalls, routing, and security accreditation, diverting effort from user-facing functionality. Delays in accreditation or infrastructure changes create bottlenecks, escalating costs and stifling innovation, especially in large organisations with complex networks (Aouni et al., 2025). Development velocity often outpaces integration, particularly in large organisations with complex networks, where heightened risks amplify coordination challenges. For example, prolonged firewall approvals can delay application releases, hindering agility and increasing time-to-market in dynamic IT environments.</p><h4>Data Silos</h4><p>Bespoke formats, databases, and protocols in modern IT systems can lead to data silos, obstructing interoperability and application utility. Accessing siloed data demands custom services, interfaces, and network paths. Such development requires substantial justification, sharing of intellectual property, network engineering and developer effort to achieve (Adams &amp; Nelson, 2022; Dart et al., 2013; Habibi et al., 2023; vom Brocke et al., 2018). Further, applications are coupled to the deployed system networking configuration, security accreditation and data layers which perpetuates those silos. Skills gaps and resistance hinder solutions like Data Mesh or Data Fabric. This fragments data flow, complicates integration, and entrenches reliance on inefficient, legacy systems.</p><h4>Data Quality</h4><p>Poor data quality, such as incomplete, inconsistent, or outdated data, exacerbates IT complexity by undermining application reliability and decision-making. Complexity from fragmented technology stacks and data silos often leads to data inconsistencies, as disparate systems use incompatible formats or lack synchronisation (Habibi et al., 2023). For example, an enterprise relying on multiple legacy databases may struggle to reconcile conflicting customer records, requiring costly manual interventions or custom integrations. This reduces system efficiency, increases costs, and hinders modernisation by perpetuating reliance on error-prone, siloed data.</p><h4>Inefficient use of Communications Bearers</h4><p>In modern IT systems, the value of exchanged data is often a small fraction of the total data size due to inefficient tools, legacy technologies, application-specific data flows and user procedures. Legacy systems are also incompatible with advanced architectures that prioritise flexible data exchange such as Software Defined Networking (Xia et al., 2015), which prevents even attempting system-wide trade-offs. This limitation is pronounced in distributed systems like IoT or edge computing, where low-bandwidth environments are common. Such inefficiencies hinder scalability, increase costs, increase latency for end-users, and complicate integration efforts.</p><h4>Weakened Security</h4><p>Complexity weakens security by creating vulnerabilities and hindering timely updates. Legacy security models, like perimeter-based defenses, persist for compatibility reasons but are ill-suited for distributed systems like edge computing or IoT (Baniya et al., 2024). Interdependencies make patching vulnerabilities or adopting advanced security (e.g., decentralized authentication) resource-intensive, requiring specialised expertise. This leaves systems exposed to evolving threats, as organisations prioritise maintaining legacy compatibility over implementing robust, modern security measures.</p><h3>5. The Difficulty of IT Modernisation</h3><p>These interconnected causes &amp; consequences make modernisation inherently difficult and are even more pronounced in large-scale systems, with more interdependencies and legacy constraints. As an analogy you could say IT modernisation is <em>non-linear</em> since small changes yield unpredictable outcomes, we may only be able to understand and modernise local pockets of functionality at a time. We could imagine how upgrading a complex IT system leads to systemic impacts.</p><blockquote>As a vignette, consider a major e-commerce retailer who aims to consolidate legacy systems into a cloud-based platform for inventory management and real-time analytics. Complexity from disparate systems, incompatible data formats, and siloed workflows causes a data migration error, triggering a week-long outage. This costs millions in revenue, frustrates customers, strains IT teams, and erodes executive trust, forcing a scaled-back project that retains legacy systems.</blockquote><p>This case illustrates how the complexity of interconnected systems, underestimated integration challenges, and lack of holistic planning can derail modernisation efforts.</p><p>As a result of this difficulty and often the inability to make constructive upgrades, progress and utility for the whole-system can plateau. This is the essence of IT modernisation complexity which is a persistent barrier and cause of waste for many organisations.</p><h3>6. Summing Up</h3><p>IT systems are inherently complex, making modernisation efforts exceedingly difficult. Modernisation efforts often yield suboptimal outcomes, resulting in waste and stalled progress. This is self-reinforcing making it difficult to break out of.</p><p>In a <a href="https://medium.com/@tdedgx/towards-data-liquidity-3e35420885b4">follow-up article</a>, I will present a potential solution to this challenge which may provide a way to navigate the complexity, it is about a new evaluation method and focus that would be akin to removing the <em>non-linearity</em> from this modernisation puzzle, enabling constructive progress.</p><h3>References</h3><pre>Adams, Z., &amp; Nelson, A. (2022). Breaking Down Silos: Integrating Big Data <br>    Across Organizational Functions. International Journal of Network and <br>    Communication Research, Vol.7(No. 1), 81–89.<br>Alper Ardıç, M. (2021). Three Internal Barriers to Technology Integration <br>    in Education: Opinion, Attitude and Self-Confidence. Shanlax International<br>    Journal of Education, 9(S1-May), 81–96.<br>Aouni, F. El, Moumane, K., Idri, A., Najib, M., &amp; Jan, S. U. (2025). A <br>    systematic literature review on Agile, Cloud, and DevOps integration: <br>    Challenges, benefits. Information and Software Technology, 177, 107569. <br>    https://doi.org/10.1016/j.infsof.2024.107569<br>Aslan, Ö., Aktuğ, S. S., Ozkan-Okay, M., Yilmaz, A. A., &amp; Akin, E. (2023). <br>    A Comprehensive Review of Cyber Security Vulnerabilities, Threats, Attacks,<br>    and Solutions. Electronics, 12(6), 1333. https://doi.org/10.3390/electronics12061333<br>Baniya, P., Agrawal, A., Abid, K., Nath, J., Chaudhary, B. K., &amp; Kunwar, B. (2024). <br>    The Internet of Things: Security Challenges and Opportunities. 2024 3rd <br>    International Conference on Power Electronics and IoT Applications in <br>    Renewable Energy and Its Control (PARC), 153–158.<br>Cherdantseva, Y., &amp; Hilton, J. (2013). A Reference Model of Information <br>    Assurance and Security. 2013 International Conference on Availability, <br>    Reliability and Security, 546–555. https://doi.org/10.1109/ARES.2013.72<br>Dart, E., Rotman, L., Tierney, B., Hester, M., &amp; Zurawski, J. (2013). The <br>    science DMZ: A network design pattern for data-intensive science. <br>    International Conference for High Performance Computing, Networking, <br>    Storage and Analysis, SC. https://doi.org/10.1145/2503210.2503245<br>Duan, Q. (2017). Cloud service performance evaluation: status, challenges, <br>    and opportunities – a survey from the system modeling perspective. Digital<br>     Communications and Networks, 3(2), 101–111.<br>Ertmer, P. A., Ottenbreit-Leftwich, A. T., Sadik, O., Sendurur, E., &amp; Sendurur, P. (2012). <br>    Teacher beliefs and technology integration practices: A critical <br>    relationship. Computers &amp; Education, 59(2), 423–435.<br>Foo, P. H., &amp; Ng, G. W. (2013). High-level Information Fusion: An Overview. <br>    J. Adv. Inf. Fusion, 8, 33–72.<br>Habibi, P., Moghaddassian, M., Shafaghi, S., &amp; Leon-Garcia, A. (2023). Data <br>    Fabrics for Multi-Domain Information Systems. 2023 19th International <br>    Conference on Network and Service Management (CNSM), 1–5. <br>    https://doi.org/10.23919/CNSM59352.2023.10327791<br>Kurtz, C. F., &amp; Snowden, D. J. (2003). The new dynamics of strategy: Sense-making <br>    in a complex and complicated world. IBM Systems Journal, 42(3), 462–483.<br>Lloyd, S. (2001). Measures of complexity: a nonexhaustive list. IEEE Control <br>    Systems, 21(4), 7–8.<br>Raeisi-Varzaneh, M., Dakkak, O., Habbal, A., &amp; Kim, B.-S. (2023). Resource <br>    Scheduling in Edge Computing: Architecture, Taxonomy, Open Issues and <br>    Future Research Directions. IEEE Access, 11, 25329–25350.<br>Siegenfeld, A. F., &amp; Bar-Yam, Y. (2020). An Introduction to Complex Systems <br>    Science and Its Applications. Complexity, 2020, 1–16.<br>Stonebraker, M., &amp; Cetintemel, U. (2005). “One size fits all”: an idea whose <br>    time has come and gone. 21st International Conference on Data Engineering <br>    (ICDE’05), 2–11. https://doi.org/10.1109/ICDE.2005.1<br>Tan, B., Xiao, X., Chau, M., Tan, F. T. C., &amp; Leong, C. (2025). The dynamics, <br>    organisation and evolution of digital platforms and ecosystems. Information <br>    Systems Journal, 35(2), 417–421. https://doi.org/10.1111/isj.12548<br>Triantafyllou, A., Sarigiannidis, P., &amp; Lagkas, T. D. (2018). Network Protocols, <br>    Schemes, and Mechanisms for Internet of Things (IoT): Features, Open <br>    Challenges, and Trends. Wireless Communications and Mobile Computing.<br>vom Brocke, J., Maaß, W., Buxmann, P., Maedche, A., Leimeister, J. M., &amp; Pecht, G. (2018). <br>    Future Work and Enterprise Systems. Business &amp; Information Systems Engineering, 60(4), 357–366.<br>Xia, W., Wen, Y., Foh, C. H., Niyato, D., &amp; Xie, H. (2015). A Survey on <br>    Software-Defined Networking. IEEE Communications Surveys &amp; Tutorials, <br>    17(1), 27–51. https://doi.org/10.1109/COMST.2014.2330903</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f5d96769673" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Foray into Price Prediction with AI Agents]]></title>
            <link>https://ai.plainenglish.io/a-foray-into-price-prediction-with-ai-agents-67baa513cfee?source=rss-f40b51ecaf27------2</link>
            <guid isPermaLink="false">https://medium.com/p/67baa513cfee</guid>
            <category><![CDATA[price-prediction]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[decision-support-systems]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tim Edge]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 09:20:11 GMT</pubDate>
            <atom:updated>2025-06-13T03:29:16.714Z</atom:updated>
            <content:encoded><![CDATA[<h4>A tale of the race to capitalise on AI, integrating live data and achieving trust without limiting potential</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1kg1-AS82f-oF9CvPDGZQ.jpeg" /></figure><p>I was curious about what kinds of questions could be asked of an AI Large Language Model (LLM) agent and where the computation occurs. Using price predictions as an example of augmented decision making, can I ask it to output trading signals directly? What is the minimum context needed to be able to do a decent job? Can I ask it to output portable models on my behalf so I can deploy it in my own Machine Learning Operations (MLOps) framework? Or can I only ask it to generate code that I should run to generate those models?</p><p>I was trying to get as close to the point where I can have a conversation and add arbitrary sources, features and techniques to the predictions interactively and with minimal intervention, yet know the provenance and to understand, curate and oversee performance of the models. I wanted to maximise the potential but with positive control so I can trust the results. This story mostly targets enthusiasts of AI-augmented decision support or technical trading.</p><p>The Cardano blockchain is chosen for analysing price data. It is an open and permissionless system with a broad ecosystem of 24/7 trading activity. The tokens referenced here are Cardano Native Tokens (CNTs).</p><p>Here’s what I found…</p><h3>1. Straight to the Point Questions</h3><blockquote><strong><em>Are any of the top 10 Cardano native tokens flashing a BUY, SELL or HOLD trading signal right now?</em></strong></blockquote><p>Grok<strong>:</strong></p><blockquote>“Due to the complexity of the Cardano ecosystem and the lack of sufficient real-time data for June 2025, I cannot provide definitive buy, sell, or hold signals for the top 10 Cardano native tokens .. can’t find any reported signals .. can provide a general assessment based on trends and sentiment .. can infer some signals .. there’s no universally agreed-upon list of the top 10 Cardano tokens .. here’s a general assessment: INDY BUY, MIN HOLD, LQ BUY, SUNDAE HOLD, DANA HOLD”</blockquote><p>Claude (sometimes with a bit of coaxing to get it out):</p><blockquote>“specific trading signals for individual native tokens are limited in the results .. The technical indicators are predominantly showing SELL signals, with bearish MACD and declining trading volume. However, the recent partnerships and its status as Cardano’s leading meme coin could provide some fundamental support .. SNEK SELL, DJED HOLD”</blockquote><h4>Key Observations</h4><p>Firstly, DANA was a failed project, no longer being built and DJED is a stablecoin not really intended to be traded for profit other than arbitrage. Otherwise, seems ok, a blend of technical and fundamental analysis, that we could continue asking deeper questions about while forming our own opinion.</p><p>It is capable of evaluating already reported data that it can access, however isn’t using live data and making any computation from it. The signals are likely already out of date. Its strength is the fusion of hard (technical) and soft (fundamental) data in its assessment.</p><p>To overcome the limitation of outdated signals, in the next part I took it a step further by integrating live price data from an external source.</p><h3>2. Questions when Integrated with Live Price Data</h3><p>Let’s add an Model Context Protocol (MCP) Server enabling the agent to query price and volume data using an Application Programming Interface (API) with our own subscription and rate limits. MCP standardises the integration with external services meaning it can operate independent of the agent.</p><p>The purpose is to</p><ol><li>Allow agent to understand format of live data</li><li>Allow agent to include live data in its analysis</li></ol><h4>Install Price Data MCP Server</h4><p><strong>1. Clone this repository</strong></p><pre>git clone https://github.com/Edgxtech/realfi-info-mcp.git  <br>cd realfi-info-mcp</pre><p><strong>2. Build the jar file</strong></p><pre>./gradlew clean build</pre><p><strong>3. Get access to the price data</strong></p><p>The API uses ‘<em>Delegation as a Subscription</em>’ meaning you don’t pay for it but rather choose / delegate which Stakepool to join for earning staking rewards, benefiting the pool and yourself. Its also just an association with the pool, the funds never leave your wallet. To get an access token:</p><ul><li>Delegate a Cardano wallet to the <a href="https://ausstaker.com.au/">AUSST Stakepool</a></li><li>Go to <a href="https://realfi.info/">https://realfi.info</a>, login as a web3 user with the delegating wallet to retrieve your token e.g. ey......</li></ul><p><strong>4. Install </strong><a href="https://claude.ai/download"><strong>Claude Desktop</strong></a></p><p><strong>5. Create or edit the Claude Desktop configuration file</strong></p><pre># MacOS <br>mkdir -p ~/Library/Application\ Support/Claude/ <br>nano ~/Library/Application\ Support/Claude/claude_desktop_config.json</pre><p>Add the following configuration</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;realfi-info&quot;: {<br>      &quot;command&quot;: &quot;java&quot;,<br>      &quot;args&quot;: [&quot;-jar&quot;, &quot;/path/to/realfi-info-mcp/app/build/libs/realfi-info-mcp.jar&quot;],<br>      &quot;env&quot;: {<br>        &quot;REALFI_API_BASE_URL&quot;: &quot;https://api.realfi.info/data&quot;,<br>        &quot;REALFI_API_KEY&quot;: &quot;&lt;your-api-token-from-above&gt;&quot;<br>      },<br>      &quot;stdio&quot;: true<br>    }<br>  }<br>}</pre><p>Replace /path/to/ with the absolute path to this project.</p><p><strong>6. Restart Claude Desktop</strong></p><p>You should see the MCP server in Claude’s developer settings section.</p><p><strong>7. To test the integration, try asking questions like:</strong></p><ul><li>“<em>What are the top 25 tokens on Cardano</em>”</li><li>“<em>Plot the price of Cardano’s SNEK token for the last month</em>”</li><li>“<em>What are the current prices of the top 10 Cardano Tokens</em>”</li></ul><blockquote><strong><em>Are any of the top 10 Cardano native tokens flashing a BUY, SELL or HOLD trading signal right now?</em></strong></blockquote><blockquote>“Let me first get the current top tokens by trading volume, then fetch their latest prices to assess potential signals .. I need to analyze price trends over time. Let me get some historical data ..</blockquote><blockquote>BUY Signals:<br>SNEK - Currently showing strong upward momentum<br>Price: ~0.00394 ADA<br>Recent recovery from lows around 0.00355 ADA<br>Trading near recent highs with good volume support</blockquote><blockquote>iUSD - Bullish breakout pattern<br>Price: ~1.56-1.67 ADA range<br>Strong volume spike and price surge from ~1.46 to 1.67 ADA<br>Currently consolidating above key support levels</blockquote><blockquote>HOLD Signals:</blockquote><blockquote>WorldMobileTokenX - Neutral with slight bullish bias<br>Price: ~0.254 ADA<br>Consolidating after recent gains<br>Wait for clearer directional move</blockquote><blockquote>IAG - Sideways consolidation<br>Price: ~0.256-0.261 ADA<br>Holding support levels but no clear breakout</blockquote><blockquote>SELL/CAUTION Signals:</blockquote><blockquote>USDA - Stablecoin behavior<br>Price: ~1.51 ADA<br>As a stablecoin, limited upside potential</blockquote><blockquote>STRIKE - Weakening momentum<br>Price: ~1.28-1.35 ADA<br>Lower volume, unclear direction”</blockquote><h4>Key Observations</h4><p>Predictions sound more confident, no longer indicating a limitation in accessing up-to-date price data. Still some oddities such as including various stable coins in the analysis.</p><p>In the next part we’ll take it a step further by seeking to use and compare the performance of multiple models.</p><h3>3. Questions seeking further Model Types and Performance Validation</h3><blockquote><strong><em>Can you predict the price of the top Cardano token and let me know if it’s a BUY, SELL or HOLD signal? Use a few different recommended prediction models and one months worth of historical data and let me know performance of the models and confidence in predictions</em></strong></blockquote><blockquote>“Let me start by getting the current top tokens by volume and then gather historical data .. Now let me get one month of historical data to perform the analysis .. Let me also get the current price to have the most recent data point”</blockquote><p>This line of questioning inevitably results in a static website file enabling visualisation in the users machine when run in their browser, or in the Claude Desktop application console itself. To which Claude renders and continues the analysis summarising results.</p><p>An example is here:<a href="https://github.com/Edgxtech/realfi-info-mcp.git">https://github.com/Edgxtech/realfi-info-mcp.git</a> see <a href="https://github.com/Edgxtech/realfi-info-mcp/blob/main/example/snek_price_analysis.html">example/snek_price_analysis.html</a>.</p><p>Snippets like the following are included, with analytical values however no explanation or code showing how the values were derived</p><pre>&lt;div class=&quot;model-card ema&quot;&gt;<br>    &lt;h3&gt;Exponential Moving Average (EMA)&lt;/h3&gt;<br>    &lt;p&gt;&lt;strong&gt;12-Day EMA:&lt;/strong&gt; &lt;span id=&quot;ema12&quot;&gt;0.004321&lt;/span&gt; ADA&lt;/p&gt;<br>    &lt;p&gt;&lt;strong&gt;26-Day EMA:&lt;/strong&gt; &lt;span id=&quot;ema26&quot;&gt;0.003689&lt;/span&gt; ADA&lt;/p&gt;<br>    &lt;p&gt;&lt;strong&gt;Prediction:&lt;/strong&gt; &lt;span id=&quot;emaPrediction&quot;&gt;0.004289&lt;/span&gt; ADA (+9.5%)&lt;/p&gt;<br>    &lt;p&gt;&lt;strong&gt;Signal:&lt;/strong&gt; &lt;span class=&quot;signal buy&quot; id=&quot;emaSignal&quot;&gt;BUY&lt;/span&gt;&lt;/p&gt;<br>    &lt;div class=&quot;confidence-bar&quot;&gt;<br>        &lt;div class=&quot;confidence-fill&quot; style=&quot;width: 82%; background: #2ecc71;&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;p&gt;&lt;strong&gt;Confidence:&lt;/strong&gt; 82% - Recent price action favors bulls&lt;/p&gt;<br>&lt;/div&gt;</pre><p>The price history data is supplied as hardcoded data in an inline script, in this case it was just to allow rendering of the historical price chart rather than to perform any computations</p><pre>&lt;script&gt;<br>    // Historical price data from API<br>    const historicalData = [<br>        {date: &#39;2024-11-01&#39;, price: 0.00287491},<br>        ...<br>        {date: &#39;2024-12-02&#39;, price: 0.0064076}<br>    ];<br>&lt;/script&gt;</pre><p>The result looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iwym0Ni94rNEKqr66yVVQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPjTD-gWIvwSiPF9MWPBBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ety5kwtg6wD8OdDPW1lncw.png" /></figure><p>This is a good start. We’re on the right track for testing and comparing different models. However we can do better to get visibility of how the calculations are made.</p><p>You can coax it a bit further to provide more details under-the-hood including javascript code for each calculation, which is intended to either run in the users browser, or in the Claude Desktop application console itself, to which Claude renders and continues the analysis summarising results.</p><p>An example React based app that behaves this way, rendering signals on request is here:<a href="https://github.com/Edgxtech/realfi-info-mcp.git">https://github.com/Edgxtech/realfi-info-mcp.git</a> see <a href="https://github.com/Edgxtech/realfi-info-mcp/tree/main/example/snek-price-analysis-react">example/snek-price-analysis-react</a>.</p><p>Here’s a snippet showing predictor models. Further logic is contained in the app to convert the prediction to a trading signal</p><pre>const historicalData: HistoricalDataPoint[] = [<br>  { time: 1717545600, price: 0.00300427, date: &#39;2024-06-05&#39; },<br>  ...<br>  { time: 1733443200, price: 0.00662794, date: &#39;2024-12-06&#39; },<br>];<br><br>const currentPrice = 0.00662794;   <br> <br>const linearRegressionModel = (data: HistoricalDataPoint[]): PredictionModel =&gt; {<br>  const n = data.length;<br>  const x = data.map((_, i) =&gt; i);<br>  const y = data.map(d =&gt; d.price);<br>  const sumX = x.reduce((a, b) =&gt; a + b, 0);<br>  const sumY = y.reduce((a, b) =&gt; a + b, 0);<br>  const sumXY = x.reduce((sum, xi, i) =&gt; sum + xi * y[i], 0);<br>  const sumXX = x.reduce((sum, xi) =&gt; sum + xi * xi, 0);<br>  const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);<br>  const intercept = (sumY - slope * sumX) / n;<br>  const predictions: number[] = [];<br>  for (let i = 0; i &lt; 30; i++) {<br>    const nextIndex = n + i;<br>    predictions.push(Math.max(0, slope * nextIndex + intercept));<br>  }<br>  const yMean = sumY / n;<br>  const ssRes = y.reduce((sum, yi, i) =&gt; sum + Math.pow(yi - (slope * i + intercept), 2), 0);<br>  const ssTot = y.reduce((sum, yi) =&gt; sum + Math.pow(yi - yMean, 2), 0);<br>  const rSquared = 1 - ssRes / ssTot;<br>  return {<br>    predictions,<br>    rSquared,<br>    name: &#39;Linear Regression&#39;,<br>    confidence: Math.max(0, Math.min(100, rSquared * 100)),<br>  };<br>};    </pre><p>And these are the results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTaMZORp2Ly6tA3xP3Wfbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9CnYG_lm8mSJ-Zxh020Lw.png" /></figure><h4>Key Observations</h4><p>Detailed analysis and reporting is performed across models in both cases. Computation and provenance of signals <em>can</em> also be obtained with more specific instructions to perform the computation in the generated app such that the code and methods can be inspected.</p><p>However now we’re getting into deeper water. To trust these signals for use in a production system we need to better understand and fine tune the models as well as achieve positive control over signalling.</p><p>In the next part we’ll try to take it a step in this direction and create models that work with external Machine Learning Operations (MLOps) frameworks.</p><h3>4. Questions seeking integration with MLOps frameworks</h3><blockquote><strong><em>Can you produce a recommended price prediction model that works with </em></strong><a href="https://github.com/Edgxtech/cardano-price-modeller."><strong><em>https://github.com/Edgxtech/cardano-price-modeller.</em></strong></a><strong><em> I want you to make a new type of model based on your recommendations that works with this framework. I want it to be a module to this framework rather than requiring changes to the framework, just add the model which matches the structure of the examples in models/ and let me know how to hook it in.</em></strong></blockquote><blockquote>“I’ll examine the Cardano price modeller framework first to understand its structure .. I can see it’s designed to train models in ONNX format with integrated historical price/volume data .. Let me create a sophisticated ensemble model that should work as a drop-in module”</blockquote><p>This line of questioning results in a Model Class file encapsulating all the functions predict(), prepare_features(), train(), etc... needed to be compatible with the MLOps framework.</p><p>It has not produced an ONNX file (a popular portable format for machine learning pipelines) that I can immediately run, which is okay since we prefer to see the computations in the code as well as perhaps run the training on custom high-performance hardware, but it does know that it needs to be able to export as such. The idea of getting an ONNX file directly is interesting though, perhaps for another time with function calling to a model training MCP service.</p><p>We just then need to hook into the framework for model generation, which also provides performance monitoring and control benefits. Due to the modular software architecture of the framework, this is (ideally) a simple addition.</p><p>The agent knows the functions it needs to implement and their input and output interfaces. It knows PyTorch (widely adopted Machine Learning libraries) is available in the environment although may suggest other libraries. It also used its vast knowledge of the literature to decide on a model which is distinct from the current examples of a <em>Feedforward Neural Network</em>, <em>Recurrent Neural Network</em> and a <em>Transformer Model with Deep Learning</em>.</p><p>It produced a <em>Transformer Ensemble Model</em>, in some sense a different arrangement and parameter selection of the example <em>Transformer Model</em>, which can be assessed for performance and “<em>generated</em>” in the ONNX format. Here’s how…</p><h4>Install Price Prediction Framework</h4><p><strong>1. Clone this repository</strong></p><pre>git clone https://github.com/Edgxtech/cardano-price-modeller.git<br>cd cardano-price-modeller</pre><p>This is a simplified version of such a framework that I developed for thinking about this problem. It performs training and evaluation including backtesting, filtering and ranking as well as export of the models for live implementation.</p><p><strong>2. Drop-in the new Model Class</strong></p><p>In my case this was adding the Agent generated Python file (Python was matched to the targeted framework automatically) as:</p><p>/path/to/cardano-price-modeller/models/TransformerEnsemblePriceModel.py</p><p>Where /path/to is the absolute path to your clone of the repository.</p><p><strong>3. Hook into the framework</strong></p><p>Edit the /path/to/cardano-price-modeller/model_generator.py file</p><pre>from models.TransformerEnsemblePriceModel import TransformerEnsembleModel<br><br>class ModelGenerator:<br>    def __init__(self):<br>        &quot;&quot;&quot;Initialize ModelGenerator with model types and client.&quot;&quot;&quot;<br>        self.model_types = {<br>            &#39;ffnn&#39;: FFNNPriceModel,<br>            &#39;lstm&#39;: LSTMPriceModel,<br>            &#39;transformer&#39;: TransformerPriceModel,<br>            &#39;ensemble&#39;: TransformerEnsembleModel # Add new model<br>        }</pre><p><strong>4. Configure Python environment</strong></p><p>Install <a href="https://www.anaconda.com/docs/getting-started/miniconda/install">Conda</a>, then install dependencies in a new Conda environment</p><pre># Create Conda environment named cntmodeller<br>conda create -n cntmodeller   <br><br># Activate it and install python dependencies to the environment<br>conda activate cntmodeller    <br>pip install -r requirements.txt</pre><p><strong>5. Configure access to price data</strong></p><pre># Define environment variables  <br>cp .env.example .env   <br><br># Edit .env, adding your access token from the realfi.info API used above  <br>REALFI_API_TOKEN=&lt;insert-your-token&gt;</pre><p>The live data is used directly in the framework here rather than through MCP. MCP integration may still be useful for discovering data formats.</p><p><strong>6. Run the model generator</strong></p><pre>python model_generator.py</pre><p>This will produce .onnx files in model_results/ and a model.properties file which can be curated to choose models you want to retain for live use. E.g.</p><pre># Model manifest for recommended models<br># Generated: 2025-06-04 14:40:54<br># Format: symbol.model_name.key=value<br># Performance metrics included as comments<br><br># SNEK - ffnn<br># Test R²: -4.1718, Test MAE: 0.001128, Backtest R²: 0.9580, Backtest MAE: 0.000281, Total Return: 0.324266, Sharpe Ratio: 0.4936<br>SNEK.ffnn.path=model_results/cardano_models_SNEK_ffnn.onnx<br><br># SNEK - lstm<br># Test R²: -2.2189, Test MAE: 0.000927, Backtest R²: 0.9594, Backtest MAE: 0.000267, Total Return: 0.142957, Sharpe Ratio: 0.4217<br>SNEK.lstm.path=model_results/cardano_models_SNEK_lstm.onnx</pre><p><strong>7. Run the live signaller app</strong></p><pre>python live_signalling_app.py</pre><p>This will use model.properties from the model generation step to load models and produce trading signals from monitoring live data.</p><p><strong>8. Run the live simulated trader app</strong></p><pre>python live_simtrader_app.py</pre><p>This will use the same models and signalling however will conduct trades and manage a portfolio from a <em>simulated</em> initial capital amount.</p><h4>Key Observations</h4><p>Complex models <em>can</em> be generated which support direct integration in MLOps frameworks, meaning positive human-on-the-loop control and observability can be maintained while benefiting from deep knowledge of techniques. This supports the approach where we can feasibly throw a bag of options at a bag of tokens and see what models show promise, interacting with the agent to improve performances.</p><p>A quick note that various iterations and interventions were required to address incompatibility issues. These included being specific about Model Class implementations, variable names and aligning feature and data matrix shapes throughout the pipelines. Also note that changes to the framework rather than modules are sometimes also suggested. Ideally the framework is sufficiently general and modular to prevent this. Adding more specificity to the question helps, although what may be useful is defining a standard “<em>AI look at these instructions for generating modules</em>” type file that lives in the repo itself.</p><h3>Caveats</h3><p>Note that the predictions and models here are for demonstration purposes only. Use with caution. Also, note that there are risks associated with using similar methods (e.g., over-reliance on AI signals, market volatility) and ethical considerations (e.g., responsible use of trading models).</p><h3>Summing Up</h3><p>We explored AI agent-assisted price predictions in four steps.</p><ol><li>Straight to the point questions</li><li>Questions when integrated with live price data</li><li>Questions seeking further model types and performance validation, and</li><li>Questions seeking integration with Machine Learning Ops (MLOps) frameworks</li></ol><p>The results were increasingly <em>informative</em> in terms of showing the source of prediction and increasingly <em>integrated</em> with outside systems whether it be custom data feeds or execution frameworks.</p><p>The power to interact with AI/LLMs for sensitive or critical use-cases with appropriate human-on-the-loop curation and hardware or environment customisation, perhaps lies in the approach where we integrate with an architecture of distributed live data feeds and an external “<em>Ops”</em> framework for observability and execution.</p><p>This constrains the agents’ generation and facilitates trust while preserving it’s freedom with the user to explore and innovate on different techniques. Training the Agent itself is a wider effort to stay updated with research and software libraries matched to hardware performance advances.</p><p>Hope you found this useful!</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67baa513cfee" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/a-foray-into-price-prediction-with-ai-agents-67baa513cfee">A Foray into Price Prediction with AI Agents</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started as a Data Engineer with a Blockchain Scenario — Part XII]]></title>
            <link>https://medium.com/towards-data-engineering/getting-started-as-a-data-engineer-with-a-blockchain-scenario-part-xii-39adf47c1fa3?source=rss-f40b51ecaf27------2</link>
            <guid isPermaLink="false">https://medium.com/p/39adf47c1fa3</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Tim Edge]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 06:34:27 GMT</pubDate>
            <atom:updated>2025-04-13T06:34:27.203Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started as a Data Engineer with a Blockchain Scenario — Part XII</h3><h4>Visualise and Analyse Data using Jupyter Lab and Neo4j</h4><p>Continuing on from our last major objective where we <em>Orchestrated the Enrichment of Blockchain Data</em> by aggregating <em>Token Volumes</em> and calculating the Page Rank of our <em>Wallet Transfers</em> data, the next objective is to visualise and briefly analyse this new data using Jupyter Labs. We will also demonstrate visualisations for graph oriented data that come out of the box with the Neo4j browser.</p><h3>Visualise and Analyse Results</h3><p>From here it is a matter of operational use of the data and preferences for how to do that including how to display, interface or augment with the user. Perhaps a <a href="https://grafana.com/">Grafana</a> or similar dashboard or custom web app is the final end-state.</p><p>However, we will utilise <a href="https://jupyter.org/">Jupyter Lab</a> as a means to interact with and plot part of the data. Jupyter Lab makes it easier to explore, share and collaborate with such results, still using the Python ecosystem.</p><p>We will also use Neo4j’s native Web Interface since it’s naturally good at interacting with graph oriented data. There are options to do this with Python libraries and other tools, but it’s hardly worth the effort at this stage.</p><h4>Install Jupyter Lab</h4><p>First we will install Jupyter Lab (the successor to <em>Jupyter Notebooks</em> which remains a popular tool).</p><pre>conda activate sparkenv<br>conda install jupyterlab</pre><p>And from a new blockchain-data-engineering/src/jupyter directory in our project, start Jupyter Labs with</p><pre>jupyter lab<br>#  &gt; automatically opens in browser: http://localhost:8888/lab</pre><p>Note: By starting in the src/jupyter directory, this is now set as our <em>Python</em> current working directory.</p><p>A browser tab will automatically open at: <a href="http://localhost:8888/lab"><em>http://localhost:8888/lab</em></a> similar to the following. You can also reopen in any other browser by copying this address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T6nEbRUsXndQ0xAVKIkQow.png" /><figcaption>Jupyter Start Screen</figcaption></figure><p>The analytics we are working towards include producing a <em>Stack Area Plot</em> of the changing volumes transacted by token, as well as determining which addresses are the most connected via the <em>Page Rank</em> algorithm.</p><h4>Stack Plot in Python</h4><p>The intention is to visualise the proportion of volumes transacted by token over time, which we might expect to show trends in popular tokens, dominance of certain tokens etc…</p><p>Before we get started we’ll install a few additional libraries to our sparkenv Conda environment, specifically for use with our Jupyter based data exploration and visualisation activities.</p><ul><li><em>psycopg2</em> library for communications with PostgreSQL</li><li><em>matplotlib</em> which provides a wide range of plotting options in Python</li><li><em>neo4j</em> library for communications with Neo4j</li><li><em>dash-cytoscape</em> library for working with and plotting graphs and networks</li></ul><p>Create a new dependencies file specifically for Jupyter use src/jupyter/requirements.txt</p><pre>psycopg2==2.9.10<br>matplotlib==3.9.3<br>neo4j==5.26.0<br>dash-cytoscape==1.0.2</pre><p>And install into our Conda <em>sparkenv</em></p><pre>conda activate sparkenv<br>pip install -r src/jupyter/requirements.txt</pre><p>Now add the following cells to a new Jupyter Notebook (i.e. <em>Notebook: Python3</em>) for building our visualisation app code. Once you rename from ‘untitled’ you will have a new file; src/jupyter/cardano_analytics.ipynb</p><h4>Key capabilities of the snippets below:</h4><ul><li>The first ‘cell’ here is functionally about ‘extracting’ the data we need</li><li>We establish a connection with Postgres using the psycopg2 library</li><li>We query the <em>vol_by_block</em> data and make it into a Pandas DataFrame, which gives us time-series oriented data since it is by block</li><li>We query the <em>vol_all_time</em> data to pull the top 10 tokens by all time volume and also making it into a Pandas DataFrame</li></ul><pre>## Extract<br>import psycopg2<br>import pandas as pd<br><br>def get_connection():<br>    try:<br>        return psycopg2.connect(<br>            database=&quot;bde&quot;,<br>            user=&quot;myuser&quot;,<br>            password=&quot;password&quot;,<br>            host=&quot;127.0.0.1&quot;,<br>            port=5432,<br>        )<br>    except:<br>        return False<br><br>conn = get_connection()<br>curr = conn.cursor()<br>curr.execute(&quot;SELECT * FROM vol_by_block;&quot;)<br>by_block_df = pd.DataFrame(curr.fetchall(), columns=[&#39;unit&#39;,&#39;height&#39;,&#39;value_adj&#39;])<br><br>curr = conn.cursor()<br>curr.execute(&quot;SELECT unit FROM vol_all_time order by value_adj DESC limit 10;&quot;)<br>totals_df = pd.DataFrame(curr.fetchall(), columns=[&#39;unit&#39;])</pre><p><em>Shift-Enter</em> to execute this cell. You should see [*] turn to [1] to the left of the cell, and the cursor move to the next empty cell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPe5vVeL0tEbDk5lEFm-Eg.png" /><figcaption>Executing Cell #1</figcaption></figure><p>Keep in mind the Jupyter Notebook we are creating is using the same Python kernel under the hood, therefore variables are shared to successive cells. Now add the following to the next cell.</p><h4>Key capabilities of the snippets below:</h4><ul><li>The second ‘cell’ here is functionally about ‘transforming’ the data into a format suitable for plotting</li><li>We create a Pandas DataFrame <em>top_by_block_df</em> by merging the <em>vol_by_block</em> data based on the top 10 tokens by total volume. To demonstrate different approaches this can be achieved with a DataFrame merge operation, or using an SQL inner join</li><li>We use the popular <em>Numpy</em> package for dealing with matrices and arrays</li><li>arrange() creates evenly spaced values for an interval, in this case creates an array of height values from the lowest to highest in this dataset, in increments of 1 (since we know thats how the blockchain protocol increments)</li><li>.zeros() pads an array with zeros</li><li>We then merge a DataFrame of zeros zeros_df with our retrieved data top_by_block_df since our persisted data only contains a value if there is volume, and is left empty where there is no volume. This wouldn&#39;t chart well, so we need to pad with zeros first. The method is to transform each tokens values with a Pandas combine_first() operation which updates <em>null</em> (empty) locations with value from the <em>zeros_df</em></li><li>We compute the <em>cumulative moving average</em> using Pandas .expanding().mean(). .expanding() makes the subsequent calculation be performed on an expanding window, which achieves what we need in this case. This is merged in a new DataFrame with our original <em>zeros padded</em> data from the database</li><li>Finally we extract out a <em>Numpy</em> array of the <em>cumulative moving average</em> smoothed data, weighted as a percentage compared to the other top-10 tokens by volume</li></ul><pre>## Transform<br>import numpy as np<br><br># Inner Join to filter down to the top all-time tokens <br># Alternate in SQL; <br># select * from vol_by_block <br># join (select unit from vol_all_time order by value_adj desc limit 5) as ALLTIME on ALLTIME.unit = vol_by_block.unit <br># order by vol_by_block.unit, vol_by_block.height;<br>top_by_block_df = pd.merge(by_block_df, totals_df[&#39;unit&#39;], on=[&#39;unit&#39;], how=&#39;inner&#39;).sort_values(by=[&#39;unit&#39;,&#39;height&#39;])<br><br>heights = np.arange(min(top_by_block_df.height),max(top_by_block_df.height) + 1)<br><br># Pad with zeros where there are no values for a particular height<br>zeros=np.zeros((1, heights.__len__()))<br>zeros_df=pd.DataFrame({&#39;height&#39;: heights, &#39;value_adj&#39;: zeros.tolist()[0]}).set_index(&#39;height&#39;)<br>values_by_unit_df=(top_by_block_df<br>            .groupby(&#39;unit&#39;)[[&#39;height&#39;,&#39;value_adj&#39;]]<br>            .apply(lambda x: x.set_index(&#39;height&#39;).combine_first(zeros_df)))<br><br># Merge Cummulative Moving Average (CMA) data into df; after merge, <br># value_adj_x contains the unsmoothed data, value_adj_y contains smoothed data<br>cma_df = (values_by_unit_df.reset_index().set_index(&#39;height&#39;)<br>            .groupby(&#39;unit&#39;)[&#39;value_adj&#39;]<br>            .expanding()<br>            .mean())<br><br>values_cma_df=values_by_unit_df.merge(cma_df, on=[&quot;unit&quot;,&quot;height&quot;], how=&quot;left&quot;).fillna(0)<br><br># Compute proportions by unit for each block. Stylistic choice to show a proportional stack area chart<br>chart_values_dict = values_cma_df.groupby(&#39;unit&#39;)[&#39;value_adj_y&#39;].apply(lambda x: x.values).to_dict()<br>values = np.array(list(chart_values_dict.values()))<br>values_sum = values.sum(axis=0).astype(float)<br>values_sum[values_sum == 0] = 1<br>proportional_chart_values = (values / values_sum) * 100</pre><p>And finally create a plot from the proportional smoothed chart values against the block heights, pasting the following into another cell</p><h4>Key capabilities of the snippets below:</h4><ul><li>We use a Python native .map() operation to transform a list of the &#39;unit&#39; of the top-10 tokens by volume (&#39;unit&#39; is a tokens unique ID which is a concatenation of token policy and hex encoded name). We essentially take the bit beyond character 56 (length of a token policy) and decode that as a UTF-8 string, which gives us the on-chain registered name.</li><li>We use the <em>matplotlib</em> .stackplot() to plot our data with custom labels and annotations</li></ul><pre>## Plot<br>import matplotlib.pyplot as plt<br><br># Decode Asset Name; hex encoded part of the &#39;unit&#39; &amp; standardise Legend format<br>labels_=map(lambda x: f&#39;{x[:5]}...{x[x.__len__()-5:]} ({bytes.fromhex(x[56:]).decode(&#39;utf-8&#39;)})&#39; if x != &#39;lovelace&#39; else x, list(chart_values_dict.keys()))<br><br>plt.stackplot(heights,<br>              proportional_chart_values, <br>              labels=labels_)<br><br>plt.legend(fontsize=&#39;x-small&#39;, bbox_to_anchor=(1.02, 1),)<br>plt.title(&#39;Volume Transacted by Token&#39;)<br>plt.xlabel(&#39;Block&#39;)<br>plt.ylabel(&#39;Proportion ADA (%)&#39;)<br>plt.ticklabel_format(useOffset=False)</pre><p>The result you obtain will depend on how much data you had persisted in the original <em>vol</em> PostgreSQL table, and the subsequent <em>vol_by_block</em> and <em>vol_all_time</em> tables after the Airflow jobs were run. You should obtain a <em>Stack Area Plot</em> similar to the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*Sm5bpwH2IsGfjRBjsW7tRA.png" /><figcaption>Cumulative Moving Average (CMA) Plot of Proportional Token Volumes</figcaption></figure><h4>Graph Plot in Python</h4><p>Next we will make use of the graph oriented data in Neo4j to make a network graph in Python. Here we are using the <em>Dash</em> framework for running interactive web applications in Python. It uses <em>Plotly</em> and <em>Cytoscape</em> (for network visualisations) under the hood for plotting purposes, and includes standard User Interface (UI) elements such as dropdowns, sliders and graphs.</p><p>We have already installed <em>dash_cytoscape</em> Python library above, so this should be available in your Conda environment already.</p><p>First, make sure Neo4j is running (can access at <a href="http://localhost:7474/browser"><em>http://localhost:7474/browser</em></a>), otherwise start it using; neo4j start</p><p>Then add these snippets to separate cells in the same notebook, or make a new notebook (depending on your information management preferences)</p><p>Cell 1 — Extracting all SENT_TO relationships using a Cypher query with the <em>neo4j</em> Python library</p><pre>## Extract<br>from neo4j import GraphDatabase<br><br>driver = GraphDatabase.driver(&quot;neo4j://127.0.0.1:7687&quot;, auth=(&quot;neo4j&quot;, &quot;mypassword&quot;))<br>driver.verify_connectivity()<br>session = driver.session()<br><br>nodes = session.run(&quot;MATCH (s)-[t:SENT_TO]-&gt;(r) RETURN s, r, t  LIMIT 50&quot;)</pre><p>Cell 2 — Transforming data into the <em>graph</em> variable, an array of nodes and edges that is compatible with a <em>Cytoscape</em> plot. We are taking the properties of interest for the nodes which is just the <em>address</em> and the edges which is the sender address, receiver address, transaction hash and value transferred. We are also including labels which are trimmed down strings, to prevent overloading the display.</p><pre>## Transform<br>df = nodes.to_df()<br>graph = []<br>sender_nodes = [{&#39;data&#39;: {&#39;id&#39;: s.get(&#39;address&#39;), \<br>                   &#39;label&#39;: f&#39;{s.get(&#39;address&#39;)[:1]}...{s.get(&#39;address&#39;)[s.get(&#39;address&#39;).__len__()-3:]}&#39;}} \<br>                for s in df.s]<br>receiver_nodes = [{&#39;data&#39;: {&#39;id&#39;: r.get(&#39;address&#39;), \<br>                   &#39;label&#39;: f&#39;{r.get(&#39;address&#39;)[:1]}...{r.get(&#39;address&#39;)[r.get(&#39;address&#39;).__len__()-3:]}&#39;}} \<br>                 for r in df.r]<br>edges = [{&#39;data&#39;: {&#39;source&#39;: s.get(&#39;address&#39;), \<br>                   &#39;target&#39;: r.get(&#39;address&#39;), \<br>                   &#39;label&#39;: f&#39;{t.get(&#39;tx_hash&#39;)[:4]}...{t.get(&#39;tx_hash&#39;)[t.get(&#39;tx_hash&#39;).__len__()-4:]}&#39;, \<br>                   &#39;tx_hash&#39;: t.get(&#39;tx_hash&#39;), \<br>                   &#39;value&#39;: t.get(&#39;value&#39;)}} \<br>         for s,r,t in zip(df.s,df.r,df.t)]<br>graph.extend(sender_nodes)<br>graph.extend(receiver_nodes)<br>graph.extend(edges)</pre><p>Cell 3 — Starting a <em>Dash</em> web app with a simple HTML div containing the Cytoscape plot. This example is fairly basic, however adds annotations for nodes and edges via the <em>stylesheet</em> property.</p><pre>## Plot<br>from dash import Dash, html<br>import dash_cytoscape as cyto<br><br>app = Dash(__name__)<br><br>app.layout = html.Div(style = {&#39;padding&#39;: &#39;20px&#39;, &#39;backgroundColor&#39;: &#39;whitesmoke&#39;, &#39;width&#39;: &#39;90%&#39;}, className=&#39;column&#39;, children=[ <br>        html.P(&quot;Transaction Graph&quot;),<br>        cyto.Cytoscape(<br>            id=&#39;cytoscape-plot&#39;,<br>            elements=graph,<br>            style={&#39;width&#39;: &#39;100%&#39;, &#39;minHeight&#39;: &#39;300px&#39;},<br>            minZoom=0.2,<br>            maxZoom=1,<br>            layout={&#39;name&#39;: &#39;cose&#39;, &#39;padding&#39;: 100},<br>            stylesheet=[<br>                {<br>                    &#39;selector&#39;:&#39;edge[label]&#39;,<br>                    &#39;style&#39;:{<br>                        &#39;label&#39;:&#39;data(label)&#39;,<br>                        &#39;curve-style&#39;: &#39;bezier&#39;,<br>                        &#39;target-arrow-shape&#39;: &#39;triangle&#39;,<br>                    }<br>                },<br>                {<br>                    &quot;selector&quot;: &quot;node[label]&quot;,<br>                    &quot;style&quot;: {<br>                        &quot;label&quot;: &quot;data(label)&quot;<br>                    }<br>                 }<br>            ],<br>        ),<br>    ])<br>  <br>app.run_server(debug=True, mode=&#39;jupyterlab&#39;)</pre><p>You should obtain a network graph similar to the following, which is interactive allowing to select, click and drag nodes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mbcx956z0umcb3svp3ElFg.png" /><figcaption>Python Transfers Graph — Basic</figcaption></figure><p>And we can make an upgrade that lets us easily view the graph in different layout styles as well as report the key properties upon selection of Nodes and Edges. This involves writing callback functions which detect changes in the UI and make updates as necessary.</p><p>First, restart the Jupyter Python Kernel so the Dash server is restarted, run the ‘Extract’ and ‘Transform’ cells then run the following upgraded cell.</p><pre>## Plot2<br>from dash import Dash, html, no_update, dcc<br>import dash_cytoscape as cyto<br>from dash.dependencies import Output, Input<br><br>app = Dash(__name__)<br><br>app.layout = html.Div(style = {&#39;padding&#39;: &#39;20px&#39;, &#39;backgroundColor&#39;: &#39;whitesmoke&#39;, &#39;width&#39;: &#39;90%&#39;}, className=&#39;column&#39;, children=[ <br>        html.P(&quot;Transaction Graph&quot;),<br>        html.Div(style={&#39;display&#39;: &#39;flex&#39;}, children=[<br>            html.P(style={&#39;flex&#39;: &#39;10%&#39;}, children=[&quot;Layout style&quot;]),<br>            dcc.Dropdown(<br>                id=&#39;layout-selector&#39;,<br>                style={&#39;flex&#39;: &#39;70%&#39;},<br>                value=&#39;cose&#39;,<br>                clearable=False,<br>                options=[<br>                    {&#39;label&#39;: name.capitalize(), &#39;value&#39;: name}<br>                    for name in [&#39;breadthfirst&#39; ,&#39;grid&#39;, &#39;random&#39;, &#39;circle&#39;, &#39;cose&#39;, &#39;concentric&#39;]<br>                ]<br>            ),<br>        ]),<br>        cyto.Cytoscape(<br>            id=&#39;cytoscape-plot&#39;,<br>            elements=graph,<br>            style={&#39;width&#39;: &#39;100%&#39;, &#39;minHeight&#39;: &#39;300px&#39;},<br>            minZoom=0.2,<br>            maxZoom=1,<br>            layout={&#39;name&#39;: &#39;cose&#39;},<br>            stylesheet=[<br>                {<br>                    &#39;selector&#39;:&#39;edge[label]&#39;,<br>                    &#39;style&#39;:{<br>                        &#39;label&#39;:&#39;data(label)&#39;,<br>                        &#39;curve-style&#39;: &#39;bezier&#39;,<br>                        &#39;target-arrow-shape&#39;: &#39;triangle&#39;,<br>                    }<br>                },<br>                {<br>                    &quot;selector&quot;: &quot;node[label]&quot;,<br>                    &quot;style&quot;: {<br>                        &quot;label&quot;: &quot;data(label)&quot;<br>                    }<br>                 },<br>            ],<br>        ),<br>        html.Div(id=&#39;selection-div&#39;, style={&#39;minHeight&#39;: &#39;100px&#39;, &#39;width&#39;: &#39;100%&#39;}, children=[]),<br>    ])<br><br>@app.callback(<br>    Output(&#39;cytoscape-plot&#39;, &#39;layout&#39;),<br>              Input(&#39;layout-selector&#39;, &#39;value&#39;)<br>)<br>def update_layout(layout_value):<br>    return {&#39;name&#39;: layout_value, &#39;animate&#39;: True}<br><br>@app.callback(<br>    Output(&#39;selection-div&#39;, &#39;children&#39;),<br>    Input(&#39;cytoscape-plot&#39;,&#39;selectedNodeData&#39;),<br>    Input(&#39;cytoscape-plot&#39;,&#39;selectedEdgeData&#39;)<br>)<br>def update_layout(selected_nodes, selected_edges):<br>    if selected_nodes is None and selected_edges is None:<br>        return no_update<br>    else:<br>        output = []<br>        if selected_nodes is not None:<br>            output.extend([html.Li(f&quot;Node =&gt; Address: {x[&#39;id&#39;]}&quot;) for x in selected_nodes])<br>        if selected_edges is not None:<br>            output.extend([html.Li(f&quot;Edge =&gt; Sender: {x[&#39;source&#39;]}, \<br>                Receiver: {x[&#39;target&#39;]}, \<br>                TxHash: {x[&#39;tx_hash&#39;]},  \<br>                Value(lovelace): {x[&#39;value&#39;]}&quot;) for x in selected_edges])<br>        return html.Div([<br>                    html.H3(&quot;Selections&quot;),<br>                        html.Ul(output)])   <br> <br>app.run_server(debug=True, mode=&#39;jupyterlab&#39;)</pre><p>You should obtain network graph(s) similar to the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlJBFoMAhUWWGCyqCtx8Mg.png" /><figcaption>Python Transfers Graph — Cose Layout</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0B-mFZQV3L_TgZOXx2j5VA.png" /><figcaption>Python Transfers Graph — Breadthfirst Layout</figcaption></figure><h4>Graph Plot in Neo4j</h4><p>Neo4j comes with an interactive plotting capability available through their UI, which is also a good option for exploratory analysis if you don’t need customisations.</p><p>Navigate to <a href="http://localhost:7474/browser"><em>http://localhost:7474/browser</em></a> in your browser, and use the following Cypher query.</p><pre>MATCH p=()-[r:SENT_TO]-&gt;() RETURN p LIMIT 50</pre><p>Where you can produce and save plots similar to the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EJaS2q6n0SL_xzV7Wdfvg.png" /><figcaption>Neo4j Graph Plot of Token Transfers</figcaption></figure><p>And interact with the plot as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dWyvDJxjYfBnBDI93pFiA.png" /><figcaption>Neo4j Graph Plot of Token Transfers — Interactive</figcaption></figure><h4>Query Page Ranks</h4><p>Lastly we’ll inspect the Page Rank (connectedness) data which was computed in our Airflow DAG above.</p><p>From your PostgreSQL shell bde=#</p><pre>select * from address_pagerank order by score desc limit 10;<br># &gt;                                                  address                                                 |       score        <br>#---------------------------------------------------------------------------------------------------------+--------------------<br># addr1qxljmlhuwjqu26lrfxfnfz3ruk9z04ldzgeezy6556fw59dslp3k84yk4n7y4xk7tq5ajkh6vrfyexk7e0e094ghrnlsgznjc7 | 2.8274999999999997<br># addr1zyd0sj57d9lpu7cy9g9qdurpazqc9l4eaxk6j59nd2gkh4275jq4yvpskgayj55xegdp30g5rfynax66r8vgn9fldndsqzf5tn | 1.1830354172252915<br># ...</pre><p>Which shows addr1qxl...lsgznjc7 in this example (may be different for your dataset) has the highest score. This is consistent with a quick sanity check if we look in the Neo4j Web UI, where if we query all data, e.g. with the following Cypher query</p><pre>MATCH p=()-[r:SENT_TO]-&gt;() RETURN p</pre><p>We can see that the same wallet address is at the center of the largest ‘looking’ cluster of wallets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C8c4vMQlZFgdGx4TMX4MxA.png" /><figcaption>Large cluster of wallet interactions</figcaption></figure><p>So we have covered basic data visualisation and analysis using Jupyter Lab and Neo4j. In the next part we’ll containerise our app code using <em>Docker</em> and build local infrastructure to test the application(s) in an emulated production cluster based on <em>Kubernetes.</em></p><h3>Complete application</h3><p>The code used here is available at:</p><p>Github: <a href="https://github.com/Edgxtech/blockchain-data-engineering"><em>https://github.com/Edgxtech/blockchain-data-engineering</em></a></p><p>See specifically: src/jupyter/</p><h3>Key successes we’ve had at this check point</h3><ul><li>We learnt how to orchestrate ETL jobs using Airflow to enrich data that we had indexed previously</li><li>We performed advanced analytics to load data in a format that enables extraction of insights and visualisations including, volumes by block and token as well as Page Rank (connectedness) of wallets</li><li>We created a Stack Area Plot showing proportional changing volumes of the top-10 tokens by historical volume</li><li>We created basic network plots using our graph oriented data contained in Neo4j, showing wallets that sent tokens to other wallets</li></ul><h3>Key learning outcomes achieved at this check point</h3><ol><li>Installation of Apache Airflow</li><li>Restoration of data backups in PostgreSQL and Neo4j</li><li>Basic DAG development in Apache Airflow</li><li>Basic Analytics with Graph Data Science (GDS) for Neo4j</li><li>Installation of Jupyter Lab</li><li>Plotting in Python using <em>matplotlib</em> and <em>dash_cytoscape</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39adf47c1fa3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/getting-started-as-a-data-engineer-with-a-blockchain-scenario-part-xii-39adf47c1fa3">Getting Started as a Data Engineer with a Blockchain Scenario — Part XII</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started as a Data Engineer with a Blockchain Scenario — Part XI]]></title>
            <link>https://medium.com/towards-data-engineering/getting-started-as-a-data-engineer-with-a-blockchain-scenario-part-xi-dff408abcfe4?source=rss-f40b51ecaf27------2</link>
            <guid isPermaLink="false">https://medium.com/p/dff408abcfe4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Tim Edge]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 09:42:18 GMT</pubDate>
            <atom:updated>2025-03-27T09:42:18.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started as a Data Engineer with a Blockchain Scenario — Part XI</h3><h4>PageRank (Connectedness) using Airflow and Graph Data Science (GDS)</h4><p>Continuing on from <a href="http://localhost:3000/">Aggregation and Ranking of Data using Airflow</a> where we create an Airflow DAG to enrich our <em>Volumes</em> Data, the next objective is to perform a similar ETL job on a scheduled basis to enrich our <em>Wallet Transfers</em> data, gaining insights about the data beyond what is otherwise available.</p><h3>PageRank using Airflow and Graph Data Science (GDS)</h3><p>Here we will perform some further analysis of the Transfers data, to rank the top most ‘connected’ addresses using the Page Rank algorithm and make it available for consumption in a PostgreSQL table. This is again just another example of data enrichment and advanced analytics, this time performing graph data analytics.</p><p>PageRank for blockchain analytics is useful because it can help reveal influential nodes that are highly connected such as exchanges and can help detect patterns, and flows of value between entities and smart contracts on a blockchain network. It can also help detect bad actors creating multiple fake identities (Sybil attacks) to gain influence. by assigning lower scores to suspiciously uniform or circular transaction patterns. It can also help with resource optimisation, aiding miners, validators, or analysts to prioritise monitoring high-impact nodes.</p><p>We are using the Neo4j extension GDS to perform basic PageRank analysis. It is worth noting there is also a Spark <em>GraphX</em> capability which can perform distributed graph analytics should we need to perform computations in a scaleable way.</p><p>First, we’ll configure airflow to be able to connect to our local Neo4j service.</p><pre>conda activate airflow<br>pip install apache-airflow-providers-neo4j==3.8<br>airflow connections add &quot;bde_graph_default&quot; --conn-json &#39;{<br>  &quot;conn_type&quot;: &quot;neo4j&quot;,<br>  &quot;host&quot;: &quot;127.0.0.1&quot;,<br>  &quot;schema&quot;: &quot;neo4j&quot;,<br>  &quot;login&quot;: &quot;neo4j&quot;,<br>  &quot;password&quot;: &quot;mypassword&quot;<br>}&#39;</pre><p>Create a Graph Data Science (GDS) graph (an extension module to Neo4j) from the transfers data. You can run this Cypher query (e.g. <em>MATCH …</em>) from the Neo4j browser <a href="http://localhost:7474/"><em>http://localhost:7474</em></a> or using the Cypher Shell as follows</p><pre># Alternatively input into the Neo4j browser.<br>cypher-shell -u neo4j -p mypassword &quot;MATCH (source:Wallet)-[r:SENT_TO]-&gt;(target:Wallet)\<br>                                    RETURN gds.graph.project(&#39;txGraph&#39;,source,target,{ relationshipProperties: r { .value_adj } })&quot;<br># &gt; graphName: &quot;txGraph&quot; ...</pre><h4>What can go wrong:</h4><ul><li><em>Returns </em><strong><em>NULL</em></strong> =&gt; it is likely you have no <em>:Wallet</em> nodes or <em>:SENT_TO</em> relationships data actually persisted in Neo4j, see above for method to sync up some data</li></ul><p>Then we’ll create some new tables in PostgreSQL, we are again using a bit of foresight about the kind of output data we might encounter, however can always be prepared to adjust this if needed later.</p><p>From your Postgres shell; bde=#</p><pre>DROP TABLE IF EXISTS ADDRESS_PAGERANK;<br>CREATE TABLE ADDRESS_PAGERANK(<br>           ADDRESS TEXT NOT NULL PRIMARY KEY,<br>           SCORE FLOAT);<br>ALTER TABLE public.address_pagerank OWNER TO myuser;</pre><p>Now create a new DAG; airflow/dags/etl_pagerank_dag.py</p><p>Our DAG will be performing the following ETL pipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*qh2qmPiVvP9YVQgM8Ki49A.png" /><figcaption>ETL PageRank DAG</figcaption></figure><h4>Key capabilities of the snippets below:</h4><ul><li>We use the built-in Airflow Operator PythonOperator as the first of our DAG tasks extract_pageranks() which makes use of a Python Neo4j library to execute a custom Cypher query. The Cypher query uses the GDS graph &#39;txGraph&#39; and the GDS in-built <em>gds.pageRank</em> capability to produce rankings for all the Wallets</li><li>The results are passed through to the load_pageranks() custom defined task intending to persist this data in PostgreSQL, again using an UPSERT type operation</li><li>Lastly, we order the DAG tasks based on the required flow, keeping in mind what tasks depending on what other tasks.</li></ul><pre>from datetime import timedelta<br>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from airflow.providers.neo4j.hooks.neo4j import Neo4jHook<br>from airflow.providers.postgres.hooks.postgres import PostgresHook<br>from airflow.utils.dates import days_ago<br>from airflow.decorators import task<br>import pandas as pd<br>import psycopg2<br>import psycopg2.extras as extras<br><br>pg_hook = PostgresHook(postgres_conn_id=&#39;bde_default&#39;)<br>neo4j_hook = Neo4jHook(conn_id=&#39;bde_graph_default&#39;)<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: days_ago(2),<br>    &#39;email&#39;: [&#39;airflow@example.com&#39;],<br>    &#39;email_on_failure&#39;: False,<br>    &#39;email_on_retry&#39;: False,<br>    &#39;max_active_runs&#39;: 1,<br>    &#39;retries&#39;: 3<br>}<br><br>def upsert_values(conn, df, table, pri_keys):<br>    tuples = [tuple(x) for x in df.to_numpy()]<br>    cols = &#39;,&#39;.join(list(df.columns))<br>    prikeys = &#39;,&#39;.join(pri_keys)<br>    query = &quot;INSERT INTO %s(%s) VALUES %%s ON CONFLICT (%s) DO UPDATE SET score = excluded.score&quot; % (table, cols, prikeys)<br>    cursor = conn.cursor()<br>    try:<br>        extras.execute_values(cursor, query, tuples)<br>        conn.commit()<br>    except (Exception, psycopg2.DatabaseError) as error:<br>        print(&quot;Error: %s&quot; % error)<br>        conn.rollback()<br>        cursor.close()<br>        return 1<br>    print(&quot;the dataframe is inserted&quot;)<br>    cursor.close()<br><br>def extract_pageranks():<br>    results = neo4j_hook.run(&quot;CALL gds.pageRank.stream(&#39;txGraph&#39;)\<br>         YIELD nodeId, score\<br>         RETURN gds.util.asNode(nodeId).address as address, score\<br>         ORDER BY score DESC&quot;)<br>    return pd.DataFrame(results)<br><br>with DAG(<br>    &#39;etl-pagerank&#39;,<br>    start_date=days_ago(2),<br>    default_args=default_args,<br>    max_active_tasks=3,<br>    max_active_runs=1,<br>    schedule_interval=timedelta(minutes=1),<br>    tags=[&#39;cardano&#39;,&#39;pagerank&#39;],<br>    catchup=False<br>) as dag:<br><br>    extract_pageranks_task=PythonOperator(<br>        task_id=&quot;extract_pageranks&quot;,<br>        python_callable=extract_pageranks<br>    )<br><br>    @task<br>    def load_pageranks(**context):<br>        conn = pg_hook.get_conn()<br>        pageranks_data = context[&#39;ti&#39;].xcom_pull(task_ids=&#39;extract_pageranks&#39;, key=&#39;return_value&#39;)<br>        pageranks_df = pd.DataFrame(pageranks_data, columns=[&#39;address&#39;, &#39;score&#39;]) \<br>                            .drop_duplicates(keep=&#39;last&#39;, inplace=False)<br>        upsert_values(conn, pageranks_df, &#39;address_pagerank&#39;, [&#39;address&#39;])<br><br>extract_pageranks_task &gt;&gt; load_pageranks()</pre><p>This can be run in the Airflow UI <a href="http://localhost:8080/"><em>http://localhost:8080</em></a>, by clicking ‘unpause’ or the run symbol of the DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-bZ_pV8cwqnr9uh-sA1QBQ.png" /><figcaption>Starting the DAG</figcaption></figure><p>And if you click on the DAG name, and select ‘Graph’ view you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PufODhWIt9p9Uflqt4QEMQ.png" /><figcaption>DAG executing correctly</figcaption></figure><p>From there you can look through ‘Logs’ and ‘XCom’ (cross task communications) data associated with individual tasks.</p><p>So we are again performing ETL mechanics within an Airflow microcosm this time interfacing with our graph oriented data in Neo4j and using an advanced data analytics technique to rank the connectedness of wallets. In the next part we’ll look through, visualise and briefly analyse the recently generated data using Jupyter Labs with Python and some popular plotting libraries as well as in the Neo4j browser.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dff408abcfe4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/getting-started-as-a-data-engineer-with-a-blockchain-scenario-part-xi-dff408abcfe4">Getting Started as a Data Engineer with a Blockchain Scenario — Part XI</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started as a Data Engineer with a Blockchain Scenario — Part X]]></title>
            <link>https://medium.com/towards-data-engineering/getting-started-as-a-data-engineer-with-a-blockchain-scenario-part-x-3cfea609f50a?source=rss-f40b51ecaf27------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cfea609f50a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Tim Edge]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 05:47:06 GMT</pubDate>
            <atom:updated>2025-03-25T05:47:06.902Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started as a Data Engineer with a Blockchain Scenario — Part X</h3><h4>Aggregation and Ranking of Data using Airflow</h4><p>Continuing on from <a href="http://localhost:3000/">Orchestration of Data Processing using Airflow</a> where we installed and configured Airflow as well as made sure we have a dataset ready to test with, the next objective is to perform micro ETL jobs on a scheduled basis to enrich the data we have, making it more useful for analysis and visualisation.</p><h3>Aggregation and Ranking of Data using Airflow</h3><p>Here we will perform some further filtering and aggregation of the <em>volumes</em> data we persisted in the last part.</p><p>We will aggregate volume quantities <em>by block</em>, as well as aggregation for all blocks by token. This will allow us to display a running ‘<em>Stack Area Chart</em>’, sorted by top all-time volume tokens.</p><p>This is an effective way to visualise changing dominance of volumes by token over time, however is just an example of what can be done through data enrichment and advanced analytics.</p><p>First, we’ll create some new tables in PostgreSQL, at this stage we are using a bit of foresight about what kind of output data we might encounter, however can always adjust these if needed later.</p><h4>Key capabilities of the snippets below:</h4><ul><li><em>VOL_BY_BLOCK</em> table is intended to hold unique token volumes per block. We expect to have many token ‘unit’ values per block and many blocks. This is an appropriate situation to use a ‘composite primary key’; <em>UNIT</em>, <em>HEIGHT</em></li><li><em>VOL_ALL_TIME</em> table is intended to hold a running total of a single Tokens volume to date. Thus we only need the tokens unit as the primary key</li></ul><p>From your PostgreSQL database shell bde=#</p><pre>DROP TABLE IF EXISTS VOL_BY_BLOCK;<br>DROP TABLE IF EXISTS VOL_ALL_TIME;<br>CREATE TABLE VOL_BY_BLOCK(<br>           UNIT TEXT NOT NULL,<br>           HEIGHT BIGINT,<br>           VALUE_ADJ FLOAT,<br>           primary key(UNIT,HEIGHT));<br>CREATE TABLE VOL_ALL_TIME(<br>            UNIT TEXT NOT NULL,<br>            VALUE_ADJ FLOAT,<br>            primary key(UNIT));<br>ALTER TABLE public.vol_by_block OWNER TO myuser; <br>ALTER TABLE public.vol_all_time OWNER TO myuser;</pre><p>Now to create the enrichment application, we will turn to Airflow. Airflow ‘applications’ are referred to as DAGs (Directed Acyclic Graph), meaning there’s a chain of actions in a determinate way.</p><p>We first need somewhere to store our DAGs, there are some different ways of doing this such as using a dedicated Github repository which helps with synchronising changes with distributed airflow worker(s). However, in this case all we need is to create a DAGs directory in your Airflow install directory. To make working with DAGs easier, just so we can manage the dags from our Integrated Development Environment (IDE), we will link that directory within the ‘blockchain-data-engineering’ project under a new directory called ‘airflow’.</p><p>From the project root blockchain-data-engineering</p><pre>mkdir -p $AIRFLOW_HOME/dags<br>mkdir airflow<br>ln -s $AIRFLOW_HOME/dags airflow/dags</pre><p>Now create our first DAG as a new file; airflow/dags/etl_vol_dag.py. Note, the real file location will be in <em>$AIRFLOW_HOME/dags</em>, however we can create it and manage it in the blockchain-data-engineering/airflow/dags linked directory.</p><p>And our DAG will be performing the following ETL pipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IrpJNL-8luAGFJZytB8ZOQ.png" /><figcaption>ETL Volumes DAG</figcaption></figure><h4>Key capabilities of the snippets below:</h4><ul><li>We create <em>dag</em> of type <em>DAG</em> and define various properties such as name and it’s schedule</li><li>We use the built-in Airflow Operator SQLExecuteQueryOperator as the first of our DAG tasks extract_vols() which simply pulls the volumes data that we persisted in the last part (i.e. volumes for every block and token)</li><li>We use the <em>@task</em> annotation to declare a particular custom function transform_vols_by_block() as an Airflow task. This function receives data from a separate task&#39;s return value via Airflow&#39;s cross communications (xcom) capabilities. After which it performs the familiar groupby sum type aggregation, seeking to collect total of all token values across transactions by block (we use block &#39;height&#39; to achieve this since within this blockchain, height is a consecutive number that uniquely identifies a block). Grouping by the composite key [unit,height], rather that transaction (hash) summarises this down to &#39;volumes&#39; by block (height) and token (unit)</li><li>The results are passed through to the load_vols_by_block() custom defined task intending to persist this data. We <em>could</em> us a built-in operator to simply dump the data in, however we will implement this <em>Load</em> with an SQL UPSERT via upsert_values() which has the advantage of inserting or overwriting and thus updating any existing data</li><li>We can see how <em>upsert</em> is achieved in PostgreSQL with the <em>ON CONFLICT (KEYS) DO UPDATE</em> pattern. On other databases it is similar but different e.g. MySQL; <em>ON DUPLICATE KEY UPDATE</em></li><li>We also briefly make use of the popular <em>numpy</em> capabilities for high performance matrix and array operations</li><li>Next we define another Airflow task transform_vols_all_time() aiming to find the total volume exchange per token, aggregating over all blocks and all transactions. This is just so we can have a holistic view of the highest volume tokens to use in out analysis and visualisations later</li><li>the final <em>task</em> is to ‘Load’ these volume totals, again we will upsert the values, and since we defined the upsert_values() function generically we can reuse it</li><li>Lastly, we order the DAG tasks based on the required flow, keeping in mind what tasks depending on what other tasks</li></ul><pre>from datetime import timedelta<br>from airflow import DAG<br>from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator<br>from airflow.providers.postgres.hooks.postgres import PostgresHook<br>from airflow.utils.dates import days_ago<br>from airflow.decorators import task<br>import pandas as pd<br>import psycopg2<br>import psycopg2.extras as extras<br><br>pg_hook = PostgresHook(postgres_conn_id=&#39;bde_default&#39;)<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: days_ago(2),<br>    &#39;email&#39;: [&#39;airflow@example.com&#39;],<br>    &#39;email_on_failure&#39;: False,<br>    &#39;email_on_retry&#39;: False,<br>    &#39;max_active_runs&#39;: 1,<br>    &#39;retries&#39;: 3<br>}<br><br>def upsert_values(conn, df, table, pri_keys):<br>    tuples = [tuple(x) for x in df.to_numpy()]<br>    cols = &#39;,&#39;.join(list(df.columns))<br>    prikeys = &#39;,&#39;.join(pri_keys)<br>    query = &quot;INSERT INTO %s(%s) VALUES %%s ON CONFLICT (%s) DO UPDATE SET value_adj = excluded.value_adj&quot; % (table, cols, prikeys)<br>    cursor = conn.cursor()<br>    try:<br>        extras.execute_values(cursor, query, tuples)<br>        conn.commit()<br>    except (Exception, psycopg2.DatabaseError) as error:<br>        print(&quot;Error: %s&quot; % error)<br>        conn.rollback()<br>        cursor.close()<br>        return 1<br>    print(&quot;the dataframe is inserted&quot;)<br>    cursor.close()<br><br>with DAG(<br>    &#39;etl-vol&#39;,<br>    start_date=days_ago(2),<br>    default_args=default_args,<br>    max_active_tasks=3,<br>    max_active_runs=1,<br>    schedule_interval=timedelta(minutes=1),<br>    tags=[&#39;cardano&#39;,&#39;vol&#39;],<br>    catchup=False<br>) as dag:<br><br>    extract_vols = SQLExecuteQueryOperator(<br>        task_id=&quot;extract_vols&quot;,<br>        conn_id=&quot;bde_default&quot;,<br>        sql=&quot;SELECT * FROM vol where value_adj != 0;&quot;,<br>        dag=dag<br>    )<br><br>    @task<br>    def transform_vols_by_block(**context):<br>        vols_data = context[&quot;ti&quot;].xcom_pull(task_ids=&quot;extract_vols&quot;, key=&quot;return_value&quot;)<br>        vols_df = pd.DataFrame(vols_data, columns=[&#39;hash&#39;, &#39;height&#39;, &#39;slot&#39;, &#39;unit&#39;, &#39;value_adj&#39;])<br>        by_block_df = (vols_df<br>                        .groupby([&#39;unit&#39;, &#39;height&#39;])[&#39;value_adj&#39;]<br>                        .sum()<br>                        .apply(lambda x: x / 1000000)<br>                        .reset_index())<br>        return by_block_df<br><br>    @task<br>    def load_vols_by_block(**context):<br>        pg_hook = PostgresHook(postgres_conn_id=&#39;bde_default&#39;, schema=&#39;bde&#39;)<br>        conn = pg_hook.get_conn()<br>        by_block_df = context[&#39;ti&#39;].xcom_pull(task_ids=&#39;transform_vols_by_block&#39;, key=&#39;return_value&#39;)<br>        upsert_values(conn, by_block_df, &#39;vol_by_block&#39;, [&#39;height&#39;, &#39;unit&#39;])<br><br>    @task<br>    def transform_vols_all_time(**context):<br>        vols_data = context[&quot;ti&quot;].xcom_pull(task_ids=&quot;transform_vols_by_block&quot;, key=&quot;return_value&quot;)<br>        vols_df = pd.DataFrame(vols_data, columns=[&#39;unit&#39;, &#39;height&#39;, &#39;value_adj&#39;])<br>        totals_df = (vols_df<br>                      .groupby([&#39;unit&#39;])[&#39;value_adj&#39;]<br>                      .sum()<br>                      .reset_index()<br>                      .sort_values(&#39;value_adj&#39;, ascending=False))<br>        return totals_df<br><br>    @task<br>    def load_vols_all_time(**context):<br>        conn = pg_hook.get_conn()<br>        all_time_df = context[&#39;ti&#39;].xcom_pull(task_ids=&#39;transform_vols_all_time&#39;, key=&#39;return_value&#39;)<br>        upsert_values(conn, all_time_df, &#39;vol_all_time&#39;, [&#39;unit&#39;])<br><br>    transform_vols_by_block_task = transform_vols_by_block()<br><br>    extract_vols &gt;&gt; transform_vols_by_block_task &gt;&gt; load_vols_by_block()<br><br>    transform_vols_by_block_task &gt;&gt; transform_vols_all_time() &gt;&gt; load_vols_all_time()</pre><p>This can be run in the Airflow UI <a href="http://localhost:8080/"><em>http://localhost:8080</em></a>, by clicking ‘unpause’ or the run symbol of the DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2MAvY6tnqq5ZcxF_htKGQ.png" /><figcaption>Starting the DAG</figcaption></figure><p>And if you click on the DAG name, and select ‘Graph’ view you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouBaGGROiRUo5UojzJQKIA.png" /><figcaption>DAG executing correctly</figcaption></figure><p>From there you can look through ‘Logs’ and ‘XCom’ (cross task communications) data associated with individual tasks.</p><h3>Extensions</h3><p>Airflow allows for other more advanced configurations including customising delays, retries and sending of notifications &amp; alerts. These will be discussed in further detail during the cloud deployment part(s) down the track.</p><p>For a real production deployment you will also need to consider testing and validation of DAGs and other code developed. There are a few examples of tests in the companion repository</p><p>So we are performing ETL mechanics within an Airflow microcosm and which acts downstream of the overall blockchain streaming ETL (e.g. the prior Spark Streaming ETL application). In the next part we’ll enrich our other graph dataset by finding the PageRank / Connectedness rankings of different wallets, again using Airflow for job orchestration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cfea609f50a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/getting-started-as-a-data-engineer-with-a-blockchain-scenario-part-x-3cfea609f50a">Getting Started as a Data Engineer with a Blockchain Scenario — Part X</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>