LoginSignup
16
11

More than 5 years have passed since last update.

solidityでのつまずきについて

Posted at

はじめに

しばらくQiitaはROM専だったのですが、備忘録のために残します。

最近、仮想通貨とか暗号通貨とかブロックチェーンとかについて色々調べています。
ただ、ネットにある情報が若干(数か月前の情報ですが)古いために、サンプルコードがまともに動かないことが多くて
その調査だけで時間が掛かっています。

私自身が経験したつまずいたことを書いていきます。

バージョン違いによる仕様変更

2018/05現在、solidityのバージョンは v0.4.23です。
ですので、このバージョンと以前のバージョンでの違いについてがメインとなります。
いろいろ変わっていますので、対応が必要です。

public などの関数の可視性

以前バージョン

method(uint param) {   // 可視性はなくてもOKでした
   ....
   ....
}
v0.4.23.sol

method(uint param) public {   // 可視性が必要です
   ....
   ....
}

多言語でよくある public int method(int param)のような形ではありません。
関数名の後ろに付けるのがsolidityです。これに気が付くまでに時間が掛かりました。

ちなみに戻り値があるときは、可視性の後ろにreturns修飾子を付けます。

v0.4.23.sol

method(uint param) public returns(bool ret) {
   ....
   ....
}

コンストラクタについて

以前バージョン
contract TestToken {

    TestToken() {    // 以前は、コントラスト名と同じでした
        ....
        ....
    }
}
v0.4.23.sol
contract TestToken {

    constructor () public { // constructorというキーワードです
        ....
        ....
    }
}

constructor という表記方法に代わっています。
もちろんですが可視性(public)も必要です。

uintについて

以前バージョン

method(uint param) {   // uintでOKでした
   ....
   ....
}
v0.4.23.sol

method(uint256 param) public {   // uintだとWarningが発生しますので、uint256などに変更
   ....
   ....
}

uint型は、推奨ではないようです。
ERC20のコードなどを見るとuint256を使用しているケースが多いので、
uint256にしておくのが良いかと。

event修飾子

以前バージョン

event Transfer(address indexed _from, address indexed _to, uint _value);

function sendCoin(address receiver, uint amount) public returns(bool sufficient) {
    if (balances[msg.sender] < amount) return false;
    balances[msg.sender] -= amount;
    balances[receiver] += amount;
    Transfer(msg.sender, receiver, amount);       // 特になにもする必要はありませんでした
    return true;
}

v0.4.23.sol

event Transfer(address indexed _from, address indexed _to, uint _value);

function sendCoin(address receiver, uint amount) public returns(bool sufficient) {
    if (balances[msg.sender] < amount) return false;
    balances[msg.sender] -= amount;
    balances[receiver] += amount;
    emit Transfer(msg.sender, receiver, amount);    // emit修飾子を使います
    return true;
}

event(トランザクションへのログ出力)を実行するときはemitをつける必要があります。

終わりに

オープンソースですので、仕様の変更がよくあるのは仕方がないと割り切っていますが、
情報を探すが結構大変です。公式サイトなどをしっかり読めば気づくのでしょうけど・・・

参考URL

solidity(https://solidity.readthedocs.io/en/latest/index.html)
https://github.com/OpenZeppelin/openzeppelin-solidity/issues/932

16
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
11