Vous êtes sur la page 1sur 15

Smart Contracts for Dummies

All you need to know before you start using them.

PlutusX Follow
Feb 24, 2018 · 10 min read

You may have heard this term floating around the crypto-community
for a while, and even if you’re new the the HODL life you possibly heard
the term smart contracts used before.


HODLer: “Man, I just bought this lambo with a smart contract once my
BTC hit 20k.”

This sounds great, like the real future of contracts but what exactly are
smart contracts, how are they different than traditional contracts, and
why are they more superior? Lets dive into some history real quick.

What are Smart Contracts?

The concept of “smart contracts” has been around since 1996. Nick
Szabo’s, first publication, “Smart Contracts: Building Blocks for Digital
Free Markets” was published in Extropy #16, and then later reworked
as “Formalizing and Securing Relationships on Public Networks.” These
documents explained how it would be possible to take advantage of
electronic commerce protocols to establish contract law and related
business practices, circa the infancy of the public Internet.

While a standard contract outlines the terms of a relationship (usually

one enforceable by law), a smart contract enforces a relationship with
cryptographic code. One of the best things about the blockchain is that,
because it is a decentralized system that exists between all permitted
parties, there’s no need to pay intermediaries (Middlemen) and it saves
you time and conflict. Blockchains have their problems, but they are
rated, undeniably, faster, cheaper, and more secure than traditional
systems, which is why banks and governments are turning to them.

What are Smart Contracts?

Byzantine fault-tolerant algorithms allowed digital security through
decentralization to form smart contracts. Additionally, the
programming languages with various degrees of Turing-completeness
as a built-in feature of some blockchains make the creation of custom
sophisticated logic possible.

Notable examples of implementation of smart contracts are:

1. Decentralized cryptocurrency protocols are smart contracts with

decentralized security, encryption, and limited trusted parties that
fit Szabo’s definition of a digital agreement with observability,
verifiability, privity, and enforceability.

For the purpose of this article, we will elaborate on the Ethereum

implementation. Ethereum runs a nearly Turing-complete language on
its blockchain, a prominent smart contract framework. We’ll dive into
the ERC20 token later on but for now, I want to cover the fundamental
basics of the smart-contract framework.
Smart contracts take advantage of blockchain technology which
effectively “Sets in stone” the agreement which by default makes the
contract immutable. Therefore, the contracts then inherit the attributes
associated with blockchain technology such as trust-less, immutable,

These characteristics align perfectly when executing a smart contract.

Let’s break down the word ‘Smart-Contracts’. When we (proverbial

‘we’) say contract we tend to automatically associate exclusively with
legal documents and agreements between 2 or more entities. In reality,
a ‘Smart-Contract’ is simply a self-exulting program.
Instead of reinventing the wheel I will use the most widely-circulated
example which is the simple vending machine.

These machines run a basic program that states “if money enters & click
button = drink”. If you put in $1.00 into the machine and click coca-
cola the system program acts as some type of agreement and as a result
the coke is dispensed.

In the terms of a traditional document-based contract, we can say that

the program is like the contract, the code is the words, and clicking the
button is the signature. The pseudo code looks something like:

> If money received == $1.00

> && the button pressed is “coca-cola”
> Then release coca_Cola

As you can see this sniper of code Is essentially a contract. There’s a

statement of declarations, some terms, and the program even fulfills its
end of the bargain for you without some middleman.

This proposes a serious problem with trust as you scale up. The purpose
of the middleman (escrow for example) is to enact trust between both
parties to reassure that either party won’t defraud the other. The
solution lies in the blockchain tech. The complete transparency places
the code publicly to be verified. This removes the need for the middle-
man and takes advantage of the trust-less ecosystem native to the

Security Issues
Because of the visibility in the trestles environment the program is
susceptible to malicious actors. Potential bugs including security holes
are exposed. The biggest example was the DAO attack in June of ’16.
These problems are not easily fixable, and the solution resulted in a
hard fork.

You could possibly send the wrong code, or, as lawyer Bill Marino
points out, I send the right code, but an apartment is condemned (i.e.,
taken for public use without my consent) before the rental date arrives?
If this were the traditional contract, I could rescind it in court, but the
blockchain is a different situation. The contract performs, no matter

These re-challenges that we have been tackling to improve upon.

Use Case
The use cases for smart contracts are endless across almost every major
industry imaginable.

* Real Estate
* Healthcare
* Automobile
* Government
* And much more

With notable examples such as supply chains and management.

In 2015 the Depository Trust & Clearing Corp. (DTCC) used a

blockchain ledger to process more than $1.5 quadrillion worth of
securities, representing 345 million transactions.

Here is a video of Siraj talking about how smart contracts work.

4 Ways to Use Smart Contracts

A Smart Contract Example

Now let’s get into the code. This finalizes our mini-lesson on smart
contracts. We’ll tie all this together using the ERC20 token. THIS PART

Like mentioned, we will be using ethereum as our example case but

know that smart contracts can be used on any blockchain. Tron and few
other platforms are proving to become far more superior in most cases.

pragma solidity ^0.4.16;

contract owned {

address public owner;

function owned() public {
owner = msg.sender;
modifier onlyOwner {
require(msg.sender == owner);
function transferOwnership(address newOwner) onlyOwner
public {
owner = newOwner;

interface tokenRecipient { function receiveApproval(address

_from, uint256 _value, address _token, bytes _extraData)
public; }

contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid
changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256))
public allowance;
// This generates a public event on the blockchain
that will notify clients
event Transfer(address indexed from, address indexed
to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);

* Constrctor function
* Initializes contract with initial supply tokens to
the creator of the contract
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 **
uint256(decimals); // Update total supply with the decimal
balanceOf[msg.sender] = totalSupply;
// Give the creator all initial tokens
name = tokenName;
// Set the name for display purposes
symbol = tokenSymbol;
// Set the symbol for display purposes
* Internal transfer, only can be called by this
function _transfer(address _from, address _to, uint
_value) internal {
// Prevent transfer to 0x0 address. Use burn()
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] +
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find
bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] ==

* Transfer tokens
* Send `_value` tokens to `_to` from your account
* @param _to The address of the recipient
* @param _value the amount to send
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);

* Transfer tokens from other address
* Send `_value` tokens to `_to` in behalf of `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
function transferFrom(address _from, address _to,
uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
// Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
* Set allowance for other address
* Allows `_spender` to spend no more than `_value`
tokens in your behalf
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
function approve(address _spender, uint256 _value)
public returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;

* Set allowance for other address and notify
* Allows `_spender` to spend no more than `_value`
tokens in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to
the approved contract
function approveAndCall(address _spender, uint256
_value, bytes _extraData)
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value,
this, _extraData);
return true;

* Destroy tokens
* Remove `_value` tokens from the system irreversibly
* @param _value the amount of money to burn

function burn(uint256 _value) public returns (bool

success) {
require(balanceOf[msg.sender] >= _value); //
Check if the sender has enough
balanceOf[msg.sender] -= _value; //
Subtract from the sender
totalSupply -= _value; //
Updates totalSupply
Burn(msg.sender, _value);
return true;
* Destroy tokens from other account
* Remove `_value` tokens from the system irreversibly
on behalf of `_from`.
* @param _from the address of the sender
* @param _value the amount of money to burn
function burnFrom(address _from, uint256 _value) public
returns (bool success) {
require(balanceOf[_from] >= _value);
// Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]);
// Check allowance
balanceOf[_from] -= _value;
// Subtract from the targeted balance
allowance[_from][msg.sender] -= _value;
// Subtract from the sender's allowance
totalSupply -= _value;
// Update totalSupply
Burn(_from, _value);
return true;


contract MyAdvancedToken is owned, TokenERC20 {

uint256 public sellPrice;

uint256 public buyPrice;

mapping (address => bool) public frozenAccount;

/* This generates a public event on the blockchain

that will notify clients */
event FrozenFunds(address target, bool frozen);

/* Initializes contract with initial supply tokens to

the creator of the contract */
function MyAdvancedToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol)
public {}

/* Internal transfer, only can be called by this

contract */
function _transfer(address _from, address _to, uint
_value) internal {
require (_to != 0x0);
// Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value);
// Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]);
// Check for overflows
// Check if sender is frozen
// Check if recipient is frozen
balanceOf[_from] -= _value;
// Subtract from the sender
balanceOf[_to] += _value;
// Add the same to the recipient
Transfer(_from, _to, _value);
/// @notice Create `mintedAmount` tokens and send it
to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will
function mintToken(address target, uint256
mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);

/// @notice `freeze? Prevent | Allow` `target` from

sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze)
onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);

/// @notice Allow users to buy tokens for

`newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the
/// @param newBuyPrice Price users can buy from the
contract function setPrices(uint256 newSellPrice,
uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;

/// @notice Buy tokens from contract by sending ether

function buy() payable public {
uint amount = msg.value / buyPrice;
// calculates the amount
_transfer(this, msg.sender, amount);
// makes the transfers

/// @notice Sell `amount` tokens to contract

/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice);
// checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount);
// makes the transfers
msg.sender.transfer(amount * sellPrice);
// sends ether to the seller. It's important to do this last
to avoid recursion attacks

. . .

Smart contracts are simply a program that are used as a tool to more
efficiently execute agreements without a middleman charging extra on
top. The trust-less environment removed the need for a middle man but
also acts as a catch-22 because the code is public, therefore vulnerable
to malicious actors. As we continue to perfect these contracts we will
soon see a massive adoption which will result in changes within major

. . .

Thanks for reading! :) If you enjoyed this

article, hit that heart button below ❤
Would mean a lot to us and it helps other
people see the story.
Say Hello On

Instagram | Twitter | YouTube

. . .
What’s New

Our Execs Newest Positions

Our executives Angel Mondragon (CEO) and Patrick Benske (CMO)
were recently announced as Senior Advisors for a Public Company for
Crypto Currency. Read Here

Whitepaper | Community
We are releasing a teaser for our whitepaper in addition to our first
months results for our fund. We are releasing it on our telegram. Find
the channel HERE.

. . .

Writer: Angel Mondragon. Edited: Patrick Benske.