What are blockchain-based smart contracts?

Blockchain is a decentralized system that exists thanks to many networked computers. Therefore, one of its main advantages is that you can avoid paying intermediaries and save your time and nerves.

Blockchain has its drawbacks, but it is faster, more reliable and more secure than traditional systems, which is why banks and government organizations are increasingly using this technology for their needs. The principle of blockchain operation is shown in the infographic:

In 1994, Nick Szabo, a legal scholar and cryptographer, realized that smart contracts, also called self-executing, digital or smart contracts, could be created using a decentralized ledger.

Such contracts can be written in code, stored and duplicated in the system, and their execution will be ensured by a network of computers that manages the blockchain. Also, using the registry, it will be possible to transfer money to each other and receive goods or services.

What are smart contracts?

Smart contracts allow you to exchange money, property, shares or other assets without resorting to intermediaries.

In order to conclude a regular transaction, you need to go to a lawyer or notary, pay and wait for the documents to be processed. Smart contracts work like vending machines: you simply throw Bitcoin into the machine (that is, into the ledger), and the contract, driver's license, or any other service you ordered stored with a third party drops into your account.

In addition, unlike traditional agreements, smart contracts not only contain information about the obligations of the parties and penalties for violating them, but also automatically ensure compliance with all terms of the contract.

Smart contracts are an electronic algorithm that describes a set of conditions, the fulfillment of which entails certain events in the real world or digital systems. The implementation of smart contracts requires a decentralized environment that completely eliminates the human factor, and to be able to use value transfer in a smart contract, cryptocurrency is required. Wikipedia definition.

At a recent blockchain summit in Washington, Vitalik Buterin, a 23-year-old programmer and creator of the Ethereum project, explained that in a smart contract, an asset or currency is transferred to a program that enforces a set of conditions.

At a certain point, this program confirms that the contract has been fulfilled and automatically determines whether the specified asset should go to one of the parties to the transaction or immediately return to the other party (or maybe the conditions are a little more complicated). All this time, the document is stored and duplicated in a decentralized registry, which ensures its reliability and does not allow either party to change the terms of the agreement.

Cryptocurrencies and blockchain

In general, cryptocurrencies appeared back in 2009. The first of them was the well-known Bitcoin payment system, and other developers were inspired by the success of its anonymous creator under the pseudonym Satoshi Nakamoto. Among these crypto enthusiasts was Vitaly Buterin , a young Russian-Canadian programmer and founder of the Ethereum platform.

Digital gold. What is cryptocurrency - using Bitcoin as an example

It was in the Bitcoin protocol that a technology called blockchain , which you can now hear about almost everywhere. In short, blockchain is a distributed and sequential ledger technology. To give you an idea of ​​it, let’s give an example .

Masha transferred 1 bitcoin to Petya. Information about this digital transaction will be placed in the same block with other transactions that occurred around the same time. A month later, Petya decides to transfer this bitcoin to his friend Vasya. Information about the new transaction will be placed in a new block, but this block will refer to the previous block, where information about the money transfer “Masha - Petya” is already stored.

Thus, we can track the entire history of the “travels” of Bitcoin, which was transferred to different electronic wallets. In the blockchain, each new transfer seems to refer to the previous one, and therefore nothing can be faked.

In short, a blockchain is something like a pedigree book, only instead of family members or an entire dynasty, there are financial transactions (down to the very first). Identical copies of such a “book” are stored on different users’ computers, so no network participant can arbitrarily falsify the “pedigree” in their own interests. Or, as they say, the blockchain is decentralized.

Let's look at a specific example of a smart contract

Here is the code written for a regular smart contract on the Ethereum blockchain platform. Contracts can be written on any blockchain, but Ethereum is the most popular because it provides unlimited possibilities for writing and working with smart contracts.

An example of a smart contract written on the Ethereum platform. Source: www.ethereum.org/token

It says that the creator of the contract should receive 10 thousand bitcoins. This contract allows anyone with enough funds in their account to transfer bitcoins to other people.

Create a standard “BLC” token agreement

incontracts/Create directoryBloggerCoin.sol file. You can also use the following command to create the file:

BloggerCoin.sol The code looks like this:

pragma solidity ^0.4.4; import "zeppelin-solidity/contracts/token/StandardToken.sol"; contract BloggerCoin is StandardToken { string public name = “BloggerCoin”; string public symbol = "BLC"; uint8 public decimals = 4; uint256 public INITIAL_SUPPLY = 666666; function BloggerCoin() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } }

Code Explanation

pragma solidity ^0.4.4;
The first line represents solidityVersion, the bytecode compiled in different versions is different, ^On behalf of upward compatibility, but the version cannot exceed 0.5.0。

import "zeppelin-solidity/contracts/token/StandardToken.sol";

This code is passed to importTo import what we need to useStandardTokenContracts.

contract BloggerCoin is StandardToken { … }

setBloggerCoinWhen entering into a contract, let BloggerCoinContract be directly inherited from StandardToken。isBoth are inherited. so BloggerCoin inherits StandardToken All state data and methods.

When we inherited the StandardToken contract also supports the following ERC20 feature specified in the standard.

functionmethod
totalSupply()Total number of issued tokens
balanceOf(A)Check the number of tokens in account A
transfer(A,x)Send x tokens to account A
transferFrom(A,x)Withdraw x tokens from account A
approve(A,x)Agree to the account to withdraw tokens from my account
allowance(A,B)Check how many tokens can be withdrawn from account A to account B

As before, it will be used to subsequently check balanceOf and transferTwo functions. because the StandardToken Contract has already implemented these functions for us, so we don't need to write it from scratch.

string public name = "BloggerCoin"; string public symbol = "BLC"; uint8 public decimals = 4; uint256 public INITIAL_SUPPLY = 666666;

The purpose of setting parameters here is to specify some characteristics of this token. Taking the yuan as an example, the name of the yuanRMBDollar code¥Take 100 yuan This is a penny to get the slightest change.0.0001Yuan. because 1 yuan The smallest can be divided by the decimal point The last 4 digits (0.0001) So, the smallest trading unit (decimals) For 4。

Here is the name of this encrypted token (name) BloggerCoin (tribal coin) Token symbol (symbol) BLC Minimum division unit 4 (Minimum can be found 0.0001 tribal coins).

NextChinese Yuan,Bitcoin,Ethernet currencies,Tribal moneyFor reference:

namesymboldecimals
R.M.B.¥4
BitcoinBTC8
EthereumETH18
BloggerCoinBLC4

Finally, the initial number of INITIAL_SUPPLY tokens is also determined. The lucky number chosen here is 666666. Additionally, when we set a global variable to public(Public), a new one that reads public variables will be added automatically when compiling the ABI interface in the truffle console. These variables can also be read in.

function BloggerCoin() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; }

With the same name as the contractBloggerCoinMethodBloggerCoincontractsConstructor(constructor), Specified in the constructortotalSupplyNumber and all initial tokensINITIAL_SUPPLYAll assigned to msg.senderThe account that is the account used to deploy this contract.totalSupplyDefined in ERC20Basic.sol in balancesDefined in BasicToken.solInch


pragma solidity ^0.4.11; import './ERC20Basic.sol'; import '../math/SafeMath.sol'; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } }

Next you will look at BasicToken.solThe content of the contract can be foundBasicToken.solImported into the contractSafeMath.solContracts.SafeMath` adds the necessary check to various numerical operations to make the numerical calculation in the contract more secure.

So we wrote a new contract with encrypted tokens that can be exchanged through an Ethereum wallet. Once this contract is deployed, it can always exist on the Ethereum blockchain, and since then a new type of crypto token has emerged in the world. As long as you can find someone who wants to have that token, that token has transaction value.

Practical application of smart contracts

Using smart contracts, you can simplify work in many areas of life, including logistics, management, law, and even elections.

Elections

According to experts, it is almost impossible to falsify election results, but thanks to smart contracts, the possibility of external interference in the voting system can be completely eliminated.

In this case, voter votes would be placed on a distributed ledger, requiring exceptional computing power to decode them. Such computers do not exist, so it will be impossible to hack this system.

Management

Blockchain not only offers a secure and transparent shared ledger, but also helps avoid misunderstandings when working together or situations where parties draw up contracts independently of each other.

Logistics and supply

Bitcoin Core protocol developer Jeff Garzik says:

“UPS can execute contracts that say, ‘If we receive payment for delivering a product, the manufacturer, many steps up in the supply chain, will immediately begin creating a new product because that product has already been delivered.”

Procurement too often suffers from bureaucracy, with different forms having to be approved by multiple authorities. Because of this, scammers get the opportunity to make money, and companies suffer losses. Blockchain avoids these problems because each participant in the supply chain has access to a secure electronic system that controls work progress and payments.

Thus, Barclays Corporate Bank uses smart contracts to register the transfer of ownership and automatically transfer payments to other financial institutions.

Cars

Think about a future where everything is automated. Google is already building on it, creating smart phones, smart glasses, and even smart cars. And this is where smart contracts come to the rescue.

Take, for example, self-driving or self-parking cars. Smart contracts will determine who is to blame for an accident: the sensor or the driver, and will also help in resolving any other situations. With the help of smart contracts, insurance companies can set premiums depending on where and under what conditions drivers operate vehicles.

Other areas

Other industries, such as acquiring, lending and accounting, will also use smart contracts - for example, for risk assessment and auditing in real time. Lawyers will be able to move from drafting traditional contracts to creating standard models of smart contracts. And on the Blockchain Technologies website, smart contracts have turned into an electronic-paper hybrid: they are confirmed by the blockchain and receive a material embodiment in the form of a paper copy.

Patrick Hubbard, Principal and Senior Product Marketing Manager at SolarWinds:

“The Yangon Stock Exchange in Myanmar makes payments using a distributed ledger. Of particular interest are those functions of blockchain that go beyond traditional uses of the technology. Thus, the Yangon Stock Exchange managed to solve the problem of settlements made at different times in a trading system that synchronizes trading only twice a day. Due to the fact that smart contracts themselves ensure the execution of transactions, blockchains with their reliable transaction system can be used in situations where complex operations are required that depend on various changing factors. That’s why Amazon, Microsoft Azure and IBM Bluemix are focusing so much on developing cloud-based blockchain-as-a-service technology.”

Prospects for ETH

Ethereum developers are planning to carry out a large-scale system update soon. The upgrade is proudly called Ethereum 2.0, and the essence is as follows:

  1. Gradual abandonment of mining and transition from proof-of-work to proof-of-stake. Mining is a very energy-intensive process. All this computing power, computers and video cards are now used in the ether network to confirm money transfers. And this is harmful to the environment (at least according to opponents of mining). ETH developers believe that the future lies in the new proof-of-stake algorithm (proof of ownership shares).
  2. Scalability and increased throughput . How many transactions on the Ether network take place in 1 second? 15 transactions. And how much, for example, is in the VISA payment system? About 1,500. For all its technical power and security, ether is quite “slow” compared to more traditional means of payment. With this “long” wait we pay for the safety and guarantee of the transfer. But since Ethereum is a huge ecosystem with tons of decentralized applications, increasing throughput should take the cryptocurrency to the next level.
  3. Implementation of shards . What could be better than blockchain? Right! Lots of blockchains! Shards are mini-blockchains that will work in parallel and communicate with the main data chain - the Beacon Chain. Thanks to shards, the load on the network will be distributed more evenly.

Ethereum co-founder leaves crypto world out of fear for his life

The promise of change has invigorated demand for ETH. In May, the historical maximum value of $4,000 was reached.

Today, the rate of this coin is about $2,130 per piece, as can be seen from the line graph:


Source Tradingview

What do you think about Ethereum? And which cryptocurrencies do you like best? Write in the comments!

We don't want to lose you, let's be friends! Subscribe to our Telegram channel, here are financial life hacks every day!

Pros of smart contracts

If we consider smart contracts when used in different spheres of life, we can highlight a number of important advantages. Among the advantages:

  • independence - you no longer need to resort to the services of intermediaries to conclude transactions;
  • security - the smart contract is located in a distributed registry, its terms cannot be changed;
  • savings - by getting rid of intermediaries, the parties to a smart contract can cooperate on more favorable terms;
  • no costs - if the terms of the contract are fulfilled, the parties immediately exchange assets.

Ethereum contracts: why do we need an oracle and how does it work?

Today, the main tasks that smart contract developers set for themselves are to improve ways to obtain data that would indicate the fulfillment of the terms of a particular contract.

Oracles are designed to process information received from sources and deliver it to the Ethereum smart contract in a form suitable for reading. This is a kind of intermediary that adapts the data.

As you understand, there are some problems in obtaining objective information: there are now a lot of sources on the Internet and many of them contradict each other. Therefore, the task of programmers today is to develop oracles that can obtain reliable and verified information. And this is not so easy to achieve.

Moreover, it is necessary to ensure that oracles have access to absolutely all possible areas of human activity: any price fluctuations on stock exchanges, the financial condition of a particular company and other important information. This will allow the use of Ethereum contracts in various transactions and ensure the security of transactions.

Nowadays, many specialists are working on developing methods for obtaining objective data. For example, Microsoft and IBM are investing heavily in developing platforms that will help collect various information in one place. But it is worth noting that there is still a lot of work to be done in this area.

Today, by the way, many programmers make good money writing smart contracts for Ethereum, because the main problem when creating code is to find a way to obtain important facts. And this is labor-intensive work that is expensive.

Disadvantages of smart contracts

Smart contracts are far from perfect. What if there are errors in the code? How should the state regulate these contracts? And how will it collect taxes on such transactions?

The list of possible problems is not limited to this. Experts are trying to solve all the issues, but such difficulties repel many potential users.

Smart contracts cannot be called an ideal tool for building relationships between people. They also have several disadvantages. Among the disadvantages:

  • legal status - for the operation of smart contracts, cryptocurrency is used, but it is not yet accepted as an official financial instrument;
  • errors - to draw up a smart contract, you need to specify all sorts of conditions and options for the development of transactions; the more complex the process, the more difficult it is to create a smart contract;
  • lack of understanding - most users still have little understanding of what smart contracts are.

Despite the above disadvantages, smart contracts have a high potential to gain a foothold in our lives in the future. They will become increasingly used as things become connected to the internet.

Blockchains, where can you conclude smart contracts?

Ethereum : An open blockchain platform that is best suited for writing and working with smart contracts. You can create any program, but you will have to pay for the computing resources of the platform with ETH coins.

NXT : This is an open blockchain platform with a limited number of smart contract samples. You can only use what's there; You can't write your own code.

Bitcoin : An excellent blockchain for Bitcoin transactions, but limited document processing capabilities.

Side Chains : Another name for blockchains parallel to Bitcoin that provide slightly greater contracting capabilities.

Compile, Deploy, Verify

In migrations/Create directory3_deploy_bloggerchain.js the content of the file is as follows:

Now run the compile and port commands

Notes: Make sure testrpc is running

  • truffle compile

/Users/liyuechun/Desktop/SmartContractDemo/BloggerCoin liyuechun:BloggerCoin yuechunli$ truffle compile Compiling ./contracts/BloggerCoin.sol… Compiling ./contracts/Migrations.sol… Compiling ./contracts/SimpleStorage.sol… Compiling zeppelin-solidity/contracts /math/SafeMath.sol… Compiling zeppelin-solidity/contracts/token/BasicToken.sol… Compiling zeppelin-solidity/contracts/token/ERC20.sol… Compiling zeppelin-solidity/contracts/token/ERC20Basic.sol… Compiling zeppelin-solidity /contracts/token/StandardToken.sol… Writing artifacts to ./build/contracts liyuechun:BloggerCoin yuechunli$

  • truffle migrate

liyuechun:BloggerCoin yuechunli$ truffle migrate Using network 'development'. Running migration: 1_initial_migration.js Deploying Migrations… … 0xac35fdd655a7b8916d5a43fb608227f1827aa666e4d4aa7b4d50347f8883de8a Migrations: 0x5c7102091425e16998b8bed1cd663 4f499ab3684 Saving successful migration to network… … 0x1131a209a1ca27cadbec4ef8f84cecbe322e59d01b2b584f3e0ddada5a7a53d8 Saving artifacts… Running migration: 2_deploy_contracts.js Deploying BloggerCoin… … 0xc23199c5fe72206 a5d74ad09797c9df17deb361c56ee1cb14b816ee0d874d5e2 BloggerCoin: 0xbacb9b3da2e3140df11516be2244c4ea230d6d39 Saving successful migration to network… … 0x32bf4f5299bb4d260cc86da76591 d9564376a82c4b8122261043d74a70c57b9e Saving artifacts… Running migration: 3_deploy_bloggerchain.js Replacing BloggerCoin… … 0x87e8c7a24727a06da750a2c9f3b4ea1bc4b87c8c3e9c8a9219c3dada911e0991 BloggerCoin: 0x5262d2b6de1a1187abdd203cb72 6b387bcd6140f Saving successful migration to network… … 0x75166d7f6ee595437718df960d9a3bc76466bd890988a92b1aac1a396dc7f018 Saving artifacts… liyuechun:BloggerCoin yuechunli$

verification

liyuechun:BloggerCoin yuechunli$ truffle console truffle(development)> let contract undefined truffle(development)> BloggerCoin.deployed().then(instance => contract = instance) …… truffle(development)> contract.balanceOf(web3.eth. coinbase) { [String: '66666'] s: 1, e: 5, c: [ 666666 ] } truffle(development)> contract.balanceOf(web3.eth.accounts[1]) { [String: '600000'] s: 1, e: 0, c: [ 0 ] } truffle(development)> contract.transfer(web3.eth.accounts[1], 600000) truffle(development)> contract.balanceOf(web3.eth.coinbase) { [String: '66666'] s: 1, e: 4, c: [ 66666 ] } truffle(development)> contract.balanceOf(web3.eth.accounts[1]) { [String: '600000'] s: 1 , e: 5, c: [ 600000 ] } truffle(development)>
For an explanation of specific methods in the verification process, please see this article: How to write a smart contract? (II) Set up a simple encrypted token

Rating
( 1 rating, average 4 out of 5 )
Did you like the article? Share with friends:
For any suggestions regarding the site: [email protected]
Для любых предложений по сайту: [email protected]