Smart Contracts 📜

for Devs

JavaScript code using Hardhat
Español
Other languages =>

     there,

I'm J.D. Nicholls 👋

- Founding Full-Stack Engineer 👷

- Open Source Contributor 👨‍💻

- Game developer (Hobby) 🎮
- Developer who loves UX 💫

- Chocolate lover 🍫

- Creator of Proyecto26 🧚

Special Thanks 🙏

Can you do everything with Blockchain & Smart Contracts?

What is Blockchain? 🤔

It's a data structure that allows for the creation of a secure, reliable, and decentralized network that stores data, exchanges value, and records transaction activity in a public ledger that is not controlled by any central authority, but rather is maintained by all participants.

Transactions are performed through a decentralized computer network and there is no government entity or intermediary between the participants 🎭

Why Blockchain? 🤷

We propose a solution to the double-spending problem using a peer-to-peer network.

Blockchain allows the controlled issuance of digital currencies (cryptocurrencies), in addition to functioning as a public ledger that records each of the transactions made, ensuring that each currency can only be used once. In this way, the security scheme is guaranteed, since each of these transactions are carried out through a decentralized network of computers and there is no government entity or intermediary between the participants.

Decentralization 🌐

Tiers:

- Architectural: number of computers, how many can it tolerate? how does the system behave (Monolithic or distributed)? Is it fault resistant (components that work independently)? Is it resistant to attacks (there is no central point that affects its operation)? Is it able to resist collusion (a user cannot benefit at the expense of others)?

- Political: How are the users involved organized, how is the system governed? How many actors does the system consist of?
- Logic: ¿Are the interfaces and data structures of the system a single entity or are they an unidentifiable swarm? ¿What could happen if we could cut the system in half, between providers and users? ¿Will they continue to operate as independent units?

Benefits of Decentralization ⚖️

- Fault tolerance: it's less prone to failure, as long as there is a node operating the system will continue to function. 

- Attack resistant: it's more expensive to attack, be destroyed or manipulated by lacking a central point.

- Collusion resistant: prevent certain users from benefiting over others, either because they have more computing power, greater participation, etc.

Descentralización

Hash on the Blockchain #️⃣

It's a cryptography method that converts any form of data into a unique result. In the Blockchain each transaction has a unique hash, and the set of transactions is considered a Block, which in turn is represented by a unique hash generated by the set of hashes of all transactions (Merkle Tree).

Merkle Tree

Each Block references the hash of the previous Block, generating a Chain of Blocks.

Nonce in a Bloque 🧱

The Nonce is a number that can only be used once::

 

A one-time random number intended for authentication of data transfers between two or more parties.

 

This random number ensures that old hashes cannot be reused in what are called replay attacks. In a blockchain network, the nonce works in combination with the hash as a control element to prevent manipulation of block information.

Normally, the nonce also implements a timestamp to prevent its repetition.

Blockchain 🔗

A blockchain is essentially a linked list; each block has a reference to the previous block. e.g: demo

If someone changes the information in a Block, the next Block would be automatically invalidated because it breaks the chain...

When there are multiple participating nodes (Peers), the ones with the longest blockchain win.

Links

Courses

What's DeFi? 💱

Unlike CeFi 🏦, where financial products only function properly in predictable scenarios (favorable conditions) and where only a few benefit:

Why DeFi? 💱

DeFi is designed to solve problems such as:

  • Inefficiency: expensive, slow, and insecure 🐌

  • Limited access: not inclusive 💳

  • Opacity: you need to trust regulators and their mixed records to monitor banks 🧐

  • Centralized control: an oligopolistic financial system that imposes higher fees than in a competitive market 📈

  • Lack of interoperability: difficulty in moving funds from one financial institution to another 💸

CeFi vs DeFi

Why not have a Trusted Arbitrator? 👮

- Single point of failure: The system stops working if there is a point of failure.

- Power concentration: "Who controls the past controls the future". This lends itself to censoring transactions, imposing new conditions to get transactions included in the history, etc.

- Don't be Evil: We shouldn't have to rely on "Promises" to protect sensitive information from intermediaries (we should trust no one).

DeFi Completely Redefines a User's Relationship to Markets

What's a DAO? 🏢

The're organizations or groups that operate without a centralized body. Instead, decision-making is done in a decentralized manner by a group of individuals working together to shape the future of the community. DAOs represent an effort to address the legitimacy problem in governance:

The agent prioritizes their personal interests over those of the collective. The challenge is governance

As DeFi protocols (Uniswap, etc) emerged, DAOs have become an integral part of decentralized finance. DAOs have the ability to execute actions autonomously through complex governance rules using "Smart contracts".

Links

What's a Smart Contract? 🤝

A contract is a binding agreement between two or more parties.

Unlike a centralized agreement with small print clauses that benefit some participants over others, Digital Contracts seek to provide total transparency in fulfilling the parties' obligations and security by not relying on the potential risks and availability of a centralized system 🏛️

Smart Contract 📋

It's a self-executing contract in which the terms of the agreement are directly defined through code (script) that cannot be changed (immutable). It implements a series of rules (conditions) through programming without the need for human interaction and/or third parties.

Smart Contracts Run on the blockchain

Digital Agreement 🆚 Smart Contract

The smart contract possesses the peculiarity of being executed on a decentralized infrastructure, such as the Blockchain, in order for the execution and fulfillment of the contract to not depend on a single entity, thereby ensuring that no one has any influence over it 🕵️

Smart Contracts are Superior Digital Agreements

Can't Be Evil 😈

Smart contracts provide a solution to a social problem: trust ("Don't trust, verify").

Cryptographic Truth > "Just Trust Us" (Promises)

Individuals, therefore, cannot act maliciously by reducing counterpart risk (the probability of a party involved in a transaction failing to fulfill their contractual obligation) and ensuring transparency that is inherent by design. In addition, Smart Contracts allow for consistently high interest returns, guaranteed by cryptography and mathematical foundations.

Truth-based Society 🙋 

Web 3

Real World Problem 🧐

Risks ⚠️

Operadores Random son un riesgo

A random number is generated by taking a multitude of different numbers from a computer as a source of randomness, which is difficult to control.

Hybrid Smart Contracts ✍️

The purpose of these contracts is to connect multiple external data sources to Blockchain networks, fairly and impartially, so that Smart Contracts can interact with real-world data through Oracles.

 

Oracles create an opportunity to build new types of cryptographically guaranteed systems that can interact with real-world information and leverage the security provided by decentralized networks. Examples:

- Connecting to existing services.
- Creating value by interoperating with the global market.
- Verifying identity (authentication, etc.).

2-way data binding ⚛️

Blockchain enables bidirectional communication with external systems.

Consistency 🛡️

Chainlink provee un Random verificable

Verifiable Randomness ✔️

This solves the problem in Blockchain where there is no source of randomness, because everything a contract can see is public.

Links

What's Ethereum? 🪙

This is a public, open-source blockchain that supports multiple protocols such as Smart Contracts (ERC-20, ERC-777) and NFTs (ERC-721). Its native currency is called ETHER (ETH).

 

Characteristics

- State-based transactions: It can be considered as a state machine, receiving inputs such as the hash of the previous block (parentHash), and generating blocks as outputs.

- Consensus mechanisms: PoW (computational power, computational competition) and transitioning to PoS (distributed consensus through validators).

- Nodes and Clients: A client is responsible for verifying transactions in each block, and the types of nodes are light, full, and storage.

- Accounts: Tokens controlled by users using a cryptographic key pair and Smart Contracts controlled by code.

- Transactions: actions (atomic operations) are initiated by an account through a cryptographic signature that modify the state of the network once they are mined. Transactions require gas to be executed.

- Blocks: comprised of a timestamp, a length number, a difficulty level, a unique identifier (mixHash), the identifier of the previous block, a list of transactions, the system state (state root), and a nonce, all within a limited size.

Ethereum 📒

Block Limit ⛏

- Blocks are mined approximately every 15 seconds.

- Each Block has a target size of 15 million "Gas", with a limit of 30 million (2 times the target size). If a block size exceeds the target, the protocol increases the "base fee" of the next block. 

- Typically, a block is composed of 150-200 transactions, but this size is variable depending on the network demand. 📈

The Ethereum

Virtual Machine 🖥️

Is a decentralized computing environment that is supported by interconnected computers running Ethereum clients. Its purpose is to ensure continuous, uninterrupted, and immutable operation of this special state machine. As such, the EVM defines the computation rules for generating a valid new state from one block to another. 

Y(S, T)= S'

The EVM behaves like a mathematical function: given an input, it produces a deterministic output. Therefore, it is quite useful to formally describe Ethereum as a state transition function.

EVM

- Turing-complete 256 bits.
- Ethereum Smart Contract Execution Environment.

- Architecture based on a stack for computations and uses bytecode to encode instructions.

- Determines the result of the executed contract logic.

Ether (ETH)

It is the native cryptocurrency of the network used to pay transaction fees and to reward miners for executing smart contract code and performing validations (finding a valid nonce, etc.).

Tokens

These are smart contracts that represent any interchangeable goods or services, such as a unit of account:

- ERC-20: same value-type, used with virtual currencies.

- ERC-721: non-fungible token, unique, used as a utility.

- ERC-677: transfer tokens to contracts with the activation logic that describes their behavior (Chainlink).

Compile code 🚧

When compiling the contract, bytecode (EVM low-level instructions for efficient execution) and the definition of the ABI (interface that specifies how to interact with the contract) are generated.

 

Application Binary Interface includes:

- Public methods

- Parameters

- Constants

- Data structures

- Event types (logs)

- Inputs/Outputs

[
  {
    "inputs": [],
    "name": "getCount",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "increment",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  }
]

Execute the contract 🎬

The bytecode of the contract is published to the Blockchain and in order to interact with it, the ABI is required to understand the inputs and outputs used by the contract.

Gas payment 💸

The execution of functions in a contract may incur a cost in gas (a unit that measures the amount of computational effort required) in order to maintain the security of the Ethereum network, e.g:
- Each CPU instruction in the EVM (during contract execution).

- Each write operation (memory and storage).

- Execution speed and size of the contract.

The prices are indicated in Gwei.
1 gwei === 0.000000001 ETH (10-9 ETH)

Gas Fees ⛽

Gas is the cost of executing transactions. Miners confirm transactions and receive a payment as a reward. Gas is the unit that measures the computational work required to run transactions or smart contracts on the EVM:

- Reading data from the Blockchain is free 🆓

- Gas is measured/paid for each contract execution.

- The lower the limit, the more delayed the transaction is.

- The limit prevents long executions (reverses transaction execution if reached) and sets a maximum amount.

- There are gas calculators such as ETH Gas Station.

Gas units (limit) * (Base fee + Tip) (in gwei) = Gas fee

Links

- Learn by coding

- Ethereum Wiki

- Ethereum Mainnet Statistics - network distribution.

- Accounts - contracts/users that participate in the network.

- Transactions - network status viewer.

- Pending Transactions (Mempool) -  not been validated yet.

- State of Ethereum - data structure that maintains all accounts linked through hashes.

- Turing completeness - Used for a distributed state-machine.
- What is Ethereum Gas? - Ethereum Gas Explained.

- Introduction to the Ethereum Stack

What's a NFT? 🖼️

display: blockchain

Why NFTs? 🎨

Copyright and royalties. NFTs provide an infallible solution to ensure the authenticity of a work through cryptography; whether it is a drawing, photo, video, audio, 3D model, code, etc.
At the same time, NFTs allow authors to define royalties percentages, number of copies to create limited editions, exclusive content, etc from the publication of the work (minting).
Royalty profits do not depend on relying on a third party to obtain the defined percentage for each new sale of the work; it works automatically and transparently through the smart contract.

Minting NFTs 🧑‍🎨

Initial Recommendations:

  • Start by creating small series of NFTs with only 3 copies each, so that you can offer them in a more accessible way to the general public and gradually grow.
  • Be careful not to mint the same artwork on different Blockchains.
  • Create a profile (twitter, instagram, biolink).
  • The sales process consists of 2 steps: minting and listing the artwork. You get to choose the number of copies to put up for sale and their price.
  • Announce each drop you make, including the name of the artwork, the floor price, the network where you minted it, and the image/link. The rarity of the artwork is valuable.

NFT & Oracles 🔮

Copyright 🗽

  • Copyright Act of 1976: law that regulates the protection of artworks, copyright holders have the exclusive right to reproduce, distribute, and publicly display their artworks.
  • Digital art:  the digital asset represented by an NFT may include an underlying work of art or other copyrighted material, and the copyright owner of that material may retain exclusive rights to reproduce and distribute the work.
  • Registration of NFTs: It is a unique piece that cannot be traded like a cryptocurrency (fungible assets). Technically, an NFT can represent any type of asset, whether digital or physical, and should not be confused with the asset itself (it's a contract that stipulates who is the owner of the work, a certification). However, digital support doesn't apply to it because it is not the work itself (transfer of property rights is required).

Links

Ideas 💡

  • Decentralized exchange; DEXT, etc.
  • Competitive games; racing.
  • Crowdfunding; support creators and artists (through memberships, etc).
  • Supply chains, logistics (value chains).
  • NFTs for discount coupons.
  • Food delivery.
  • Public surveys/polls.
  • Donations, social aid (Churches, UNICEF, etc).
  • Tracking the manufacturing and distribution of medications.
  • Online Marketplaces.
  • Collectible Card Games.
  • Royalty Sharing for Musicians.
  • Identity Verification.
  • Sporting Events.
  • Real Estate Investment.
  • Event Ticketing.

What is Solidity? 👨‍💻

A high-level, object-oriented programming language specifically designed for creating contracts on the EVM. Contracts are collections of code that contain both functions and state data that reside at a specific address on the blockchain

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 <0.9.0;

contract Storage {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function get() public view returns (uint) {
        return storedData;
    }
}

- Store (calculations, caching, persistent)

- Memory (message call, instance)

- Stack (computations)

Optimized for data storage and security.

Visibility of Variables 🔎

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

contract Marketplace {
    // only other contracts and accounts can call
    string external data1 = "external data";
    
    // any contract and account can call
    string public data2   = "public data";
    
    // only inside the contract that defines the varibale
    string private data3  = "private data";
    
    // only inside contract that inherits an internal variable
    string internal data4 = "internal data";
}

The visibility modifiers are used to restrict access to variables.

Visibility of Functions 🔎

- Public:

  It can be called from anywhere. A "Getter" is defined by default in the variables.

- External:

  It cannot be called internally, as it is designed to be called by other contracts.
- Internal:

   They can only be used internally.

- Private:
   
Accessible only within the contract.

Parameters and Data Types 🔎

// Function with a 256-byte uint parameter and no return value
function setNumber(uint256 _number) public {
  number = _number;
}

// Function with no parameters that returns a uint
function getNumber() public view returns (uint256) {
  return number;
}
  • Integers & unsigned integers (Without floating-point/decimal values)

  • Booleans

  • Strings (UTF8 encoded)

  • Address (encoded with checksum)

  • Bytes/8/32 (string data as bytes)

  • Enums

Arrays 🔎

// fixed size
uint[3] memory numbers = [1, 2, 3];
numbers[0] = 100;

Compile-time fixed size

// dynamic size
uint[] numbers = [];

function addNum(uint _num) public returns (uint) {
  numbers.push(_num);
  return numbers.length;
}

Dynamic size

Arrays can be fixed or dynamic, and can store arbitrary data types.
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;

contract Marketplace {
  // Persist key-value data
  mapping (uint => string) internal products;

  function addProduct(uint _key, string memory _product) public {
    products[_key] = _product;
  }

  function getProduct(uint _key) public view returns (string memory) {
    return products[_key];
  }
}

Mappings (key-value) 🔎

Similar to a Dictionary in some languages, or the Map object in JavaScript, it allows for storing key-value pairs.

Objects (struct) 🔎

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;

contract Marketplace {

  struct Product {
    address payable owner;
    string name;
    string image;
    string description;
    uint price;
    uint sold;
  }
  
  mapping (uint => Product) internal products;
}
  function addProduct(
    uint _key,
    string memory _name,
    string memory _description,
    uint _price
  ) public {
    uint _sold = 0;
    products[_key] = Product(
      parable(msg.sender),
      _name,
      _description,
      _price,
      _sold
    )
  }
  function getProduct(uint _key) public view returns (Product memory) {
    return products[_key];
  }
They are a collection of primitive types, which can be stored in mappings and arrays.

Create tokens 🔎

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Token {
  string public name = "Open Source Token";
  string public symbol = "OST";
  uint public totalSupply = 26000000;
  mapping(address => uint) balances;

  constructor() {
    balances[msg.sender] = totalSupply;
  }

  function transfer(address to, uint amount) external {
    require(balances[msg.sender] >= amount, "Not enough tokens");
    balances[msg.sender] -= amount;
    balances[to] += amount;
  }

  function balanceOf(address account) external view returns (uint) {
    return balances[account];
  }
}

It does not comply with the ERC-20 specification (demo purposes)

Create ERC20 token 🔎

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract OSToken is ERC20 {
  constructor(string memory name, string memory symbol) ERC20(name, symbol) {
    _mint(msg.sender, 26000000 * (10 ** 18));
  }
}
// Deploy a new token
const tokenFactory = await hre.ethers.getContractFactory("OSToken");
const osToken = await tokenFactory.deploy("Open Source Token", "OST");

Here is an example script for deploying a new token to a blockchain network:

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;

contract Marketplace {
  string internal customTokenAddress = "0x...";
  
  function buyProduct(uint _key) public payable {
    require(
      IERC20Token(customTokenAddress).transferFrom(
        msg.sender,
        products[_key].owner,
        products[_key].price
      ),
      "Transfer failed."
    );
    products[_key].sold++;
  }
}

Transferring Tokens 🔎

"payable" is a reserved keyword that indicates that we are going to transfer tokens.

Minting NFTs 🔎

// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

contract MyNFTToken is ERC721 {
  using Counters for Counters.Counter;
  Counter.Counter private _tokenIds;

  constructor() ERC721("MyAwesomeToken", "TokenName") {}

  function mintNFT(address receiver, string memory tokenURI) public returns (uint256) {
    _tokenIds.increment();
    uint256 tokenId = _tokenIds.current();

    _mint(receiver, tokenId);
    _setTokenURI(tokenId, tokenURI);

    return tokenId;
  }
}

"tokenURI" represents a JSON resource with a structure of { name, description, image }.

Links

DEMO

Other resources 🎁

Storage

SDKs

Platforms

Hardware 👛

Ledger

Bootcamps

Alchemy University

Smart Contracts

By Juan David Nicholls

Smart Contracts

A presentation about Smart Contracts and Blockchain

  • 4,039