Unit 20 – “Looks like we’ve made our First Contract!” – 第20单元-“看来我们签了第一份合同!”区块链毕设代写
区块链毕设代写本文提供国外最新区块链项目源码下载,包括solidity,eth,fabric等blockchain区块链,Unit 20 – “Looks like we’ve made our First Contract!” – 第20单元-“看来我们签了第一份合同!”区块链毕设代写 是一篇很好的国外资料
Unit 20 – “Looks like we’ve made our First Contract!”
Background
Your new startup has created its own Ethereum-compatible blockchain to help connect financial institutions, and the team wants to build smart contracts to automate some company finances to make everyone’s lives easier, increase transparency, and to make accounting and auditing practically automatic!
Fortunately, you’ve been learning how to program smart contracts with Solidity! What you will be doing this assignment is creating 3 ProfitSplitter
contracts. These contracts will do several things:
-
Pay your Associate-level employees quickly and easily.
-
Distribute profits to different tiers of employees.
-
Distribute company shares for employees in a “deferred equity incentive plan” automatically.
Files
-
AssociateProfitSplitter.sol
— Level 1 starter code. -
TieredProfitSplitter.sol
— Level 2 starter code. -
DeferredEquityPlan.sol
— Level 3 starter code.
Instructions
This assignment has three levels of difficulty, with each contract increasing in complexity and capability. Although it is highly recommended you complete all three contracts, you are only required to solve one of the three contracts. Recommended to start with Level 1, then move forward as you complete the challenges. You can build all three with the skills you already have!
-
Level One is an
AssociateProfitSplitter
contract. This will accept Ether into the contract and divide the Ether evenly among the associate level employees. This will allow the Human Resources department to pay employees quickly and efficiently. -
Level Two is a
TieredProfitSplitter
that will distribute different percentages of incoming Ether to employees at different tiers/levels. For example, the CEO gets paid 60%, CTO 25%, and Bob gets 15%. -
Level Three is a
DeferredEquityPlan
that models traditional company stock plans. This contract will automatically manage 1000 shares with an annual distribution of 250 over 4 years for a single employee.
Starting your project
Navigate to the Remix IDE and create a new contract called AssociateProfitSplitter.sol
using the starter code for level one above.
While developing and testing your contract, use the Ganache development chain, and point MetaMask to localhost:8545
, or replace the port with what you have set in your workspace.
Level One: The AssociateProfitSplitter
Contract
At the top of your contract, you will need to define the following public
variables:
-
employee_one
— Theaddress
of the first employee. Make sure to set this topayable
. -
employee_two
— Anotheraddress payable
that represents the second employee. -
employee_three
— The thirdaddress payable
that represents the third employee.
Create a constructor function that accepts:
-
address payable _one
-
address payable _two
-
address payable _three
Within the constructor, set the employee addresses to equal the parameter values. This will allow you to avoid hardcoding the employee addresses.
Next, create the following functions:
-
balance
— This function should be set topublic view returns(uint)
, and must return the contract’s current balance. Since we should always be sending Ether to the beneficiaries, this function should always return0
. If it does not, thedeposit
function is not handling the remainders properly and should be fixed. This will serve as a test function of sorts. -
deposit
— This function should set topublic payable
check, ensuring that only the owner can call the function.-
In this function, perform the following steps:
-
Set a
uint amount
to equalmsg.value / 3;
in order to calculate the split value of the Ether. -
Transfer the
amount
toemployee_one
. -
Repeat the steps for
employee_two
andemployee_three
. -
Since
uint
only contains positive whole numbers, and Solidity does not fully support float/decimals, we must deal with a potential remainder at the end of this function sinceamount
will discard the remainder during division. -
We may either have
1
or2
wei leftover, so transfer themsg.value - amount * 3
back tomsg.sender
. This will re-multiply theamount
by 3, then subtract it from themsg.value
to account for any leftover wei, and send it back to Human Resources.
-
-
-
Create a fallback function using
function() external payable
, and call thedeposit
function from within it. This will ensure that the logic indeposit
executes if Ether is sent directly to the contract. This is important to prevent Ether from being locked in the contract since we don’t have awithdraw
function in this use-case.
Test the contract
In the Deploy
tab in Remix, deploy the contract to your local Ganache chain by connecting to Injected Web3
and ensuring MetaMask is pointed to localhost:8545
.
You will need to fill in the constructor parameters with your designated employee
addresses.
Test the deposit
function by sending various values. Keep an eye on the employee
balances as you send different amounts of Ether to the contract and ensure the logic is executing properly.
Level Two: The TieredProfitSplitter
Contract
In this contract, rather than splitting the profits between Associate-level employees, you will calculate rudimentary percentages for different tiers of employees (CEO, CTO, and Bob).
Using the starter code, within the deposit
function, perform the following:
-
Calculate the number of points/units by dividing
msg.value
by100
.- This will allow us to multiply the points with a number representing a percentage. For example,
points * 60
will output a number that is ~60% of themsg.value
.
- This will allow us to multiply the points with a number representing a percentage. For example,
-
The
uint amount
variable will be used to store the amount to send each employee temporarily. For each employee, set theamount
to equal the number ofpoints
multiplied by the percentage (say, 60 for 60%). -
After calculating the
amount
for the first employee, add theamount
to thetotal
to keep a running total of how much of themsg.value
we are distributing so far. -
Then, transfer the
amount
toemployee_one
. Repeat the steps for each employee, setting theamount
to equal thepoints
multiplied by their given percentage. -
For example, each transfer should look something like the following for each employee, until after transferring to the third employee:
-
Step 1:
amount = points * 60;
-
For
employee_one
, distributepoints * 60
. -
For
employee_two
, distributepoints * 25
. -
For
employee_three
, distributepoints * 15
.
-
-
Step 2:
total += amount;
-
Step 3:
employee_one.transfer(amount);
-
-
Send the remainder to the employee with the highest percentage by subtracting
total
frommsg.value
, and sending that to an employee. -
Deploy and test the contract functionality by depositing various Ether values (greater than 100 wei).
-
The provided
balance
function can be used as a test to see if the logic you have in thedeposit
function is valid. Since all of the Ether should be transferred to employees, this function should always return0
, since the contract should never store Ether itself. -
Note: The 100 wei threshold is due to the way we calculate the points. If we send less than 100 wei, for example, 80 wei,
points
would equal0
because80 / 100
equals0
because the remainder is discarded. We will learn more advanced arbitrary precision division later in the course. In this case, we can disregard the threshold as 100 wei is a significantly smaller value than the Ether or Gwei units that are far more commonly used in the real world (most people aren’t sending less than a penny’s worth of Ether).
-
Level Three: The DeferredEquityPlan
Contract
In this contract, we will be managing an employee’s “deferred equity incentive plan” in which 1000 shares will be distributed over 4 years to the employee. We won’t need to work with Ether in this contract, but we will be storing and setting amounts that represent the number of distributed shares the employee owns and enforcing the vetting periods automatically.
-
A two-minute primer on deferred equity incentive plans: In this set-up, employees receive shares for joining and staying with the firm. They may receive, for example, an award of 1,000 shares when joining, but with a 4 year vesting period for these shares. This means that these shares would stay with the company, with only 250 shares (1,000/4) actually distributed to and owned by the employee each year. If the employee leaves within the first 4 years, he or she would forfeit ownership of any remaining (“unvested”) shares.
-
If, for example, the employee only sticks around for the first two years before moving on, the employee’s account will end up with 500 shares (250 shares * 2 years), with the remaining 500 shares staying with the company. In this above example, only half of the shares (and any distributions of company profit associated with them) actually “vested”, or became fully owned by the employee. The remaining half, which were still “deferred” or “unvested”, ended up fully owned by the company since the employee left midway through the incentive/vesting period.
-
Specific vesting periods, the dollar/crypto value of shares awarded, and the percentage equity stake (the percentage ownership of the company) all tend to vary according to the company, the specialized skills, or seniority of the employee, and the negotiating positions of the employee/company. If you receive an offer from a company offering equity (which is great!), just make sure you can clarify the current dollar value of those shares being offered (based on, perhaps, valuation implied by the most recent outside funding round). In other words, don’t be content with just receiving “X” number of shares without having a credible sense of what amount of dollars that “X” number represents. Be sure to understand your vesting schedule as well, particularly if you think you may not stick around for an extended period of time.
-
Using the starter code, perform the following:
-
Human Resources will be set in the constructor as the
msg.sender
, since HR will be deploying the contract. -
Below the
employee
initialization variables at the top (afterbool active = true;
), set the total shares and annual distribution:-
Create a
uint
calledtotal_shares
and set this to1000
. -
Create another
uint
calledannual_distribution
and set this to250
. This equates to a 4 year vesting period for thetotal_shares
, as250
will be distributed per year. Since it is expensive to calculate this in Solidity, we can simply set these values manually. You can tweak them as you see fit, as long as you can dividetotal_shares
byannual_distribution
evenly.
-
-
The
uint start_time = now;
line permanently stores the contract’s start date. We’ll use this to calculate the vested shares later. Below this variable, set theunlock_time
to equalnow
plus365 days
. We will increment each distribution period. -
The
uint public distributed_shares
will track how many vested shares the employee has claimed and was distributed. By default, this is0
. -
In the
distribute
function:-
Add the following
require
statements:-
Require that
unlock_time
is less than or equal tonow
. -
Require that
distributed_shares
is less than thetotal_shares
the employee was set for. -
Ensure to provide error messages in your
require
statements.
-
-
After the
require
statements, add365 days
to theunlock_time
. This will calculate next year’s unlock time before distributing this year’s shares. We want to perform all of our calculations like this before distributing the shares. -
Next, set the new value for
distributed_shares
by calculating how many years have passed sincestart_time
multiplied byannual_distributions
. For example:-
The
distributed_shares
is equal to(now - start_time)
divided by365 days
, multiplied by the annual distribution. Ifnow - start_time
is less than365 days
, the output will be0
since the remainder will be discarded. If it is something like400
days, the output will equal1
, meaningdistributed_shares
would equal250
. -
Make sure to include the parenthesis around
now - start_time
in your calculation to ensure that the order of operations is followed properly.
-
-
The final
if
statement provided checks that in case the employee does not cash out until 5+ years after the contract start, the contract does not reward more than thetotal_shares
agreed upon in the contract.
-
-
Deploy and test your contract locally.
-
For this contract, test the timelock functionality by adding a new variable called
uint fakenow = now;
as the first line of the contract, then replace every other instance ofnow
withfakenow
. Utilize the followingfastforward
function to manipulatefakenow
during testing. -
Add this function to “fast forward” time by 100 days when the contract is deployed (requires setting up
fakenow
):function fastforward() public { fakenow += 100 days; }
-
Once you are satisfied with your contract’s logic, revert the
fakenow
testing logic.
-
-
Congratulate yourself for building such complex smart contracts in your first week of Solidity! You are learning specialized skills that are highly desired in the blockchain industry!
Deploy the contracts to a live Testnet
Once you feel comfortable with your contracts, point MetaMask to the Kovan or Ropsten network. Ensure you have test Ether on this network!
After switching MetaMask to Kovan, deploy the contracts as before and copy/keep a note of their deployed addresses. The transactions will also be in your MetaMask history, and on the blockchain permanently to explore later.
Resources
Building the next financial revolution isn’t easy, but we need your help, don’t be intimidated by the semicolons!
There are lots of great resources to learn Solidity. Remember, you are helping push the very edge of this space forward, so don’t feel discouraged if you get stuck! In fact, you should be proud that you are taking on such a challenge!
For some succinct and straightforward code snips, check out Solidity By Example
For a more extensive list of awesome Solidity resources, checkout Awesome Solidity
Another tutorial is available at EthereumDev.io
If you enjoy building games, here’s an excellent tutorial called CryptoZombies
Submission
Create a README.md
that explains how each of the contracts work and what the motivation for each of the contracts is. Also, please provide screenshots to illustrate the functionality (e.g. how you send transactions, how the transferred amount is then distributed by each of the contracts, and how the timelock functionality can be tested with the fastforward
function). Alternatively, you can also record your interactions with the contract as a gif (e.g. https://www.screentogif.com/)
Upload the README.md
to a Github repository and provide the testnet address for others to interact with the contract.
Unit 20 – “Looks like we’ve made our First Contract!”
Background
您的新创业公司已经创建了自己的以太坊eth兼容区块链blockchain,以帮助连接金融机构,团队希望构建智能合约,使一些公司财务自动化,以使每个人的生活更轻松,增加透明度,并使会计和审计实际上自动化!
幸运的是,您已经学习了如何使用Solidity编程智能合约!你要做的是创建3个ProfitSplitter合同。这些合同可以做几件事:
-
快速、轻松地向员工支付工资。
-
将利润分配给不同层次的员工。
-
在“递延股权激励计划”中自动为员工分配公司股份。
Files
-
屁股ociateProfitSplitter.sol文件–一级起动代码。
-
TieredProfitSplitter.sol公司–2级起动代码。
-
延迟EquityPlan.sol–3级起动代码。
Instructions
这项任务有三个难度等级,每个合同的复杂性和能力都在增加。尽管强烈建议您完成所有三份合同,但您只需解决三份合同中的一份。建议从1级开始,然后在完成挑战后继续前进。你可以建立所有这三个与技能,你已经有了!
-
第一级是AssociateProfitSpliter合同。这将把乙醚纳入合同,并将乙醚平均分配给员工。这将使人力资源部能够快速有效地向员工支付薪酬。
-
第二级是分层利润分配器,它将不同百分比的乙醚分配给不同层级/级别的员工。例如,首席执行官的工资为60%,首席技术官的工资为25%,鲍勃的工资为15%。
-
第三级是一个延迟的公平计划,它模拟了传统的公司股票计划。该合同将自动管理1000股,在4年内为单个员工分配250股。
Starting your project
导航到RemixIDE并创建一个名为Ass的新契约ociateProfitSplitter.sol文件使用一级以上的起始代码。
在开发和测试合同时,使用Ganache开发链,并将MetaMask指向本地主机:8545,或将端口替换为工作区中设置的端口。
Level One: The AssociateProfitSplitter
Contract
在合同顶部,您需要定义以下公共变量:
-
employeeu one–第一个雇员的地址。确保将此设置为“应付”。
-
employeeu two—另一个代表第二个雇员的应付地址。
-
employeeu three—代表第三名员工的第三个应付地址。
创建一个构造函数,该构造函数接受:
-
应付地址u one
-
应付地址u two
-
应付地址u three
在构造函数中,将雇员地址设置为等于参数值。这将允许您避免硬编码员工地址。
接下来,创建以下函数:
-
balance—此函数应设置为public view returns(uint),并且必须返回合同的当前余额。因为我们应该总是向受益人发送乙醚,所以这个函数应该总是返回0。如果没有,存款功能将无法正确处理剩余部分,应予以修复。这将作为某种测试函数。
-
存款–此函数应设置为公共应付支票,以确保只有所有者可以调用此函数。
-
在此函数中,执行以下步骤:
-
将uint amount设置为等于消息值/3;以计算乙醚的分流值。
-
将金额转入员工账户。
-
对employeeu two和employeeu three重复上述步骤。
-
由于uint只包含正整数,而Solidity不完全支持浮点数/小数,因此我们必须在函数末尾处理一个可能的余数,因为amount将在除法过程中丢弃余数。
-
我们可能剩下1或2个魏,所以转移消息值-金额*3返回邮件发件人. 这将把数量再乘以3,然后从消息值把剩下的小薇算上帐,并送回人力资源部。
-
-
-
使用function()external payable创建一个回退函数,并在其中调用deposit函数。这将确保如果以太直接发送到合同,那么存放的逻辑将执行。这对于防止乙醚被锁定在合同中很重要,因为在这个用例中我们没有收回功能。
Test the contract
在Remix的Deploy选项卡中,通过连接到Injected Web3并确保指向MetaMask,将契约部署到本地Ganache链本地主机:8545。
您需要用指定的员工地址填写构造函数参数。
通过发送各种值来测试存款功能。在向合同发送不同数量的乙醚时,注意员工余额,确保逻辑正确执行。
Level Two: The TieredProfitSplitter
Contract
在本合同中,您将计算不同层级员工(首席执行官、首席技术官和首席执行官)的基本百分比,而不是将利润分配给员工。
使用起始代码,在存款功能中执行以下操作:
-
通过除以计算点数/单位消息值到100。
- This will allow us to multiply the points with a number representing a percentage. For example,
points * 60
will output a number that is ~60% of themsg.value
.
- This will allow us to multiply the points with a number representing a percentage. For example,
-
uint amount变量将用于存储要临时发送给每个员工的金额。对于每个员工,将金额设置为等于点数乘以百分比(例如,60代表60%)。
-
在计算完第一个雇员的金额后,将该金额添加到总数中,以保持一个连续的总数,即消息值我们目前正在分发。
-
然后,将金额转移到员工账户。对每位员工重复上述步骤,将金额设置为等于点数乘以其给定百分比。
-
例如,对于每个员工来说,每次调动都应该像下面这样,直到转移到第三个员工之后:
-
步骤1:金额=点数*60;
-
对于员工1,分配点数*60。
-
对于员工2,分配积分*25。
-
对于员工3,分配积分*15。
-
-
第2步:合计+=金额;
-
第3步:员工_一、转让(amount);
-
-
通过从总数中减去总数,将剩余部分发送给百分比最高的员工消息值,并将其发送给员工。
-
通过存储各种乙醚值(大于100μg)来部署和测试契约功能。
-
提供的余额函数可用作测试,以查看存款函数中的逻辑是否有效。因为所有的乙醚都应该转移给员工,所以这个函数应该总是返回0,因为合同本身不应该存储乙醚。
-
注意:100 wei阈值取决于我们计算积分的方式。如果我们发送小于100微,例如,80微,点将等于0,因为80/100等于0,因为余数被丢弃。我们将在本课程后面学习更高级的任意精度除法。在这种情况下,我们可以忽略阈值,因为100微是一个明显小于乙醚或Gwei单位的值,后者在现实世界中更为常用(大多数人发送的乙醚价值不低于一分钱)。
-
Level Three: The DeferredEquityPlan
Contract
在本合同中,我们将管理员工的“递延股权激励计划”,其中1000股将在4年内分配给员工。在本合同中,我们不需要使用乙醚,但我们将存储和设置代表员工拥有的已分配股份数量的金额,并自动执行审核期。
-
关于递延股权激励计划的两分钟入门:在这种情况下,员工在加入和留在公司时获得股份。例如,他们在加入时可获得1000股奖励,但这些股票的授予期为4年。这意味着这些股份将留在公司,每年只有250股(1000/4)实际分配给员工并由员工持有。如果员工在头4年内离职,他或她将丧失任何剩余(“未授予”)股份的所有权。
-
例如,如果员工在离职前的前两年只留下来,那么该员工的账户最终将持有500股股票(250股*2年),剩余的500股股票将留在公司。在上述例子中,只有一半的股份(以及与之相关的公司利润分配)实际“归属”或完全归员工所有。剩下的一半,仍然是“递延”或“未授予”,最终完全归公司所有,因为员工在激励/授予期中途离职。
-
根据公司、员工的专业技能或资历以及员工/公司的谈判立场,具体的授予期、授予股份的美元/加密价值以及股权百分比(公司所有权百分比)都会有所不同。如果你收到一家提供股权的公司的报价(那太好了!),只需确保你能澄清这些股票的当前美元价值(可能基于最近一轮外部融资所暗示的估值)。换言之,不要满足于只收到“X”个股,而对“X”个股所代表的金额没有一个可信的概念。一定要了解你的行权时间表以及,特别是如果你认为你可能不会停留在一个较长的时间。
-
使用启动程序代码,执行以下操作:
-
人力资源将在构造函数中设置为邮件发件人,因为HR将部署合同。
-
在顶部的employee初始化变量下面(bool active=true;之后),设置总份额和年度分配:
-
创建一个名为tot的uint
-
Create another
uint
calledannual_distribution
and set this to250
. This equates to a 4 year vesting period for thetotal_shares
, as250
will be distributed per year. Since it is expensive to calculate this in Solidity, we can simply set these values manually. You can tweak them as you see fit, as long as you can dividetotal_shares
byannual_distribution
evenly.
-
-
The
uint start_time = now;
line permanently stores the contract’s start date. We’ll use this to calculate the vested shares later. Below this variable, set theunlock_time
to equalnow
plus365 days
. We will increment each distribution period. -
The
uint public distributed_shares
will track how many vested shares the employee has claimed and was distributed. By default, this is0
. -
In the
distribute
function:-
Add the following
require
statements:-
Require that
unlock_time
is less than or equal tonow
. -
Require that
distributed_shares
is less than thetotal_shares
the employee was set for. -
Ensure to provide error messages in your
require
statements.
-
-
After the
require
statements, add365 days
to theunlock_time
. This will calculate next year’s unlock time before distributing this year’s shares. We want to perform all of our calculations like this before distributing the shares. -
Next, set the new value for
distributed_shares
by calculating how many years have passed sincestart_time
multiplied byannual_distributions
. For example:-
The
distributed_shares
is equal to(now - start_time)
divided by365 days
, multiplied by the annual distribution. Ifnow - start_time
is less than365 days
, the output will be0
since the remainder will be discarded. If it is something like400
days, the output will equal1
, meaningdistributed_shares
would equal250
. -
Make sure to include the parenthesis around
now - start_time
in your calculation to ensure that the order of operations is followed properly.
-
-
The final
if
statement provided checks that in case the employee does not cash out until 5+ years after the contract start, the contract does not reward more than thetotal_shares
agreed upon in the contract.
-
-
Deploy and test your contract locally.
-
For this contract, test the timelock functionality by adding a new variable called
uint fakenow = now;
as the first line of the contract, then replace every other instance ofnow
withfakenow
. Utilize the followingfastforward
function to manipulatefakenow
during testing. -
Add this function to “fast forward” time by 100 days when the contract is deployed (requires setting up
fakenow
):function fastforward() public { fakenow += 100 days; }
-
Once you are satisfied with your contract’s logic, revert the
fakenow
testing logic.
-
-
Congratulate yourself for building such complex smart contracts in your first week of Solidity! You are learning specialized skills that are highly desired in the blockchain industry!
Deploy the contracts to a live Testnet
Once you feel comfortable with your contracts, point MetaMask to the Kovan or Ropsten network. Ensure you have test Ether on this network!
After switching MetaMask to Kovan, deploy the contracts as before and copy/keep a note of their deployed addresses. The transactions will also be in your MetaMask history, and on the blockchain permanently to explore later.
Resources
Building the next financial revolution isn’t easy, but we need your help, don’t be intimidated by the semicolons!
There are lots of great resources to learn Solidity. Remember, you are helping push the very edge of this space forward, so don’t feel discouraged if you get stuck! In fact, you should be proud that you are taking on such a challenge!
For some succinct and straightforward code snips, check out Solidity By Example
For a more extensive list of awesome Solidity resources, checkout Awesome Solidity
Another tutorial is available at EthereumDev.io
If you enjoy building games, here’s an excellent tutorial called CryptoZombies
Submission
Create a README.md
that explains how each of the contracts work and what the motivation for each of the contracts is. Also, please provide screenshots to illustrate the functionality (e.g. how you send transactions, how the transferred amount is then distributed by each of the contracts, and how the timelock functionality can be tested with the fastforward
function). Alternatively, you can also record your interactions with the contract as a gif (e.g. https://www.screentogif.com/)
Upload the README.md
to a Github repository and provide the testnet address for others to interact with the contract.
部分转自网络,侵权联系删除区块链源码网
区块链知识分享网, 以太坊dapp资源网, 区块链教程, fabric教程下载, 区块链书籍下载, 区块链资料下载, 区块链视频教程下载, 区块链基础教程, 区块链入门教程, 区块链资源 » Unit 20 – “Looks like we’ve made our First Contract!” – 第20单元-“看来我们签了第一份合同!”区块链毕设代写