区块链智能合约怎么写的,区块链智能合约实例
区块链智能合约是指基于区块链技术的可执行代码,它使得参与者可以更加安全、可靠地执行合约。它是一种分布式的技术,可以让参与者之间达成共识,从而达成相互协议的目的。本文将介绍三个关键词:智能合约语言、智能合约开发和智能合约安全性。
智能合约语言是一种特定的编程语言,用于编写智能合约。它是一种特定的编程语言,可以让开发者更加方便地编写区块链智能合约。智能合约语言可以分为静态语言和动态语言。静态语言是指在编写代码时,必须先定义变量的类型,然后才能编写代码。动态语言则不需要定义变量的类型,可以直接编写代码。智能合约语言的主要特点是可以实现自动执行,可以实现去中心化,可以提高交易的安全性和透明度。
智能合约开发是指使用智能合约语言编写智能合约的过程。智能合约开发的主要步骤是:1.确定智能合约的功能;2.编写智能合约;3.编译智能合约;4.部署智能合约;5.调试智能合约。智能合约开发的主要工具有:智能合约开发框架、智能合约编译器、智能合约部署器和智能合约调试器。
智能合约安全性是指智能合约的安全级别。智能合约安全性的要素包括:1.智能合约的功能安全;2.智能合约的编程安全;3.智能合约的执行安全;4.智能合约的部署安全;5.智能合约的数据安全。智能合约安全性的重要性在于,它可以保证智能合约的正确性,确保参与者之间的交易安全,保护参与者的利益不受损害。
以上就是关于区块链智能合约的三个关键词的介绍,智能合约语言、智能合约开发和智能合约安全性,它们都是智能合约的重要组成部分,可以帮助参与者更加安全可靠地执行合约。
请查看相关英文文档
『一』What is a smart contract?
Smart Contract is a piece of code deployed on the blockchain. Once an event triggers the terms in the contract , the code will be executed automatically. In human terms: a smart contract is a digital contract based on high technology such as cryptography. The difference from a traditional paper contract is that a vending machine is equivalent to a smart contract, and a salesperson is equivalent to a paper contract.
You will understand with a simple example:
Suppose A borrows a large sum of money from B, although there is a written IOU written in black and white. However, after maturity, A refuses to repay the loan for various reasons. At this time, B can only sue if he wants to get the loan back. Smart contracts can solve this problem. If both parties A and B package the loan amount, repayment time, and the other party’s bank card information into the contract before borrowing, they will be able to solve this problem. On the agreed repayment date, the loan will be automatically transferred to B's account, even if A doesn't want to repay it, there is nothing he can do.
Source: Qian Krypton Finance
『二』 Popular Science | What is a smart contract in DeFi
A contract is a very common document in everyone’s life, and its purpose is to constrain The behavior of both parties to the transaction. When a dispute arises, trust cannot resolve the dispute. At this time, a legally binding contract can protect the legitimate rights and interests of both parties to the transaction to a large extent. Therefore, in the process of studying and working, everyone will more or less sign a rental contract, a sales contract, a labor contract, etc. When using major APPs, there is a user agreement that must be checked on the login interface. In fact, the user and the service provider have signed a contract to restrict the user's behavior during the use of the APP.
In the blockchain field, such a contract also exists, but it is more "intelligent". Its "intelligence" is reflected in: after the rules are formulated, if one party breaks the rules, the program will automatically trigger the relevant clauses in the contract without the intervention of others, avoiding the problem of being unable to confirm the liability of the violating party.
< p> Especially since 2020, DeFi has received widespread attention and discussion. In DeFi, "smart contracts" play the role of "Mr. Key". So, what is a smart contract? This article will explain it in detail.
"The term smart contract is translated from "Smart contract". This concept was originally proposed by cryptographer Nick Szabo in 1995. It is a contract designed to be disseminated, verified, and executed in an information-based manner. In other words, smart contracts replace traditional paper contracts, and after being put on the chain, the preset contract terms can be accurately and efficiently executed through programs.
This electronic trading protocol allows trusted transactions to be conducted without third-party supervision, and these transactions are traceable and irreversible.
Smart contracts can minimize disputes and eliminate dependence on trusted intermediaries. They are more secure and have lower transaction costs than traditional contracts.
In Blockchain 1.0, Bitcoin was produced, and smart contracts are a typical application in the Blockchain 2.0 era. Its advantages are reflected in the following aspects:
Due to the natural characteristics of the blockchain, all contract contents are digitally recorded on the chain. The data cannot be deleted or modified, and the entire process is transparent and traceable. , and also reduces the malicious destruction of contract content to a certain extent;
Smart contracts avoid the problems that may be affected by centralization factors in traditional contracts, and have more obvious advantages in ensuring fairness and justice;
When the preset contract content is met, the program will be automatically triggered. While avoiding manual operations, it also avoids evading responsibility.
The many advantages of smart contracts are mentioned above, but its problems are also obvious.
First of all, if the design of the smart contract itself exists Flaws that may be exploited by hackers. Even if the problem is discovered at the first time, because the data on the blockchain cannot be modified, you can only watch the losses getting worse and there is nothing you can do.
Secondly, smart contracts cannot perceive external information and need other information sources to provide information before smart contracts can make decisions. In this case, the authenticity of the external information itself will also cause hidden dangers.
One of the simplest examples is unmanned vending machines. Nick Szabo originally proposed smart contracts based on the principles of automatic vending machines. To some extent, vending machines are the first large-scale application of smart contracts.
Of course, the application scenarios of smart contracts are far more than this. Smart contract technology is used in aspects such as social security, supply chain management, authenticity identification, and intellectual property protection. Problems can be solved more economically and efficiently without the need for third-party arbitration.
Smart contracts are constantly developing and progressing, and application scenarios are also constantly expanding. Its advantages and disadvantages coexist. The features of safety, efficiency, and no need for third-party arbitration are important, but there are also many potential application risks that require more advanced technology to overcome.
『三』 One article to understand hybrid smart contracts: how to combine on-chain and off-chain computing resources
Hybrid smart contracts include code and chain running on the chain Download data and computing resources, and the oracle can provide price feeds, reserve certificates, and scalable computingand other functions.
Written by: Chainlink
Hybrid smart contracts contain code running on the blockchain and data and computing resources off the blockchain, which are transmitted by a decentralized oracle network. to the chain. Hybrid smart contracts can coordinate complex economic and social activities, have the tamper-proof characteristics of blockchain, and can securely access off-chain oracle services to achieve various innovative functions, such as scalability, confidentiality, and fair sorting. and accessing any off-chain data sources or systems.
This article will clearly define the role of hybrid smart contracts in the blockchain trust model, and explain the various decentralized services provided by Chainlink oracles for hybrid smart contracts, and how this development will Giving birth to a new generation of hybrid smart contract applications. These hybrid smart contracts that connect off-chain resources will sweep almost all mainstream industries in the future and change the way the entire society cooperates.
How oracles can expand cooperation on the blockchain
Blockchain is essentially a computing infrastructure that facilitates trusted cooperation, which is its key function. Only when participants have trust will they firmly believe that the cooperative relationship is reliable, real and effective. The most common way to build trust in a collaboration is to sign a contract. A contract defines the legal and business obligations of the parties, as well as the rewards and penalties for their actions. However, today's contractual obligation enforcement mechanism is full of loopholes. Even in some cases, a certain participant will have an absolute advantage, such as manipulating and influencing the contract execution mechanism, knowing more information than the counterparty, or having more time and capital to prolong the arbitration process. Therefore, the current contract system has become: you must trust the counterparty’s brand endorsement before you can trust that the cooperative relationship between you is solid.
The emergence of blockchain technology has shifted cooperation from brand endorsement to algorithm-based trust (math-based trust). The storage, execution and custody of the contract are all transferred to the code logic running in the decentralized network, and individuals are completely unable to intervene and tamper with it. The blockchain is like a computer without an Internet connection. It is very trustworthy because it is a closed environment and can only implement a few functions that are easy to perform, such as transferring between multiple addresses in a closed ledger. Pass. This setting is intentional. Although the closed nature and single function of the blockchain bring it tamper resistance and a high degree of certainty (which is also the most valuable part of the blockchain), it also excludes any need to access off-chain data. , calculations or functional ways of cooperating.
As users want to expand the possible ways of cooperation on the blockchain, oracles and hybrid smart contracts have emerged one after another. Oracles provide a secure portal for the blockchain to connect to the outside world, allowing smart contract applications to verify external events, trigger operations based on external systems, and complete computational tasks that cannot be achieved on the chain.
As mentioned in the Chainlink 2.0 white paper, decentralized oracle networks (DONs) have greatly expanded the on-chain cooperation methods that smart contracts can achieve. The rapid rise of decentralized finance (DeFi) is a good example. The Chainlink decentralized oracle network transmits financial market data to the blockchain and supports various hybrid smart contract protocols such as the Aave currency market, Synthetix derivatives platform, dYdX leverage trading market, and Ampleforth algorithm stablecoin, thus accelerating the development of DeFi. develop.
The components of a hybrid smart contract
A hybrid smart contract application consists of two parts, namely: 1) Smart contract - this is code that specifically runs on the blockchain ;2) Decentralized oracle network - this is a secure off-chain service provided for smart contracts. These two modules interact securely and seamlessly, forming a hybrid smart contract application. Finally, on-chain code is enhanced in many unique ways and activates a range of new application scenarios that break through the technical, legal or financial limitations of previous on-chain code.
Hybrid smart contracts synchronize two completely different computing environments to create application functions that cannot be achieved by blockchain or oracle networks alone, and combine the unique advantages of these two environments. together. The code on the chain runs in an extremely secure and functionally limited blockchain environment with a small attack surface, so users can obtain extremely high certainty when executing and storing. The code will be strictly executed and the results will be stored forever. On the chain, it cannot be tampered with. DON, on the other hand, runs off-chain and therefore has more flexibility to implement more functions and access more data.
It is worth noting that DON also has very high tamper resistance and reliability, comparable to smart contracts, but the difference is that DON runs in a closed off-chain environment and adopts A variety of security mechanisms are provided. Each DON will provide customized decentralized services for an application, which means that other smart contracts on the same blockchain have no connection with the performance of this DON, and the underlying blockchain consensus ensures the security of all smart contracts. There are no risks to the mechanism either. As an independent service, DON not only has advantages in security, but also has the flexibility to verify and calculate more complex and open off-chain data.
For example, the criteria for some smart contracts to choose to access DON are the level of decentralization and encryption economic security, while other smart contracts will choose nodes with high reputation and use advanced encryption technology to develop verifiable privacy. Calculated DON. In these heterogeneous networks, thousands or even millions of DONs can be parallelized, each DON will not depend on each other, and can provide specialized decentralized services for specific applications. same DONUsers can also share service costs (for example, many DeFi protocols currently use the Chainlink ETH/USD price feed oracle and share the costs). This framework is very important and can provide services for all blockchains and applications at the same time, such as accessing off-chain data and ensuring privacy for applications running on high-speed blockchains. In addition, applications on blockchains with a higher degree of decentralization also need access to scalable computing resources.
How hybrid smart contracts combine on-chain and off-chain computing resources
In order to further understand the differences between on-chain and off-chain modules, we first clearly define each module:
p>
On-chain module: Blockchain
Maintain ledgers, reliably host user assets, and interact with private keys.
Process irreversible transfer transactions between users and perform final settlement.
Resolve differences and establish safety guardrails to ensure the normal operation of DON's off-chain services.
Off-chain: Decentralized oracle network
Securely obtain and verify data from off-chain APIs and transmit to smart contracts in blockchain and layer-2 networks .
Execute various computational tasks for smart contracts in blockchains and layer-2 networks.
Transmit data output from smart contracts to other blockchains or off-chain systems.
Hybrid smart contracts combine on-chain code and off-chain decentralized oracle networks to enable more advanced blockchain applications
Chainlink decentralized services for hybrid smart contracts Escort
After defining the hybrid smart contract, let's discuss the various decentralized services provided by Chainlink DON for smart contracts. These decentralized services can be broadly divided into two categories, namely: off-chain data and off-chain computing.
Off-chain data
DON can build a bridge between various off-chain data and the blockchain to input the required data for hybrid smart contracts. The following are the types of data that are initially accessible:
Price feed - asset price data aggregated from hundreds of trading platforms. The data is based on volume-weighted calculations and eliminates outliers and false transactions.
Proof of Reserves - Latest data on the current reserve balance of a token asset, such as Bitcoin-collateralized assets for WBTC, or USD-collateralized assets for TUSD.
Any API - Paid data from a password-protected API interface, including weather forecasts, sports results, enterprise backend data and IoT data.
Blockchain middleware - the blockchain abstraction layer allows off-chain systems to access smart contracts in any blockchain network and read and write data in both directions.
Off-chain calculations
DON can perform a series of off-chain calculations on behalf of smart contracts, help smart contracts obtain certain data, or create functions that cannot be achieved on native blockchains, such as Privacy protection, scalability, and fair ranking. The following are some of the DON computing functions that have been implemented and will be implemented in the future:
Keeper network - refers to automated bots that regularly maintain smart contracts, start contracts at appropriate points in time, and perform key on-chain functions.
Off-chain reporting (OCR) - Aggregates data from DON oracle node responses in a scalable manner, and then sends the aggregated data to the chain in a single transaction to reduce on-chain costs.
Scalable Compute - Enables high throughput and low cost for smart contract execution, using off-the-shelf layer-2 technology to regularly synchronize with the chain.
Verifiable Random Function (VRF) - securely generates verifiable random numbers, using cryptographic proof technology to prove the integrity of the process.
Data and Computational Privacy - Privacy-preserving oracle computing capabilities use zero-knowledge proofs (DECO), trusted hardware (Town Crier), secure multi-party computation, and a specific DON committee system to keep sensitive data Confidentially transmitted to the smart contract.
Fair Sorting Service (FSS) - carries out decentralized transaction sorting based on predefined fairness principles to avoid front-running attacks and miner extractable value (MEV).
On-chain contract privacy - unbind contract logic from settlement results to protect smart contract transaction privacy, such as transmitting data between two parties through DON's Mixicles function.
Chainlink’s decentralized oracle network provides a series of rich services, expanding the functions of hybrid smart contract applications
The impact of hybrid smart contracts on various industries around the world
DON can implement an advanced hybrid smart contract framework, seamlessly connecting independent entities on different systems and blockchains to achieve secure and universal automated interactions. Chainlink overcomes the technical barriers of smart contracts for developers. Developers can take advantage of the high certainty of the blockchain and achieve various key functions such as external connections, privacy guarantees, scalability, and fair sorting through DON. Hybrid smart contracts not only create a more trustworthy and efficient cooperation space for various participants in the network, but also connect the blockchain network to the traditional off-chain infrastructure without any modifications on the back end.
DON will provide the required privacy guarantee and scalability for many smart contract applications, and cover most enterprise application scenarios and many games and financial applications, enabling high throughput and real-time decision-making. Hybrid smart contracts will also activate a series of unprecedented new application scenarios, such as achieving algorithm-based economic fairness and transparency through verifiable random numbers and decentralized transaction ordering.
Some mainstream industries that have already felt, or will soon feel the impact of hybrid smart contracts:
Identity information - Identity information can be automatically verified and information privacy protected. Smart contracts can define the personal information required as well as the required actions. DON performs calculations on these data, verifies users' personal information, and at the same time protects the information from being disclosed to counterparties and will not be stored in off-chain systems.
Finance - an open financial market that is resistant to censorship, with no barriers to access and transparent information. Smart contracts can define transaction rules for buyers and sellers, and DON can use off-chain data for pricing and settlement, and implement additional functions such as: hidden transactions, KYC verification, fair transaction sorting, and high-speed off-chain processing.
Supply Chain - A multi-party transaction protocol running on a shared ledger that digitizes product lines and automates operations across multiple systems based on verified data. Smart contracts can define contractual obligations, payment terms, and penalty mechanisms. DON can leverage private computing and IoT data to track shipping information, monitor quality control, verify customer identity and trigger settlement payments.
Insurance - establish a bilateral prediction market based on predefined events and create parametric insurance based on this. Smart contracts can define the premium and claims process, and DON can connect the contract to off-chain data, obtain quotes and process claims applications. DON can also perform risk assessment calculations, obtain complex risk assessment results from data sources such as cloud platforms, and verify user identities in a confidential manner.
Game - automatically distributes game rewards. Users can fully own in-game assets through NFT and provide authoritative proof that all participants have the same probability of winning. Smart contracts can define game rules and reward distribution modes, and DON can provide tamper-proof random numbers to ensure that the fairness of the game can be verified and that the reward distribution process is fair. After the game dApp is connected to DON, it can also access a series of off-chain data sources such as augmented reality IoT sensors, and process some game functions off-chain to improve game performance.
Marketing – Marketing campaigns automatically deliver rewards in real-time based on various parameters and metrics. Smart contracts can define a stepped reward distribution model and set specific milestone goals. DON can verify that goals are being met and perform confidential calculations on customer data and market trends to more effectively evaluate marketing campaigns.
Governance - Distributed communities can manage shared systems and fund pools safely and fairly. Smart contracts can define a complete governance framework, and DON can provide off-chain data and computing resources, trigger various operations such as profit distribution, cost sharing, and identity authentication, effectively resist witch attacks, verify the participation of each member, or even achieve automation. decision-making process.
Ultimately, DON can provide all services that cannot be implemented on the chain, and bring stronger encryption security to existing data and systems to launch an off-chain service ecosystem. Hybrid smart contract infrastructure can enrich the cooperation methods of decentralized systems, allowing various blockchain and non-blockchain infrastructures to interact seamlessly and securely, while ensuring scalability, confidentiality, customization and universal connectivity. sex. Although the current scale of cryptocurrency assets has reached trillions of dollars, and the scale of the DeFi economy is approaching $100 billion, the blockchain ecosystem is still in its early stages of development, and there is still huge potential that has not been tapped. Therefore, hybrid smart contracts and Chainlink decentralization The oracle network has huge application space and potential.
If you want to start developing hybrid smart contract applications right away and need to access off-chain data or computing resources, please check out our developer documentation. You can also ask technical questions in the Discord channel or contact Chainlink Experts communicate via telephone.
『四』How to understand the smart contract of blockchain
The term "smart contract" can be traced back to at least 1995 and was coined by a prolific cross-field legal scholar. It was proposed by Nick Szabo. He mentioned the concept of smart contracts in several articles published on his website. His definition is as follows:
“A smart contract is a set of Numerically defined promises, including protocols on which contract participants can execute these promises. ”
Let us explore the meaning of his definition in more detail.
Commitments
A set of promises agreed upon by the parties to a contract (often mutually of) rights and obligations. These commitments define the nature and purpose of the contract. Take a sales contract as a typical example. The seller promises to deliver the goods, and the buyer promises to pay a reasonable price.
Digital form
Digital form means that the contract must be written in computer-readable code. This is necessary because as long as the parties reach an agreement, the rights and obligations established by the smart contract are executed by a computer or computer network.
Further explanation:
(1) Reaching an agreement
When do the participants in a smart contract reach an agreement? The answer depends on the specific smart contract implementation . Generally speaking, a contract is discovered when a participant commits to its execution by installing the contract on the contract hosting platform.
(2) Contract execution
The true meaning of "execution" also depends on implementation. Generally speaking, implementation means active implementation through technical means.
(3) Computer-readable code
In addition, the specific "digital form" required for the contract depends very much on the protocol the parties agree to use.
Agreement
Agreement is a technical implementation, based on which contract commitments are realized or the realization of contract commitments is recorded. Which protocol is chosen depends on many factors, the most important being the nature of the assets being traded during the performance of the contract.
Take the sales contract as an example again. Assume that the parties agree to pay in Bitcoin. The protocol of choice will obviously be the Bitcoin protocol, on which smart contracts are implemented. Therefore, the "digital form" that the contract must use is the Bitcoin script language. The Bitcoin Script Language is a non-Turing complete, imperative, stack-based programming language similar to Forth.
Smart Contract
The Xueshuo Innovation Blockchain Technology Workstation under Lianqiao Education Online is a Chinese education It is the only approved "blockchain technology professional" pilot workstation for the "Smart Learning Workshop 2020-Master's Degree Innovation Workstation" launched by the Ministry of Education's Planning, Construction and Development Center. The professional base is based on providing students with diversified growth paths, promoting the reform of the training model integrating professional degree research, production, and research, and building an applied and compound talent training system.
『武』 What is a smart contract in Renren blockchain technology?
In many cases of blockchain commercial applications, we can always see the word BaaS. BaaS is the abbreviation of Blockchain
Service, and the Chinese translation is "Blockchain as a Service". So what exactly is Blockchain as a Service BaaS? With this question in mind, we followed Xiao Wang from the Renren blockchain technology team to discuss Xunsen in detail.
According to Xiao Wang: Blockchain as a Service BaaS is mainly a concept proposed by the two giants Microsoft and IBM. To put it bluntly, it is actually a new type of cloud service, a combination of blockchain and Chain technology cloud services. For example, Microsoft's Azure cloud computing platform and IBM's Bluemix
Garage cloud platform both provide blockchain as a service BaaS.
Blockchain as a Service (BaaS) is a space created by companies such as Microsoft and IBM from their own cloud service networks to run a certain blockchain node. Compared with ordinary nodes and exchange nodes, the main purpose of BaaS nodes is to quickly establish the development environment you need, provide a series of operational services such as blockchain-based search queries, exchange submission, and data analysis. These services can be either centralized or decentralized to help developers moreQuickly validate your concepts and models. The serviceability of BaaS nodes is reflected in: stronger tools, making it easier to create, deploy, run and monitor blockchains.
『Lu』 What is a smart contract in blockchain technology
A smart contract can be simply understood as a piece of code written on the blockchain, driven by events and with dynamic status , is recognized by multiple parties, and can automatically process information on the chain according to preset conditions. Once an event triggers the terms in the contract, the code will be automatically executed. The biggest advantage of smart contracts is to use program algorithms to arbitrate and execute contracts on behalf of humans.
Smart contracts are contracts that use computer language instead of legal language to record terms. Once written, they can be trusted by users. The terms of the contract cannot be changed, so the contract is immutable. The procedure will be executed when the conditions are met, without human interference, ensuring absolute fairness and justice.
3 technical characteristics of smart contracts
●Data transparency
All data on the blockchain is open and transparent, so the data processing of smart contracts is also open and transparent, and any party can run it can view its code and data.
●Cannot be tampered
All data in the blockchain itself cannot be tampered with, so the smart contract code deployed on the blockchain and the data generated by its operation are also non-tamperable. Nodes running smart contracts do not have to worry about other Nodes maliciously modify code and data.
●Permanent operation
The nodes supporting the blockchain network often reach hundreds or even thousands. The failure of some nodes will not cause the smart contract to stop. Its reliability is theoretically close to permanent operation. In this way This ensures that smart contracts can be as valid as paper contracts at all times.
『撒』 What is a smart contract?
A smart contract is a piece of computer software that is designed to be an automated self-enforcing contract, meaning that it triggers certain actions when predetermined conditions are met. Automatically executed. For example, smart contracts can be used as digital agreements to exchange cryptocurrency (or any other digital asset) between two parties. Once the terms of the agreement are set, smart contracts verify their fulfillment and allocate assets accordingly.
In other words, smart contracts are basically lines of code that perform a specific function when specific conditions are met. Code often follows "if... then..." statements that trigger predetermined and predictable actions.
For example, an online store might implement a smart contract that ensures "if payment is received, the product is delivered" - this would make the entire process more efficient and less prone to human error.
Although smart contracts have become popular in the context of blockchain and cryptocurrencies, the concept was first described by American cryptographer Nick Szabo in 1994, many years before Bitcoin.
Smart contracts in the blockchain space andPlaying an important role in the cryptocurrency market, especially in terms of ERC-20 tokens, it represents a class of tokens created on the Ethereum network that adhere to the ERC-20 standard. These tokens are typically distributed through initial coin offering events, and the use of smart contracts enables a trustless and cost-effective exchange of funds during the sale. Their use can also facilitate payment processing in decentralized applications (DApps) or decentralized exchanges (DEX).
Another area where smart contracts are applicable is the financial services industry. For example, the technology could be used to automate the clearing and settlement of trades, the payment of bond coupons, and even the calculation and payment of insurance claims.
Although they have obvious applications in finance, smart contracts are versatile and suitable for almost any industry that requires the transfer of funds, digital assets, or any type of digital information between parties. For example, the equipment rental industry uses these contracts extensively in the real world to make rental agreements more efficient.
In the healthcare field, this technology is being explored as a countermeasure against data manipulation in clinical trials. Smart contracts can even enforce intellectual property agreements by establishing a clear record of shared ownership and allocating all royalties and proceeds from the intellectual property accordingly.
- 上一篇: 区块链trc20查询,trx区块链查询
- 下一篇: 区块链需要拉人头吗,区块链就没有人赚到钱吗