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 ๐Ÿง

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

The Crypto Purgeย ๐Ÿ’ธ

Other resources ๐ŸŽ

Storage

SDKs

Platforms

Hardware ๐Ÿ‘›

Ledger

Bootcamps โ›บ

Alchemy University

Smart Contracts

By J.D Nicholls

Smart Contracts

A presentation about Smart Contracts and Blockchain

  • 4,522