<?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 Guihcneves on Medium]]></title>
        <description><![CDATA[Stories by Guihcneves on Medium]]></description>
        <link>https://medium.com/@0xneves?source=rss-5fffaaaf5cb4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5OZVTlgrkRuqo73K</url>
            <title>Stories by Guihcneves on Medium</title>
            <link>https://medium.com/@0xneves?source=rss-5fffaaaf5cb4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 20:58:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@0xneves/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 Role of Tokenization in the Future of Money]]></title>
            <link>https://medium.com/blockful/the-role-of-tokenization-in-the-future-of-money-8fb2d693a8b6?source=rss-5fffaaaf5cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fb2d693a8b6</guid>
            <category><![CDATA[the-future-of-money]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[Guihcneves]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 17:47:18 GMT</pubDate>
            <atom:updated>2023-11-17T17:47:18.786Z</atom:updated>
            <content:encoded><![CDATA[<p>Blockchain predictions and the coming back of bartering!</p><h4>Money</h4><p>Money is a fundamental aspect of the economy, serving as the backbone for trade and the store of wealth during uncertainty. But what exactly is money, what functions does it perform in our society, and where is it heading?</p><p>At its core, money functions as a means of exchange, it simplifies the process of trading goods and services. Instead of relying on a barter system, where individuals exchange one product or service for another directly. It acts as an intermediary. It enables us to trade diverse items effortlessly, promoting economic efficiency and specialization.</p><p>One critical aspect of money is its universal recognition and acceptance as a medium of exchange. For a commodity to serve as money, it must be widely recognized and valued. This recognition establishes trust in the monetary system and allows people to confidently trade goods and services using money as an intermediary.</p><p>Money’s value is not inherent but rather a matter of perception. It holds value because people believe in its ability to facilitate transactions and store wealth. This subjective nature of value is what makes different forms of money work in our diverse world. As physical currency or cryptocurrencies.</p><p>In addition to facilitating transactions, money serves as a storehold of wealth. It allows individuals to save and preserve value over time. Money’s stability as a store of wealth is crucial in financial planning and long-term economic stability.</p><p>In some economic systems, money can be considered a commodity in itself. For example, precious metals like gold and silver have historically served as both money and commodities. Their intrinsic value adds an extra layer of complexity to the concept of money, as they are sought after for both their utility and their role as a medium of exchange.</p><h4>Markets</h4><p>Money not only facilitates trade but also encourages the division of labor and specialization. In an economy where money is the medium of exchange, individuals can specialize in their skills or professions. This specialization leads to increased productivity and a more efficient allocation of resources, ultimately benefiting society as a whole. Trade is a fundamental consequence of a monetary system. Money enables individuals, businesses, and nations to engage in cross-border commerce. This exchange of goods and services on a global scale fuels economic growth and has a profound impact on the standard of living for people worldwide.</p><p>Understanding the essence of money is rooted in the concept of the ‘coincidence of wants.’ It’s a simple yet powerful idea. You want the thing that I have and I have the thing that you want. Money solves this problem. Imagine a scenario where I make apples, and you make oranges. I want some of your apples, but you don’t want my oranges. This situation exemplifies the ‘coincidence of wants.’ What do I do? I find someone who wants my apples and has something you desire, perhaps bananas. I exchange my apples for their bananas, which you’re willing to accept. In this context, bananas become the ‘medium of exchange.’</p><p>Desires and capabilities are met in a system that exchanges those things, hence the natural phenomenon of markets. The minute you start recording a relationship between a creditor and a debtor, you have something quasi-money.</p><p>Market is the name for the naturally emergent phenomena of people voluntarily exchanging things, and then it scales. Could be three people on an island, could be 8 billion people around the planet. This is hard for many to understand, capitalism and markets are not something that you need a central planner or a government officer to make happen, capitalism is just what happens when people are left to their own devices, it’s just our cognitive capacity allows us to develop tools that we can use for production and that’s what humans have been doing since they made spears to hunt — that’s probably the first capital good. So we’re constantly accumulating capital and we’re constantly trading with one another, finding opportunities and matching supply and demand and money is what makes it so powerful. Money allows it to scale, it helps go beyond small societies into something global. Because with money, you just have to specialize in one thing, and you don’t have to worry about whether the other people involved in this “want what you have and have what you want”, you just sell it for money to whoever wants it and you buy whatever you want from whoever has it. And that is an enormous reduction in the mental burden of how a market economy functions.</p><h4>Project The Future</h4><p>The first thing about money is that it allows for the division of labor, and for the market system to grow and the second thing is that money is a mechanism for storing value for the future, so as humans we develop the capacity to think for the future — we make spears so that we can hunt, if that works, we take out of the animal we hunted and we keep it for the next day’s hunt. From that, we make a better spear and a better fishing rod, a fishing net, fishing boat, and that’s our ability to think of the future. As we start building durable goods, we start thinking more and more of the future, we start becoming more future-oriented and that’s the process of civilization, the process of denying our needs now in order to think for the future.</p><p>Money ends up being the best mechanism for providing for the future. Because the future is uncertain, you know you can save your apples and oranges, the spears, the animal you hunted; although these things will rot and their value over time will not hold or even if, more durable materials, you can’t tell if you’re gonna need tomorrow or in the next year. Thus money allows you the optionality of saving the most liquid good, the most saleable good, something that you can sell tomorrow with the least uncertainty.</p><p>Money is our most advanced technology and our best technology for moving value into the future. So there is this process where our money gets harder (Bitcoin) — harder to produce — and it gets better at holding on to its value for the future and that allows us to plot for the future, makes it less uncertain, makes us more future-oriented, the harder the money is the better it is allowing us to think of the future.</p><h4>Scarcity</h4><p>Every currency has either ended as being a currency or devalued as a currency over long periods. So it evolved and it changed, but everybody needs that medium of exchange and that storehold of wealth… So it keeps changing what money is over a period of time.</p><p>Most people will realize the hardness and the scarcity, and choose them as money but money is a natural evolutionary process whereby people choose all kinds of random things as money. Those who end up making bad choices don’t end up with any wealth left whereas the people who store their wealth in the hard things to make end up maintaining their wealth and maybe even increasing it over time.</p><p>We’ve seen this happen before, culminating at the end of the 19th century, the entire planet was on a gold standard, which is basically when money is gold or at least government currencies backed by gold. The reason gold became money and not copper, not nickel, not bananas is that gold is the hardest metal in the world and it is the hardest metal to increase the supply of, and the reason for that is based on chemistry. Gold is indestructible, you can’t destroy gold in any meaningful sense, it’s been basically accumulating stockpiles for thousands of years.</p><h4>Infinite Money Glitch</h4><p>With the advent of the internet was born a need for a means of payment native to the internet, because typing your credit card number into a random website is not the way to pay for things on the internet and Bitcoin shows itself as the first iteration, the first attempt to solve the problem of “how do we pay for things” in what we must learn to call the Metaverse — We realize this as we see that Facebook quickly embraced this new concept into becoming Meta. Ever since that initial innovation the realization that you could use computing power and cryptography to create peer-to-peer payments without third-party verification triggered a revolution that has been gathering momentum, that poses a very profound threat to the existing legacy system of banks and and fiat currencies.</p><p>Most money in the world today is made by banks, not central banks. That’s what most money is, it’s entries in bank accounts. This process is often referred to as “fractional reserve banking.”</p><p>Commercial banks create money through the act of lending. When a bank issues a loan, it essentially creates a deposit in the borrower’s account. This deposit can then be used by the borrower to make payments, which in turn become deposits in other accounts, leading to a multiplier effect.</p><p>Central banks primarily control the money supply and interest rates, but they do not directly create money in the same way that commercial banks do. They can influence the money supply by setting reserve requirements and interest rates, but the actual creation of money occurs in the private banking sector through lending and deposit activities.</p><p>Those currencies that have maintained their value, those playing substantial roles in global trade, and those serving as currency reserves worldwide share a common characteristic: they exhibit the lowest supply growth rates. Their central banks practice the least inflationary policies. On the contrary, currencies with more inflationary supply growth patterns, similar to commodities like copper, often experience failure.</p><h4>Bitcoin</h4><p>What Bitcoin represents is an alternative mode of payment that should render banks obsolete. This financial revolution has progressed beyond the point where it can be halted. While it was vulnerable in its early years, it has now gained sufficient adoption and additional layers. Ethereum, in many ways, is the more important innovation because it allows the creation of an entire system of payments and, ultimately, smart contracts on top of it. It’s challenging to envision it being completely eliminated at this stage, especially after surviving significant challenges, such as China’s attempts to shut down mining and operations.</p><p>Cryptocurrencies are thriving. However, what remains uncertain is the potential damage that ill-conceived regulatory interventions might inflict on this financial revolution. Left to its own devices, decentralized finance provides a native, internet-based financial system. As we spend more time in the Metaverse, we will likely make greater use of it.</p><p>The internet’s economic landscape is evolving rapidly, and in parallel, we see a payments revolution unfolding. These two dynamics complement each other, generating substantial wealth in the process. The challenge lies in the fact that some in Washington have a strong urge to intervene and disrupt this evolutionary process. This might be due, in part, to a misguided belief that nefarious activities abound unless they step in. This overestimates the extent of criminal activity in the space and also involves vested interests.</p><h4>Blockchains and CBDC</h4><p>Central Bank Digital Currency (CBDC) is being presented as a counterproposal. However, it is a concerning idea, particularly if it resembles the Chinese model, which places all transactions under the direct surveillance of a central government institution. On one side, we have a relatively decentralized, technologically innovative, internet-native payment system with the potential to evolve and reduce transaction costs significantly by eliminating intermediaries. On the other side, we have a highly centralized system in which transactions are, by default, subject to central bank surveillance.</p><p>In considering the future of currency, the presence and strength of fiat currencies like the US dollar, Euro, and Yen — traditional currencies, backed by governments — are expected to continue to evolve by digitizing in response to changing times. However, there is also a strong belief in cryptocurrencies’ pivotal role in offering a reliable alternative. These digital assets, with their global neutrality, provide a consistent option, particularly in scenarios of high inflation, financial system disruptions, or trade disturbances.</p><p>Only time will tell if cryptocurrencies will become the main trend among people, while such a future is conceivable, it’s acknowledged that cryptocurrencies, notably Bitcoin and Ether, face the significant challenge of achieving greater price stability to be widely adopted. This conversation underscores the notion that, in the context of the history of money, cryptocurrency is still in its early days.</p><p>The inherent volatility in the demand for currency is due to economic fluctuations, technological advancements, and other factors. In cases where a currency maintains a fixed supply, changes in demand lead to substantial price volatility. However, the ideal currency, and one that cryptocurrencies should aspire to be, is characterized by supply flexibility. This means that supply can adjust according to shifts in demand, thereby mitigating price volatility.</p><p>Bitcoin, one of the prominent cryptocurrencies, is known for its specific fixed supply. Ethereum, on the other hand, offers a bit more flexibility in its supply. However, the ultimate goal is to develop a currency that is both flexible and responsive to changes in its perceived value, a characteristic that would contribute to its broader adoption and utilization in the evolving landscape of finance.</p><p>As the world of currency continues to transform, the journey of cryptocurrencies from their early days to a more stable and widely accepted form of value remains a fascinating and uncertain path, driven by the quest for stability, flexibility, and enduring relevance in the financial realm. This current paradigm will rather just keep developing itself into a multi-faceted answer as there is not a better solution but rather a combination of specialized optionality that will thrive in the future.</p><p>We can envision a future where blockchains, particularly those with advanced capabilities, play a vital role in the global economy. Smart contracts and decentralized finance (DeFi) platforms are poised to revolutionize how we conduct financial transactions, offering efficiency, security, and transparency previously unattainable but knowing that it will be inevitable to avoid privacy in its core business model when it comes to governments and certain centralized institutions. By realizing that strengthening policies on top of blockchain usage, providers and oracles shift their initial propaganda of decentralization into a more fashioned centralized one. Some household names like Consensys and Chainlink currently benefit from their data gathering from their applications, such as IP addresses from Metamask users.</p><p>Now this is a two-edged blade. Governments could easily use their policies to track your activities by requesting the provider, which would openly collaborate. While advertisements with the data collected have become a common narrative in modern days, the same tracking is susceptible to falling into the hands of bad actors, which could negatively affect your personal life. For some people, the real fear, the enemy out there, is merely other people, and not the government. Thus supply meets demand as the Zero Knowledge Proofs becomes the narrative for the next Bull-run, providing a cutting-edge privacy technology that can be validated in a decentralized manner.</p><h4>Zero Knowledge</h4><p>Ethereum scalability is a major challenge facing the blockchain industry, the network struggles to handle the increasing demand for transactions is merely an advertised campaign. ZK has been around before the 2000s. ZK-rollups are a promising solution to this problem, as they allow thousands of transactions to be executed off-chain and then submitted for verification on Ethereum. ZK-rollups are already being used in several Ethereum scaling protocols such as StarkNet, zkSync, Aleph Zero, and more upcoming blockchains that will embrace the ZK-EVM narrative.</p><p>It’s becoming common ground among most notorious crypto-experts that if your blockchain cannot be upgraded or contributed to Ethereum using ZK-EVM technology or any scalable and verifiable solution, you will become obsolete. The narrative shifts strongly to the point where people are building an Ethereum “inside” Solana, and talks are being hosted about how can Solana scale Ethereum in the future. And this is not just about Solana but is a very prominent talk in other blockchains.</p><p>Blockchain narrative for the upcoming years will be volatile and inevitably things will catch the masses by surprise. But some aspects can already be seen as fixed in time. Ethereum is the ultimate data availability, it is the ultimate source of truth for the blockchain ecosystem. Zero-knowledge will reduce computational power drastically, and fees will become reduced to a point where we’ll need discussions on how to monetize the computational power that will not be necessary in the future. Optionality for public and private interactions will be a feature. Cross-liquidity will become a widely known term across the industry, boosting liquidation mechanisms across multiple chains in its truly decentralized and verifiable aspect powered by the ZKP technology.</p><p>The significance of Zero Knowledge Proofs in the upcoming market cycle becomes evident. A retrospective analysis reveals that each historic all-time high in the blockchain ecosystem was underpinned by a fresh technological narrative.</p><h4>Context and Predictions</h4><p>In 2013, it was the surge of P2P transaction systems that perfectly allowed the exchange of value between two parties and turned the middle-man into a distributed network;</p><p>2017 marked the advent of Smart Contracts, leading the maturity era of DeFi, where gamified concepts were developed into financial instruments that would facilitate the payment layer for applications, and in the process, deliver a standard that everyone could follow;</p><p>2021 witnessed the flourishing role of NFTs, which “minted” the Decentralized Application Era (dApp). Applications could provide tokenized products and services to its customers, facilitating known businesses to expose their activities on-chain, such as clinical reports, event tickets, and synthetic tokens as in real-world assets (RWA);</p><p>Looking ahead into 2025 with an optimistic eye, the emergence of ZK-EVM and the introduction of the Bitcoin ETF are ready to reshape the landscape of blockchains, paving their path for legal acceptance and mass adoption. Banks and institutions will offer DeFi-level incentives to their customers since they have gained the tools and legal frameworks to govern their blockchain endeavors;</p><p>Fast forward to predicting 2029, we’ll see the full dApp and Tokenization (RWA) cycle, with blockchain adoption becoming not just a promotional narrative but a “must” in the tech space, encouraging other businesses to invest for the publicity as well as the potential profits and security. In this cycle, we’ll see exponential growth, and blockchain concepts previously known by the public as a “money” instrument will be recognized as the technology it is and the taboo will finally be over — not for the skeptics;</p><p>By 2033, Central Bank Digital Currencies (CBDCs) are set to proliferate globally, significantly impacting the world’s economy. The ensuing years will see narratives shifting towards heavy industrial utilization and supply chain integration. Oppression against decentralized wallet providers will remain a narrative as CVC Mixers would be heavily used by good and bad actors to hide their agenda from governments and mega-corporations.</p><p>With 2037 marking the industrial age of blockchain. Not just ideas and small projects, but a wide adoption following IOT, imbuing their machinery’s software with blockchain technology by default. It will extend its influence into sectors like automotive, agriculture, and food supply. While also playing a pivotal role in the gaming industry. As we progress, technological advances will reduce computation power and enable even the recording of mouse movements on the blockchain and the very structure of the internet itself;</p><p>2041 will be the last year before the singularity year, where the supply chain will be interconnected and monitored by AI under the control of mega-corporations, governments, and users of the decentralized and underground crypto environment. Of course, this is just my perspective about the future of blockchain, it is merely speculation based on my current knowledge of the matter.</p><p>Concerns regarding quantum security are prospected by international media among many other attempts to deceive the general public into fleeing cryptocurrencies. However, these apprehensions, for the most part, remain more theoretical than immediate, as the requisite computational power necessary to breach blockchain technology is currently far from attainment. Even if one were to embark on the monumental task of generating every conceivable public key within the Ethereum Mainnet — a vast number in the vicinity of 1.16 x 10⁷⁷ — the endeavor would prove impossible, rendering the likelihood of successful withdrawals virtually nonexistent since you still require more complex trials to search the wealth in each account’s custody.</p><p>It is worth noting that the implementation of account abstraction — which is coming soon — wherein a public key is devoid of tangible assets but serves as a simpler signer for smart contracts, substantially diminishes the susceptibility to quantum threats. Employing multi-signature security measures further fortifies one’s defenses indefinitely, as large players such as Gnosis are at the forefront of this technology. Moreover, Ethereum’s inherent upgradability affords the prospect of future quantum-proofing, achieved by augmenting the complexity of random number prediction, thereby ensuring robust security. Nevertheless, regarding quantum propaganda, I can assure you that right now, regular banks will be more targetable than the average crypto wallet but this concept will shift as banks are racing to use DeFi, if not for the yield, then merely for savings on their daily transactions.</p><h4>From Finance to Decentralized Finance</h4><p>When the first western high street bank begins to offer DeFi level interest rates to their customers — such as the ETF approvals that are running on the stream media — the floodgates will open, and all banks will implement the technology, shaking up councils and governments across the world as the race for blockchain expands in all directions: the decentralized realm and the centralized domains governed by policymakers and mega-corporations, which define the rules for its utilization.</p><p>Decentralization is measured on a spectrum, with full DeFi providing little to no safety in the form of customer service, while the centralized counterpart provides a more familiar, safer space, but with less flexibility and control over the user’s funds.</p><p>Those who are brave enough to look the zeitgeist in the eye and deviate from the media-oriented narrative will reap huge rewards over the coming years. The most disciplined minds will verify the source of truth while others will scroll endlessly into their social media feeds. Visionaries who ignited the early flames of the Blockchain are not surprised to see the turning heads of the doubtful elite. A stubborn few still remain with their backs to the blaze, seemingly prepared to stay that way until they are engulfed by the advancing inferno. We are at boiling point, the time has come to let loose the financial revolution. Burnt by the growing heat of the technological furnace. The closest skeptics melt away, sneers turn to self-seeking strategy, and cynics cry for redemption or amnesia as they shun their past beliefs and join the line to fuel the fire.</p><h4>Money is Belief</h4><p>Society has started a money race, and all sorts of money will emerge and compete for its technological properties. There will be many types of money, not just fiat, not just Bitcoin, but with the tokenization and connectiveness of everything, it might become a narrative to turn anything into money. Maybe even unifying all types of money using the same liquidation standard might bring us closer to ceasing money (Token Standard?). Now tell me, can you imagine a world without money? Where value can be quantified precisely?</p><p>We are currently operating on the fiat standard, where money holds value. In this context, paper money has value because we collectively believe it does. The belief in the value of something is, in itself, a form of value. It’s this belief that underpins the functionality of money. The belief in the worth of money is, in fact, valuable. The crucial question becomes: How much value can we attribute to this belief in the context of money’s functionality, can we quantify the value of the belief?</p><p>In economic reality, the beliefs are rewarded when they match up with the economic reality, and they are punished when they don’t. So if economic reality changes in a way that everything is available on-chain, and we use computational power to precisely measure relations on the supply chain, our beliefs will then, mostly rely on trusting this computational system and its decisions, and will be punished if we don’t. Hence some famous movie ideas such as The Exterminator or The Matrix were conceived.</p><h4>The End of Money</h4><p>In a future where economic reality relies on data and data processing for decision making and as atomic liquidations of real-world assets and digital tokens become common ground — with the help of personal AI describing our daily and future needs, we might see a strange phenomenon as bartering becomes the narrative once more. Stablecoins or stable tokens might remain active for those seeking stability during the ownership transition or simply due to the known uncertainty of time. But as time becomes more certain due to the precision of the supply chain, and our uncertainty fades away, will we need to save wealth in the format of money? It becomes automatically viable because the computer can predict our needs, and then match our needs and desires according to the value we generate for society. Will we actually need to generate value and life becomes boring?</p><p>Will our capabilities allow us to keep simulating until prediction is achieved? As it was first discussed here, money helps to scale markets due to the division of labor and storage of wealth. If we don’t have to work for society anymore, or store wealth, why would we need money?</p><h3>Stay Connected 🌐</h3><h3>Follow us on social media for more updates and content:</h3><ul><li><a href="https://twitter.com/blockful_io">Twitter</a> 🐦</li><li><a href="https://instagram.com/blockful.io">Instagram</a> 📸</li><li><a href="https://www.linkedin.com/company/blockful">LinkedIn</a> 💼</li><li><a href="https://www.youtube.com/channel/UCDU-ZFj-n7L4TohZtygslsQ">YouTube</a> ▶️</li></ul><h3>Join our community on:</h3><ul><li><a href="https://discord.gg/35WsFPYNT2">Discord</a> 🎮</li><li><a href="https://t.me/+ELs4xdxB7rs2ZTcx">Telegram</a> 📢</li></ul><p>For more insights and discussions about blockchain and technology, visit <a href="https://blockful.io/">Blockful</a> 📚🔗.</p><p>Together, let’s explore and build web3 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fb2d693a8b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blockful/the-role-of-tokenization-in-the-future-of-money-8fb2d693a8b6">The Role of Tokenization in the Future of Money</a> was originally published in <a href="https://medium.com/blockful">Blockful</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preparing your Audit with Blockful]]></title>
            <link>https://medium.com/blockful/preparing-your-audit-with-blockful-5701149c9763?source=rss-5fffaaaf5cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5701149c9763</guid>
            <category><![CDATA[audit]]></category>
            <category><![CDATA[auditing]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Guihcneves]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 06:17:54 GMT</pubDate>
            <atom:updated>2023-08-09T06:17:54.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*tO5jZbJUY3UxfulMw75S0Q.png" /></figure><h3>Understanding the audit process</h3><p>Understanding the audit process is crucial for ensuring a successful smart contract audit. A smart contract audit refers to the process of scrutinizing the underlying code of a smart contract to identify and rectify any security vulnerabilities, errors, or inefficiencies. This audit is designed to guarantee that your contract operates as expected, offers robust security, and is fully compliant with industry standards and best practices.</p><h4>The following evaluation criteria will be considered:</h4><ul><li>Ensuring contract resilience against attacks.</li><li>Ensuring adherence to best practices.</li><li>Ensuring the contract’s logic achieves the client’s objectives.</li><li>Ensuring detailed manual review of each line of code.</li></ul><h4>Within the following categories:</h4><ul><li>Readability: Evaluates if the smart contract code is clear and easy to understand.</li><li>Optimization: Examines the contract’s efficiency in terms of resource utilization.</li><li>Logic: Reviews if the algorithm’s architecture aligns with the context.</li><li>Critical: Identifies the most urgent aspects affecting the contract’s core execution.</li></ul><h3>Awareness of vulnerability classes</h3><p>When conducting a smart contract audit, it is important to be aware of different vulnerability classes that may be present in the code. These vulnerability classes help identify the severity and impact of potential issues and guide the prioritization of fixes. Here are the vulnerability classes commonly considered in smart contract auditing:</p><h4><strong>Critical:</strong></h4><ul><li>These issues compromise the usability of the code based on the provided context.</li><li>Examples include vulnerabilities that can lead to unauthorized access, hacking, or fund loss.</li><li>Critical issues require immediate attention and resolution to ensure the security and integrity of the contract.</li></ul><h4><strong>Big:</strong></h4><ul><li>Issues in this class do not compromise the main context of the contract but are exploitable or involve high human risk.</li><li>While they may not directly harm the core purposes of the protocol, they still pose a significant threat and should be addressed promptly.</li></ul><h4><strong>Medium:</strong></h4><ul><li>Medium issues typically involve contract logic and may impact on functionality or efficiency of the contract.</li><li>These issues do not compromise the contract execution but point to faulty architecture.</li></ul><h4><strong>Small:</strong></h4><ul><li>Issues in this class do not harm the code in terms of logic or compromise its execution.</li><li>They are often related to gas savings, code readability, or best practices.</li><li>While not critical, addressing small issues can improve the overall quality of the code.</li></ul><h4><strong>Informational:</strong></h4><ul><li>These issues do not affect the execution code but serve to create awareness of code documentation and the context of the project.</li><li>Informational issues may include missing or incomplete documentation, inconsistent naming conventions, or other non-critical observations.</li></ul><h3>Best Practices</h3><p>The initial destination for any developer aiming to comprehend a project is its documentation, and this sentiment is shared by our auditing team as well. Possessing a foundational grasp of the system’s structure and design empowers our team to effectively delve into the codebase scheduled for auditing.</p><p>The documentation must be lucid, and all-encompassing, and strive to elucidate the functioning of their systems. It’s crucial that this documentation remains precise, readable, and up-to-date, ensuring that auditors can fathom the rationale behind the code’s creation. Explore our essential requirements for proper documentation:</p><h4><strong>Readme:</strong></h4><p>Usually, the README is the initial file that individuals are interested in when understanding a project or repository. It’s a text document encompassing vital details such as the project’s description, along with instructions for building and running it. Given that the README file is frequently the primary stop for anyone exploring a project, maintaining its cleanliness and providing comprehensive information is crucial for making a positive initial impact.</p><h4><strong>Technical Document:</strong></h4><p>A summary of the systems, the issue that the project seeks to address, and the planned capabilities of the various components within the system. Can be in the form of Tokenomics or a Gitbook-like documentation.</p><h4><strong>Code Comments:</strong></h4><p>The foundation of optimal coding practices. Making certain that your code includes thorough comments will aid auditors in comprehending the code’s objectives and pinpointing any potential issues it might encompass. Code comments streamline and contribute to the smooth progress of the audit process.</p><h4><strong>Redundant Code:</strong></h4><p>As the development process progresses, certain sections of code might become outdated. While these obsolete areas could be easily identifiable to the developers responsible for writing the code, they might not be as apparent to our auditing team during an audit.</p><p>Eliminating unnecessary code and comments will ensure that auditors can concentrate on pertinent information and not get distracted by irrelevant particulars.</p><h4><strong>Quality of Code:</strong></h4><p>Quality code can assist in ensuring an efficient audit. With a high-quality codebase, our auditors can focus on the code itself, rather than being preoccupied with attempting to uncover the meaning behind a particular code piece.</p><h4><strong>Style Consistency:</strong></h4><p>Having a code of high quality can greatly facilitate a thorough audit process. When the codebase is well-crafted, our auditors can dedicate their attention to the code’s content, rather than expending effort on deciphering the intent behind specific code segments.</p><h3>First Analysis and proposal</h3><p>Each project has its own perks and difficulties lying ahead, meaning the audit is dynamic, but the formulation of the processes is static. Following is the step-by-step description of Blockful behavior and recommendations when understanding how to analyze and formulate a fair audit process:</p><h4><strong>First Call:</strong></h4><p>A call with our experts will quickly trigger the start of the audit process and the clock will be running for both parties to settle. Among the parameterizations of the partnership, the following aspects will be covered:</p><ul><li>Every call will be recorded to track the path of decision-making between both parties.</li><li>This document will be introduced previously or at the time of the call.</li><li>Previous public audits will be shared if requested to better comprehend the process.</li><li>The Blockful method and the client s challenges will be discussed to smooth a deal.</li></ul><h4><strong>Received Files or Forked Repository:</strong></h4><p>By sharing with Blockful the repository or files relating to the audit, make sure it follows the guidelines. Blockful can become part of the context and comprehend the protocol to a point where it becomes able to describe and offer the method as the audit service. After the first interview, Blockful will ask for access to such documents which will vary depending on the client’s need.</p><h4><strong>Analysis of the Context:</strong></h4><p>Blockful experts will narrow the project goals and align with the client before formalizing a proposal. The context given as the Tokenomics, online documentation, or a very well-explained README.md file will be deeply studied.</p><h4><strong>Analysis of the Repository:</strong></h4><p>With the context in mind, Blockful will overview the codebase and take notes about the fluxes. Mostly focused on economic agents and code quality. Each file will be reviewed and accounted for in the proposal as a stipulation in hours based on previous performance and expectations.</p><h4><strong>Formulation of the Proposal and Code Freeze:</strong></h4><p>With the context and code review well made, Blockful will have the proposal formulated and a meeting with the client will be summoned, to discuss hourly rates, duration, and next steps.</p><p>The root folder shared with Blockful containing all documents will be hashed using the sha3 algorithm to determine the codebase checkpoint. At this point, there are no more alterations to be negotiated and a new audit must be made to address new changes.</p><h4><strong>Start the Audit:</strong></h4><p>Blockful uploads the project in its test and configure the environment conditions for the contracts. A fuzz test will be made to exploit all values and types, searching for bad executions and logging the results, converting them into a described resolution about the discoveries.</p><p>Line-per-line as a static method will be used to review every single byte of the contract. This is a manual process and requires tremendous concentration, knowledge, and impartiality.</p><h4><strong>Channel on Notion:</strong></h4><p>All discoveries and code suggestions will be classified and described in the Notion App, an online software where Blockful will keep the audit’s registry. The page is shared with the client from day one to the last day of the audit. Because of this, Blockful has exposure to its methods since the beginning.</p><p>The client can comment on the process and hold an asynchronous conversation while Blockful proceeds with the audit. Have in mind that the communication and agreement process over the suggestions is slow and that the Notion progress should not be understood as definitive until the last step.</p><h3>First suggestions</h3><p>Blockful works with a one-review-only method. The client has access to the audit process in the Notion app and we assume the suggestions and the client’s concerns were being worked on during the audit process.</p><h4><strong>First Suggestion for the Audit:</strong></h4><p>The longest process is the first suggestion, it comes in the aspect of new horizons for both Blockful and the client, because it usually introduces coverage of up to 80% of the entire audit process.</p><p>Blockful will categorize all found issues by severity level and type. All critical issues will have their own tests. They are shared with the client where he’ll be able to reproduce the issue in his own local environment.</p><h4><strong>Meeting and Q&amp;A:</strong></h4><p>The client can summon a call with Blockful after the audit has been reviewed on Notion. The client should bring his questions and concerns regarding the process or method to be discussed in the meeting.</p><h3>Work on review and Deliverable</h3><p>The last review of the audit will match the client’s last concerns with the designated issues pointed at Notion. No more reviews beyond this point. Any new additions beyond the issue scope — changing architecture, adding functions — will only be considered if a re-quote is made.</p><h4>Blockful Rework on Agreed Review</h4><p>After the client has brought his concerns and suggestions, Blockful will analyze the client’s review and smooth the agreed outputs of the audit, having in mind it must follow safe standards and best practices.</p><p>At this point, all major critical issues will probably be addressed and the discussion will be rather about how low severity and informational issues should be represented in the final report.</p><p>In certain cases, the final goal of the client might change in a way that some addressed issues might be taken out of the audit scope, due to not being considered an issue anymore in that context. Having in mind that taking away part of the scope is a common practice while adding more scope will require a re-quote.</p><p>Blockful might have understood something wrong during the audit process, so it&#39;s crucial that the client is in agreement with the result of the audit.</p><h4>Deliver Audit PDF</h4><p>The last step is the official documentation with the final result of the audit. Blockful will transcribe all historical development and resolutions into a sweet report showcasing the exercise results. The client can publicly share the document as it pleases. Blockful will not deliver a new version or rework any changes after this step.</p><h3>Stay Connected 🌐</h3><h3>Follow us on social media for more updates and content:</h3><ul><li><a href="https://twitter.com/blockful_io">Twitter</a> 🐦</li><li><a href="https://instagram.com/blockful.io">Instagram</a> 📸</li><li><a href="https://www.linkedin.com/company/blockful">LinkedIn</a> 💼</li><li><a href="https://www.youtube.com/channel/UCDU-ZFj-n7L4TohZtygslsQ">YouTube</a> ▶️</li></ul><h3>Join our community on:</h3><ul><li><a href="https://discord.gg/35WsFPYNT2">Discord</a> 🎮</li><li><a href="https://t.me/+ELs4xdxB7rs2ZTcx">Telegram</a> 📢</li></ul><p>For more insights and discussions about blockchain and technology, visit <a href="https://blockful.io/">Blockful</a> 📚🔗.</p><p>Together, let’s explore and build web3 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5701149c9763" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blockful/preparing-your-audit-with-blockful-5701149c9763">Preparing your Audit with Blockful</a> was originally published in <a href="https://medium.com/blockful">Blockful</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Central Bank of Brazil confirmed its digital currency will be called $DREX]]></title>
            <link>https://medium.com/blockful/central-bank-of-brazil-confirmed-its-digital-currency-will-be-called-drex-a50f55371e12?source=rss-5fffaaaf5cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a50f55371e12</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[brasil]]></category>
            <category><![CDATA[cbdc]]></category>
            <category><![CDATA[drex]]></category>
            <category><![CDATA[brazil]]></category>
            <dc:creator><![CDATA[Guihcneves]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 00:38:35 GMT</pubDate>
            <atom:updated>2023-08-08T22:30:37.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKNZrBEZHAmJ-7G5JgVVSw.png" /></figure><p>Central Bank Digital Currency (CBDC) is a digital currency issued by a country&#39;s central bank. It is a tokenized form of the money we are familiar with, such as fiat money. The concept of CBDC aims to streamline transactions and enhance financial inclusion. Brazil is one of the countries exploring the development of a CBDC called the Digital Brazilian Real. The Central Bank of Brazil (BCB) has been working on developing the CBDC and has selected 14 institutions, including major local private banks, the largest public Brazilian bank, and multinational companies, to participate in the pilot of the CBDC.</p><p>CBDC technology can potentially improve financial infrastructure, programmability, and encryption. It serves as a public infrastructure for exchange and contract execution, enabling the creation of new applications. Example use cases highlight the potential of CBDC technology, such as how CBDC can improve existing subsidized credit policies, how decentralized finance tools can match small and medium enterprise borrowers with foreign investors, and how to improve real assets ownership transfers.</p><p>Digital currencies like CBDC can potentially reduce the use of cash and increase welfare. A sufficiently attractive digital currency reduces holdings of both cash and bank deposits. Since cash use is costly, digital currency may increase welfare.</p><p>CBDCs can create greater resilience for domestic payment systems and foster more competition, which may lead to better access to money, increase payment efficiency, and lower transaction costs. CBDCs can also improve transparency in money flows and help reduce currency substitution (when a country uses a foreign currency instead of its own).</p><p>The banking system in Brazil operates with three forms of money: fiat money, bank deposits, and bank reserves. These forms are convertible to each other. The central bank buys bonds from commercial banks and issues bank reserves, which go to the commercial bank&#39;s balance sheet. The commercial bank can issue bank deposits based on the amount of bank reserves. For example, when Joãozinho takes a loan to buy a bakery, the bank deposit is transferred to Joãozinho’s bank account and can be converted into currency at any time.</p><p>The proposal for CBDC is to “tokenize” these bank reserves directly, allowing individuals to have accounts at the central bank and transact bank reserves directly. This would make it easier for the central bank to track peer-to-peer transactions and reduce the possibility of money laundering. Transactions would be fast, simple, and secure. However, it is important to note that with CBDC, the government would access individuals’ consumption patterns and assets, raising privacy concerns.</p><p>CBDC technology can potentially revolutionize how we transact and interact with money. Brazil is one of the countries that have been exploring the development of a CBDC, and the potential benefits of CBDC technology in Brazil include improving financial infrastructure, programmability, and encryption. While there are concerns about privacy and government access to individuals’ consumption patterns and assets, the potential benefits of CBDC technology cannot be ignored.</p><h3>DREX</h3><p>In an exciting development, Brazil’s Central Bank (BC) has officially announced the name of its forthcoming digital currency. The virtual currency, equivalent to money in circulation, will be called DREX. The BC economist Fabio Araujo, the initiative&#39;s coordinator, confirmed the name during the monetary authority’s weekly live session on YouTube.</p><h3>Banco Central BR on Twitter: &quot;O projeto de moeda digital de banco central (CBDC), criado e operado pelo Banco Central do Brasil, chama-se Drex. pic.twitter.com/n6L8mAeGUG / Twitter&quot;</h3><p>O projeto de moeda digital de banco central (CBDC), criado e operado pelo Banco Central do Brasil, chama-se Drex. pic.twitter.com/n6L8mAeGUG</p><p>The name “DREX” holds significant meaning, with each letter representing a key aspect of the digital currency. The “D” stands for digital, highlighting the currency’s digital nature. The “R” represents the real, official currency of Brazil. The “E” signifies electronic, emphasizing the electronic nature of the currency. Lastly, the “X” conveys the idea of modernity and connection while paying homage to Pix, Brazil’s instant transfer system launched in 2020.</p><p>The introduction of DREX is expected to bring about numerous benefits for Brazilians. The BC stated that the digital currency, previously referred to as Real Digital, will provide a safe and regulated environment for the generation of new businesses. It aims to offer more democratic access to the benefits of the digitalization of the economy for both citizens and entrepreneurs.</p><p>The BC has been diligently developing DREX, with plans for a scheduled launch in 2024. The digital real is designed as a wholesale form of central bank money, primarily intended for settling interbank transactions. Banks&#39; involvement in the solution&#39;s development is a key aspect of Bacen’s strategy, ensuring that lenders play a significant role in implementing the digital currency.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F253qlxanAK4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D253qlxanAK4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F253qlxanAK4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4f1e128bce503fb406b4502d947864c/href">https://medium.com/media/b4f1e128bce503fb406b4502d947864c/href</a></iframe><p>To facilitate the pilot version of DREX, the BC has selected 14 financial institutions to participate in the program. These institutions include major local private banks such as Bradesco, Nubank, Itaú Unibanco, Banco do Brasil, and the local stock exchange B3. Multinational companies like Visa and Microsoft have also been chosen to participate in the pilot program.</p><p>The introduction of DREX aligns with the global trend of exploring central bank digital currencies (CBDCs). CBDCs have gained significant attention worldwide, with each project taking a unique approach. In Brazil, the BC aims to achieve what Pix did for retail payments, commoditizing financial services and providing a common infrastructure with programmability and composability. The BC envisions a future where banks’ balance sheets can be completely tokenized, offering enhanced efficiency and accessibility.</p><p>As Brazil prepares to launch DREX, it joins the ranks of countries embracing the potential of CBDCs. The digital real has the potential to revolutionize the Brazilian economy, promoting financial inclusion, improving payment solutions, and fostering new business opportunities. With DREX, Brazil is taking a significant step towards a more digital and connected future.</p><h3>Applications</h3><p>Unlike cryptocurrencies, whose price is tied to demand and supply and has a lot of volatility, Drex will have the same value as the Brazilian real. Each BRL 1 will be worth 1 Drex, with the digital currency guaranteed by the Central Bank, while cryptocurrencies are not guaranteed by any monetary authority.</p><p>Drex will function similarly to Pix in practice but with different purposes and value scales. While Pix is mainly used for commercial transactions and obeys security limits, Drex can buy real estate, vehicles, and even government bonds.</p><p>Stablecoins, such as Drex, have the potential to rival fiat currencies as the dominant form of payment. Stablecoins’ value is relatively stable, and they can be sent instantly without the transaction fees associated with credit cards or international remittance services such as Western Union. Moreover, because stablecoins can be used by anyone with a smartphone, they represent an opportunity to bring millions of people who lack traditional bank accounts into the financial system.</p><h3>Next Steps</h3><p>The Central Bank has been diligently working towards this goal, and in March, they selected the platform that will facilitate transactions using this digital currency and is set to become available to the public by the end of 2024.</p><p>Laying the groundwork for this innovation, the Central Bank has granted permission to 16 consortia to develop advanced financial tools and instruments. These innovations will be tested in a series of simulated operations starting in September. These tests are designed to assess the security and efficiency of interactions between the digital Real and tokenized deposits, which are digital representations of real assets held by financial institutions.</p><p>The pilot project will encompass a range of valuable assets, including deposits from bank reserves, settlement accounts, the National Treasury’s single account, bank demand deposits, payment accounts held by payment institutions, and even federal government securities. The testing will be conducted in phases, gradually incorporating these assets into simulated transactions. Notably, the National Treasury securities simulation is slated to occur in February of the following year.</p><p>This initiative marks a significant step towards a future where the digital real will enhance financial transactions, offering enhanced security and ease of use. As the tests kick-off, anticipation is building for a transformative leap in how we interact with our currency and assets.</p><h3>TechTudo on Twitter: &quot;Drex: nova moeda digital gera memes nas redes sociais; veja os melhores https://t.co/zR9JbWoucj pic.twitter.com/n0xbqjVep4 / Twitter&quot;</h3><p>Drex: nova moeda digital gera memes nas redes sociais; veja os melhores https://t.co/zR9JbWoucj pic.twitter.com/n0xbqjVep4</p><h3>Stay Connected 🌐</h3><h4>Follow us on social media for more updates and content:</h4><ul><li><a href="https://twitter.com/blockful_io">Twitter</a> 🐦</li><li><a href="https://instagram.com/blockful.io">Instagram</a> 📸</li><li><a href="https://www.linkedin.com/company/blockful">LinkedIn</a> 💼</li><li><a href="https://www.youtube.com/channel/UCDU-ZFj-n7L4TohZtygslsQ">YouTube</a> ▶️</li></ul><h4>Join our community on:</h4><ul><li><a href="https://discord.gg/35WsFPYNT2">Discord</a> 🎮</li><li><a href="https://t.me/+ELs4xdxB7rs2ZTcx">Telegram</a> 📢</li></ul><p>For more insights and discussions about blockchain and technology, visit <a href="https://blockful.io/">Blockful</a> 📚🔗.</p><p>Together, let’s explore and build web3 🚀</p><h3>O Banco Central do Brasil confirmou que sua moeda digital se chamará $DREX</h3><p>A #CBDC é uma moeda digital emitida pelo banco central de um país. É uma forma simbólica do dinheiro com que estamos familiarizados, como a moeda fiduciária. O conceito de CBDC visa agilizar as transações e aumentar a inclusão financeira.</p><p>O Brasil é um dos países que tem explorado o desenvolvimento de uma CBDC chamada Real Digital Brasileiro. O <a href="https://www.linkedin.com/post/edit/7094487703479549952/?author=urn%3Ali%3Acompany%3A82172438#">Banco Central do Brasil</a> (Bacen) tem trabalhado no desenvolvimento da CBDC e selecionou 14 instituições, incluindo os principais bancos privados locais, o maior banco público brasileiro e empresas transnacionais, para participarem no projeto-piloto da CBDC.</p><p>A tecnologia das CBDCs tem o potencial de melhorar a infraestrutura financeira, a programabilidade e a encriptação. Funciona como uma infraestrutura pública para troca e execução de contratos, permitindo a criação de novas aplicações. Exemplos de casos de uso destacam o potencial da#tecnologia CBDC, tais como a forma como a CBDC pode melhorar as políticas de crédito subsidiado existentes, como as ferramentas financeiras #descentralizadas podem combinar mutuários de pequenas e médias empresas com investidores estrangeiros e como melhorar as transferências de propriedade de ativos reais.</p><p>As CDB podem criar uma maior resiliência para os sistemas de pagamento nacionais e promover uma maior concorrência, o que pode levar a um melhor acesso ao dinheiro, aumentar a eficiência dos pagamentos e, por sua vez, reduzir os custos de transação. As CBDC podem também melhorar a transparência dos fluxos monetários e ajudar a reduzir a substituição de moeda (quando um país utiliza uma moeda estrangeira em vez da sua própria moeda).</p><p>O sistema bancário no Brasil opera com três formas de moeda: moeda fiduciária, depósitos bancários e reservas bancárias. Essas formas são conversíveis entre si. O banco central compra obrigações dos bancos comerciais e emite reservas bancárias, que vão para o balanço do banco comercial. Com base no montante das reservas bancárias, o banco comercial pode emitir depósitos bancários. Por exemplo, quando o Joãozinho contrai um empréstimo para comprar uma padaria, o depósito bancário é transferido para a conta bancária do Joãozinho e pode ser convertido em moeda em qualquer altura.</p><p>A proposta da CBDC é #tokenizar diretamente estas reservas bancárias, permitindo que os indivíduos tenham contas no Banco Central e transacionem diretamente as reservas bancárias. Desta forma, seria mais fácil para o #Bacen acompanhar as transações entre pares e reduzir a possibilidade de branqueamento de capitais. As transações seriam rápidas, simples e seguras. No entanto, é importante notar que, com a CBDC, o governo teria acesso aos padrões de consumo e aos ativos dos indivíduos, o que suscita preocupações em matéria de privacidade.</p><p>A tecnologia CBDC tem o potencial de revolucionar a forma como transacionamos e interagimos com o dinheiro. O Brasil é um dos países que tem vindo a explorar o desenvolvimento de uma CBDC, e os potenciais benefícios da tecnologia CBDC no Brasil incluem a melhoria da infraestrutura financeira, a programabilidade e a encriptação. Embora existam preocupações sobre a privacidade e o acesso do governo aos padrões de consumo e ativos dos indivíduos, os potenciais benefícios da tecnologia CBDC não podem ser ignorados.</p><h3>DREX</h3><p>O Banco Central do Brasil anunciou oficialmente o nome da sua futura moeda digital. A moeda virtual, que deverá ser equivalente ao dinheiro em circulação, chamar-se-á #DREX. O economista do Bacen, <a href="https://www.linkedin.com/post/edit/7094487703479549952/?author=urn%3Ali%3Acompany%3A82172438#">Fabio Araujo</a>, coordenador da iniciativa, confirmou o nome durante a sessão semanal ao vivo da autoridade monetária no YouTube.</p><p>O nome “DREX” tem um significado importante, com cada letra a representar um aspeto fundamental da moeda digital. O “D” significa digital, destacando a natureza digital da moeda. O “R” representa o real, a moeda oficial do Brasil. O “E” significa electronic, enfatizando a natureza eletrónica da moeda. Por fim, o “X” transmite a ideia de modernidade e conexão, além de homenagear o Pix, sistema de transferências instantâneas lançado no Brasil em 2020.</p><p>Espera-se que a introdução do DREX traga inúmeros benefícios para os brasileiros. O Bacen afirmou que a moeda digital, antes chamada de Real Digital, proporcionará um ambiente seguro e regulado para a geração de novos negócios. O objetivo é oferecer um acesso mais democrático aos benefícios da digitalização da economia, tanto para os cidadãos quanto para os empreendedores.</p><p>O Bacen tem trabalhado diligentemente no desenvolvimento da DREX, com planos para um lançamento previsto para 2024. O real digital será concebido como uma forma de moeda do banco central por grosso, destinada principalmente à liquidação de transações interbancárias. O envolvimento dos bancos no desenvolvimento da solução é um aspeto fundamental da estratégia do Bacen, garantindo que os credores desempenhem um papel significativo na implementação da moeda digital.</p><p>Para facilitar a versão #piloto da DREX, o Bacen selecionou 14 instituições financeiras para participar do programa. Essas instituições incluem grandes bancos privados locais, como <a href="https://www.linkedin.com/post/edit/7094487703479549952/?author=urn%3Ali%3Acompany%3A82172438#">Bradesco</a>, <a href="https://www.linkedin.com/post/edit/7094487703479549952/?author=urn%3Ali%3Acompany%3A82172438#">Nubank</a> e <a href="https://www.linkedin.com/post/edit/7094487703479549952/?author=urn%3Ali%3Acompany%3A82172438#">Itaú Unibanco</a>, bem como o <a href="https://www.linkedin.com/post/edit/7094487703479549952/?author=urn%3Ali%3Acompany%3A82172438#">Banco do Brasil</a> e a bolsa de valores local <a href="https://www.linkedin.com/post/edit/7094487703479549952/?author=urn%3Ali%3Acompany%3A82172438#">B3</a>. Empresas multinacionais como <a href="https://www.linkedin.com/post/edit/7094487703479549952/?author=urn%3Ali%3Acompany%3A82172438#">Visa</a> e <a href="https://www.linkedin.com/post/edit/7094487703479549952/?author=urn%3Ali%3Acompany%3A82172438#">Microsoft</a> também foram escolhidas para participar do programa piloto.</p><p>A introdução da DREX está alinhada com a tendência global de explorar as moedas digitais do banco central (CBDCs). As CBDCs ganharam uma atenção significativa em todo o mundo, com cada projeto adotando uma abordagem única. No Brasil, o Bacen pretende alcançar o que o #Pix fez para os pagamentos de varejo, comoditizando os serviços financeiros e fornecendo uma infraestrutura comum com capacidade de programação e composição. O Bacen prevê um futuro em que os balanços dos #bancos possam ser completamente t#okenizados, oferecendo maior eficiência e #acessibilidade.</p><p>O Brasil se prepara para lançar a DREX e junta-se ao grupo de países que abraçam o potencial das CBDCs. A realidade digital tem o potencial de revolucionar a economia brasileira, promovendo a inclusão financeira, melhorando as soluções de pagamento e fomentando novas oportunidades de negócios. Com a DREX, o Brasil está a dar um passo significativo em direção a um futuro mais digital e conectado.</p><h3>Aplicações</h3><p>Diferentemente das #criptomoedas, cujo preço está atrelado à demanda e oferta e tem muita volatilidade, a Drex terá o mesmo valor do real. Cada R$ 1 valerá 1 Drex, sendo que a moeda digital é #garantida pelo Banco Central, enquanto as criptomoedas não são garantidas por nenhuma autoridade monetária.</p><blockquote><em>R$1 = 1DREX</em></blockquote><p>Na prática, o Drex funcionará de forma semelhante ao Pix, mas com finalidades e escalas de valores diferentes. Enquanto o Pix é usado principalmente para transações comerciais e obedece a limites de segurança, a Drex pode ser usada para comprar imóveis, veículos e até títulos públicos.</p><p>As #stablecoins, como a Drex, têm o potencial de rivalizar com as moedas fiduciárias como forma dominante de pagamento. O valor das stablecoins é relativamente estável e podem ser enviadas instantaneamente sem as taxas de transação associadas aos cartões de crédito ou aos serviços de remessas internacionais, como a <a href="https://www.linkedin.com/post/edit/7094487703479549952/?author=urn%3Ali%3Acompany%3A82172438#">Western Union</a>. Além disso, como as stablecoins podem ser utilizadas por qualquer pessoa com um #smartphone, representam uma oportunidade para trazer para o sistema financeiro milhões de pessoas que não têm contas bancárias tradicionais.</p><h3>Próximos passos</h3><p>O Banco Central tem trabalhado diligentemente para atingir este objetivo e, em março, selecionou a plataforma que facilitará as transações com esta moeda digital, que deverá estar disponível ao público até ao final de 2024.</p><p>Para lançar as bases desta inovação, o Banco Central concedeu autorização a 16 #consórcios para desenvolverem ferramentas e instrumentos financeiros avançados. Estas inovações serão postas à prova numa série de operações simuladas, que terão início em setembro. Esses testes têm como objetivo avaliar a segurança e a eficiência das interações entre o Real digital e os depósitos tokenizados, que são representações digitais de ativos reais mantidos por instituições financeiras.</p><p>O projeto piloto abrangerá uma série de ativos de valor, incluindo depósitos de reservas bancárias, contas de liquidação, conta única do Tesouro Nacional, depósitos à vista de bancos, contas de pagamento de instituições de pagamento e até títulos públicos federais. Os testes serão realizados em fases, incorporando gradualmente esses ativos nas transações simuladas. Destaca-se que a simulação com títulos do Tesouro Nacional está prevista para fevereiro do próximo ano.</p><p>Na sua essência, esta iniciativa marca um passo significativo em direção a um futuro em que o real digital melhorará a forma como as transações financeiras são conduzidas, oferecendo maior segurança e facilidade de utilização. Com o arranque dos testes, é de esperar um salto transformador na forma como interagimos com a nossa moeda e os nossos ativos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a50f55371e12" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blockful/central-bank-of-brazil-confirmed-its-digital-currency-will-be-called-drex-a50f55371e12">Central Bank of Brazil confirmed its digital currency will be called $DREX</a> was originally published in <a href="https://medium.com/blockful">Blockful</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[ENS] NameWrapper]]></title>
            <link>https://medium.com/blockful/ens-namewrapper-7db1ce50c763?source=rss-5fffaaaf5cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7db1ce50c763</guid>
            <category><![CDATA[ethereum-name-service]]></category>
            <category><![CDATA[en]]></category>
            <category><![CDATA[name-wrapper]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Guihcneves]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 21:10:14 GMT</pubDate>
            <atom:updated>2023-08-08T20:10:53.636Z</atom:updated>
            <content:encoded><![CDATA[<h3>ENS NameWrapper</h3><p>The last big update on Ethereum Name Service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*iRpMzWauILRJnLfmuKwmLA.gif" /></figure><p>It seems yesterday that ENS was <a href="https://twitter.com/ensdomains/status/1448711625469538311?s=20">talking about</a> name wrapping as a future improvement to the ecosystem… Today we see the fruit planted a long time ago, grow higher and reach the sunshine, as the Name Wrapper update tastes the sun! V3 DAPP is also <a href="https://mirror.xyz/taytems.eth/0EDU9u4zItawHZdoQmJN0evj7UZLAdYepR1Yz2oADP8">here</a>!</p><p>The ENS Name Wrapper system is set to usher in a new era of interaction with domain names within the web3 landscape. It promises to unlock a multitude of exciting possibilities, transforming the way users engage with domain names and expanding the horizons of web3 innovation.</p><p>This discussion is highly relative to Blockful as ENS is not just our <a href="https://twitter.com/avsa/status/1572259073994924037?s=20">first client</a>, but the technology we got most attached to for a while. With currently half the delegation power of Coinbase, Blockful is taking public appearances in conversations about the future and overall contribution to the ecosystem.</p><p>This article aims to be a quick introduction to the Name Wrapper update, what changed from the past version of contracts and what are the advantages and disadvantages the ecosystem will harvest from there.</p><h4><strong>What is the Name Wrapper</strong></h4><p>The Name Wrapper is a groundbreaking smart contract designed to enhance the functionality of subdomains within the Ethereum Name Service (ENS) ecosystem. Traditionally, subdomains like “sub.domain.eth” were not treated as distinct Non-Fungible Tokens (NFTs), limiting their transferability, rental potential, and saleability. However, the Name Wrapper revolutionizes this by creating subdomains as individual NFTs, unlocking a whole new range of possibilities.</p><p>With the Name Wrapper, subdomains can now be easily transferred between wallets, rented out, or sold, bringing a new level of flexibility and value to these unique digital assets. Additionally, the Name Wrapper introduces an unprecedented level of customization by introducing the concept of “burning fuses.” This innovative feature allows subdomain owners to selectively revoke sets of permissions, adjusting the degree of ownership and control over their subdomain.</p><p>In summary, the Name Wrapper is a powerful smart contract that transforms subdomains into distinct NFTs, enabling seamless transferability and unlocking new avenues for customization and ownership control.</p><h4>ERC721 to ERC1155</h4><p>The transition from ERC721 to the ERC1155 standard marked a significant milestone in the protocol’s evolution. Previously, subdomains were intricately tied to the parent domain and lacked the ability to exist as independent NFTs. This limitation was primarily due to the exclusive use of ERC721, which offered a singular level of modularization.</p><p>However, with the introduction of the Name Wrapper, this paradigm has been completely transformed. The Name Wrapper empowers any ENS name, including subdomains, to be enveloped within a comprehensive ERC-1155 framework. This groundbreaking mechanism allows for the seamless conversion of subdomains into fully-fledged ERC-1155 tokens.</p><p>In essence, the Name Wrapper revolutionizes the way subdomains are treated by encapsulating them within the ERC-1155 standard. This empowers subdomains to transcend their previous limitations and embrace the vast possibilities offered by ERC-1155, paving the way for enhanced ownership, transferability, and engagement with ENS.</p><h4><strong>Fuses</strong></h4><p>The second most drastic change is the fuses mechanism. Take a look at the structure and scroll down for a brief description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*vUs7Yro7TRdMA01_4vvwfw.jpeg" /></figure><p>The Nodes will manage the Fuses, which will apply certain perks or restrictions to the NFT, like making the NFT non-transferable and setting the resolver, among other features, allowing flexibility over your ownership.</p><p>Subnames will eventually be created, thus they will remain anchored to a parent NFT which will hold access to all of the child&#39;s fuses.</p><p>The name might be wrapped but is not yet emancipated. In order to operate on itself, a parent must burn a fuse named <em>parent cannot control</em>, revoking the access of the parent over the subname.</p><p>The surname is now in the emancipated state, but it cannot yet burn its own fuses or fuses of its own subname. In order to do that you must lock the name.</p><p>To lock a name you must burn the <em>cannot unwrap </em>field. Means it cannot be unwrapped. The name is now locked and you will gain access to all other fuses and sub-names fuses as well.</p><p>This entire process of managing fuses and wrapping, even on multiple names at once, is now available in a single transaction thanks to all contributors.</p><p>Here is a list of available fuses in the deployed contracts on Mainnet:</p><pre>CANNOT_UNWRAP = 1;<br>CANNOT_BURN_FUSES = 2;<br>CANNOT_TRANSFER = 4;<br>CANNOT_SET_RESOLVER = 8;<br>CANNOT_SET_TTL = 16;<br>CANNOT_CREATE_SUBDOMAIN = 32;<br>CANNOT_APPROVE = 64;<br>PARENT_CANNOT_CONTROL = 1 &lt;&lt; 16;<br>IS_DOT_ETH = 1 &lt;&lt; 17;<br>CAN_EXTEND_EXPIRY = 1 &lt;&lt; 18;<br>CAN_DO_EVERYTHING = 0;<br>PARENT_CONTROLLED_FUSES = 0xFFFF0000;<br>USER_SETTABLE_FUSES = 0xFFFDFFFF;</pre><p>The way you read this is by summing the values of the fuses, and the final uint256 will represent the ones that are present and the ones that are not. The bitwise &quot;&lt;&lt;&quot; is being used to move the zeroes to the side, but let&#39;s not get into that.</p><h4>Estates of ENS Names</h4><p><a href="https://ens.mirror.xyz/0M0fgqa6zw8M327TJk9VmGY__eorvLAKwUwrHEhc1MI">From ENS directly.</a> Accessed July 17, 2023.</p><ul><li>Unregistered: The name has not even been registered/created yet, or it has expired.</li><li>Unwrapped: The name exists and has not expired (in the case of .eth second-level names). The Name Wrapper contract does not have ownership over the name. You own the name in the registry and/or .eth registrar.</li><li>Wrapped: The Name Wrapper contract has ownership of the name (in the registry/registrar). You are issued an ERC-1155 NFT in return, which proves that you are the actual owner. You can unwrap the name at any time, which burns the ERC-1155 NFT, and returns ownership in the registry/registrar back to you. If your name is a subname like that, then the owner name.eth can technically replace the subname and transfer it to a different owner. In addition, the patent owner can burn parent-controlled fuses on your name.</li><li>Emancipated: The owner of the parent name is no longer able to replace this name or burn any additional fuses on it. All .eth second-level names (like name.eth) are automatically put into the Emancipated state when they are wrapped. The name can still be unwrapped and rewrapped by the owner.</li><li>Locked: The name can no longer be unwrapped. The owner can now burn owner-controlled fuses on the name. Fuses for subnames of this name can now be burned as well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*mXHs6RA7TSw7RDmOUy_vCQ.jpeg" /><figcaption>The flow of name estates</figcaption></figure><p>Blockful is at the forefront of blockchain technology, building impactful solutions that innovate the way we relate to markets. We are a company specializing in Smart Contracts and DeFi Infrastructure, Consulting, and Auditing for Blockchain projects. We have a multidisciplinary team specialized in the development of Blockchain solutions. From idea to final product.</p><h3>Stay Connected 🌐</h3><h3>Follow us on social media for more updates and content:</h3><ul><li><a href="https://twitter.com/blockful_io">Twitter</a> 🐦</li><li><a href="https://instagram.com/blockful.io">Instagram</a> 📸</li><li><a href="https://www.linkedin.com/company/blockful">LinkedIn</a> 💼</li><li><a href="https://www.youtube.com/channel/UCDU-ZFj-n7L4TohZtygslsQ">YouTube</a> ▶️</li></ul><h3>Join our community on:</h3><ul><li><a href="https://discord.gg/35WsFPYNT2">Discord</a> 🎮</li><li><a href="https://t.me/+ELs4xdxB7rs2ZTcx">Telegram</a> 📢</li></ul><p>For more insights and discussions about blockchain and technology, visit <a href="https://blockful.io/">Blockful</a> 📚🔗.</p><p>Together, let’s explore and build web3 🚀</p><h4>References</h4><p><a href="https://ens.mirror.xyz/0M0fgqa6zw8M327TJk9VmGY__eorvLAKwUwrHEhc1MI">ENS main thread about the topic.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7db1ce50c763" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blockful/ens-namewrapper-7db1ce50c763">[ENS] NameWrapper</a> was originally published in <a href="https://medium.com/blockful">Blockful</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Registrar Controller Update]]></title>
            <link>https://medium.com/blockful/registrar-controller-update-3015f8b97d50?source=rss-5fffaaaf5cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3015f8b97d50</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum-name-service]]></category>
            <category><![CDATA[en]]></category>
            <dc:creator><![CDATA[Guihcneves]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 15:28:31 GMT</pubDate>
            <atom:updated>2023-07-17T15:36:39.758Z</atom:updated>
            <content:encoded><![CDATA[<h4>Name Wrapper arrived! Follow the technical changes on the main contract of the ecosystem!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*iRpMzWauILRJnLfmuKwmLA.gif" /></figure><p>ENS cycle update is here bringing us a more dynamic approach when managing our domain names, with a lot of editability of our name&#39;s descriptions, a modular node approach when handling ERC1155, and inheritance features allowing fuses to dictate ownership controls.</p><p>This very recent update has been at boiling point for a while and now it&#39;s time to describe what is happening from Blockful&#39;s perspective.</p><p>The following chapters will record the changes on the smart contract known as ETHRegistrarController.sol.</p><h3>ETHRegistrarController Update:</h3><p>From v0.5.16 to v0.8.17</p><h4><strong>Pragma Solidity Changed</strong></h4><p>The previous version of the contract belongs to “pragma solidity &gt;= 0.5.0”, which stands for any compiler version that equals or above 0.5.0. In the case of “pragma solidity ~0.8.17”, it means that the contract is compatible with any version of the Solidity compiler that is greater than or equal to 0.8.17 and less than 0.9.0. This is because the tilde symbol specifies a range that includes all patch versions within the same minor version, but excludes the next major version.</p><h4><strong>Imports Changed</strong></h4><p>The new syntax, introduced in Solidity 0.8.0, is known as “import aliases”. It provides a way to selectively import specific contracts, libraries, or other symbols from a module, rather than importing the entire module as a single unit. This can help to reduce gas costs and simplify the code by allowing only the necessary symbols to be imported.</p><p>Following are the new imports and main changes at the ETHRegistrarController with a commented description of each one:</p><pre>// Will be used at the constructor, when calling ReverseClaimer.<br>import {ENS} from &quot;../registry/ENS.sol&quot;<br><br>// ReverseClaimer contract is being inherited by the ETHRegistrarController<br>// contract by specifying it as a base contract in the constructor. <br>// This means that the ETHRegistrarController contract will inherit all of <br>// the state variables and functions defined in ReverseClaimer, and can use <br>// them in its own code.<br>// This means that the Reverse ENS record of the Registrar will be transferred<br>// to the new owner, a.k.a contract deployer.<br>import {ReverseClaimer} from &quot;../reverseRegistrar/ReverseClaimer.sol&quot;<br><br>// This library was added to execute low-level calls in the &quot;_setRecords&quot;.<br>import {Address} from &quot;@openzeppelin/contracts/utils/Address.sol&quot;;<br><br>// This contract was introduced in the implementations to create a &quot;reverse <br>// name&quot; at the same time the ENS name is registered.<br>import {ReverseRegistrar} from &quot;../reverseRegistrar/ReverseRegistrar.sol&quot;;<br><br>// The baseRegistrar was handling all of the registrations business inside <br>// the &quot;registerWithConfig&quot; function. Nevertheless the nameWrapper will be <br>// doing this job from now on, replacing its mentions in the main &quot;register&quot; <br>// function for a single &quot;nameWrapper&quot; function call, literally a &quot;wrap&quot; of <br>// the token content.<br>// The NameWrapper will also be the one storing the public names from now on.<br>// It will handle expirations, renews and other stuff relating any process <br>// that involves ENS names. We&#39;ll be reviewing all this in the function scope <br>// of this doc.<br>import {INameWrapper} from &quot;../wrapper/INameWrapper.sol&quot;;<br><br>// Contract is used to recover ERC20 tokens sent to the contract by mistake.<br>// The contract is Ownable and only the owner of the Registrar can call the <br>// recovery function.<br>import {ERC20Recoverable} from &quot;../utils/ERC20Recoverable.sol&quot;</pre><h4><strong>Introducing Error Handlings</strong></h4><p>Error handlers were introduced in the new version, changing all “<em>require</em>” statements to their corresponding error using revert. The use of the &quot;<em>if</em>&quot; statement alongside error handlings with &quot;<em>revert</em>&quot; utilize less gas than a &quot;<em>require</em>&quot; - which will always be a string memory, to pre-compiled typed errors which will assist in both protocol development and for devs implementing the smart contract.</p><pre>error CommitmentTooNew(bytes32 commitment);<br>error CommitmentTooOld(bytes32 commitment);<br>error NameNotAvailable(string name);<br>error DurationTooShort(uint256 duration);<br>error ResolverRequiredWhenDataSupplied();<br>error UnexpiredCommitmentExists(bytes32 commitment);<br>error InsufficientValue();<br>error Unauthorised(bytes32 node);<br>error MaxCommitmentAgeTooLow();<br>error MaxCommitmentAgeTooHigh();</pre><h4><strong>Contract “is” More Stuff:</strong></h4><p>This will follow the import statements we overlooked in the beginning and tell the principal contract that those importations are part of it.</p><pre>contract ETHRegistrarController is<br>    Ownable,<br>    IETHRegistrarController,<br>    IERC165,<br>    ERC20Recoverable,  // new<br>    ReverseClaimer  // new<br>{</pre><h4><strong>State Variables Changed</strong></h4><p>Now it is setting interfaces in a better way by utilizing ERC165 for supportsInterface(…) and actually implementing an interface-type contract. The contract used to have all the interfaces as <em>hashed</em> <em>bytes</em> while XORing to encode the functions and find their interface ID:</p><pre>bytes4 private constant COMMITMENT_CONTROLLER_ID =<br>     bytes4(<br>      keccak256(&quot;rentPrice(string,uint256)&quot;) ^<br>          keccak256(&quot;available(string)&quot;) ^<br>          keccak256(&quot;makeCommitment(string,address,bytes32)&quot;) ^<br>          keccak256(&quot;commit(bytes32)&quot;) ^<br>          keccak256(&quot;register(string,address,uint256,bytes32)&quot;) ^<br>          keccak256(&quot;renew(string,uint256)&quot;)<br>     );<br><br>// It will be a bigger brainner to just leave like this:<br>type(IETHRegistrarController).interfaceId;</pre><p>A quite odd found here in the contract is the following line:</p><pre>uint64 private constant MAX_EXPIRY = type(uint64).max:</pre><p>A private variable can only be accessed from within the same contract and funny as it is, this line doesn’t affect anything in the contract, and it&#39;s not even worth a getter function apparently. 😆</p><p>Variables initialized in the constructor for later use in eligible functions:</p><pre>BaseRegistrarImplementation immutable base;<br>ReverseRegistrar public immutable reverseRegistrar;<br>INameWrapper public immutable nameWrapper;</pre><p>And nevertheless, the hardcoded bytes at contract deployment. Used in a lot of validations and auths in the ENS protocol:</p><pre>bytes32 private constant ETH_NODE:</pre><h3><strong>New Functions:</strong></h3><h4>function _setRecords(…)</h4><p>Internal function _setRecords(…) will set the records for a given ENS name at the time of registration. Records might be realized as data in the form of contexts and content which the token owner can save on-chain — or off-chain in case an off-chain resolver is being used.</p><p>Input parameters:</p><pre>function _setRecords(<br>    address resolverAddress,<br>    bytes32 label,<br>    bytes[] calldata data<br>) internal</pre><p>_setRecords(…) calls the resolver to run a <em>for loop</em> in case <em>data</em> had a <em>length</em> bigger than 0, and checks after the first 4 <em>bytes </em>of data if the <em>bytes32 </em>result matches the nodehash, which was calculated in the ETHRegistrarController. Let&#39;s untangle this.</p><p>It will use a low-level function to call each data imputed to set the records. The function in the ETHRegistrarController at version 0.8.17 is:</p><pre>// Get the nodehash and send along with the data to a resolver address <br>// calling multicallWithNodeCheck.<br>bytes32 nodehash = keccak256(abi.encodePacked(ETH_NODE, label));<br>Resolver resolver = Resolver(resolverAddress);<br>resolver.multicallWithNodeCheck(nodehash, data);</pre><p>Inside the &quot;multicallWithNodeCheck&quot;, the nodehash is verified to be different than empty bytes — it will never be empty since the ETH_NODE and the bytes32 label of the name will never result in the 0 address. Perhaps it is being used for a certain function when called from another contract in the ecosystem.</p><p>The first 4 bytes are matched to the selector while the following bytes should match the nodehash, which was passed as an input parameter alongside the data array.</p><p>The multicall will then delegate the call passing the data to be executed. If it fails, the transaction will be reverted:</p><pre>(bool success, bytes memory result) = address(this).delegatecall(<br>    data[i]<br>);<br>require(success);</pre><h4>function setReverseRecord(…)</h4><p>This will simply call the reverseRegistrar contract and try setNameForAddr(…). As input parameters, it will take “msg.sender”, “owner”, “resolver” and “name”+”.eth”.</p><p>After trying to claim ownership of the name, it will call setName(…) in the NameResolver contract in case the owner matches the sender.</p><h3>Unchanged Functions</h3><p>Old but gold.</p><pre>function rentPrice()<br>function valid()<br>function available()<br>function withdraw()</pre><h3>Change of Mechanics</h3><h4><strong>function supportsInterface(…)</strong></h4><pre>// From manual XORing:<br>interfaceID == INTERFACE_META_ID<br>interfaceID == COMMITMENT_CONTROLLER_ID<br>interfaceID == COMMITMENT_WITH_CONFIG_CONTROLLER_ID<br><br>// To light and legible syntax:<br>interfaceID == type(IERC165).interfaceId<br>interfaceID == type(IETHRegistrarController).interfaceId</pre><h4>function makeCommitment(…)</h4><p>This function was an extension from makeCommitmentWithConfig(…) in case no “resolver” or “addr” was provided.</p><p>The function would have the same effect as makeCommitmentWithConfig(…) in the case called using address 0 as the input for the resolver and addr parameters.</p><p>The idea is to validate some of the inputs for the commit to happen, then generate a 32 bytes commit from all provided data to avoid front-running. But if the data was provided without a resolver, the function will revert as the resolver is needed when using _setRecords(…).</p><p>The arguments needed for commit changed to allow more setups to be made when registering the name for the first time. The removal of the commitment with config took place to have all fields in the same function:</p><pre>+--------------+----------------------+<br>| v0.5.16 args |     v0.8.17 args     |<br>+--------------+----------------------+<br>| name         | name                 |<br>| owner        | owner                |<br>| secret       | duration             |<br>| resolver     | secret               |<br>| addr         | resolver             |<br>| ----         | data                 |<br>| ----         | reverseRecor         |<br>| ----         | ownerControlledFuses |<br>+--------------+----------------------+</pre><p>A few things have changed:</p><ul><li>We don’t use “addr” anymore in the register parameters but rather set through records (data arg)</li><li>“duration” was introduced in the commitment phase instead of directly being inputted as a register argument.</li><li>“resolver” and “ownerControlledFuses” are now being used with the nameWrapper contract to handle the validations, mint the ENS name, and also set the parental control.</li><li>“data” was introduced to allow setting different records for names at the time of registration.</li><li>“reverseRecord” is now available to be set at the commit phase as well.</li><li>Fuses are been upgraded to the following</li></ul><pre>CANNOT_UNWRAP = 1;<br>CANNOT_BURN_FUSES = 2;<br>CANNOT_TRANSFER = 4;<br>CANNOT_SET_RESOLVER = 8;<br>CANNOT_SET_TTL = 16;<br>CANNOT_CREATE_SUBDOMAIN = 32;<br>CANNOT_APPROVE = 64;<br>PARENT_CANNOT_CONTROL = 1 &lt;&lt; 16;<br>IS_DOT_ETH = 1 &lt;&lt; 17;<br>CAN_EXTEND_EXPIRY = 1 &lt;&lt; 18;<br>CAN_DO_EVERYTHING = 0;<br>PARENT_CONTROLLED_FUSES = 0xFFFF0000;<br>USER_SETTABLE_FUSES = 0xFFFDFFFF;</pre><h4>function commit(…)</h4><p>The <em>require</em> statement was changed for the <em>if</em> statement using <em>revert</em> to handle <em>custom errors</em>.</p><h4>function _consumeCommitment(…)</h4><p>Was previously calculating and returning the cost as <em>uint256</em>, requiring that<em> </em>“msg.value &gt;= price”. This validation is now being called at register(…) directly, using “IPriceOracle”.</p><p>Now it doesn’t have returns, it rather validates transaction data and deletes the commitment afterward.</p><p>The <em>require</em> statement was changed for the <em>if</em> statement using revert to handle custom errors.</p><h4>function register(…)</h4><p>This function changed drastically, with a lot of new inputs and contract calls to handle the registration. It was previously calling registerWithConfig(…) passing resolver and address as the 0 address.</p><p>Here is the complete change in the input structure:</p><pre>+--------------------+-----------------------------+<br>|    v0.5.16 args    |        v0.8.17 args         |<br>+--------------------+-----------------------------+<br>| string memory name | string calldata name        |<br>| address owner      | address owner               |<br>| uint256 duration   | uint256 duration            |<br>| bytes32 secret     | bytes32 secret              |<br>| ----               | address resolver            |<br>| ----               | bytes[] calldata data       |<br>| ----               | bool reverseRecord          |<br>| ----               | uint16 ownerControlledFuses |<br>+--------------------+-----------------------------+</pre><p>The costs are calculated firstly using the price oracle and will revert in case the amount is incorrect.</p><p>Variable “cost” is now <em>price.base</em> and <em>price.premium</em>. Which is a struct type from the IPriceOracle interface.</p><p>The “expiry” is calculated automatically at the NameWrapper, which will also handle the NFT creation. Although expiry is settled as an <em>uint256</em> variable in the register(…) function, it will only be used to be emitted in the registration event.</p><pre>uint256 expires = nameWrapper.registerAndWrapETH2LD(<br>    name,<br>    owner,<br>    duration,<br>    resolver,<br>    ownerControlledFuses<br>);</pre><p>Function _setRecords(…) will check for a length above 0 in the &quot;data&quot; argument before being called. The resolver must implement the multicall and also be allowed to manage records.</p><p>Function _setReverseRecord(…) will be triggered if the boolean argument <em>reverseRecord</em> is set to true.</p><p>The event emission has changed the &quot;cost&quot; argument to emit both <em>price.base</em> and <em>price.premium</em>.</p><p>The refund is done based on the sum of <em>price.base</em> and <em>price.premium</em>.</p><h4>function renew(…)</h4><p>It didn’t change much at all, inputs remain the same, but the <em>require</em> is now following the error handling using <em>ifs</em> and <em>revert.</em></p><p>The variable &quot;cost&quot; of type <em>uint</em> is now handled by the type IPriceOracle using only <em>price.base</em>, not mentioning <em>price.premium</em>.</p><p>Expiration is now handled by the nameWrapper instead of the baseRegistrar.</p><h3>Removed Functions</h3><p>This won&#39;t be part of the new contract. And the reason for that is because simply it doesn&#39;t make any sense to call a function just to fill inputs with the zero address.</p><h4>function makeCommitmentWithConfig(…)</h4><p>It could be called passing the address for the resolver or the address for the primary name. It could also be called from makeCommitment(…) which would fill <em>resolver</em> and <em>addr</em> parameters with the zero address.</p><h4>function registerWithConfig(…)</h4><p>Same as making a commitment with a configuration, it takes the <em>resolver</em> and the <em>addr </em>inputs<em> </em>to perform a complete name configuration. In the new version, the register(…) function is the one doing this.</p><p>We can imagine that both functions with the suffix &quot;WithConfig&quot; turned out to become the names without the suffixes, which takes all input arguments. While the purposes of the old functions makeCommitment(…) and register(…) to fill zero addresses vanished from existence in the new contracts.</p><p>Now the makeCommitment(…) and register(…) are the big deal in the new contracts while the suffix “WithConfig” will remain in the game for those that still want to use the cheapest gas usage option available when registering an ENS name.</p><p>Blockful is at the forefront of blockchain technology, building impactful solutions that innovate the way we relate to markets. We are a company specializing in Smart Contracts and DeFi Infrastructure, Consulting, and Auditing for Blockchain projects. We have a multidisciplinary team specialized in the development of Blockchain solutions. From idea to final product.</p><p>Follow us and join the Blockful!</p><p><a href="https://blockful.io/"><strong>Blockful</strong></a><strong> </strong>|<strong> </strong><a href="https://twitter.com/Blockful_io">🐦</a> | <a href="https://github.com/blockful-io">🐱</a> |<a href="https://www.linkedin.com/company/blockful"> 👤</a></p><h4>References</h4><p><a href="https://github.com/ensdomains/ens-contracts">ens-contract</a>s on GitHub. Last access on July, 16.</p><p><a href="https://etherscan.io/address/0x283af0b28c62c092c9727f1ee09c02ca627eb7f5#code">ETHRegistrarCotroller</a> <strong>— v0.5.16</strong></p><p><a href="https://etherscan.io/address/0x253553366da8546fc250f225fe3d25d0c782303b#code">ETHRegistrarController</a><strong> — v0.8.17</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3015f8b97d50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blockful/registrar-controller-update-3015f8b97d50">Registrar Controller Update</a> was originally published in <a href="https://medium.com/blockful">Blockful</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blockful Experience]]></title>
            <link>https://medium.com/blockful/block-3290d9c02b15?source=rss-5fffaaaf5cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3290d9c02b15</guid>
            <category><![CDATA[blockful]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Guihcneves]]></dc:creator>
            <pubDate>Fri, 14 Jul 2023 22:25:51 GMT</pubDate>
            <atom:updated>2023-07-17T19:28:48.064Z</atom:updated>
            <content:encoded><![CDATA[<p>“Striving for optimal efficiency by minimizing energy consumption”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvcRJfyS93aZ3JP0ZhsASw.jpeg" /></figure><h4><strong>Introduction</strong></h4><p>I am a self-taught smart contract developer with extensive experience integrating Blockchain technology into web2 applications. While I did not hold any degree as I fled college, my expertise lies in engineering efficient smart contracts that deliver the desired results while preserving legibility and minimizing extra costs due to good optimization.</p><p>Apart from being a skilled tech researcher, technocrat, and chart analyst, I also have an insatiable wanderlust for knowing. My passion is driven by the conviction that cryptocurrencies are destined to be at the forefront of governance models where “code becomes law,” hence why they will eventually become ubiquitous across industries globally.</p><p>I’m part of several communities within this thriving industry that inform me daily about emerging trends. This allows me to network with notable thinkers who shape public opinion regarding worldwide digital currency adoption.</p><p>I was once fully immersed in video games, particularly MMORPGs. I always strived to obtain the best items and constantly researched the game’s mechanics through a practice known as “theory crafting.” As a player, I studied every possible aspect of the games and tried endless combinations of strategies, which led me to gain knowledge, earn rewards, and make great friends.</p><p>I bring up my gaming experience because it has greatly influenced my journey in crypto as it has shown an impact on other players. Tokens as valuable items and charts as the price history. I’ve realized how much the gaming community resembles the crypto community. ICOs felt like unlocking new characters or discovering new islands, while communities were similar to guilds. The main issue being only that MMORPG in web2 has corporate and government influence… you have to respect all of its rules while migrating in-game content between games is a human process based on trust and illegal.</p><p>However, there are well-established and non-governmental bubbles around the gamified environments in the crypto realm. Users can utilize the same identity mechanisms, token standards, and custom currencies that communicate easily with one another. It’s like cryptocurrency is the seed, the baseline for the technocracy the human race will live in one day, and this is just the beginning!</p><p>As a smart contract developer, I play an integral part in the Blockchain ecosystem. I’m responsible for researching and implementing optimization techniques to ensure contracts function efficiently within the EVM or WASM environment. I’ve also had experience setting up SDKs for contracts and facilitating communication between Web2 and Web3.</p><p>Although my primary role within the company is as a smart contract developer, I also take on the additional responsibility of reinforcing Blockchain fundamentals to my team. In doing so, I’m always available to answer any questions they may have and enjoy researching any topics I cannot address.</p><p>It’s amazing how we at Blockful share a passion for exploring the secrets hidden deep within the rabbit hole, and we strive together toward the common goal of mass adoption and empowerment of the people.</p><p>As a smart contract developer, I am well-versed in research, planning, testing, implementing, integrating, optimizing, and auditing.</p><p>If you’re looking to put anything on-chain, then I’m your guy.</p><h4><strong>Company Background</strong></h4><p>Blockful provides DeFi infrastructure and smart contract creation services for protocols, DAOs, financial institutions, fintechs, and entrepreneurs with Blockchain projects.</p><p>It all started with our founder Alex T. Netto and his dream to consolidate a software house to provide solutions for the ecosystem while riding the trend of mass adoption.</p><p>I was hired to fulfill an Ethereum Name Service (ENS) grant application, which consists of remodeling the controller contract, which operates the purchases and renewals of ENS names. We created a referral system for the acquaintance of names while exploring the benefits of batch registrations and renewals. By executing the job, we proved efficiency when batching, reducing costs by large amounts. You can read more about it in our <a href="https://medium.com/@guihcneves/ethereum-name-service-5494c49930bf">article</a>.</p><p>The ENS seal of approval was the spark of where the company was heading. The evaluation of our work was getting a market appetite. Alex started traveling the world looking for knowledge and partnerships across the industry, bringing more customers to our client pool.</p><p>Our business model was strictly B2B, allowing us to focus on solving problems for other big businesses in the market. We worked with great companies such as Balancer, Aztec Network, and NameHash.</p><p>Regarding public appearance and networking, Blockful is always participating in major Hackathons in its birthplace: Brazil. We never lost a Hackathon and always challenged ourselves to code the best project in the shortest time, sometimes staying awake over 48h just to conclude the chores.</p><p>During this development of partnerships, Blockful entered multiple structuration phases: we needed a face for the market, vision, mission, and internal tools to facilitate our job, metrics, and culture. This would cultivate the company environment for long-term growth, leading to the constant alignment of our vision and working on our company’s culture in every aspect we can, using all the techniques we are aware of, being known by us or researched by our members and brought to the team.</p><p>The recollection of our experiences resembles a never falling chart — simple mistakes, rapidly healed.</p><p>At Blockful, we have weekly meetings to start and finish the week, allowing us to start and end the week with decent feedback on everyone’s whereabouts without pushing it for obligatory dailies. We also allow reschedules of those meetings through communication.</p><p>There is a study group every Friday where we bring Blockchain concepts for all members of the team as we realize how important it is for everyone in a Blockchain company to understand basic concepts such as virtual machines, nodes, miners, layers, and all sorts of abstractions that lead to better insights and understandings of the tech.</p><p>Every Thursday, we have TechDay, which consists of members of the team bringing the studies they’ve made to enlighten the company with knowledge. Nevertheless, we host an operational meeting every Tuesday to discuss time-saving techniques and the roadmap of our practices in the company. We are constantly working around a balanced and fun interaction, keeping the team together and aware of what the companies are doing.</p><p>By this writing, Blockful had expanded its actuation area, bringing more product space while heating its open source and community side. The production of intellectual content regarding our past experiences is more valuable as time progresses. New initiatives are allowing Blockful members to profit from delivering articles to the public, building the personal brand of the team while also showing to be a strong strategy for smart money to follow.</p><h4><strong>Job Responsibilities</strong></h4><p>In my role, I play a pivotal part in guiding the company through the uncertain waters of the Blockchain industry by developing smart contracts, strategizing, crafting proposals, generating comprehensive reports, auditing ecosystems, and writing public articles.</p><p>At the heart of client interactions, I’m like the translator who deciphers the abstract desires of our clients and converts them into quantifiable hours of development. This involves a blend of meticulous research and harnessing our accumulated expertise. It is akin to turning dreams into blueprints, to which we then attach the company’s hourly rates.</p><p>The process commences with us diving into market research, exploring the context of the idea, and jumping to understanding the fundamentals and vision of the product or service being learned to validate its applicability. This part is important because we conduct extensive benchmarking on large players to identify methods and solid statistics to guide successful cases and avoid failures.</p><p>After floor research is established, we create the fluxes of each economic agent and contract function, describing the tokenomics and modus operandi. Finally, we can make the entire process backlog while developing the product/service roadmap.</p><p>All this research and planning is like peeling an onion — there are seven layers we need to go through. These layers help us see every part of the project. Our to-do list is the building block for making the application, and the economics and timeline allow us to get other people interested and involved.</p><p>Sometimes clients already have a running business, but they need extra features. In these cases, we focus less on research and more on understanding the client’s existing system before adding the new features. A good example of this is when we worked with Balancer and Aztec.</p><p>Balancer and Aztec are big names in the market, and they wanted to join forces to create something new for the public. The balancer is a large DEX in Ethereum with billions of dollars in circulation, while Aztec provides privacy through relayers, providing decentralized calculations and operations with zk-rollup. With this integration, users could anonymously operate in the 4th largest crypto DEX.</p><p>It required a deep understanding of how Balancer’s Vault Contract worked, as well as Aztec. This product had close to zero examples online, and Balancer’s case didn’t fit the Aztec contract layout due to its liquidity mechanic holding more than a pair of tokens for each pool. Turnarounds had to be developed to make it possible to negotiate said multiple assets.</p><p>Working on projects developing vanguard technologies and new market challenges is just what Blockful likes to face. Each problem we encounter can be sorted into categories and polished, matching previous profiles to create a flowchart and a proposal. We then send this proposal to the client, who decides if they want to continue the adventure with Blockful.</p><p>Every project is like opening a mystery box with new challenges and lessons. We take these lessons, chew them over, and store the learning for future use cases. One of my special tasks is to spot patterns in these challenges and insert them into our company’s flux. This helps us work faster and smarter on future projects, as we can draw on experience to solve new challenges.</p><p>My skill in writing from documents to code makes me stand out in the team. I create strong reports and articles that let people see and feel Blockful’s expertise. It’s like giving people a taste of the secret sauce that makes Blockful special. This helps the public understand what we do and showcases the value and depth of knowledge we bring to the table.</p><p>However, the most important part of my job is to research, write, and everything smart contract related. Consider contracts as the heart of how things work in the Blockchain world. They must be built carefully so everything runs smoothly and keeps working over time.</p><p>Smart contracts are written in a special computer language. Every tiny piece of this language tells the computer what to do. It’s like giving instructions to a robot. But in this case, it’s all about moving information and money. When someone uses a smart contract, it’s like they are asking it to change the Blockchain. To do this, the person must pay a small fee called ‘gas’ to make the contract work.</p><p>It’s crucial to think hard about the logic that goes into smart contracts. We need to test them a lot and learn from any mistakes. This helps ensure that everything happening on the Blockchain is done as intended. Smart contracts are like a set path; they only do exactly what they’re programmed to do and nothing else. They don’t rely on anything outside of their code.</p><p>Imagine these contracts are handling millions or even billions of dollars every month. Those simple lines of code suddenly feel like a maze filled with traps. Walking through a field filled with hidden surprises is like being super careful with each step.</p><p>That’s why my job is so important. By crafting and checking these smart contracts, I help ensure that they work perfectly and safely, protecting not just the company’s interests but also the huge amounts of money flowing through them.</p><h4><strong>Lessons Learned</strong></h4><p>Learning Zk-Sync, Balancer Vault, and Phantom Pools was a challenging task with many rewards. This experience is worth sharing even a little… It all started with the integration of Balancer Vaults with Aztec Privacy Network. During the integration, we found some relevant context that summed up as research for both ecosystems.</p><p>We realized the lack of on-chain accessibility for Balancer. The ecosystem relies on off-chain queries to calculate swaps at the vault. When considering asset management, a big protocol like Balancer should think about on-chain treasuries and how they could connect to the vault through on-chain calls. We highlighted this necessity and provided a solution during our integration with Aztec Network using Foundry, which enables solidity files to be tested with other solidity files.</p><p>We also experienced incompatibility in the modus operandi of the Aztec Bridge Contract, which limited swaps of two assets for one (2–1) or one for two(1–2). This was limiting because Balancer works with multiple tokens in most vaults (N-N). We had to create an encoding mechanic to overlay the bridge contract itself to carry data that could extrapolate the input limitations of the rollup. Pointing out that N to N assets exchange was needed to capitalize on the protocol power, Aztec Bridge Connect was closed later to focus on Aztec 3, which promises to integrate a feature that assists multiple token transfers in cases like Balancer.</p><p>This journey has surely been full of lessons, extraordinary people, projects, and a shared vision for a better future. What called me into crypto was the absurdity of how overall, people are blinded with information, misled by social media, and strong followers of the wrong disseminated call. Writing books was the backbone of the human race that enabled the strong evolution of the culture. Historically, cutting access to information left the world in darkness and sickness, but nowadays, we live blinded by the screens, and it has become the god of many.</p><p>Blockchain is the perfect use case for a technology that can avoid censorship and is resilient to time, making it a public book — or contemporaneous terms, a database — for the entire world to access.</p><p>I’ve been following all the game theory and use cases enabled by Blockchain technology, and they are surely bigger than the media describes. Only the ones that ignore the algorithm and dive into deeper meanings will realize the crucial role Blockchain is playing.</p><p>This industry will prove itself with time. The ones that look the zeitgeist in the eye will collect huge rewards in the upcoming era carved out in zeroes and ones.</p><h4><strong>Company Culture</strong></h4><p>Regarding the personal interest of each Blockful member, it can be summed up into a shared vision for an era of crypto; its job is to guarantee the future of data integrity and accessibility for all.</p><p>Blood in the eyes can be perceived in Blockful members, as most people believe our company used to have over fifteen members when it was only around five. By the time of this article, you bet we are already expanding and acquiring the best minds to illuminate a path that the world can follow.</p><p>Thinking of Blockful team when they are together triggers good mind records. Mindful people, good people, all battling towards a better future, looking to care for themselves and the ones they love, and living the technology, building the technocracy.</p><p>It all started with weird noises and butt slaps, but as more people joined, we became more professional, although we kept being very childish-like people.</p><p>Towards a common goal that provides a use case. An organization’s purpose is delivering utility to society; Blockful can be realized as an outperforming source of utility. This is due to the hardcore background of all members and the constant struggle to be at the forefront of the blockchain industry. The mindset to keep up with everything that we do and speak requires a lot of awareness and wisdom — otherwise, you’d get lost.</p><p>I think it’s safe to say that most people work 8h per day and need 2h to destress.. but as I recall, all Blockful members hit over 12h a day of pure working hours. I might be driving this average up because it is around 16h for me if I’m let alone in my cave. We are workaholics and addicted to cr; we are devouring the new financial system.</p><p>No is not an option, and timing is meticulously calculated; Blockful will hit the news soon.</p><h4><strong>Advice For Others</strong></h4><p>When it comes to being a smart contract developer, be ready to face hours of attempting multiple combinatorial possibilities until you fully understand the constant changing of the architecture, which is the Blockchain.</p><p>Like Zion survivors watched the Matrix from inside Nebuchadnezzar, you must navigate on Etherscan and other block explorers<em>.</em></p><p>Must comprehend the applied concepts of gas, miners, validators, providers, blocks, nodes, optimization, security, and even assembly is a pre-requirement if you want to excel.</p><p>My advice for you — who is only learning about Blockchain now, is to learn a bit of javascript, python, then try solidity with a good dive into the Ethereum official documentation. The world will soon be digital, and a huge bubble will form once again, but this time, we hold both the powers of Crypto and AI; their bubble joining together will lead humanity to a massive tech run.</p><p>Try to start a project as soon as possible and invest daily hours into that; even if it stresses you out, discipline will guide your success narrative. After the first signal of failing, fail as fast as possible and jump to the next project, but this time with more knowledge and a bigger smile.</p><p>Don’t get too comfortable in only doing one thing; try to be a master of all arts, but specialize in 2 or more. If you can speak two languages plus the computational logic language, with internet access, you can be anything you want; I mean it, you can conquer the world.</p><h4><strong>Conclusion</strong></h4><p>In closing, I would like to express my heartfelt gratitude to all those who have supported me throughout my career. I am incredibly grateful for the opportunities I have had at Blockful, a company that has nurtured my growth and allowed me to contribute to the exciting world of Blockchain.</p><p>I would like to thank my colleagues at Blockful, who have been a constant source of inspiration, collaboration, and shared vision. Together, we have tackled challenges, explored new frontiers, and worked tirelessly toward our collective goal of mass adoption and empowerment through Blockchain.</p><p>I would also like to express my appreciation to the clients and partners who have entrusted their projects to me and my team. Your trust and support have been instrumental in our success, and it has been a privilege to collaborate with you and bring your visions to life.</p><p>To the wider Blockchain community, thank you for your knowledge-sharing, thought-provoking discussions, and collective drive to push the boundaries of what is possible. Through our collaborative efforts, we continue to shape the future of technology and contribute to a more decentralized and inclusive world.</p><p>Lastly, I am grateful to my friends, family, and loved ones for their unwavering support and understanding. Your encouragement and belief in me have been fundamental in my journey.</p><p>As I look toward the future, I am excited about the possibilities. The Blockchain industry is ever-evolving, and I am committed to staying at the forefront of this dynamic field, continuously learning, innovating, and making a positive impact.</p><p>Thank you, once again, to everyone who has played a role in my career. I am truly honored and appreciative of the opportunities and experiences that have shaped me as the Technocrat I’m today. Here’s to a future filled with endless possibilities and collective achievements.</p><p>Blockful is at the forefront of blockchain technology, building impactful solutions that innovate the way we relate to markets. We are a company specializing in Smart Contracts and DeFi Infrastructure, Consulting, and Auditing for Blockchain projects. We have a multidisciplinary team specialized in the development of Blockchain solutions. From idea to final product.</p><p>Follow us and learn more!</p><p><a href="https://blockful.io/"><strong>Blockful</strong></a><strong> </strong>|<strong> </strong><a href="https://twitter.com/Blockful_io">🐦</a> | <a href="https://github.com/blockful-io">🐱</a> |<a href="https://www.linkedin.com/company/blockful"> 👤</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3290d9c02b15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blockful/block-3290d9c02b15">Blockful Experience</a> was originally published in <a href="https://medium.com/blockful">Blockful</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[ENS] Referral Feature]]></title>
            <link>https://medium.com/blockful/ens-referral-feature-cc6bbd9c241b?source=rss-5fffaaaf5cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc6bbd9c241b</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[domains]]></category>
            <category><![CDATA[ethereum-name-service]]></category>
            <dc:creator><![CDATA[Guihcneves]]></dc:creator>
            <pubDate>Fri, 14 Jul 2023 21:16:42 GMT</pubDate>
            <atom:updated>2023-08-08T00:48:40.016Z</atom:updated>
            <content:encoded><![CDATA[<h3>ENS Referral Feature</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*iRpMzWauILRJnLfmuKwmLA.gif" /></figure><h4><strong>Intro</strong></h4><p>Blockful contributed to ENS a year ago and covered a wide range of features, including Batch Commit, Batch Registration, Referral System, and Tips for Registrations. During that period the pragma version of ENS contracts was already above 0.8.0, meaning our contribution would have been part of the Name Wrapper update. You can read the article about it <a href="https://medium.com/blockful/ethregistercontrollerv2-29d04eec48a5">here</a>.</p><p>After all this time we finally see the new ETHRegistrarController deployed on Mainnet. Unfortunately, our contribution was only indexed but not implemented alongside the Name Wrapper update. Meaning we cannot yet batch on the controller itself, refer a friend, or leave a tip for someone to register our name for us.</p><p>In this article, we aim to bring back specifically the Referral Feature back to life, explaining how it works, how to use and the implications in the ecosystem.</p><h4><strong>Motivation</strong></h4><p>ENS marketplaces, which are essentially a front and a back-end that batches or interfaces a name creation, charge a fee in the process. But they could be more than just gas savers from batching their clients’ transactions.</p><p>A contribution on <a href="https://dune.com/taytems/ensip14">Dune</a> Dashboard shows us where the aggregated interactions are coming from thanks to <a href="https://docs.ens.domains/ens-improvement-proposals/ensip-14-platform-source-parameter"><em>ENSIP-14</em></a>:</p><pre>+----------------+-------------+------------+<br>|  app_id_label  | occurrences | percentage |<br>+----------------+-------------+------------+<br>| Unknown Source |       82903 |       51.6 |<br>| enslabs.eth    |       57805 |         36 |<br>| ens.vision     |       17578 |       10.9 |<br>| ensfairy.eth   |         242 |        0.2 |<br>| 0x2AFF6E58     |         322 |        0.2 |<br>| 0x1234567      |          84 |        0.1 |<br>| 0x2224567      |         114 |        0.1 |<br>+----------------+-------------+------------+</pre><p>Unknown Source is the aggregation of every single address that registered a name prior to the ENSIP-14 dated 2023–02–07.</p><p>ENS realized they take a considerable part in the overall process when it comes to using their own technology. But their ideal of being the infrastructure should not sustain their high score when selling names, rather incentivize the projects that are using their technology to enlarge the user base.</p><p>If you are interested to learn about the beginning of this motivation, you wouldn&#39;t want to miss this <a href="https://discuss.ens.domains/t/ens-affiliate-marketing-affiliate-program/11819">reading</a>.</p><h4><strong>How Does It Work?</strong></h4><p>A protocol that is facilitating user growth for ENS will be sustaining a front-end server. When preparing the payload for the user to sign before acquiring the name, the front end should insert its own address as a referrer parameter when calling `register` in the ETHRegistrarController.</p><p>The referral fee will start at 10% of the purchase cost. Meaning the DAO is willingly sharing 10% of the profits with the front end that integrated the protocol and brought another ENS name to life.</p><pre>contract ETHRegistrarController is .. {<br><br>    ...<br><br>    uint256 public referralFee = 1000; // 10%<br><br>    ...<br><br>}</pre><p>The public function `referralFee` indicates the fee a referrer will profit from registering a name. We&#39;ll utilize two decimals to avoid under/overflows.</p><p>To manage the fee percentage, we introduce a function called only by the contract owner (DAO), which allows for the fee to be set between 0 and 10000 ( 0.00% ~ 100.00% ).</p><pre>function setReferralFee(uint256 newFee) public {<br>    if (msg.sender == owner() &amp;&amp; newFee &lt;= 10000) {<br>        referralFee = newFee;<br>        emit ReferralFeeChanged(newFee);<br>    }<br>}</pre><p>We don&#39;t have to check if it&#39;s below `0` because the type uint256 is already assuring this.</p><p>And of course, we emit an event to inform whomever uses the protocol that the current mechanics have changed.</p><p>If you realized by now, in theory, you could set yourself as the referrer and get a discount on the name purchase. That is why the DAO is thinking about a minimum withdrawal amount. Turning over the user base interest to the projects implementing front-ends, which can collect bigger referral fees, surpassing the minimum amount easily.</p><pre>function setWithdrawMin(uint256 weiAmount) public {<br>    if (msg.sender == owner()) {<br>        withdrawMin = weiAmount;<br>        emit MinimumWithdrawChanged(weiAmount);<br>    }<br> }</pre><p>The `withdrawMin` will carry the minimum wei amount required for an address to withdraw from the contract. The function to set the minimum amount can only be called by the contract owner and will emit an event.</p><p>The above, highlights the configurations of the referral feature. But we move further preparing the mapping that will index each addresses balance.</p><pre>contract ETHRegistrarController is .. {<br><br>    ...<br><br>    mapping(address =&gt; uint256) public balances;<br><br>    uint256 public referralFee = 1000; // 10%<br>    uint256 public withdrawMin = 1 ether; // 1 ETH<br><br>    ...<br><br>}</pre><p>Balances Map will hold the accountability for all addresses earns, including protocol fees and, to ingress into this balance sheet, one must be referred by a registree.</p><p>We also considered using a unique uint256 identifier for the contract balance, resulting in 72 gas units saved for every balance summed. Since this value corresponds to as low as 0.1% of the total gas cost when handling balances, we decided to use the balances map for all cases to preserve legibility and avoid unnecessary &quot;if else&quot;.</p><h4>Inner Mechanics</h4><p>The function `register` and `renewal` received a new input parameter: the address of the referrer. Meaning, the interface will also need an extra parameter and the existing dApps will need to adopt this feature eventually.</p><pre>function register(<br>    string calldata name,<br>    address owner,<br>    address referrer,//          &lt;--  new input<br>    uint256 duration,<br>    bytes32 secret,<br>    address resolver,<br>    bytes[] calldata data,<br>    bool reverseRecord,<br>    uint16 ownerControlledFuses<br>) external payable override;<br><br>function renew(<br>    string calldata name,<br>    address referrer,//          &lt;--  new input<br>    uint256 duration<br>) external payable override;</pre><p>Depending on each of the functions called, the referral fee will draw a percentage over the cost. When handling registrations, the cost will be `price.base + price.premium`. Renewals will be using solely `price.base`.</p><p>Diving into the `register` function: the execution will ask the Oracle the price of a given name multiplied by its duration, while the `cost` variable will therefore be used to avoid repetitive arithmetics and reduce gas usage.</p><p>If the message value cannot cover the costs, execution will be reverted.</p><p>Any extra value sent over the costs will be refunded. No worries about the referral fee, it will take a percentage of the total cost and not the entire message value.</p><pre>function register(<br>    ...<br><br>    IPriceOracle.Price memory price = rentPrice(name, duration);<br><br>    ...<br><br>    uint256 cost = price.base + price.premium;<br><br>    if (msg.value &lt; cost) {<br>        revert InsufficientValue();<br>    }<br><br>    _setBalances(referrer, cost);<br><br>    if (msg.value &gt; cost) {<br>        payable(msg.sender).transfer(msg.value - cost);<br>    }<br>)</pre><p>The `renew` function won&#39;t change much from the `register`. We can see that there is no `cost` variable and we are using only `price.base` instead.</p><pre>function renew(<br>    ...<br><br>    IPriceOracle.Price memory price = rentPrice(name, duration);<br><br>    if (msg.value &lt; price.base) {<br>        revert InsufficientValue();<br>    }<br><br>    ...<br><br>    _setBalances(referrer, price.base);<br><br>    if (msg.value &gt; price.base) {<br>        payable(msg.sender).transfer(msg.value - price.base);<br>    }<br>)</pre><p>After handling correctly the operational costs, refunds, events(will be mentioned soon), and optimizations, the core function of this feature lies ahead. You might&#39;ve realized that both of these functions will call an internal function `_setBalance`.</p><p>In the ENS contracts, we spot a pattern where an underscore in the front of a function name denotes its internal status on the protocol.</p><p>To call this function we must pass the referrer address and the total operational cost for registering or renewing a name.</p><pre>function _setBalances(address referrer, uint256 balance) internal {<br><br>    if (referrer == address(0) || referralFee == 0) {<br>        balances[address(this)] += balance;<br><br>    } else {<br>        uint256 reward = (balance * referralFee) / 10000;<br><br>        balances[referrer] += reward;<br>        balances[address(this)] += balance - reward;<br>    }<br><br>}</pre><p>The first tiebreaker will be the current `referralFee`. If it&#39;s set to zero, means no referral fee is applied and the protocol will take 100% of the balance in all case scenarios.</p><p>Secondly, it&#39;s checked if the referrer address provided as the first argument is the address 0. If so, the contract address itself will receive the balance. This means that the fundamental key for the referral system to be used properly is to place the referrer address as a parameter. Otherwise leaving it to the zero address will result in the behavior that we are aware of today.</p><p>In case all criteria were met for the referral to work, the reward will be calculated by multiplying the balance in wei for the `referralFee` value, then dividing by 10.000.</p><p>The division by 10.000 is due to the use of two decimals to increase the fraction correctly. Let&#39;s say we have a low wei balance such as 86400, by multiplying by 1000 (referral fee at 10%), we get enough zeroes to divide by 10.000 (100%).</p><pre>86400 * 1000 = 86400000 / 10000 = 8640<br><br>protocol fee = 86400 - 8640<br>referral fee = 8640</pre><h4>How to Withdraw?</h4><p>This elegant `withdraw` function will only revert when the balance of a given address is less than the amount specified by the `withdrawMin` variable.</p><p>To execute this function, one should call the contract function `withdraw` and as the only input: hand the address which will be withdrawn.</p><pre>function withdraw(address addr) public {<br>    uint256 balance = balances[addr];<br>    if (balance &lt; withdrawMin) revert InsufficientValue();<br><br>    balances[addr] = 0;<br><br>    payable(addr == address(this) ? owner() : addr).call{value: balance}(<br>        &quot;&quot;<br>    );<br>}</pre><p>The address received as input will be used to create a temporary uint256 with the value that the address holds in the contract. The balance of that address in the map will then be set to 0.</p><p>The tactic of zeroing is used to avoid reentrancy while the removal of the notorious &quot;if (!sent)&quot; from the low-level call is a pointless reason and also an impeditive in a withdraw function.</p><p>A low-level call with no data but message value is put in place with a ternary operator determining the destination of the balance.</p><p>If the address provided in the first argument is the contract address itself, the balances withdrawn will be sent to the contract owner&#39;s address, otherwise, it would call the address passed as a parameter.</p><p>A good reminder that this function is public and can be called by any address to any address.</p><h4>Contract Changes</h4><p>A few modifications in the contract ETHRegistrarController are needed to embrace this feature, they are:</p><p><strong>Business rules:</strong></p><ul><li>ReferralFee starts at 10%</li><li>WithdrawMin starts at 1 ETH</li><li>Functions to set referralFee and withdrawMin called only by the contract owner</li><li>Withdraw should be a public function</li><li>MakeCommitment won’t receive the referrer address</li><li>Renew with Referrer is also possible</li><li>Referrals will only apply when the address is not 0</li><li>Referrers will show up in event emissions when applied</li></ul><p><strong>Three new functions:</strong></p><ul><li>setReferralFee ( uint256 newFee )</li><li>setWithdrawMin ( uint256 weiAmount )</li><li>_setBalances ( address referrer, uint256 balance )</li></ul><p><strong>Two new events:</strong></p><ul><li>MinimumWithdrawChanged ( uint256 weiAmount )</li><li>ReferralFeeChanged ( uint256 newFee )</li></ul><p><strong>Modified functions and interfaces:</strong></p><ul><li>register ( address referral … )</li><li>renew ( address referral … )</li></ul><h4>Considerations</h4><p>The referrer is not necessary for the `makeCommitment` process because it won’t be a bad thing if someone pays 90% of the name cost plus gas fees by front-running a pre-purchased name. It also avoids having another variable allocated in memory during contract execution.</p><p>Variable names and code locations in the contract are not yet certain and may vary as time passes and the discussion moves further next steps.</p><h4><strong>Gas Comparison</strong></h4><p>Of course, we cannot just blindly implement something without realizing the gas costs attached to the change itself. The method used to measure gas usage was through `estimateGas` function from Ethers Library.</p><pre>+----------------------+--------+-----------------------+--------+<br>| Current Operation(s) |  gas   | Referral Operation(s) |  gas   |<br>+----------------------+--------+-----------------------+--------+<br>| Reg                  | 236878 | Reg                   | 284504 |<br>| Reg, Res             | 262602 | Reg, Res              | 309492 |<br>| Reg, Res, Rec        | 300774 | Reg, Res, Rec         | 348414 |<br>| Reg, Res, Rev        | 356009 | Reg, Res, Rev         | 404021 |<br>| Reg, Res, Rec, Rev   | 392215 | Reg, Res, Rec, Rev    | 440065 |<br>+----------------------+--------+-----------------------+--------+<br>Reg = Registration<br>Res = Resolver<br>Rec = Records (setAddr)<br>Rev = Reverse</pre><p>Besides the `if` statements and event emissions, what really drives gas consumption crazy is writing in state variables. For both the referrer and contract, storage must be written, spending above 40000 gas units in doing so.</p><p>It is a relevant rise in expenses and further studies regarding the equilibrium carried out by this proposal must make it to public space.</p><p>Must be compensation by raising end-user gas usage, and the question here is: Will the referrer fee of 10% be enough to offer profits to the implementers while also providing cheap registration service in comparison with old controller versions?</p><h4>Backward Compatibility</h4><p>Past versions of the ETHRegistrarController won&#39;t be able to usufruct the referral benefits.</p><h4>Security Considerations</h4><p>Users that adventure themselves into coding their ways into registering names and projects experimenting on Mainnet should be cautious when using the referrer address as an argument.</p><p>Any successful attempts will correctly deliver the referral reward to the user balance, but it takes a large ETH quantity to withdraw from the contract.</p><p>The only way to retrieve fractions from the contract is in case the DAO decides to lower the minimum withdrawal fee to 0.</p><h4>Rationale</h4><p>We observe ENS becoming the core infrastructure for domain registration and management using Blockchain technology. Currently, EVM-focused and soon multi-chain, ENS moves into all the infrastructure aspects of itself, preparing the ground for its user base to monetize on the technology distribution of thoughtful dApps and elegant front-ends.</p><p>We see big players working around this technology, preparing the soil, sowing with affection, harvesting with splendor, and the future rewards that await the bringers of this tech. Currently, the following companies are introducing ENS technology:</p><ul><li><a href="https://ensfairy.xyz/">ENS Fairy</a></li><li><a href="https://ens.vision/">ENS Vision</a></li><li><a href="https://namehash.io/">NameHash</a></li></ul><h4>Timeline</h4><p>Apr 2022 — The discussion where the motivation started can be seen in the <a href="https://discuss.ens.domains/t/ens-affiliate-marketing-affiliate-program/11819">ENS Forum</a>.</p><p>May 2022 — A more structured debate was started by Alex Van de Sande in the <a href="https://discuss.ens.domains/t/adding-referral-fees-to-ethregistrarcontroller-sol/12599?u=avsa">Forum</a> as well.</p><p>Sep 2022 — Blockful first <a href="https://github.com/ensdomains/ens-contracts/pull/128">pull request</a> regarding the first contribution.</p><p>Sep 2022 — Blockful post <a href="https://medium.com/blockful/ethregistercontrollerv2-29d04eec48a5">Medium article</a> about the implementation.</p><p>May 2022 — <a href="https://ensgrants.xyz/rounds/22/proposals/595">ENS proposal</a> to bring this feature to life.</p><p>Jul 2023 — Blockful public <a href="https://github.com/blockful-io/ens-contracts">repository</a> working on the referral feature.</p><h4>Thank you</h4><p>By all means, join ENS and Blockcul at public community calls every week. Where the current status and future of the protocol will be discussed by the best minds behind it. You can start by adding the public <a href="https://calendar.google.com/calendar/u/0/embed?src=8im77u2b3euav0qjc067qb00ic@group.calendar.google.com&amp;ctz=auto">calendar</a> to your agenda.</p><p>Follow us and learn more!</p><p><a href="https://blockful.io/"><strong>Blockful</strong></a><strong> </strong>|<strong> </strong><a href="https://twitter.com/Blockful_io">🐦</a> | <a href="https://github.com/blockful-io">🐱</a> |<a href="https://www.linkedin.com/company/blockful"> 👤</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc6bbd9c241b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blockful/ens-referral-feature-cc6bbd9c241b">[ENS] Referral Feature</a> was originally published in <a href="https://medium.com/blockful">Blockful</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swaplace]]></title>
            <link>https://medium.com/blockful/swaplace-f9fd222d5636?source=rss-5fffaaaf5cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9fd222d5636</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[dex]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[evm]]></category>
            <dc:creator><![CDATA[Guihcneves]]></dc:creator>
            <pubDate>Wed, 10 May 2023 04:40:36 GMT</pubDate>
            <atom:updated>2023-07-12T19:20:21.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tm2AVs4VlhOLMUhWAcs69g.png" /></figure><h4>Next generation P2P swaps.</h4><p><strong>Context</strong></p><p>Blockful provides DeFi infrastructure and smart contract creation services for protocols, DAOs, financial institutions, fintechs, and entrepreneurs with blockchain projects.</p><p>To drive the industry forward, Blockful has pioneered a peer-to-peer (P2P), feeless and ownerless decentralized exchange (DEX) capable of on-chain swaps of any digital asset. Recognizing the barriers to technology adoption, Blockful has designed this solution as its inaugural open-source contribution, democratizing access for the broader community.</p><p>Swaplace is conceived as a groundbreaking P2P DEX, diverging from the standard models prevalent in the market. To actualize this vision, we are meticulously documenting and cultivating knowledge from every stage of development. Much like the article you’re currently reading, a wealth of insights awaits in future releases, each one more detailed and enlightening than the last.</p><p>Now, we’re about to delve into the technical specifics of a single topic among the entire protocol, just a tiny fraction of the development as a whole. If you’re not a developer or if blockchain architecture feels like uncharted territory, brace yourself for some complex concepts. However, if you’re on a quest for knowledge about smart contract development, prepare to hit a gold mine.</p><p><strong>Swaplace — Intro</strong></p><p>Swaplace is a protocol where anyone can swap anything on-chain as long as it is in the same blockchain and has a EVM architecture. The contract has no owners and charges no fees.</p><p>Swaplace operates via four primary mechanisms:</p><ul><li>Prepare trades</li><li>Create trades</li><li>Accept trades</li><li>Gather information</li></ul><p>This article will delve into the ‘acceptTrade’ function, which is designed to match assets requested by the trade owner, dispatched by the trade acceptor, with the assets offered by the owner, transferred to the trade acceptor.</p><p>It’s important to note that the contract itself does not manage approvals. Consequently, any front-end application integrating this contract must provide its users with the capability to create approvals using the data encapsulated within the contract.</p><p>In scenarios where approvals from both the trade owner and the trade acceptor are secured, the trade is executed by the trade acceptor.</p><p>To illustrate, let’s consider a trade scenario: 1x ERC20 and 1x ERC721 tokens are swapped from User A to User B, reciprocated with a function call that transfers 1x ERC721 token from User B to User A.</p><p>The Solidity version utilized for this application is ^0.8.17.</p><p><strong>Transferring Multiple Assets</strong></p><p>In instances where multiple assets need to be transferred, we typically employ a function such as the following:</p><pre>for (uint256 i = 0; i &lt; assets.length; i++) {<br>  Interface(addr).transferFrom(<br>    from,<br>    to,<br>    tokenId<br>  );<br>}</pre><p>When it comes to transferring various assets, we usually invoke functions such as transferFrom, safeTransferFrom, or other transfer methods that are associated with recognized ERC standards. This is realized by modifying the structure of the function, which can be represented as:</p><p>ContractLayout(contractAddress).contractFunction(param1, param2…)</p><p>This approach results in gas consumption, which is directly influenced by the way the transfer function is implemented. Theoretically, maximizing gas efficiency not only results in long-term cost savings but also expedites transaction execution. As this project strives for ownerlessness and permanence, every single gas drop counts!</p><p>Let’s consider the ‘for loop’ as an example. While it is absolutely necessary, there may be ways to decrease the gas expenditure. My initial idea was to leverage encoded function calls and other strategies to minimize the gas costs. However, before taking such a significant leap, it’s imperative to gain a deeper understanding of the inner contract communications occurring within the execution stack and to identify the most cost-effective pathways.</p><p>First: Let’s analyze the standard “this is how the function should be”:</p><pre>for (uint256 i = 0; i &lt; trade.asking.length; i++) {<br>     Asset memory asking = trade.asking[i];<br><br>     if (asking.assetType == AssetType.ERC20) {<br>         IERC20(asking.addr).transferFrom(<br>             msg.sender,<br>             trade.owner,<br>             asking.amountOrId<br>         );<br>     } else if (asking.assetType == AssetType.ERC721) {<br>         IERC721(asking.addr).transferFrom(<br>             msg.sender,<br>             trade.owner,<br>             asking.amountOrId<br>         );<br>     }<br> }<br><br> for (uint256 i = 0; i &lt; trade.assets.length; i++) {<br>     Asset memory assets = trade.assets[i];<br><br><br>     if (assets.assetType == AssetType.ERC20) {<br>         IERC20(assets.addr).transferFrom(<br>             trade.owner,<br>             msg.sender,<br>             assets.amountOrId<br>         );<br>     } else if (assets.assetType == AssetType.ERC721) {<br>         IERC721(assets.addr).transferFrom(<br>             trade.owner,<br>             msg.sender,<br>             assets.amountOrId<br>         );<br>     }<br> }</pre><p>In the above explanation, we’re discussing a ‘for loop’ that processes two types of transfers and two types of asset lists. The first asset array, termed ‘assets’, contains the elements of the trade that the trade owner is willing to part with in exchange for what they desire, which is held in the second asset array named ‘asking’. There’s a thought to rename ‘assets’ to ‘giving’ or ‘bidding’ for clarity — what are your thoughts? Please feel free to share in the comments!</p><p>For each asset in ‘assets’, we identify its type to access the corresponding interface functions. This allows us to invoke the underlying functions of the given contract at ‘assets.addr’ or ‘asking.addr’.</p><p>Now, let’s execute the following lines of code: (Note: The code environment being used is TypeScript within the Hardhat framework.)</p><pre>const gasEstimate = await Swaplace.connect(acceptee).estimateGas.acceptTrade(tradeId);<br>console.log(&quot;Gas estimation for accepting a trade: &quot;, gasEstimate.toString())</pre><p>In this step, we are establishing a connection between the acceptor (User B) and the contract instance. We are also estimating the gas consumption for accepting a trade, which corresponds to the function above.</p><p>The gas result of the code proposed was….:</p><p>Gas estimation for accepting a trade: 144213</p><p>Awesome, let’s fill up a table, this is a good start!</p><pre>+------------------------------------------+-----------+<br>|                 Methods                  | Gas Usage |<br>+------------------------------------------+-----------+<br>| Standard                                 |    144213 |<br>+------------------------------------------+-----------+</pre><p><strong>The optimization</strong></p><p>Now we begin the fun part, where we try to reduce gas usage, to become different from the average Joe.</p><p>I’m curious to see if I can reduce the cost by removing the following variables being settled:</p><pre> Asset memory asking = trade.asking[i];<br> Asset memory assets = trade.assets[i];</pre><p>I can remove these references above from the for loop and change on the contract from this:</p><pre>asking.amountOrId</pre><p>..to this:</p><pre>trade.asking[i].amountOrId</pre><p>The result for the above modifications is the following:</p><pre>for (uint256 i = 0; i &lt; trade.asking.length; i++) {<br>   if (trade.asking[i].assetType == AssetType.ERC20) {<br>       IERC20(trade.asking[i].addr).transferFrom(<br>           msg.sender,<br>           trade.owner,<br>           trade.asking[i].amountOrId<br>       );<br>   } else if (trade.asking[i].assetType == AssetType.ERC721) {<br>       IERC721(trade.asking[i].addr).transferFrom(<br>           msg.sender,<br>           trade.owner,<br>           trade.asking[i].amountOrId<br>       );<br>   }<br>}<br><br>for (uint256 i = 0; i &lt; trade.assets.length; i++) {<br>   if (trade.assets[i].assetType == AssetType.ERC20) {<br>       IERC20(trade.assets[i].addr).transferFrom(<br>           trade.owner,<br>           msg.sender,<br>           trade.assets[i].amountOrId<br>       );<br>   } else if (trade.assets[i].assetType == AssetType.ERC721) {<br>       IERC721(trade.assets[i].addr).transferFrom(<br>          trade.owner,<br>           msg.sender,<br>           trade.assets[i].amountOrId<br>       );<br>   }<br>}</pre><p>Running the same estimate gas test again will return the following output:<br>Gas estimation for accepting a trade: 144707</p><pre>+------------------------------------------+-----------+<br>|                 Methods                  | Gas Usage |<br>+------------------------------------------+-----------+<br>| Standard                                 |    144213 |<br>| Not setting &quot;Asset&quot; as variable          |    144707 |<br>+------------------------------------------+-----------+</pre><p>Conclusion: Not worth it!<br>The access to read the large variable multiple times is not compensating to set only a part of it. Standard wins… for now.</p><p><strong>Universal Transfer</strong></p><p>I observed that the ‘transferFrom’ interface for both ERC20 and ERC721 tokens utilizes the same interface identifier. As a result, it led me to conclude that the type of asset being transacted becomes irrelevant as long as the tokens are possessed and the transaction functions as intended.</p><pre>interface IUniversalTransfer {<br>   function transferFrom(<br>       address from,<br>       address to,<br>       uint256 amountOrId<br>   ) external;<br>}</pre><p>By modifying the method used to identify the asset type, I’m able to significantly streamline the size of the function:</p><pre>for (uint256 i = 0; i &lt; trade.asking.length; i++) {<br>   Asset memory asking = trade.asking[i];<br><br><br>   IUniversalTransfer(asking.addr).transferFrom(<br>       msg.sender,<br>       trade.owner,<br>       asking.amountOrId<br>   );<br>}<br><br>for (uint256 i = 0; i &lt; trade.assets.length; i++) {<br>   Asset memory assets = trade.assets[i];<br><br><br>   IUniversalTransfer(assets.addr).transferFrom(<br>       trade.owner,<br>       msg.sender,<br>       assets.amountOrId<br>   );<br>}</pre><p>Gas estimation for accepting a trade: 143505</p><p>The gas output came with better results for us! That is a smart move, 10 points for Gryffindor.</p><pre>+------------------------------------------+-----------+<br>|                 Methods                  | Gas Usage |<br>+------------------------------------------+-----------+<br>| Standard                                 |    144213 |<br>| Not setting &quot;Asset&quot; as variable          |    144707 |<br>| Using universal interface                |    143505 |<br>+------------------------------------------+-----------+</pre><p><strong>For the sake of curiosity</strong></p><p>In our continuous pursuit of gas optimization, we’ll attempt to eliminate the Asset variable once more, which would result in the function taking the following form:</p><pre>for (uint256 i = 0; i &lt; trade.asking.length; i++) {<br>   IUniversalTransfer(trade.asking[i].addr).transferFrom(<br>       msg.sender,<br>       trade.owner,<br>       trade.asking[i].amountOrId<br>   );<br>}<br><br>for (uint256 i = 0; i &lt; trade.assets.length; i++) {<br>   IUniversalTransfer(trade.assets[i].addr).transferFrom(<br>       trade.owner,<br>       msg.sender,<br>       trade.assets[i].amountOrId<br>   );<br>}</pre><p>Will the gas cost be less now that we are calling it less times??</p><p>Gas estimation for accepting a trade: 143661</p><pre>+------------------------------------------+-----------+<br>|                 Methods                  | Gas Usage |<br>+------------------------------------------+-----------+<br>| Standard                                 |    144213 |<br>| Not setting &quot;Asset&quot; as variable          |    144707 |<br>| Using universal interface                |    143505 |<br>| Not setting &quot;Asset&quot; and using universal  |    143661 |<br>+------------------------------------------+-----------+</pre><p>Still bigger in gas cost. 🙁<br>Did you notice the decrease in gas cost from our first attempt to the second? This suggests there may be an optimal threshold to investigate, indicating that further modifications may yield diminishing returns in terms of gas optimization.</p><p>What If we set the ‘Assets’ array outside? As so:</p><pre>Asset[] memory asking = trade.asking;<br> for (uint256 i = 0; i &lt; asking.length; i++) {<br>     IUniversalTransfer(asking[i].addr).transferFrom(<br>         msg.sender,<br>         trade.owner,<br>         asking[i].amountOrId<br>     );<br> }<br><br> Asset[] memory assets = trade.assets;<br> for (uint256 i = 0; i &lt; assets.length; i++) {<br>     IUniversalTransfer(assets[i].addr).transferFrom(<br>         trade.owner,<br>         msg.sender,<br>         assets[i].amountOrId<br>     );<br> }</pre><p>Gas estimation for accepting a trade: 143598</p><pre>+------------------------------------------+-----------+<br>|                 Methods                  | Gas Usage |<br>+------------------------------------------+-----------+<br>| Standard                                 |    144213 |<br>| Not setting &quot;Asset&quot; as variable          |    144707 |<br>| Using universal interface                |    143505 |<br>| Not setting &quot;Asset&quot; and using universal  |    143661 |<br>| Universal and &quot;Assets&quot; outside the for   |    143598 |<br>+------------------------------------------+-----------+</pre><p>That was a huge jump LOL !! Way to go!</p><p>Can I reutilize the same variable to reduce gas cost? By not setting a second one, this might reduce our costs…</p><pre> Asset[] memory assets = trade.asking;<br> for (uint256 i = 0; i &lt; assets.length; i++) {<br>     IUniversalTransfer(assets[i].addr).transferFrom(<br>         msg.sender,<br>         trade.owner,<br>         assets[i].amountOrId<br>     );<br> }<br><br><br> assets = trade.assets;<br> for (uint256 i = 0; i &lt; assets.length; i++) {<br>     IUniversalTransfer(assets[i].addr).transferFrom(<br>         trade.owner,<br>         msg.sender,<br>         assets[i].amountOrId<br>     );<br> }</pre><p>Gas estimation for accepting a trade: 143566</p><pre>+------------------------------------------+-----------+<br>|                 Methods                  | Gas Usage |<br>+------------------------------------------+-----------+<br>| Standard                                 |    144213 |<br>| Not setting &quot;Asset&quot; as variable          |    144707 |<br>| Using universal interface                |    143505 |<br>| Not setting &quot;Asset&quot; and using universal  |    143661 |<br>| Universal and &quot;Assets&quot; outside the for   |    143598 |<br>| Universal and &quot;Assets&quot; outside + reuse   |    143566 |<br>+------------------------------------------+-----------+</pre><p>Isn’t this getting more fun as it goes? I wonder what else we can explore while finding simpler ways to build important stuff! 🤓</p><p><strong>Using function encoding</strong></p><p>I’ll just print here the monster and explain after the DOM renders it 😂.</p><pre>Asset[] memory assets = trade.asking;<br>for (uint256 i = 0; i &lt; assets.length; i++) {<br>   bytes memory data = abi.encodeWithSelector(<br>       IUniversalTransfer.transferFrom.selector,<br>       msg.sender,<br>       trade.owner,<br>       assets[i].amountOrId<br>   );<br><br><br>   (bool success, bytes memory returned) = assets[i].addr.call(data);<br><br><br>   if (!success) {<br>       revert FunctionCallFailedWithReason(returned);<br>   }<br>}<br><br><br>assets = trade.assets;<br>for (uint256 i = 0; i &lt; assets.length; i++) {<br>   bytes memory data = abi.encodeWithSelector(<br>       IUniversalTransfer.transferFrom.selector,<br>       trade.owner,<br>       msg.sender,<br>       assets[i].amountOrId<br>   );<br><br><br>   (bool success, bytes memory returned) = assets[i].addr.call(data);<br><br><br>   if (!success) {<br>       revert FunctionCallFailedWithReason(returned);<br>   }<br>}</pre><p>Just kidding, let’s go! What is happening above?</p><p>What we’re doing here is taking the elements of the trade that were originally intended to populate the transfer function. However, we’ll encode these elements using the function selector from our imported interface, subsequently calling the contract to execute the function using the generated ‘bytes data’. If any errors arise, we will print a revert message.</p><p>As diligent coders, no errors occurred and here is the resulting gas cost for this modification:</p><p>Gas estimation for accepting a trade: 145946</p><pre>+------------------------------------------+-----------+<br>|                 Methods                  | Gas Usage |<br>+------------------------------------------+-----------+<br>| Standard                                 |    144213 |<br>| Not setting &quot;Asset&quot; as variable          |    144707 |<br>| Using universal interface                |    143505 |<br>| Not setting &quot;Asset&quot; and using universal  |    143661 |<br>| Universal and &quot;Assets&quot; outside the for   |    143598 |<br>| Universal and &quot;Assets&quot; outside + reuse   |    143566 |<br>| Universal + Function Call + Assets       |    145946 |<br>+------------------------------------------+-----------+</pre><p>It appears that the encoding process is consuming an excessive amount of gas, and the inclusion of conditional statements within the scope is further compounding the load. Frankly, the results are somewhat disheartening. 😣</p><p>A key challenge with function calls is their ability to proceed regardless of success or failure — they only perform the operation, without necessarily validating it. This makes the use of conditional ‘if’ statements vital for handling potential failures.</p><p>If I change this:</p><pre>(bool success, bytes memory returned) = assets[i].addr.call(data);<br><br><br>   if (!success) {<br>       revert FunctionCallFailedWithReason(returned);<br>   }</pre><p>..to this:</p><pre>(bool success,) = assets[i].addr.call(data);<br>require(success, &quot;Transfer failed&quot;);</pre><p>We get a gas estimation of 145918. Which is slightly lesser, but this is achieved at the cost of proper error handling standards. Therefore, we’ve decided not to adopt this modification and will maintain the revert mechanism to ensure robust error handling.</p><p><strong>Using pre-built encoded function</strong></p><p>What would happen if we encoded the function and its arguments off-chain and then simply initiated the trade? Or what if the function parameters were already present on-chain and all we had to do was call them? Could these approaches lead to considerable cost reductions? What if we stored the encoded function instead of the token parameters? Given that these parameters remain constant from the creation of the trade to its finalization, could we leverage this instead of the overall parameters?</p><p>Before we proceed, it’s important to note that this approach won’t work for functions that depend on dynamic changes during their execution. For instance, we don’t know in advance who will accept the trade, so a pre-configured transfer function wouldn’t know where to send the assets since the recipient is unknown…</p><p>However, for the sake of this experiment and for the enhancement of our collective knowledge, let’s imagine a scenario where we do know the destination of the assets. We are essentially trading a function execution, a pre-configured execution that will only complete if the trade meets the defined criteria!</p><p>I changed the variable name from ‘amountOrId’ to ‘amountOrIdOrCall’:</p><pre> struct Asset {<br>     address addr;<br>     uint256 amountOrIdOrCall;<br>     AssetType assetType;<br> }</pre><p>I also made up three function for this small environment, allowing users to fill up an index of possible calls they wish to execute:</p><pre>uint256 public index = 0;<br>mapping(bytes32 =&gt; bytes) private executions;<br><br><br>function registerExecution(bytes calldata data) public {<br>   index++;<br>   bytes32 id = keccak256(abi.encodePacked(index, msg.sender, data));<br>   executions[id] = data;<br>}<br><br><br>function getExecutionId(<br>   uint256 _index,<br>   address _addr,<br>   bytes memory data<br>) public pure returns (bytes32) {<br>   return keccak256(abi.encodePacked(_index, _addr, data));<br>}<br><br><br>function getExecutions(bytes32 id) public view returns (bytes memory) {<br>   return executions[id];<br>}</pre><p>We are accounting for every single registration in the index, along with the creator of the data and the data itself. All of this information is encoded and hashed to form its own unique ID.</p><p>We’ve also constructed a read function that allows users to generate IDs, along with a method to retrieve data from the execution mapping by supplying a ‘bytes32 id’.</p><p>Please note that this registration method is beyond the scope of this article and will not be optimized or considered as such.</p><p>Given that we’re registering the ID as a bytes32, we have the option to use uint256(bytes32) to convert the bytes32 identifier into a value that can be accommodated within ‘amountOrId’. This is why our only requirement is to include the FUNCTION_CALL option in our enumerator!</p><pre>   enum AssetType {<br>       ERC20,<br>       ERC721,<br>       FUNCTION_CALL<br>   }</pre><p>Now the option to execute a function call will depend on the asset type as so:</p><pre>Asset[] memory assets = trade.asking;<br><br>for (uint256 i = 0; i &lt; assets.length; i++) {<br>   if (assets[i].assetType == AssetType.FUNCTION_CALL) {<br>       (bool success, bytes memory reason) = assets[i].addr.call(<br>           executions[bytes32(assets[i].amountOrIdOrCall)]<br>       );<br><br><br>       if (!success) {<br>           revert FunctionCallFailedWithReason(reason);<br>       }<br>   } else {<br>       IUniversalTransfer(assets[i].addr).transferFrom(<br>           msg.sender,<br>           trade.owner,<br>           assets[i].amountOrIdOrCall<br>       );<br>   }<br>}<br><br>assets = trade.assets;<br><br>for (uint256 i = 0; i &lt; assets.length; i++) {<br>   if (assets[i].assetType == AssetType.FUNCTION_CALL) {<br>       (bool success, bytes memory reason) = assets[i].addr.call(<br>           executions[bytes32(assets[i].amountOrIdOrCall)]<br>       );<br><br><br>       if (!success) {<br>           revert FunctionCallFailedWithReason(reason);<br>       }<br>   } else {<br>       IUniversalTransfer(assets[i].addr).transferFrom(<br>           trade.owner,<br>           msg.sender,<br>           assets[i].amountOrIdOrCall<br>       );<br>   }<br>}</pre><p>What’s occurring here is that if the AssetType is identified as FUNCTION_CALL, we utilize the ‘amountOrIdOrCall’ variable, converting it into a bytes32 representation. We then search the index for its activation code, which is located at the address specified in the Asset type.</p><p>Gas estimation for accepting a trade: 144033</p><pre>+------------------------------------------+-----------+<br>|                 Methods                  | Gas Usage |<br>+------------------------------------------+-----------+<br>| Standard                                 |    144213 |<br>| Not setting &quot;Asset&quot; as variable          |    144707 |<br>| Using universal interface                |    143505 |<br>| Not setting &quot;Asset&quot; and using universal  |    143661 |<br>| Universal and &quot;Assets&quot; outside the for   |    143598 |<br>| Universal and &quot;Assets&quot; outside + reuse   |    143566 |<br>| Universal + Function Call + Assets       |    145946 |<br>| Universal + Call (v2) + Assets           |    144033 |<br>+------------------------------------------+-----------+</pre><p>We remain 467 gas units away from our optimal target, which involves eliminating the use of ‘if’ statements. But hey, let’s take a moment to appreciate what we’ve achieved. Did we just create a P2P DEX capable of trading function calls within the realm of smart contracts? I’d say that’s pretty impressive. 😎</p><p>Now, let’s consider the necessary preparations for this function to operate smoothly. Here are some TypeScript snippets that demonstrate the off-chain to contract interaction:</p><pre>const index = await Swaplace.index();<br>const data = MockERC721.interface.encodeFunctionData(&quot;transferFrom(address,address,uint256)&quot;, [<br>   acceptee.address,<br>   owner,<br>   lastMinted,<br> ]);<br>const executionData = await Swaplace.getExecutionId(index + 1, acceptee.address, data);<br><br>await Swaplace.connect(acceptee).registerExecution(data);<br>expect(await Swaplace.getExecutions(executionData)).to.be.equal(data);</pre><ul><li>The index will be the current + 1, since the registration of a new encodedFunctionData will increase the total count.</li><li>The data is the encoded Function + Parameters that results in a bytes type.</li><li>The executionData will fetch the data at that index and is expected to match the data inserted.</li></ul><p><strong>Overall speaking</strong></p><p>This entire process signifies that we can effortlessly swap our ERC20 or ERC721 tokens, or indeed anything else within the ecosystem! While in this example the function calls must be pre-configured, we are actively refining this solution to accommodate all conceivable scenarios within the proposed ecosystem. Through the creation of modular functions, we can either conserve gas or expend more gas to facilitate more complex mechanics.</p><p>An intriguing idea could be to split the acceptTrade function into two: acceptTrade and acceptTradeWithCall. The first function would encapsulate the optimal code found for the initial objective, while the second function would best handle function calls. All of this could be achieved without altering the core structure of the trade.</p><p>However, given that we’re currently in the Minimum Viable Product (MvP) stage, we’ll keep things straightforward for now and refrain from dividing the functions just yet. So, without further ado, our final winner of the night is…:</p><pre>function acceptTrade(uint256 _tradeId) public {<br>   Trade memory trade = trades[_tradeId];<br><br>   Asset[] memory assets = trade.asking;<br><br>   for (uint256 i = 0; i &lt; assets.length; i++) {<br>       if (assets[i].assetType == AssetType.FUNCTION_CALL) {<br>           (bool success, bytes memory reason) = assets[i].addr.call(<br>               executions[bytes32(assets[i].amountOrIdOrCall)]<br>           );<br><br><br>           if (!success) {<br>               revert FunctionCallFailedWithReason(reason);<br>           }<br>       } else {<br>           IUniversalTransfer(assets[i].addr).transferFrom(<br>               msg.sender,<br>               trade.owner,<br>               assets[i].amountOrIdOrCall<br>           );<br>       }<br>   }<br><br>   assets = trade.assets;<br><br>   for (uint256 i = 0; i &lt; assets.length; i++) {<br>       if (assets[i].assetType == AssetType.FUNCTION_CALL) {<br>           (bool success, bytes memory reason) = assets[i].addr.call(<br>               executions[bytes32(assets[i].amountOrIdOrCall)]<br>           );<br><br><br>           if (!success) {<br>               revert FunctionCallFailedWithReason(reason);<br>           }<br>       } else {<br>           IUniversalTransfer(assets[i].addr).transferFrom(<br>               trade.owner,<br>               msg.sender,<br>               assets[i].amountOrIdOrCall<br>           );<br>       }<br>   }<br><br><br>   delete (trades[_tradeId]);<br>}</pre><p>Woooooo… What a nice function we got here after all this development!</p><p>After adding the deletion of a trade after its conclusion and the nonReentrant modifier, our final gas usage is:</p><ul><li>Gas estimation for accepting a trade: 144033</li><li>Gas estimation for accepting a trade (delete): 180540</li><li>Gas estimation for accepting a trade (delete+nonReentrant): 188059</li></ul><pre>+------------------------------------------+-----------+<br>|                 Methods                  | Gas Usage |<br>+------------------------------------------+-----------+<br>| Standard                                 |    144213 |<br>| Not setting &quot;Asset&quot; as variable          |    144707 |<br>| Using universal interface                |    143505 |<br>| Not setting &quot;Asset&quot; and using universal  |    143661 |<br>| Universal and &quot;Assets&quot; outside the for   |    143598 |<br>| Universal and &quot;Assets&quot; outside + reuse   |    143566 |<br>| Universal + Function Call + Assets       |    145946 |<br>| Universal + Call (v2) + Assets           |    144033 |<br>| Best Practices + nonR + delete           |    188059 |<br>+------------------------------------------+-----------+</pre><p>That’s a 30% increase for the sake of security!! 👮🔒</p><p><strong>‘’Delete Function’’ gas cost is killing me!</strong></p><p>Spending gas just to erase history from the blockchain doesn’t seem quite right, does it? Let’s give this function another go in an effort to further reduce the gas cost. By the way, we’re not going to modify the nonReentrant, given that we’re dealing with low-level function calls — which could be likened to handling molten lava with our bare hands!</p><p>My initial considerations about the delete statement were as follows</p><ul><li>I don’t want to establish a new state or delete an existing one.</li><li>I should modify something already present in the trade to invalidate it once it’s accepted.</li></ul><p>An idea then came to mind to incorporate an expiry option. Utilizing a feature like an expiration period could define the window within which the trade should be accepted, while also invalidating it if it falls outside of this range.</p><pre>struct Trade {<br>   address owner;<br>   uint256 expiry;<br>   Asset[] assets;<br>   Asset[] asking;<br>}</pre><p>The trade structure appears as straightforward as it ought to be.</p><pre>if (trade.expiry &lt; block.timestamp) {<br>   revert TradeExpired();<br>}</pre><p>The above conditional will check if the trade expiration is still valid, otherwise, revert with custom error.</p><pre>function acceptTrade(uint256 _tradeId) public nonReentrant {<br>          <br>   . . .<br><br>   if (trade.expiry &lt; block.timestamp) {<br>             revert TradeExpired();<br>          }<br><br>   . . .<br><br>   trades[_tradeId].expiry = 0;<br>}</pre><p>By setting the expiry to ‘0’, we ensure that the trade will never be accepted again, while also maintaining the history of the trade intact. Although this approach will cost us a bit more in terms of gas, let’s take a moment to appreciate the outcome:</p><p>Gas estimation for accepting a trade: 154485</p><pre>+------------------------------------------+-----------+<br>|                 Methods                  | Gas Usage |<br>+------------------------------------------+-----------+<br>| Standard                                 |    144213 |<br>| Not setting “Asset” as variable          |    144707 |<br>| Using universal interface                |    143505 |<br>| Not setting “Asset” and using universal  |    143661 |<br>| Universal and “Assets” outside the for   |    143598 |<br>| Universal and “Assets” outside + reuse   |    143566 |<br>| Universal + Function Call + Assets       |    145946 |<br>| Universal + Call (v2) + Assets           |    144033 |<br>| Best Practices + nonR + delete           |    188059 |<br>| Best Practices + nonR + Expired          |    154485 | <br>+------------------------------------------+-----------+</pre><p>This approach has significantly amplified the contract’s potential! A well-considered architecture can guide a project towards its most luminous days.</p><p>In the blockchain industry, the importance of code architecture and gas optimization cannot be overstated. A sound code architecture is the foundation upon which robust, reliable, and scalable blockchain systems are built. It determines how different components interact with each other, the system’s response to user input, and how data flows within the system.</p><p>Moreover, a well-optimized contract not only reduces costs but also enhances transaction speed and the overall performance of the blockchain. This ultimately improves the user experience, making the blockchain platform more accessible and attractive to users.</p><p>In an industry where competition is fierce and efficiency is key, effective code architecture and gas optimization serve as crucial differentiators. They are not merely technical considerations but strategic imperatives that can propel a blockchain project to success.</p><p><strong>But wait, there is more!</strong></p><p>There is one last play I saved for last! I think most that followed through will enjoy it!</p><pre>for (uint256 i = 0; i &lt; assets.length;) {</pre><p>By removing the “i++” from the for loop and inserting it at the bottom of the for execution as it is shown in the next snippet:</p><pre>for (uint256 i = 0; i &lt; assets.length;) {<br>   if (assets[i].assetType == AssetType.FUNCTION_CALL) {<br>       (bool success, bytes memory reason) = assets[i].addr.call(<br>           executions[bytes32(assets[i].amountOrIdOrCall)]<br>       );<br><br>       if (!success) {<br>           revert FunctionCallFailedWithReason(reason);<br>       }<br>   } else {<br>       IUniversalTransfer(assets[i].addr).transferFrom(<br>           msg.sender,<br>           trade.owner,<br>           assets[i].amountOrIdOrCall<br>       );<br>   }<br>   unchecked {<br>       i++;<br>   }<br>}</pre><p>We can skip solidity’s safeMath for which the compiler intrinsically sums to the gas cost. By placing the equation inside the ‘unchecked’ statement, safe checks are unused, thus saving us a bunch of gasses!</p><p>This method is dangerous and should only be used when you are aware that it functions as intended. In the current scenario, we’re only summing one plus one without any exterior variable inferring in adulteration of the outcome. Making it safe to apply this good practice.</p><p>And the result? Well let’s see, but first I’ll leave the final state of the polished function for the acceptTrade method:</p><pre>function acceptTrade(uint256 _tradeId) public nonReentrant {<br>   Trade memory trade = trades[_tradeId];<br><br>   if (trade.expiry &lt; block.timestamp) {<br>       revert TradeExpired();<br>   }<br><br>   Asset[] memory assets = trade.asking;<br><br>   for (uint256 i = 0; i &lt; assets.length; ) {<br>       if (assets[i].assetType == AssetType.FUNCTION_CALL) {<br>           (bool success, bytes memory reason) = assets[i].addr.call(<br>               executions[bytes32(assets[i].amountOrIdOrCall)]<br>           );<br><br>           if (!success) {<br>               revert FunctionCallFailedWithReason(reason);<br>           }<br>       } else {<br>           IUniversalTransfer(assets[i].addr).transferFrom(<br>               msg.sender,<br>               trade.owner,<br>               assets[i].amountOrIdOrCall<br>           );<br>       }<br>       unchecked {<br>           i++;<br>       }<br>   }<br><br>   assets = trade.assets;<br><br>   for (uint256 i = 0; i &lt; assets.length; ) {<br>       if (assets[i].assetType == AssetType.FUNCTION_CALL) {<br>           (bool success, bytes memory reason) = assets[i].addr.call(<br>               executions[bytes32(assets[i].amountOrIdOrCall)]<br>           );<br><br>           if (!success) {<br>               revert FunctionCallFailedWithReason(reason);<br>           }<br>       } else {<br>           IUniversalTransfer(assets[i].addr).transferFrom(<br>               trade.owner,<br>               msg.sender,<br>               assets[i].amountOrIdOrCall<br>           );<br>       }<br>       unchecked {<br>           i++;<br>       }<br>   }<br><br>   trades[_tradeId].expiry = 0;<br>}</pre><p>Gas estimation for accepting a trade: 154038</p><pre>+------------------------------------------+-----------+<br>|                 Methods                  | Gas Usage |<br>+------------------------------------------+-----------+<br>| Standard                                 |    144213 |<br>| Not setting “Asset” as variable          |    144707 |<br>| Using universal interface                |    143505 |<br>| Not setting “Asset” and using universal  |    143661 |<br>| Universal and “Assets” outside the for   |    143598 |<br>| Universal and “Assets” outside + reuse   |    143566 |<br>| Universal + Function Call + Assets       |    145946 |<br>| Universal + Call (v2) + Assets           |    144033 |<br>| Best Practices + nonR + delete           |    188059 |<br>| Best Practices + nonR + Expired          |    154485 |<br>| Best Pract. + nonR + Expired + unchecked |    154038 |<br>+------------------------------------------+-----------+</pre><p><strong>Conclusion</strong></p><p>“Usually the best path is the simplest one, and it’s research is the longest one” — Axis</p><p>Optimization and architecture will guide your development into more complex areas of expertize. What was proposed here is the mental process I have to face daily while developing smart contracts and the experimentation one needs to challenge himself to better perform in this industry.</p><p>I hope we can keep learning and delivering together for business and DAOs to empower ourselves and deliver best results for the community. We pledge quality content, if you liked this, follow us on social media for more.</p><p>Follow us and learn more!</p><p><a href="https://github.com/blockful-io"><strong>Blockful</strong></a><strong> </strong>|<a href="https://twitter.com/Blockful_io"><strong> </strong>🐦</a> |<a href="https://github.com/blockful-io"> 🐱‍👤</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9fd222d5636" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blockful/swaplace-f9fd222d5636">Swaplace</a> was originally published in <a href="https://medium.com/blockful">Blockful</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blockful integrates Balancer’s Vault with Aztec Privacy Network]]></title>
            <link>https://medium.com/blockful/blockful-integrates-balancers-vault-with-aztec-privacy-network-440ed2988b55?source=rss-5fffaaaf5cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/440ed2988b55</guid>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[balancer]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[zkrollup]]></category>
            <category><![CDATA[aztec-network]]></category>
            <dc:creator><![CDATA[Guihcneves]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 01:50:28 GMT</pubDate>
            <atom:updated>2023-04-10T16:49:18.879Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSEaMZinq8WuuACorK6MJQ.png" /></figure><p>As Blockful, we are excited to announce the conclusion of the integration between the Aztec protocol and the Balancer protocol that is bringing privacy to users while managing their DeFi positions. A simple optic of this integration is our task to hide Balancer’s customers operations using Aztec as a relayer.</p><p>Balancer provides access to secure infrastructure for liquidity applications while Aztec enables decentralized applications to access privacy and scalability. Blockful builds tailor-made integrations and applications for the web3 industry.</p><p>The biggest challenge faced during the integration was the difference in programming languages used by the two platforms. Balancer uses Typescript while Aztec uses Solidity (Foundry). To overcome this, we had to recreate the necessary off-chain mechanism within the Aztec test suite, but in Solidity, making it dynamically programmable for all Balancer’s vault action cases.</p><p>Another key element in this integration is the usage of the Convert function, which is an immutable standard interface for the Aztec rollup.</p><p>We encoded the necessary vault inputs into a uint64 format using solidity instead of typescript, then saved the inputs in a storage mapping, and called the Convert(…) function, passing the encoded inputs as parameters to fetch the storage ref, all in a single transaction. While this method may require extra gas, it can reach further into the convert function limitation of simple swaps and fully capitalize on Balancer’s full potential of handling N to N tokens assets.</p><p>The above method used in the Balancer Bridge to call Balancer’s vault actions, perfectly showcases that we can implement any functionalities with ease. The contract is currently handling the following actions:</p><ul><li>Single Swaps</li><li>Batch Swaps</li><li>Join/Exit Pools</li></ul><p>We are true believers that integrations like this have the potential to significantly enhance the DeFi ecosystem and provide privacy for our users.</p><p>Blockful thanks both the Aztec and Balancer teams for their support during the development of this integration. The collaboration between these two well-established protocols has made it possible for Blockful to grow from this experience leave a trail of knowledge to empower the future newcomers of the ZK and Privacy industry.</p><p><strong>About Aztec</strong></p><p>Aztec Network is the first private ZK-rollup on Ethereum, enabling decentralized applications to access privacy and scale. Aztec Connect is the VPN for Ethereum — a set of tools that connects Ethereum DeFi protocols directly to Aztec’s private rollup, allowing for composable, private DeFi to be done on Ethereum for the first time ever.</p><p><strong>About Balancer</strong></p><p>Balancer’s mission is to accelerate innovation in DeFi by providing access to secure infrastructure for liquidity applications. As a core building block of DeFi, Balancer Protocol is community driven and is reliable, open-source, and permission-less. Projects build on Balancer to create new, innovative types of pools and financial DApps. Visit balancer.fi to learn more.</p><p>Follow us and learn more!</p><p><a href="https://github.com/blockful-io"><strong>Blockful</strong></a><strong> </strong>|<strong> </strong><a href="https://twitter.com/Blockful_io">🐦</a> | <a href="https://github.com/blockful-io">🐱‍👤</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=440ed2988b55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blockful/blockful-integrates-balancers-vault-with-aztec-privacy-network-440ed2988b55">Blockful integrates Balancer’s Vault with Aztec Privacy Network</a> was originally published in <a href="https://medium.com/blockful">Blockful</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum Name Service V2]]></title>
            <link>https://0xneves.medium.com/ethereum-name-service-v2-e7831e96f261?source=rss-5fffaaaf5cb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7831e96f261</guid>
            <category><![CDATA[en]]></category>
            <category><![CDATA[ethereum-name-service]]></category>
            <category><![CDATA[eth]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Guihcneves]]></dc:creator>
            <pubDate>Thu, 08 Sep 2022 18:39:54 GMT</pubDate>
            <atom:updated>2022-09-15T19:58:20.801Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ethereum Name Service</h3><p>Brief introduction on what’s boiling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*YIfXxTWz8ngfdRCSg7ITjg.png" /></figure><h3>1. Intro</h3><p>This present article will cite the more relevant modifications embracing the features voted by the ENS community. The full technical article can be found <a href="https://medium.com/@guihcneves/ethereum-name-service-5494c49930bf">here</a> and the gas tests <a href="https://docs.google.com/spreadsheets/d/18bcSbpRuz2cPuy2_foI3jQLFJS_WYHciOGgEWkITtnI/edit">here</a>.</p><p>Embracing the features voted by the ENS community and demonstrating the gas savings of up to 40% per registration and 75% per renew in relation to the current method.</p><h3>2. Features Implemented</h3><p><strong>2.1. Referral: </strong>This feature aims at giving power to registrar apps and influencers as the protocol will shares its service fees with the referrer.</p><p>Front-end apps can be built to prospect the ENS services in their own domain. It is expected an increase in the engagement and more elaborated gamifications of the protocol.</p><p><strong>2.2. Commit with Payment</strong></p><p>Currently the ENS app requires two transactions, the first being a plain commitment and the second a reveal where the user sends funds.</p><p>Currently a commitment has a minimal waiting period of 1 minute and a maximum expiry date of 1 week, meaning that the user could commit to one name and only send the transaction a few days later, but this is not recommended as the name is only registered on the last step, taking 4 steps for the payment to happen. We changed the process so that users could pay first and have their names revealed later by the front-end app.</p><p><strong>2.3. Batch Commit</strong></p><p>Since in the previous feature we added the option to pay in the commitment and the referral system, we expect single transactions to be more expensive due to storage use and more checks, but with the batch feature, we made the overall cost of multiple names a cheaper process.</p><p><strong>2.4. Batch Reveal</strong></p><p>This feature aims to reveal an entire batch of names at once. It will consume the credits of the commit creator that resides on the contract or use msg.value to reveal the batch, in case it meets all criteria.</p><p>We made this feature in a way where batches are the intention to register multiple names, containing multiple registrations residing in an array. Even 1 name, is an array with length 1, and so on.</p><p><strong>2.5. Batch Renew</strong></p><p>We found that renews could also be done in batch , thus we tested the efficiency of it finding out that renewing a batch of 100 names will save up to 74% gas in a single transaction instead of running the same function 100 times.</p><h3>3. Contracts Modifications</h3><p>Organizing the core functions of the protocol, we implemented an interface(solidity’s struct), that will become a more elegant way of managing the registrations in batches:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d097df0924ff154e5b1fc35f5f81805/href">https://medium.com/media/2d097df0924ff154e5b1fc35f5f81805/href</a></iframe><p>Every registration holds enough information to guarantee the purchase of names and services. This allows the contract to loop the batch, registering all names in it. Since the consumeCommitment is now called only once in multiple names registered, the gas consumption is reduced for batch name reveals.</p><p>We registered 190 names and measured the gas uses for the commits, reveals and renews comparing the current batch (v2) approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*0GRUVAa7m-SoEsHnKeTA1w.png" /></figure><p>We first realize that there is a massive saving with the commit operation itself, since the quantity of times this would be called would change from 190 to 1. Reducing the gas cost of the commits from 8398190 to 44201. If you notice, this will save around 99% of the current cost.</p><p>Now jumping to the reveal function which is the last step before firming the registration, we’ve managed totaling 262705 of average gas cost for simple reveals including all the new features, this is an increase of around 12% for single registrations.</p><p>Although the first name might have a cost increase, the batch mechanism slightly reduces each subsequent name revealed, rapidly finding a plateau at around 40% discount for each name. After 10 names, the discount on new registrations would be reduced by 36%.</p><p>We can see in the chart bellow, the economy when registering batches in relation to a single registration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*JahhItyKAbDrZJjI0lH-TQ.png" /></figure><p>Notice how fast the batch registration pushes up the discount on a small quantity of names. While slightly decreasing the discount on the next name and so on. Every new batch unity is cheaper than the previous as it is showed bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*XFrN5oQmqkQYoeWADVdBpg.png" /></figure><p>What amazed us the most were the batch renew. By doing the same 190 name renews we plotted the same chart doing a comparison between the single renew with the referrer feature and the batch renew:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*cRR7CHNpXchg6BrlYsKvKQ.png" /></figure><p>At the 200&#39; name, the cost for each subsequent name will be at 75% discount. Reducing the usage of a single renew from 84921 to 21780.</p><p>Following is the cost of each unity across renewals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*4-ccDTvEagn8cg4uR6mSMQ.png" /></figure><p>If you want to check all the test data, more charts or contribute, the google sheets is available in <a href="https://docs.google.com/spreadsheets/d/18bcSbpRuz2cPuy2_foI3jQLFJS_WYHciOGgEWkITtnI/edit?usp=sharing">here</a> to read and comment.</p><h3>6. Conclusion</h3><p>Overall speaking about the project: We saw a fascinating growing hole for the ENS ecosystem, it feels that getting to know and work with all the mechanics in the contract somehow told us a story about the mission we are helping to build.</p><p>It was incredible having to draw all the diagrams, aiming at delivering the product with beauty and efficiency, thinking around the clock on how to deliver this new gamification for the front-end apps. The opportunity to optimize one of the core functions in ENS blows up our mind in a way that we gracefully took care of all the possible aspects our minds crossed, from architecture and security to efficiency and longevity.</p><p>Following are important information considered by us:</p><p><strong>When it comes to more gas consumed in a single batch </strong>is something that can only be countered by duplicating the internal _register function for which the only purpose is to reveal a single name. Let’s say 20% of transactions are made to a single registration and not for a batch, this implies almost a raise in 20000 gas for each of those reveals (~8% gas).</p><p>Having a function for simple name reveals, just to acquire the ENS name with the smallest of the options available would reduce gas cost across purchases.</p><p><strong>When it comes to the batches itself, </strong>we realized that a front-end app that build a service to connect people with ENS, should not be considered as a ‘security’ company, thus we build in a way that they will only access user funds through honest on-chain jobs.</p><p>But in case a shoppe app wanted to save more gas an raise profit of its operations, it could become a security by holding both the users assets and commit information, settling a more comfortable ground for managing the registrations due to the possibility of creating a dynamic batch holding not just one client information, but rather how many the front-end could elegantly match the data into the commit while respecting the gas limit of a single transaction.</p><p><strong>When it comes to withdraw from our commit</strong> and move on to a regular reveal, this won’t probably be done by the registrar app but rather by the user itself, thus, we could make the contract in a way to allow that, but losing some beauty in our code and overall efficiency for most users.</p><p>These approaches will use more ether to execute the if statements, raising the total execution cost of each registration.</p><p>Otherwise, as it is, naturally, the commit would become forever invalid after the withdraw, thus, a new commitment should be made. We believe this is a better approach since getting the commitment wrong will be done by a small population of users and front end apps. Raising all costs to avoid small group mistakes and losing code elegance doesn’t look like the approach.</p><p>Follow us and learn more!</p><p><a href="https://github.com/blockful-io"><strong>Blockful</strong></a><strong> </strong>|<strong> </strong><a href="https://twitter.com/Blockful_io">🐦</a> | <a href="https://github.com/blockful-io">🐱‍👤</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7831e96f261" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>