OUTSMARTING SMART CONTRACTS
Traditional contracts are sets of agreed-upon terms which are enforceable by law and are described in a natural, human language. Nowadays, smart contracts coexist with traditional contracts. But, what is so smart about them? In essence, they are computer programs that automate the enforcement of terms. In this article, we will try to outsmart smart contracts by grasping their concept and deeply exploring possible use cases and benefits.
LET’S SET IT ON BLOCKCHAIN!
‘Let’s set this agreement in stone!’. That’s the phrase used when two parties reach an agreement after an exhausting negotiation.
Even though it is just a phrase, it seems a little… outdated, at least. Web 3.0 has arrived, and with it, it is fair to say that it is time to set it on the blockchain
Blockchain is probably the best invention since the Internet itself. The unique mix of cryptography and decentralization gives this technology the properties of permanence, transparency, and neutrality.
Its magic resides in allowing value exchange without needing a third party or central authority. With only a few lines of code, transactions can be managed quicker, cheaper, and more securely.
What is a SMART CONTRACT?
The easiest way to explain smart contracts is by picturing them as a vending machine.
As you already know, when using a vending machine you decide what you want and enter the money into the machine. Once you click the button or insert the code for the item, the machine automatically releases the selected product. After certain conditions are met, you receive the desired good.
Smart contracts essentially work in the same way. After certain conditions are met, they automatically execute themselves and enforce the contract clauses on the parties.
To recap, a smart contract is a CODE intended to implement the negotiation or performance of an agreement. It allows us to complete credible transactions without third parties because these transactions are embedded in blockchains, which automatically triggers the contractual terms of an agreement to be enforced.
SMART CONTRACT USE CASES.
Use cases can be found in banking, insurance, energy, e-government, telecommunications, music and film industry, fine art, mobility, education, and many more. Their applications may vary from simple to complex. They can be used for
- A simple economic transaction like sending money from A to B
- Registering any kind of ownership and property rights, like land registries, intellectual property, or even managing smart access control for the sharing economy.
In this article, we will explore some areas in which the use of smart contracts becomes even more tempting since we get to solve well-known challenges that were not resolved until blockchain arrived.
DIGITAL IDENTITY
Digital identity is a set of data living on the Internet and representing real-world’s identity. A significant section of society uses digital identities for daily tasks, such as accessing government benefits, bank accounts, education, etc. Some services are inaccessible without a digital identity.
Yet, issues regarding authentication and privacy are challenges that are yet to be addressed. Guaranteeing that the user’s identity corresponds to whom it claims to be or that the user’s information is shared with those they authorize is still a challenge.
Fortunately, blockchain can answer these challenges regarding authentication and privacy.
BLOCKCHAINS TO THE RESCUE!
Tackling authentication challenges
Nowadays, blockchain-driven solutions are the best options to deal with authentication challenges.
But how is it done?
Essentially, each user has a wallet, and each blockchain wallet has a private and a public key. The private key generates a signature, which is used in each transaction to guarantee the user’s identity. Inside the blockchain, nodes will verify that the signature was generated correctly utilizing the user’s public key.
Hence, each transaction that is added to the blockchain will have a digital signature that ensures that the user who has created the transaction is who he claims to be.
And voilá! The authentication problem is solved.
Let’s see an example in code:
This smart contract is named Authentication.
It is written in Solidity programming language. In this article, we won’t explain the basics of this programming language, but after coding, we will revisit the code for further clarification.
As you can see, there is a mapping named users that relates a wallet address with a boolean value. There is also a function that registers the user who wants to authenticate the address and assigns him the boolean value of true.
In essence, when the authenticate method is called, a transaction is created and added to a block inside the blockchain, which is signed with the public and private keys of the user.
What about tackling privacy issues?
Let’s walk through an example in code.
The following smart contract is named Identity and is coded to illustrate how to protect the users’ privacy.
It has two structs with users’ information. The BasicInfo struct has basic information, such as name and email. The PersonalInfo struct has more personal data, such as salary and address.
Then, we have created an enum with the different user types that the user who deploys the contract can have: Basic and Personal. Basic users can access BasicInfo, and Personal users can access PersonalInfo.
We have created an error that will be launched when one of the users attempts to retrieve information without being authorized.
Then, we have defined three variables:
- ‘basicInfo’ stores the user’s basic information.
- ‘personalInfo’ stores the user’s personal information.
- ‘owner’ stores the address of the user who is deploying the contract.
We have added a mapping named ‘basicUser’ to store all the basic users who have access to basic information and a ‘personalUser’ with all the users who have access to personal information.
The constructor defines the values that will have the ‘basicInfo’ and the ‘personalInfo’ and establishes who is the owner of the contract.
The function ‘getBasicInfo’ returns the basic information of the contract’s owner. The function is of type ‘view’ as it only returns a value and does not modify any value of the contract’s body.
The function uses the ‘authorizeUser’ modifier. This modifier checks if the user has the required permissions to access the desired information. If the user is the owner or if he/she is authorized to access personal information, then permission will be granted. If the user is type basic, the modifier will check if the user is inside the mapping ‘basicUser’ and in which case the information will be given. If none of the above conditions are met, then we will launch the error stating that the user is not authorized.
The function ‘registerUser’ can only be used by the owner. The ‘onlyOwner’ modifier checks if who is calling the function is indeed the contract’s owner. The function will receive the user that we want to authorize and its type. If the user type is ‘basic’, we will add them to the ‘basicUsers’ mapping, and if it is ‘personal’, to the ‘personalUsers’ mapping.
In this way, information can only be accessed if the user is authorized. This successfully solves all challenges regarding the user’s privacy.
FINANCIAL SERVICES
Financial services are the economic services provided by the finance industry. It encompasses a broad range of businesses that manage money. Among them, we may include credit unions, banks, credit-card companies, insurance companies, accountancy companies, consumer-finance companies, stock brokerages, investment funds, individual asset managers, and some government-sponsored enterprises.
The truth is that financial institutions become a sort of black box for users who do not know how their money is moving inside these institutions.
With blockchain, light can be shed into that darkness.
All network participants have a copy of the ledger, which grants absolute transparency. This will provide complete information about all the participants on the network and their transactions. Also, the P2P nature of payments enabled by smart contracts reduces transaction costs, which means that micropayments could become economically more feasible than they are today.
OUR OWN NICACOIN!
So, once again, blockchain offers a solution. Changing the paradigm from a centralized system to a decentralized one means that:
- There will be no more intermediaries
- The responsibility for money management rests with the user
- There is equal access for all users who just need to have a wallet.
These systems are frequently based on DApps. They allow users to interact with the blockchain more naturally without having to know the technical details of how it works
Let’s create our own NicaCoin!
First, we have assigned a name to our token, ‘NicaCoin’. Then, we defined a symbol for our token ‘NIC”, which usually goes from 3 to 5 letters. Finally, we have added how many decimals our token can have. A balance of our token can be written with 18 decimals.
The variable _totalSupply will store the number of tokens to be created for distribution.
Mappings are used in Solidity to store data in the form of key-value pairs. We have created two mappings. In the first one, the key is the wallet address, and the value is the balance of the account. In that way, we keep track of how many tokens a user owns. In the second one, the key is associated with a value of type mapping. An address can grant other addresses the right to spend a certain amount of tokens.
We have also created two events. The ‘Transfer’ event will be executed every time we transfer NicaCoins from one account to another, and the Approval event will be executed each time the owner allows a third-party spender to use his tokens on his behalf.
The constructor initializes the ‘totalSupply’ and gives the total amount of created tokens to the account of the user who displays the contract.
The ‘totalSupply’ function returns the tokens generated at the beginning.
The ‘balanceOf’ function returns how many tokens belong to a specific account.
The transfer function transfers tokens from the owner’s wallet to another one. Inside the function, we validate that the account from which our NicaCoins are being transferred has a sufficient amount of coins. Then, it subtracts from the balance of the NicaCoins being transferred. Finally, the event transfer is launched.
The approve function will allow a third-party spender to use a certain quantity of tokens on behalf of the owner. It will allow someone or another smart contract to use our NicaCoins on our behalf. It will launch the approval event with the corresponding information.
The allowance function will verify how many tokens are remaining in the owner’s wallet.
The ‘transferFrom’ function allows us to transfer tokens from one account to another. It will first validate that there are sufficient tokens to be transferred and that the third-party spender is authorized to use those tokens. Then, the tokens being transferred are subtracted and added to each corresponding balance, and the event transfer is launched.
DIGITAL ASSETS
Digital assets are files that can be saved digitally, such as images, videos, audio, or other documents. They have an owner and can be distributed to the general or specific public.
But… how do we guarantee that our digital asset won’t be modified during its distribution? How do we guarantee that our digital assets won’t be duplicated? How do we guarantee our authorship?
What’s the solution? Blockchain’s immutability. This means a blockchain ledger remains unchanged, unaltered, and indelible. Setting something on a blockchain is like setting something in stone.
Once it is set on the blockchain, it’s on!
WELCOME TO TOKEN-LAND. LET’S CREATE OUR NFT
Tokens or digital assets, also known as crypto tokens, are units of value that represent an asset or provide unique utility within its native blockchain network.
There are a variety of token standards that enable interoperability within a given blockchain. For example, within the Ethereum network, the most widely used token standard is the ERC-20 standard, which allows the creation of interoperable tokens with the rest of the Ethereum ecosystem and applications (our own NicaCoin!)
There are also various archetypes of tokens, including asset-backed tokens, non-fungible tokens, digital currencies, utility tokens, governance tokens, security tokens, and much more.
Therefore, NFTS are digital assets that live inside the blockchain. This guarantees that they have a unique value and a unique owner. The standard ERC-721 defines which features must be followed by a smart contract for it to be considered as an NFT inside the Ethereum network.
Let’s create an NFT and go through our code.
As can be seen, we use OpenZeppelin, which is in charge of creating standards for blockchain security.
First, we import the contract ERC721 from OpenZeppelin and then an extension to this contract that will allow us to store the URI of this token. The URI is where all the metadata of our NFT will be stored.
In our contract, we have defined two variables. The first one, ‘tokenIds’, will define which token will be assigned each time a user wants to obtain our NFT. The ‘tokenIds’ must be unique.
The second variable is ‘owner’, which defines who has deployed this contract.
In the constructor, we will call the contract ERC721 with the token name and a symbol as function parameters. The variable ‘owner’ will assign the address of who is deploying the contract.
After that, we have defined a function mintNFT that will allow us to assign our NFT to another user inside the blockchain. The function receives the user’s wallet and the tokenURI. The function has the modifier ‘onlyOwner’ that verifies that whoever is deploying the contract is the real owner. Inside the function, the tokenId will be increased by one, and the function mint, provided by OpenZeppelin, will be called. This function will add the generated token to the account balance.
Finally, we will call the function setTokenURI, provided by OpenZeppelin, which will relate the tokenId with the tokenURI. That unique tokenId that has been generated will be returned.
SUPPLY CHAIN
A supply chain is the series of activities that a product requires to reach an end user. The process starts with the raw material and ends with the final product that the user buys.
But.. how can we coordinate all the intermediaries in the supply chain? How can we scale the manufacturing process of a product?
Guess what? Once again, blockchain through smart contracts gives us an answer.
A Blockchain does not need intermediates, and all coordination is given by the rules stated in the smart contract. Also, once a transaction is added to the blockchain, all nodes are informed. All nodes will have the final version of the blockchain. This will allow an automatic synchronization between all the intermediates that participate in the manufacturing of the product. Last but not least, automatic payments will be able to be made between all those who have participated in the supply chain.
Wondering how it could be implemented? Let’s take a look at the code…
NEITHER RAW, OVERCOOKED, NOR WELL-DONE… I WANT MY STEAK IN BLOCKCHAIN!
We will now draft a smart contract for obtaining a meat stake all the way from the farm through the processor, the distributor, and the retailer until it finally reaches the user’s table.
As you can see, in the contract, we have defined a struct named ‘Step’, which will save the status of the product and the metadata that will be needed by each intermediate in every step.
After that, we created an enum with the following states: ‘created’, ‘ready_for_pick_up’, ‘picked_up’, ‘ready_for_delivery’, and ‘delivered’.
An event named ‘RegisteredStep’ has been created and will inform us every time a step in the manufacturing of the product is concluded. It has the following characteristics: productId, a status that has been registered, the metadata of this step, and finally, who was the one that called this event.
We have created a mapping that will relate a productId with every step named ‘product’.
The function ‘registerProduct’ allows us to create a new product. It will receive a productId and will validate that the productId does not have steps associated and will then assign the first status of ‘CREATED’.
The function ‘registerStep’ receives a productId, and the metadata that intermediates will need to be able to act. This function will validate that: a) the product exists and there are steps associated with it; b) the last step’s status is correct; c) this status is no greater than the last one named “Delivered”. After that, we will assign the corresponding next state, and it will be added to our product mapping. Finally, the event that informs us that a new step has been concluded is launched.
CYBERSECURITY
Cybersecurity is the set of practices used to protect a system’s information. This information is protected through integrity, confidentiality, and availability.
But… how can we guarantee that information will arrive as we expect it to? How can we be certain that only authorized people have access to it? How can we ensure that information will always be available when needed?
Once more, the answer lies in blockchain.
Since it is immutable, its network is permanent and unalterable. This means that any validated records are irreversible and cannot be changed. Hence, no one will be able to edit, change or delete it.
Also, being a distributed network means that the blockchain will continue to answer with no problem, even if one of the nodes fails.
Lastly, I know confidentiality does not seem to go hand in hand with blockchains since they aim to provide transparency. Nevertheless, setting access rules in smart contracts or building private blockchains make it possible to keep critical data confidential.
BLOCKCHAIN FOR BUSINESS
Imagine a private company with its private blockchain. We will draft a contract in which each node will inform the events inside the blockchain to cybersecurity.
Let’s see it in code….
First, we have defined an event that will be launched each time a node adds an event inside the blockchain.
Also, we have set a mapping named ‘events’ that will relate the wallet address of the node that publishes the event, the eventId, and the event data.
We have also added another mapping named ‘eventsCounter’ to store the number of events published by a blockchain node.
The variable ‘threshold’ defines how many events a node can register. We need to take into account that if we store a great deal of data in the blockchain, our contract’s gas will rise, and therefore it will become more expensive.
The variable ‘owner’ will store the contract’s owner. In our constructor, we have assigned the threshold and the owner values.
The function createEvent receives the event as a parameter. Inside the function, we will have a counter of how many events have been added by a node, and we will increment it in one so that each event has a unique id.
We then verify if the ‘eventId’ is greater than our threshold, and in that case, we will overwrite all events so as not to store too many events.
Then, we add the ‘eventId’ in our ‘eventCounter’ mapping, and in our ‘event’ mapping we will add the node that has added that event, the ‘eventId’, and its metadata. Lastly, we call our event ‘newEventCreated’ to inform our network about the new event that has been created. The function ‘setThreshold’ is for changing the variable threshold and will only be used by the owner of the contract.
CONCLUSION
In this article, we have thoroughly examined smart contracts and their use cases. We have highlighted the challenges that are solved with the use of blockchain and have displayed the code that aids in its implementation.
Nevertheless, it is important to underline that these are only a set of examples of how this disruptive technology named blockchain, through smart contracts, can offer solutions to well-known problems.
The exponential growth of smart contract implementation is due to the obvious benefits that blockchain technology provides. Technology itself does not add value to society, but when it is addressed to solving society’s real problems, that is when the true difference is made. Smart contracts are the quintessential example of it.
As developers, all that is left is outsmarting their smartness and truly mastering them. As individuals living in society, we have no better option than to seize their huge benefits.