J.D Nicholls
Founding Full-Stack Web3 Engineer at @baxusco | Digital nomad ๐ | Mentor ๐จโ๐ซ | Speaker ๐ฃ๏ธ | Developer ๐จโ๐ป | Creator of @proyecto26 #opensource #developer
Other languages =>
- Founding Full-Stack Engineer ๐ท
- Open Source Contributor ๐จโ๐ป
- Game developer (Hobby) ๐ฎ
- Developer who loves UX ๐ซ
- Chocolate lover ๐ซ
- Creator of Proyecto26ย ๐ง
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 ๐ญ
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.
- 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?
- 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.
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).
Each Block references the hash of the previous Block, generating a Chain of Blocks.
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.
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.
Unlike CeFi ๐ฆ, where financial products only function properly in predictable scenarios (favorable conditions) and where only a few benefit:
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 ๐ธ
- 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).
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".
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 ๐๏ธ
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.
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 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.
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.
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.).
Blockchain enables bidirectional communication with external systems.
This solves the problem in Blockchain where there is no source of randomness, because everything a contract can see is public.
- From Web 1.0 to Web3: How the Internet Grew Over The Years.
โ- What is the math behind elliptic curve cryptography?
- 77+ Smart Contract Use Cases Enabled By Chainlink.
- 5 Ways To Use Chainlink Functions in Your Decentralized Applications.
- Chainlink Workshops: Intro to Solidity & Blockchain.
- Chainlink Tutorials:ย Random Numbers Tutorial.
- Chainlink Hackathon: Example Projects.
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.
- 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. ๐
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.
- 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.
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.).
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).
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"
}
]
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.
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 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.
- 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.
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.
Initial Recommendations:
by @muisca_
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.
// 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.
- 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.
// 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
// 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];
}
}
Similar to a Dictionary in some languages, or the Map object in JavaScript, it allows for storing key-value pairs.
// 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.
//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)
//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++;
}
}
"payable" is a reserved keyword that indicates that we are going to transfer tokens.
// 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 }.
- Introduction to Smart Contractsย - Solidity guide.
- Intro to Solidity: Ship an Ethereum dApp
- Open Zeppelin Wizard
- Solidity by Example
- Hardhat Console Log
- Exercises with Chainlink: Price Feeds, API Request, Random.
The Crypto Purgeย ๐ธ
Ledger
By J.D Nicholls
A presentation about Smart Contracts and Blockchain
Founding Full-Stack Web3 Engineer at @baxusco | Digital nomad ๐ | Mentor ๐จโ๐ซ | Speaker ๐ฃ๏ธ | Developer ๐จโ๐ป | Creator of @proyecto26 #opensource #developer