Skip to main content
All Posts By

uchami

Code Like a Pro: The Quick Path to Smart Contract Mastery

Code like a pro

This article was written by Boro and Uri, Mighty Block blockchain developers, You will find in it the path to becoming a Smart Contract Developer!

Stepping into the digital realm’s dynamic frontier, where innovation intertwines with decentralization, is the path of a smart contract developer. In a world shifting from Web 2.0 to Web 3.0, our role has gained unprecedented prominence.

Imagine writing code that represents unalterable agreements and cutting out intermediaries – that’s the magic of smart contracts. This article is your gateway to understanding what it takes to become a master of this blockchain-powered craft. From unraveling the intricacies of different programming languages to illuminating the deployment process on diverse blockchain platforms, we’ll embark on a journey that unveils the profound evolution from lines of code to immutable digital contracts.

What is a smart contract?

At its core, a smart contract is a decentralized digital agreement that runs on a blockchain. Imagine a traditional contract that outlines the terms and conditions of a transaction or agreement. And now envision this contract automated, enforced, and executed without needing intermediaries. This is where smart contracts shine.

Structurally, code composes a smart contract and defines the rules, logic, and conditions of an agreement. Think of it as executing a virtual ‘if-then’ statement: if certain pre-defined conditions meet, then the contract executes a specific set of actions. This structure ensures the transactions to be tamper-proof, transparent, and irreversible once executed on the blockchain.

Why web3

In the evolution of the internet, we’ve moved from the static websites of Web 1.0 to the interactive platforms of Web 2.0. The transition to Web 2.0 brought us social media, online collaboration, and user-generated content, all centralized on platforms owned by big tech companies.

However, the model came with drawbacks. User data privacy concerns and the centralized control of information became apparent as platforms monetized user data and exercised content moderation power.

This sets the stage for Web 3.0, a decentralized paradigm shift. Web 3.0 leverages blockchain technology to distribute control, data ownership, and transactions across a network of participants. This means that users own more of their data and identities, and execute transactions in a transparent and secure manner without intermediaries.

As data breaches, content censorship, and privacy issues continue to plague the digital landscape, the move towards Web 3.0 gains momentum. Its emphasis on user empowerment, privacy, and open protocols is driving innovation. With the potential to redefine how we interact online, from social networking to financial transactions.

Main smart contract structure

Let’s say we want to create an ERC20, the MightyBlockCoin that goes by the ticker MBC, our contract should keep track of MBC wallet balances, allow to transfer between wallets, amongst other functionalities. This is what the structure of such a contract would look like:

  • Constructor: This piece of code executes before the deployment finishes and typically sets some initial data on the storage of the contract. Since deployment is the only time this code runs, the system uses and tosses it, and does not actually store it on the chain.
    For MightyBlockCoin we want to limit wallets to a maximum of 10 MBC per transfer. Our constructor will set maxTransferAmount to 10.
  • Storage definition: These are your persisting variables, where you will keep useful information for the usage of the contract. You have the well-known integers, strings and bools and also complex data structures that go by “structs” on Solidity, but the most useful ones are mappings that basically work as non-iterable dictionaries with very fast access by key.
    Our ERC20 will need to keep track of balances, for such purpose there will be a mapping(address => uint256) this means a dictionary where the wallet addresses are the keys and their balances are the values, we also need to store the maxTransferAmount that we set on the constructor.
  • View methods: Allow the user to access a piece of information without modifying the storage-state and incur no gas cost, thereby not making all transactions equal.You can try to restrict access to view methods, but it’s generally a bad practice to do so and the barrier is easily avoidable by skilled inquirers.
    In our example, we would have a getBalance method where walletAddress is the parameter and we return the MBC balance of such wallet.

Next steps of a smart contract structure

  • Storage-modifying methods: Methods for security, access, consistency, and permission checks, which allow storage to mutate, form the backbone of a smart contract. When these checks pass, the system performs the storage altering actions.
    The transfer function for MBC validates that the sender has enough balance and the transfer amount is lower (or equal) than maxTransferAmount. Lastly it stores the new balances for both the sender and the receiver.
  • Events: Transactions on the blockchain do not provide any response other than the fact that it executed. We emit personalized events defined on the contract to keep some type of log of what happened. Events come with a name and parameters, they are the basic tool that most platforms use to keep track of what’s going on.
    For an MBC transfer we would want a Transfer event with parameters sender, receiver and transfer amount.

EVM vs NO EVM + testing

Venturing further into the realm of developing smart contracts, it’s crucial to grasp the landscape of blockchain ecosystems and programming languages that power them.

We can broadly categorize blockchain platforms into those that utilize the Ethereum Virtual Machine (EVM) and those that don’t. EVM-based blockchains, like Ethereum blockchain itself, offer a standardized execution environment for smart contracts, ensuring consistency across different nodes. On the other hand, non-EVM blockchains networks, such as Algorand and Solana, employ their own unique execution environments optimized for specific purposes.

smart-contract-developer

When it comes to programming languages for a smart contract developer, Solidity stands tall as the primary choice for Ethereum-based contracts. It is a statically-typed language specifically with a design for writing smart contracts. That is the importance of Solidity smart contract development.

Vyper is another language for Ethereum network that focuses on security and simplicity, making it a preferred option for scenarios where code clarity is paramount. Beyond Ethereum, Rust has gained attention for its use in the Solana blockchain due to its efficiency and safety features.

Testing and developing smart contracts

But programming languages are just one piece of the puzzle. Testing and development environments play a crucial role in ensuring the reliability of a simple smart contracts. Tools like Hardhat, a JavaScript-based development environment, and Brownie, its Python counterpart, provide testing, deployment and debugging capabilities.

They enable developers to simulate blockchain environments locally, helping to catch errors and security vulnerabilities before deployment. These tools offer sophisticated testing frameworks and integration with popular testing libraries, enabling developers to write comprehensive test suites to ensure contract functionality and security.

Navigating the landscape for smart contract developer involves understanding the nuances of EVM and non-EVM blockchains, choosing the right programming language for the job, and utilizing robust testing frameworks. As the ecosystem evolves, developers need to stay adaptable, continually learning and adapting their skills to keep up with the dynamic world of blockchain technology.

New challenges in web3

Testing

Our experience with testing Solidity has been quite challenging, for our particular use case and technology stack, we decided that Python + Brownie suited us best.

The reality of the matter is that Brownie emulates a real environment locally.This means that deploying smart contracts is necessary for sending transactions against them. Since you can only interact with the public/external methods, the ability to create unit tests is limited, as calling internal or private methods is not possible.

smart-contract-development

Deployment

Deploying smart contracts can be even more challenging than testing. Usually developers and owners are different people, this means that a developer might not have access to the private key, which in turn means that someone else, following the dev’s lead, has to send the transaction with the owner wallet.

Since smart contracts code are immutable by design, each deployment is a big deal. For that reason we work to ensure that the experience is secure, smooth and seamless as there are no rollbacks. In practical terms, for every deployment that we schedule, we plan ahead and create a checklist with the step by step guide of what to do, which commands to run and in what given order.

Security

The mix of the monetary value stored inside a contract and its immutability makes thinking about security crucial ahead of time, as rules cannot change on the fly. On top of that, every transaction is independent, there is no such thing as a session, it must check all possible scenarios every time to ensure that only the intended usage is the allowed usage.

Any open exploits serve as entry points for hackers and malicious actors, and even when detected, the issue remains unfixable since altering the contract is not possible.

Technical limitations of Solidity

There are no floating point numbers, this leads to using integers to store numbers with decimal places, making it sometimes confusing to know the number’s scale.

Another impractical limitation is Solidity’s inability to keep complex data structures in storage, requiring the developer to find a workaround to store the data in a more complex but Solidity-friendly way.

Thirdly, an arch enemy of the developer is Solidity’s impossibility to handle dynamic size arrays. For example, when searching all elements that meet certain condition, the data must be looped through once to determine the array’s size and then one extra time to populate said array with the matching elements.

Last in this list but definitely not least is the infamous “stack too deep” error, which appears when too many variables are being used in the context of one given function, forcing workarounds to remove variables or reorganize code into separate smaller functions until the error is gone.

Liveops

Once the contract has been deployed, all types of issues may arise, the blockchain scanner, blockchain query tools amongst other, are essential tools to master to be able to handle such scenarios. This usually entails following transactions around and reading logs/events until the root cause unravels.

Paradigm shifts

It’s quite common to encounter accesibility modifiers on functions such as public and private when working on a Web 2.0 project. In Solidity, 2 other visibilities must be taken into account including external and internal, security concerns of each option should be considered when using them.

The next big paradigm shift comes in the form of storage types. Storage is used in situations where memory isn’t best suited and viceversa, mastering the usage of storage types is essential as they are mandatory for most variable declarations. Finally, units are stored in different scales, most values might need some multiplication or division by 10**18 to account for the difference between wei and eth values.

External resources

Managing third party information requires workarounds as there are no APIs you can call or external resources you can access easily. Calling other contracts requires you to store their address and importing their interface in order to interact with them. The challenge of getting external information becomes substantial and oracles come to fill that void. Oracles are paid services that offer on-chain information that is not easily accesible otherwise, they represent to web3 what public APIs do for web2.

Language caveats

How would you sort an array of elements in Java? Well, you would simply call Array.sort(), that’s not an option in Solidity. Usually builtin methods entail a trade-off between performance and readability. Solidity is not willing to trade performance off, since performance is gas and gas is money. There are options like OpenZeppelin, which provides a library of frequently used methods to make the code more readable while still performing best practices. Nonetheless, implementing the methods for this basic operations still tends to be the best option. Other missing methods in Solidity are: min, max, filter, removeAt, foreach, etc.

Conclusions from a smart contract developer

As we conclude this epic journey through the realm of a smart contract developer, it’s evident that the digital landscape is undergoing a transformation unlike any other. The shift from Web 2.0 to Web 3.0 signifies a pivotal moment where decentralization, security, and user empowerment take center stage.

In the world of smart contracts, we’ve delved deep into their structure, the intricate web of challenges and opportunities that await the intrepid developer. Testing and deployment have proved to be crucibles where code is refined, ensuring the reliability of smart contracts. Security remains paramount, as every line of code written in the blockchain is etched in history, unalterable by design. Technical limitations and paradigm shifts have been embraced as challenges, not obstacles, by the developers pioneering this new era.

In this brave new world, we’ve witnessed the rise of oracles, the intricacies of storage types, and the relentless pursuit of performance. The absence of built-in methods has sparked creativity, making the Solidity developer a master of their craft.

Through it all, we’ve come to realize that Web 3.0 is not just a technological shift; it’s a philosophical one. It champions the ideals of decentralization, data sovereignty, and transparency. As the blockchain ecosystem continues to evolve, adaptability and continuous learning become the armor of the smart contract developer.

We are waiting for your talent like smart contract developer

So, fellow adventurers in the digital realm, take these learnings with you as you embark on your journey into the ever-expanding universe of smart contracts. From the humble lines of code to the immutable contracts etched in the blockchain, you are the architects of a decentralized future, where trust is forged in code and the magic of Web 3.0 becomes a reality.

As the digital frontier beckons, remember, you are the pioneers, the masters of blockchain’s arcane arts, and the guardians of a more equitable and decentralized digital world. The future awaits your code.

We are always looking for Web3 talent !

Mighty Block is one of the partners of Forte, a platform to enable game publishers to easily integrate blockchain technologies into their games. We believe blockchain will enable new economic and creative opportunities for gamers around the world and have assembled a team of proven veterans from across the industry (Kabam, Unity, GarageGames, ngmoco, Twitch, Disney), as well as a $100M developer fund & $725M funding, to help make it happen. That’s where you come into play.

Feel free to browse all our current open job opportunities in the following link 👇

Culture, team, and games amidst the World Cup

blockchain gaming

The World Cup is here and at Mighty Block we love football. As most of our team is Argentinian (me included) and we cannot help our fandom for our national team. We’ve been waiting and preparing for this event for months and we created a betting smart contract football game for it, exclusively for Mighty Block’s team facilitated by blockchain technology on the Polygon blockchain with a smart contract. How did this project came to be? Follow me on this adventure as I tell you the tale of this game and how company culture helps to build amazing things while having fun and being responsible.

The “prode”

During the World Cup it’s very traditional that every group of friends would have a ‘dealer’ that would organize what we call ‘Prode’. This is basically a betting game that consists in everybody submitting their guesses on match results and some type of point system is set up, for example:

  • 10 points if you guess winner and scores
  • 7 points if you guess winner and one of the scores
  • 5 points if you guess winner but not score
  • 2 points if you guess one score but not winner
  • 0 points otherwise

This same person gathers money (the same amount) from everybody. After all matches have been played, the group gathers, the ‘dealer’ shows the results and rewards the winners (usually first, second and third places) with all the money gathered.

This system is heavily dependent on the ‘dealer’ keeping everything orderly and transparent, usually this ends up with discussions about rules, points, how much money was gathered, if the dealer changed any result, etc. This leads naturally to:

  • Ban this type of betting in a professional setting (since it can create issues between the team) or change the dynamic of the game, where the company funds the reward and there’s not betting per sé.
  • Ban the ‘dealer’ from participating in the betting.
  • Even when all the above happen, there is still a sense of distrust in the dealer after the game ended.

As the World Cup was getting closer and closer and everybody at the office started gossiping about the players, the news (and even one of our coworkers went to Qatar himself!) a light bulb went on. What if we make this heavily centralized and ugly betting game into a trustless system facilitated by Blockchain and Smart Contracts? (A smart contract football game!)c.µ.

Just like that, our minds started running, we were thinking of ways to make this happen. How would it look? Where do we take the results from? Do we use an oracle? How do we split the reward? What would happen if there is a tie?. As programmers we could not help our anxiety in any other way than coding the damn thing. 

We spent 4 hours making this solidity Smart Contract in the dirtiest way possible, following no guidelines of clean, scalable and sustainable code. After all it was an MVP of a joke, we were not planning to really do this, right?

Ok, let’s back up. How did we end up here? Why on earth are we working on an MVP of a joke instead of working on our clients needs on company time?

Mighty blocks culture policies

At Mighty Block we take culture very seriously. A very important exercise was done approximately 6 months ago, were HR gathered ‘the most important thing that you value from a teammate’ and distilled a list of core values that we as an organization value.

At first sight, it doesn’t sound at all special. Just another set of empty words that nobody follows. Well, this is where Mighty Block makes the difference. 

You can read more about that process here, but TL;DR, the HR team listed the things that we REALLY value, not just a poster on a wall, these are the things that we want to keep and grow:


Quarterly face-to-face workshops

Mighty Block is a fully remote company, we have teammates all around the world yet once a quarter we try to meet face-to-face. Our HR team makes a great effort to make this week as productive, fun and fulfilling as possible. These meetings really help to spark inspiration and to show our new team members how we put into practice the core values. It’s not forced indoctrination, rather it’s simply making how we work transparent to the whole team and since our core values express that, the newcomers can sense and learn that.

What does all of this have to do with the ‘Prode’ project? Well, everything. Our ‘real’ project (the one our client was paying for) was under control and the client was happy with our productivity at the time. We were not crunching nor under a lot of pressure. On the other hand, we were sure that if the Prode project failed, nobody would tell us off, it would go against most core values and if we succeeded building the Prode and found ways to circumvent all the issues, Mighty Block would support us and facilitate all the resources needed to make it happen. 

It was a can’t lose type of situation

Only in that state of mind can you make progress in a relaxed, healthy, fun and productive manner. It was not only important, it was the key for being able to make this project a reality, otherwise it would have been a comment, a joke, a thought, but never a real thing.

The smart contract was just the beginning

Writing the smart contract was just the beginning of our adventure. After this rush of adrenaline and inspiration we had a rough, untested and dirty smart contract that did the thing. We had a Prode v0.1. After making sure that no big barrier would prevent us from making the World Cup Prode a reality, we pitched our smart contract football game idea with HR, they loved the project and we started thinking on what else we should add. Ideas started flowing, adrenaline went down and we planned our next steps.

How to make this work in a professional setting? The smart contract plays the ‘dealer’ role here, so that helps a lot but also Mighty Block funded the prize. So no betting, just a company game.

Mb team Coding
Uri and Boro coding

But interacting with a smart contract is a very annoying thing, we needed a frontend and that’s where the rest of the team comes to play. Most of the development of this project happened in the span of 5 days, during one of our quarterly workshops. While Ignacio and I were writing (and now testing and refactoring) the Smart Contract, the rest of the team heard our conversation and started asking questions, everybody was excited to try it!

Julian, our frontender, was one the excited coworkers, he offered to build a frontend for us. He had no experience making a dApp, so it was a learning experience for everybody involved. I helped to connect the frontend with the Smart contract while Ignacio was finishing tests and HR was deciding the proper prize.

During Julian’s process he had questions about UX, Constanza, our UXer, helped with that. 

Frontend
Juli working on the Smart Contract Football game frontend

Overall it was a team project, a great experience not only for building the technology and then playing with the game we created on real time during the world cup, but also a bonding experience. Next time I have a question I’m more confident asking Constanza, Julian or Ignacio. The whole team sees this vibe of having fun and building stuff together, and wants to join in, the best example of this is our participation rate of 95%, almost the whole team played the game. This is a positive feedback loop that we need to nourish and nurture, that’s our philosophy, that’s why we have core values and that’s why we do what we do.

Follow us

We are always looking for Web3 talent !

Mighty Block is one of the partners of Forte, a platform to enable game publishers to easily integrate blockchain technologies into their games. We believe blockchain will enable new economic and creative opportunities for gamers around the world and have assembled a team of proven veterans from across the industry (Kabam, Unity, GarageGames, ngmoco, Twitch, Disney), as well as a $100M developer fund & $725M funding, to help make it happen. That’s where you come into play.

Feel free to browse all our current open job opportunities in the following link 👇