智能合约Solidity学习(第三课)

@@@ 合约的构造函数

跟C++,java类似,合约的构造函数名跟合约名一样,其会在合约创建时仅被调用一次

/**
 * @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;
  }

}

@@@Function Modifier

关键字:modifier

被modifier  修饰的方法不能被直接调用 ,其通常用于方法头的后面来改变方法的行为。

contract MyContract is Ownable {
  event LaughManiacally(string laughter);

  // Note the usage of `onlyOwner` below:
  function likeABoss() external onlyOwner {
    LaughManiacally("Muahahahaha");
  }
}


@@@代码执行开销

在以太坊上执行任何一个写操作都需要耗费gas, 且代码的复杂度越高,需要的gas就越多,因此开发Dapp要格外注意程序的

高效。

通常uint8 代表着经 unit32更低的存储空间占用,但是通常情况下,以太坊是不区分这两者的,都会统一当成是uint;但是有个例外,那就是在结构体struct里,数据是严格按照变量类型来存放的,而且把相同类型的变量放在相临会消耗更少的gas

If you have multiple uints inside a struct, using a smaller-sized uint when possible will allow Solidity to pack these variables together to take up less storage. For example:

struct NormalStruct {
  uint a;
  uint b;
  uint c;
}

struct MiniMe {
  uint32 a;
  uint32 b;
  uint c;
}

// `mini` will cost less gas than `normal` because of struct packing
NormalStruct normal = NormalStruct(10, 20, 30);
MiniMe mini = MiniMe(10, 20, 30);

@@@ 时间单位

在solidity中,有以下时间单位可用:

变量now,代表unix时间戳(秒数) ;

变量seconds

变量minutes

变量hours

变量days

变量weeks

变量years

以上六个变量的值会以秒数来表示,例如

1 minutes 的值为60 (seconds)

uint lastUpdated;

// Set `lastUpdated` to `now`
function updateTimestamp() public {
  lastUpdated = now;
}

// Will return `true` if 5 minutes have passed since `updateTimestamp` was 
// called, `false` if 5 minutes have not passed
function fiveMinutesHavePassed() public view returns (bool) {
  return (now >= (lastUpdated + 5 minutes));
}




猜你喜欢

转载自blog.csdn.net/dongshengliao/article/details/80975682