《solidity學習筆記》chapter 3-solidity其他知識
Ownable contracts
OpenZeppelin Solidity庫裏的合約之一,可以通過繼承使用。
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
其中與合約同名的函數是合約的構造函數,在合約創建時運行一次之後不會再調用。
Ownable 合約:
合約創建,運行構造函數,將合約所有人限定為msg.sender,也就是部署合約的人。
增加修飾符 onlyowner,限制陌生人的訪問,將訪問某些函數的權限鎖定在 owner上。
有函數可以將合約所有權轉讓給他人。
節省Gas的方式
一般情況下我們不用考慮像數據類型uint等的變種uint8等,因為solidity對這些類型都是當做uint看待的,但是有種情況下不一樣,那就是struct中,我們可以通過將同類型的變量放在一起來節省空間,solidity會將這些同類型的打包在一起。
栗子:
struct aaaa{
uint a;
uint8 b;
uint8 c;
string d;
……;
}
我們還可以通過使用view來節省,因為在以太坊裏每個寫操作都會創建一個事務,view因為不需要寫操作,我們可以通過這個結合函數修飾符(external)來使用,讓操作只進行在本地節點,不消耗gas。
註意:如果一個 view
函數在另一個函數的內部被調用,而調用函數與 view
函數的不屬於同一個合約,也會產生調用成本。這是因為如果主調函數在以太坊創建了一個事務,它仍然需要逐個節點去驗證。
時間單位
Solidity 除了now之外,還包含秒(seconds)
,分鐘(minutes)
,小時(hours)
,天(days)
,周(weeks)
和 年(years)
等時間單位。它們都會轉換成對應的秒數放入 uint
中。
可支付
可支付也是一個修飾符,payable。用來表明這個函數調用是需要花費gas的。
function buyPDF() external payable{
require(msg.value == 0.01 ether);
transferPDF(msg.sender);
}
這其中我們可以使用this.balance獲取合約獲得的以太,並通過預定的函數傳輸到我們的以太地址。
《solidity學習筆記》chapter 3-solidity其他知識