W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
構(gòu)建合約的模塊化方法可幫助您降低復(fù)雜性并提高可讀性,這將有助于在開發(fā)和代碼審查期間識別錯誤和漏洞。如果您單獨指定和控制行為或每個模塊,則您必須考慮的交互只是模塊規(guī)范之間的交互,而不是合約的所有其他移動部分。在下面的示例中,合約使用庫move的方法來檢查地址之間發(fā)送的余額是否符合您的預(yù)期。通過這種方式,庫提供了一個獨立的組件,可以正確跟蹤賬戶余額。很容易驗證Balances BalancesBalances庫永遠不會產(chǎn)生負余額或溢出,并且所有余額的總和在合約的整個生命周期內(nèi)都是不變量。
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.9.0; library Balances { function move(mapping(address => uint256) storage balances, address from, address to, uint amount) internal { require(balances[from] >= amount); require(balances[to] + amount >= balances[to]); balances[from] -= amount; balances[to] += amount; } } contract Token { mapping(address => uint256) balances; using Balances for *; mapping(address => mapping (address => uint256)) allowed; event Transfer(address from, address to, uint amount); event Approval(address owner, address spender, uint amount); function transfer(address to, uint amount) external returns (bool success) { balances.move(msg.sender, to, amount); emit Transfer(msg.sender, to, amount); return true; } function transferFrom(address from, address to, uint amount) external returns (bool success) { require(allowed[from][msg.sender] >= amount); allowed[from][msg.sender] -= amount; balances.move(from, to, amount); emit Transfer(from, to, amount); return true; } function approve(address spender, uint tokens) external returns (bool success) { require(allowed[msg.sender][spender] == 0, ""); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function balanceOf(address tokenOwner) external view returns (uint balance) { return balances[tokenOwner]; } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: