Smart Contracts in 10 minutes: Risks, NFTs, storage options
Published: 2023-01-12 09:11:42

_This is a series of posts on Blockchain, Ethereum, Smart Contracts and their security. The work was done in collaboration with [Dr. Andrew Melnik](https://www.linkedin.com/in/andrewmelnik/), Marvin Koppka and Mustafa Erdogan at Bielefeld University under [ISY Project: NFTs and Cryptocurrencies With Smart Contracts](https://ekvv.uni-bielefeld.de/kvv_publ/publ/vd?id=335090496&lang=EN) with the aim to provide a reference material on the blockchain technology._

In this final post we will consider Smart Contracts, give their quick overview, talk about advantages and limitations, as well as risks, including reentrancy attack, and the way to cope with these by following ERC standards. We will provide a popular NFT use case with the objective to examine its storage options and associated risks.

## Part 3. Smart Contracts

_See also [Part 1. Blockchain](https://dev.to/yuryoparin/smart-contracts-blockchain-13-25ph) for an overview of Blockchain, its security fundamentals and issues arising from the choice of its consesus algorithm, such as 51% attack and energy consumption, and [Part 2. Ethereum](https://dev.to/yuryoparin/ethereum-workflow-and-consensus-algorithms-in-10-minutes-3be4) on its architecture and two consensus algorithms, Proof of Work and Proof of Stake, which allow all nodes in the network to agree on a single state of the blockchain._

### 3.1 What Are Smart Contracts And Their Advantages?

Smart contracts is a type of code that allows for verification and execution of a contract securely and automatically. These smart contracts run on the Blockchain system, with well-defined rules and penalties depending on the contract agreement and automatically enforce those obligations. Also, smart contracts can call other smart contracts or run independently.

When the predetermined conditions are verified and reached, nodes execute the set actions. Actions include the transferring of funds to appropriate parties, emitting events or calling other smart contracts, which update the blockchain state.

As required, contracts could be set with more than one stipulation, focusing on each participant's satisfaction and competent task execution. Participants determine how their transactions and execution data should be represented on the blockchain by agreeing on the rules that control the transactions.

In that case, developers could program and customize smart contracts on the blockchain. For example, Ethereum allows developers to access the Ethereum Virtual Machine (EVM) for execution of smart contract code. Further, organizations implementing blockchains offer web templates and other online tools that can help developers form a basic structure for smart contracts.

Smart contracts have a number of advantages. The primary one is transparency, a result of transaction distribution across all nodes in the network. This provides the parties with security and trust because they always have access to the data and information relating to the contract thereby minimizing the possibility of contract manipulation or misuse.

As smart contracts are deployed on blockchain, they guarantee immutability of their data, allowing contracts and agreements to be made without the need to know each other and prevent potential breaches of conditions or errors in the management and execution of the contract.

Secondly, autonomy is another advantage of smart contracts that provide trusted third parties with no intervention from intermediaries. This feature reduces costs and increases process speed compared to how traditional contracts with intermediaries are executed. 

The next section will focus on topics specific to non-fungible tokens (NFTs).

### 3.2 NFTs

NFTs come in many forms but the most typical one is a metadata file that contains information encoded with a digital tokenized version of the work. The second form involves uploading a complete piece of work to the blockchain, although it is less frequent because of high cost of uploading large files to the blockchain. These files are uploaded to NTF Smart Contracts which are based on the ERC-721 standard, discussed further in Section [3.5](#35-erc). This standard specifies required and optional elements, see Figure <a href="#fig-1">1</a>.

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmm6wijpvjr0xeml3w5o.png" alt="Figure 1: NFT Metadata.">
  <figcaption><span id="fig-1">Figure 1</span>: NFT Metadata.<sup><a href="#ref-10">[10]</a></sup></figcaption>
</figure>

The TokenID, a number generated when the token is created, is the first required field. The NFT Smart Contract address, a blockchain address that can be examined searched by using a blockchain scanner, for example, is the second fundamental component. Only one token on the blockchain is allowed to have a given combination of TokenID and contract address, making tokens unique across the blockchain.

These two numbers are the only fundamental components of NFTs. Other components may also be included in the NFT Smart Contract. One of them is the creator’s wallet address, which links the NFT back to its originator. In the next section we will see how we can verify the originality of NFTs.

#### 3.2.1 Copyright

Most of NFTs are metadata files that have been encoded with works that may or may not be covered by copyright protection (it is possible to create an NFT of a trademark), or it could even be a work that is in the public domain. An NFT may be created from anything that can be converted into a digital format, the original work is only required at the initial phase of the process when creating a unique combination of the TokenID and the contract address. Therefore, in theory, copyright is not enforced by NFTs.

Nevertheless, there is a rising interest in NFTs from a copyright perspective. This is partly due to the fact that many works are being exchanged as NFTs, such as work of art which is covered by copyright. This is particularly true for NFTs representing digital objects, e.g. in digital rights management, where NFT Smart Contract and blockchain functionality is enough to enforce copyright.

For NTFs that do not fully encapsulate the protected object, such as a physical object or actual files, there is a prevalent misunderstanding of the rights that buyers acquire when they purchase an NFT. Some buyers believe they acquire the underlying work of art together with all its rights,
while they only purchase metadata related to the work and not the work itself.

While most NFTs do not transfer the rights for their protected object, the seller occasionally offers to turn the token into an actual transfer of copyright ownership of the original work. However, it is challenging to determine if this complies with the formal procedure required by law to transfer copyright.

In the next section we will explain the limitations of smart contracts.

### 3.3 Limitations of Smart Contracts

#### 3.3.1 Irreversibility

Given that smart contracts are immutable on the blockchain, it is impossible to change the way they work after they have been deployed and hence fix code errors. Another issue comes from the fact that successful transactions are irreversible which combined with the first issue makes them vulnerable and defenseless against exploits and hacks.

#### 3.3.2 Crack

The idea of good faith stipulates that parties will deal fairly and refrain from obtaining unethical gains from a smart contract. However, it is challenging to guarantee that these terms are followed in accordance with what was agreed upon when utilizing smart contracts. This is mostly related to hacks of smart contracts that exploit system design vulnerabilities, e.g. Reentrancy attacks, described in Section [3.6.2](#362-reentrancy-attack).

#### 3.3.3 Third Party Assessment

Even while smart contracts aim to do away with third parties, it is impossible to do so fully. In contrast to the functions they play in conventional contracts, third parties take on new responsibilities. For instance, attorneys won't be required to draft individual contracts, but developers will still need them to comprehend the conditions when writing the code for smart contracts.

#### 3.3.4 Uncertainty Terms

Smart contracts cannot always manage unclear terms and conditions since contracts often include phrases that aren’t always clear, with most typical of them being "within a reasonable period of time", "without undue delay" or "obligations to cooperate."

After explaining limitations, we will move on to the functionality of smart contracts.

### 3.4 Functionality of Smart Contract

"Smart contracts work by following simple _if/when...then..._ statements that are written into code on a blockchain. A network of computers executes the actions when predetermined conditions have been met and verified. These actions could include releasing funds to the appropriate parties (DeFi Protocols allow individuals to borrow funds against a collateral cryptocurrency or Token Protocols, such as USDC and other stablecoins), registering a vehicle (DIMO makes possible applications like parametric insurance, peer-to-peer car sharing and vehicle marketplaces), sending notifications (Push Protocol enables cross-chain notifications and messaging for dapps, wallets, and services), or issuing a ticket (Ticketmaster recently announced they would let event organizers issue NFTs tied to tickets). The blockchain is then updated when the transaction is completed. That means the transaction cannot be changed, and only parties who have been granted permission can see the results."<sup><a href="#ref-5">[5]</a></sup>

Currently, Ethereum is the most popular among other smart contract platforms, while several other cryptocurrency blockhains, including as Tron, Polkadot, Avalanche and Solana, are also capable of supporting smart contacts. These blockchains made it easy for developers to create and deploy smart contracts. There is a selection of programming languages to write code in, e.g. Solidity, WebAssembly or Rust. Smart contracts are usually stored on the blockchain with their code and current state visible and queryable even via online scanner websites.

Moreover, along with the blockchain and transaction data, every node on the network keeps a copy of all active smart contracts and their current state. All nodes in the network execute smart contract code when users interact with.

Because of this smart contracts may run safely without the need for a centralized authority, even when users conduct complex financial transactions with unidentified entities. On Ethereum, users often have to pay a charge called “gas” to execute a smart contract (so-called because these fees keep the blockchain running).

Another important behavior of smart contracts is that once deployed onto a blockchain, they cannot be changed, even by their creators. Partly to cope with issues arising from that last point (see the previous Section [3.3](#33-limitations-of-smart-contracts)), the Ethereum community came up with the process of standardization, which we will discuss in the next section.

### 3.5 ERC

"ERC is essentially an acronym for Ethereum Request for Comments. In general, ERCs are specifications for Ethereum applications, such as token standards, name registries, library formats, and package formats. An author may create an Ethereum Blockchain app with an ERC token, but they will need to clarify their standard and gain community approval."<sup><a href="#ref-12">[12]</a></sup>

#### 3.5.1 What Are ERC Standards?

Ethereum Request for Comments (ERC) is a document with specifications that smart contract developers use to write smart contracts on the Ethereum blockchain platform. The Ethereum developers and community utilize this procedure, also known as the Ethereum Improvement Proposal (EIP), to examine these documents and suggest changes which can be taken into account by the document authors and result in revisions published.

The most common ERC standard is ERC-20 Token Standard. It makes it easy to develop, use and trade Ethereum-based fungible tokens by providing a standard set of fields and functions for a token smart contract. For non-fungible tokens or NFTs there is another widely used standard ERC-721. Unlike traditional fungible tokens, NFTs cannot be split up and are unique. They may be owned and transacted by one person or they may be assigned to another party. NFTs can signify ownership over digital or physical assets.

Figure <a href="#fig-2">2</a> depicts popular ERC standards and gives their brief descriptions.

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6wcfpwx3t2b1047hgh7p.png" alt="Figure 2: ERC Standards List for Tokens.">
  <figcaption><span id="fig-1">Figure 2</span>: ERC Standards List for Tokens.<sup><a href="#ref-13">[13]</a></sup></figcaption>
</figure>

In the next section we will look at some of the risks and issues with Smart Contracts.

### 3.6 Risks and Issues

#### 3.6.1 Immutability Issue

Smart Contracts, unlike traditional contracts, miss an important feature, namely a severability clause. This clause refers to a clause added to complex contracts which prevents mistakes in the contract to fully invalidate it. This however happens to Smart Contracts. If a deployed Smart Contract is found invalid, it cannot be changed, even though it might entail crucial bugs. As such, the Blockchain gets flooded with immutable, not optimized and partially faulty code. The ERC Standards mentioned in Section [3.5](#35-erc) prevent crucial bugs from happening, such as Reentrancy attacks, which led to a famous The DAO Hack on Ethereum in 2016 discussed in the next section.

#### 3.6.2 Reentrancy Attack

This destructive attack involves two Smart Contracts calling each other when sending funds, see Figure <a href="#fig-3">3</a>. An untrusted Contract B requests its funds from Contract A, which after checking Contract B's balance, sends the requested funds to Contract B. Contract B uses a special fallback function that is triggered when a contract receives _Ether_ without any data sent with the transaction. This function requests more funds from Contract A, which hasn't yet updated Contract B's balance because the external call to Contract B happens in the same transaction and hence is executed sequentially for both contracts on the Blockchain. This allows Contract B to drain all of Contract A's funds.

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wnug2r73dbdf6xx1jflb.png" alt="Figure 3: Reentrancy Attack.">
  <figcaption><span id="fig-1">Figure 3</span>: Reentrancy Attack.<sup><a href="#ref-11">[11]</a></sup></figcaption>
</figure>

That type of attack is the most well-known attack on the Blockchain because of the The DAO Hack on Ethereum in 2016, leading to a loss of 3.6 million _Ether_. The hack worked by having the attacking smart contract continuously calling the withdraw function of The DAO before it updated the balance of the vulnerable smart contract. This attack scenario was successfully repeated in 2021 with the SIREN protocol hack, draining approximately $3.5 million from its AMM pools by using a similar fallback mechanism in ERC-1155.

The next section will discuss issues with storing NFTs.

#### 3.6.3 NFT On-Chain and Off-Chain Storage

Non-fungible Tokens or NFTs is a trending technology supported by the ERC-721 standard.<sup><a href="#ref-14">[14]</a></sup> The most common use case of NFTs is creating and distributing art pieces that carry crucial information such as the history of its owners on the blockchain and is known to be duplicate-proof. However an important factor to consider is the way NFTs are stored by applications.

##### On-Chain NFTs

On-Chain NFTs are tokens that are written on the Blockchain (e.g. Ethereum), including their image and metadata, see Section [3.2](#32-nfts). This information also includes the transaction hash of the generated NFT, which makes NFTs more unique.

##### Off-Chain NFTs

However some NFT projects store their Smart Contracts on the Blockchain while keeping the NFT image and metadata off-chain in order to save on gas costs. This off-chain storage can be placed with the cloud service providers, such as AWS, GCP, Azure but also Google Drive and Dropbox. Even more trendy is to keep metadata on the "interplanetary file system" (IPFS) nodes designed to address issues with distributed web. In all those cases, problems still exist. For example, an NFT file or metadata can be deleted by the NFT creator at any time, severing the connection between the file and the blockchain on which the NFT ownership for the file is recorded.

Another issue concerned with NFTs are impersonation attacks, also called sleepminting, in which an NFT is minted to a different address than that of the transaction sender.<sup><a href="#ref-20">[20]</a></sup> The creator of the NFT is therefore displayed at this different address, confusing buyers, as certain creators have a higher innate value to their creations, such as CryptoPunks. If bought, the original transaction sender initiates another transaction for the NFT to be transferred to the buyer and receives the funds.

Evidently, some issues and risks for this "decentralized payment platform that would revolutionize the way we pay everything" still persist for the Blockchain and its resulting technologies.<sup><a href="#ref-13">[13]</a></sup> Former issues of banks were partially solved, but new issues are created. As such, existing issues shifted.

## Conclusion

This series of posts ([Part 1. Blockchain](https://dev.to/yuryoparin/smart-contracts-blockchain-13-25ph), [Part 2. Ethereum](https://dev.to/yuryoparin/ethereum-workflow-and-consensus-algorithms-in-10-minutes-3be4) and [Part 3. Smart Contracts](https://dev.to/yuryoparin/ethereum-workflow-and-consensus-algorithms-in-10-minutes-3be4)) summarizes the design of blockchain and its main components. One of them is smart contracts, which are now widely used in digital finance and applications where ownership of digital assets is transferred, for example, NFTs. Being exposed to the public, these applications require bulletproof protection from potential attacks. This protection was originally believed to come from the blockchain itself, which includes various security features such as sophisticated encryption mechanism, Merkle trees, consensus algorithms and data distribution across the whole peer-to-peer network.

However faced with numerous attacks, the blockchain community came up with additional measures realized in the form of standards, with the most famous one on Ethereum, the ERC. Surprisingly, that wasn't enough. Because of high cost and small throughput of running transactions on blockchains, specifically Ethereum, developers do not store all application state in smart contracts, offloading its biggest part to off-chain storage that neither has security guaranties of the blockchain nor follows the smart contract community standards. This particularly concerns NFTs, as their buyers need to be aware of the risks involved when purchasing widespread Off-Chain NFTs versus more expensive On-Chain NFTs.

## References

<ol>

<li id="ref-1">The Merge on Ethereum, <a href="https://ethereum.org/en/upgrades/merge/">https://ethereum.org/en/upgrades/merge/</a>.</li>

<li id="ref-2">Ethereum nodes and clients, <a href="https://ethereum.org/en/developers/docs/
nodes-and-clients">https://ethereum.org/en/developers/docs/
nodes-and-clients</a>.</li>

<li id="ref-3">Chapter 4. Cryptography — Elliptic Curve Cryptography Explained, <a href="https://www.oreilly.com/library/view/mastering-ethereum/9781491971932/ch04.html">https://www.oreilly.com/library/view/mastering-ethereum/9781491971932/ch04.html</a>.</li>

<li id="ref-4">Ethereum Yellow Paper, <a href="https://ethereum.github.io/yellowpaper/paper.pdf">https://ethereum.github.io/yellowpaper/paper.pdf</a>.</li>

<li id="ref-5">Functionality of smart contracts, <a href="https://www.ibm.com/topics/smart-contracts">https://www.ibm.com/topics/smart-contracts</a>.</li>

<li id="ref-6">The Keccak reference, <a href="https://keccak.team/files/Keccak-reference-3.0.pdf">https://keccak.team/files/Keccak-reference-3.0.pdf</a>.</li>

<li id="ref-7">The Keccak SHA-3 submission, <a href="https://keccak.team/files/Keccak-submission-3.pdf">https://keccak.team/files/Keccak-submission-3.pdf</a>.</li>

<li id="ref-8">Merkle Tree, <a href="https://soliditydeveloper.com/merkle-tree/">https://soliditydeveloper.com/merkle-tree/</a>.</li>

<li id="ref-9">Blogpost of Vitalik Buterin — Merkling in Ethereum, <a href="https://blog.ethereum.org/2015/11/15/merkling-in-ethereum">https://blog.ethereum.org/2015/11/15/merkling-in-ethereum</a>.</li>

<li id="ref-10">NFT Metadata, <a href="https://www.weforum.org/agenda/2022/02/non-fungible-tokens-nfts-and-copyright/">https://www.weforum.org/agenda/2022/02/non-fungible-tokens-nfts-and-copyright/</a>.</li>

<li id="ref-11">Reentrancy attack in a Solidity smart contract, <a href="https://cryptomarketpool.com/reentrancy-attack-in-a-solidity-smart-contract/">https://cryptomarketpool.com/reentrancy-attack-in-a-solidity-smart-contract/</a>.</li>

<li id="ref-12">ERC Token Standards - The Ultimate List, <a href="https://www.blockchain-council.org/ethereum/erc-token-standards/">https://www.blockchain-council.org/ethereum/erc-token-standards/</a>.</li>

<li id="ref-13">Why Does Bitcoin Use So Much Energy? <a href="https://www.forbes.com/advisor/ca/investing/cryptocurrency/bitcoins-energy-usage-explained/">https://www.forbes.com/advisor/ca/investing/cryptocurrency/bitcoins-energy-usage-explained/</a>.</li>

<li id="ref-14">ERC-721 Non-Fungible Token Standard, <a href="https://ethereum.org/en/developers/docs/standards/tokens/erc-721/">https://ethereum.org/en/developers/docs/standards/tokens/erc-721/</a>.</li>

<li id="ref-15">Ethereum block architecture, <a href="https://ethereum.stackexchange.com/questions/268/ethereum-block-architecture">https://ethereum.stackexchange.com/questions/268/ethereum-block-architecture</a>.</li>

<li id="ref-16">Ethereum Virtual Machine, <a href="https://ethereum.org/en/developers/docs/evm/">https://ethereum.org/en/developers/docs/evm/</a>.</li>

<li id="ref-17">Ethereum Wallets, <a href="https://ethereum.org/en/wallets/">https://ethereum.org/en/wallets/</a>.</li>

<li id="ref-18">Cryptographic Hashes and Bitcoin, <a href="https://freecontent.manning.com/cryptographic-hashes-and-bitcoin/">https://freecontent.manning.com/cryptographic-hashes-and-bitcoin/</a>.</li>

<li id="ref-19">Private and public keys on Ethereum, <a href="https://www.massmux.com/private-and-public-keys-on-ethereum/">https://www.massmux.com/private-and-public-keys-on-ethereum/</a>.</li>

<li id="ref-20">What Is Sleepminting And Will It Ruin NFT Provenance? <a href="https://timdaub.github.io/2021/04/22/nft-sleepminting-beeple-provenance/">https://timdaub.github.io/2021/04/22/nft-sleepminting-beeple-provenance/</a>.</li>

<li id="ref-21">Pentagon finds concerning vulnerabilities on blockchain, <a href="https://www.techrepublic.com/article/pentagon-finds-concerning-vulnerabilities-on-blockchain/">https://www.techrepublic.com/article/pentagon-finds-concerning-vulnerabilities-on-blockchain/.</li>

<li id="ref-22">A. M. Antonopoulos and G. Wood. Mastering Ethereum: Building Smart Contracts and DApps. O’Reilly Media, 2018.</li>

<li id="ref-23">Bitcoin Energy Consumption Index, <a href="https://digiconomist.net/bitcoin-energy-consumption">https://digiconomist.net/bitcoin-energy-consumption.</li>

</ol>