CryptoZombiesのコードを解説します。コントラクトの関係全体を見たい方はこちらへ。
library SafeMath
みんな大好きSafeMath。
数値演算のアンダーフロー、オーバーフローを検知し、安全に実施するためのライブラリです。Ownable同様、OpenZepperinからの流用です。Solidityのuseは、派生コントラクトにも影響を与えます。したがって他のZombieXXXコントラクトも、SafeMathによる安全な数値演算を使うことができます。
関連するレッスン、チャプター
ソースコード・解説
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
// ライブラリ宣言
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
// 掛け算は割ったら元の数になるか確認。
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
// 0割はEVM任せ。0割以外の割り算は検算不要。整数同士なので。
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
// アンダーフローをチェック
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
// オーバーフローをチェック
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
「CryptoZombiesコード解説 SafeMath」への1件のフィードバック
コメントは停止中です。