In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "solidity case study". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
0. Background of the problem
There was an old man who wanted nothing but to pass on his property to other family members through his will in the last years of his life.
In the traditional will, the estate distribution plan is implemented in the legal documents, and then when the distribution really begins, the judge needs to review the documents and make a decision accordingly. Common problems occur in the dispute over the distribution ratio among family members, which even leads to the breakdown of the relationship between family members. In the court hearing stage, these will affect the judge's final decision, and thus may lead to unfair results, and even cause further harm to family relations.
So, if we can allow the estate distribution to be carried out automatically, can the above situation be avoided?
If the inheritance is a smart contract, then there is no need for a judge. The grandfather can use the contract to manage the assets on his own, and then the process will distribute the inheritance to the family members after his death. The code in the contract determines the final distribution, so there is no need for a judge to intervene. For example, Sarah gets $10000, Ben gets $5000, and Juliet gets $2000. After the code is executed, assets are automatically allocated to these family members in the form of tokens or cryptocurrencies without human intervention. Although there is no guarantee that every member will be satisfied with the distribution of the inheritance, no one will argue with the code. That sounds feasible, doesn't it?
Remember this case, in this quick tutorial, we will use solidity to develop a simple testamentary contract for the old man to fulfill his last wish.
1. Build the solidity development environment.
The easiest way to develop solidity smart contracts is to use the official online integrated development environment REMIX. You can click here to open remix and complete the writing, compilation and deployment of solidity smart contracts on the web page:
After you open the remix page, notice that in the run options page on the right, in the environment drop-down box, select JavaScript VM. This option means to use an in-memory emulated ethersquare node as the running platform for your solidity smart contract, so that you don't have to consider the accounts, funds, and computational fees needed to interact with the actual ethernet master, but can focus on learning how to use solidity to express your business logic.
Click the + icon at the top left of the remix page to create a new code file, which we name will.sol. Multiple files can be displayed at the same time in the editing area in the middle of the remix page, and the file name is displayed as the active option page for the file that is currently being edited.
2. Declare the solidity compiler version
Solidity is still a very early language, constantly evolving from syntax to compiler, so in the first line of solidity code, be sure to use the pragma keyword to declare which version of the compiler is needed for the solidity code in this file. For example:
Note that in solidity, the semicolon at the end cannot be omitted.
3. Write the first solidity contract
Then we can define our first contract:
Use the contract keyword to define a contract, and solidity's contract is similar to the classes in the familiar OOP, so the contract's initials are usually capitalized, such as Will. A pair of curly braces are used to define the implementation logic of the contract, and single-line comments are also used / /, similar to many development languages.
4. Global variables and constructors in solidity
Before we start writing code, we should first clarify the terms of the will. Suppose the grandfather's legacy is 50 etheric coins, of which 20 are left to his son Conrad and the remaining 30 to his wife Lisa. In the real world, when the grandfather dies, there should be an external program that will invoke the method defined in the contract to allocate the inheritance, but we will do it ourselves in order to make it easier to learn.
Now, let's complete the following code first:
Variables representing the owner of the contract
A variable that characterizes the amount of heritage
A variable indicating whether the grandfather is still alive or not.
A constructor that sets the initial values of the above variables
Line 5 defines the owner of the contract. When we define a variable in solidity, we must first declare its type. Address is a special type of solidity that represents an etheric place address. Variables of type address have some special methods, which we will learn more about later.
The fortune variable defined in line 6 is used to hold the number of grandpa's legacies, and its type is uint or unsigned int, meaning that the variable is 0 or a positive integer. There are many data types in solidity, but we won't cover them all here. You can learn more about the data types of solidity in the official documentation.
The isDeceased variable defined in line 7 is used to identify whether the grandfather has died, which is a switch quantity, so its type is boolean, there are only two possible values: true or false, and the default value is false.
Lines 9-13 are the constructor of the contract, and this special function will be executed automatically when the contract is deployed.
The public keyword is called the visibility modifier, and its function is to declare whether the modified method allows external calls. Public means that the method can be called either inside or outside the contract (by another contract or someone else).
The payable keyword is one of the features of solidity, which enables the modified method to send or receive etheric coins. Declaring the payable keyword for the constructor means that when we deploy the contract, we can deposit the etheric currency directly into the contract, for example, 50 etheric coins as an inheritance. When the etheric coins are received by the contract, they are kept on the contract address.
Inside the constructor, we set the value of the owner variable to msg.sender, which is a global variable preset by the Ethernet Fong platform, indicating the account address of the calling contract method, which in our case is Grandpa's.
At the same time, we set the value of the fortune variable to msg.value, which is another global variable that represents the number of ethernet coins received by the called method.
Although the variable isDeceased is automatically initialized to the default value of false, we explicitly set it to false for clarity.
5. Use the solidity modifier
In solidity, the Modifier can attach additional conditional logic to the function. For example, suppose I have a method to turn off the light, and there is a modifier that requires the light switch to be in the on state, then we can attach this modifier to the method to ensure that this method can only be called if the light switch is in the on state, otherwise an exception will be thrown.
Line 15 defines the onlyOwner modifier. If a method appends declares this modifier, then the account number (msg.sender) of the calling method is required to match the value of the owner variable (don't forget that we set the value of owner in the constructor). This invocation condition contributes to the allocation of the inheritance, as we will see later.
The require keyword means that the value of the expression in parentheses must be true (true), or an exception will be thrown and the code will no longer be executed.
_; acts as a placeholder, and during execution, the Taifang virtual machine replaces it with the modified method code.
Line 20 defines the mustBeDeceased modifier. If a method appends this modifier, the method can be called only if the value of the isDeceased variable is true, otherwise an exception will be thrown.
In the above code, we use modifiers to define the execution conditions of the method, or we can use require directly in the method implementation code without modifiers, but the modifiers look more advanced and easier to reuse the code.
6. Set up the estate distribution plan.
Now we will continue to complete the task of allocating the inheritance among family members, which requires their wallet address and allocated quantity.
As we mentioned earlier, Conrad will receive 20 etheric coins and Lisa will inherit 30. Let's create an array to hold their wallet addresses, and then write a method to allocate the inheritance.
Line 25 defines an empty array familyWallets that holds the wallet addresses of all family members. As with other languages, arrays are stored sequentially and can be accessed using ordinal numbers in solidity. Note the keyword paybale before the square brackets. Only variables of type address payable can receive etheric coins, which is one of the differences between version 0.5 of solidity and previous versions.
Line 27 creates a mapping table variable inheritance from type address to type uint to hold the number of legacies for each wallet address. This is a key / value pair data structure, similar to dictionaries or hashes in other languages, where keys can be used to access values.
Line 29 defines a method that adds a wallet address to the familyWallets array and then sets the number of legacies for that address in the inheritance mapping table. Notice the additional onlyOwner modifier, and guess why we declare this modifier here?
Line 30 appends the wallet address of the incoming method to the end of the familyWallets array.
Line 31 sets the number of inheritance of the incoming method to the value of the specified address of the mapping table inheritance (another parameter to the incoming method).
7. Realize the automatic distribution of heritage
Let's sum it up. So far, we have learned about global variables, data types, constructors, special keywords such as payable and public, built-in global variables such as msg.sender and msg.value, modifiers and require, arrays, mapping tables, and methods. We have set up the framework of the contract, now let's integrate the various parts and finally complete the contract.
As the code for the last part of this tutorial, we will implement the automatic allocation of family members' inheritance.
Line 34 defines the payout () method. Notice the private keyword, a visibility modifier that is the opposite of public and allows only modified methods to be called within the contract, as in line 42. The main reason for using private here is security, because we don't want any calls from outside the contract. Notice the last mustBeDeceased modifier, we still can't meet the conditions required by this modifier to execute the payout () method.
Line 35 is a for loop that traverses the familyWallets array. The syntax is as follows:
Define a counter variable I
Declare the execution conditions of the loop
Counter variable I plus 1 per cycle
Line 36 is the core of the entire contract. We call the transfer () method of an address object of type address to transfer the predetermined number of inheritance to that address. Inheritance [I] represents the value of the key familyWallets [I] in the inheritance mapping table, that is, the inheritance number of the I family member.
Lines 40-42 define a method that will be called when the grandfather dies to trigger the allocation of the inheritance. Here we set the value of the variable isDeceased to true.
Are we done now?
Actually, not exactly.
The code for this smart contract is finished, but how do we use it? Now is the time to harvest the fruit.
8. Solidity contract deployment and interaction
Your remix page should look like this:
Switch to the compile options page on the right side of the remix page, confirm that the compiler version is selected as shown below, and then click [start to compile]:
You may see a blue text box generated by the static analysis. We ignore its reminder for the time being and switch to the run options page:
Make sure Javascript VM is selected in the Environment drop-down box. Clicking on the account drop-down menu will show 5 test accounts, each with 100 etheric coins. Let's choose the first one.
The deployment contract to the ethernet blockchain is not free, and the deployer has to pay a handling fee, often referred to as gas. The purpose of introducing this mechanism is to avoid malicious abuse of blockchain computing resources. To learn more about gas, you can check out this article: 1 minute to figure out Gas/ Gas Price/ Gas Limit.
The default value for the gas limit field is fine. Let's not modify it yet.
The value field indicates the number of etheric coins we want to send to the contract when we deploy the contract. Enter 50, remember the payable keyword we appended when we defined the constructor?
Now go ahead and click [deploy].
You may notice three things right away. First of all, the selected account balance is now 49.9999. This is because we transferred 50 etheric coins to the contract and deducted a little deployment fee. The console at the bottom of the page will also provide detailed information about the deployment process, which you can check. Now it looks like this:
Our contract has been successfully deployed! It generates its own address and shows the two contract methods we defined. As contract holders, the first thing we need to do is to set the number of family members to inherit: Conrad (20), Lisa (30). Suppose we use the second in the account drop-down menu as Conrad's account and Lisa's third.
Select the second account, click the [copy to clipboard] icon, and enter the text input box after the setInheritance in the image above.
Before we execute the setInheritance method, there are a few things to remember.
The units of the etheric currency quantity introduced into the contract are wei rather than etheric coins, 1 ETH = 100000000000000000000000000 WEI, which is a very small unit, so we need to convert the amount of the estate in Taiyuan to the value in WEI first.
After converting the amount of the estate, write it to the text input box after the setInheritance in the image above, and after the address you entered before, be careful to separate the two values with a comma.
Also, don't forget to select the first account in the account drop-down box. Remember the onlyOwner modifier? Only the holder of the contract can call the setInheritance method!
Now let's execute the setInheritance method for Conrad and Lisa in turn. You should see the success message from the console output. Take a look at the decoded input:
You see, it shows the data we entered.
The inheritance was distributed, but the bad news came. My grandfather died of a heart attack during an expedition to the North Pole at the age of 73. He is always so passionate and energetic.
As we commemorate the old man, we also call the deceased () method of the testamentary contract to fulfill the old man's last wish.
This is the end of the solidity case study. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.