EGO-LOG

40代2児の父。主にプログラム学習と開発、仮想通貨、メタバース、たまに関係ないことを綴る。

CryptoZombiesにSolidityを学ぶ Lesson.2(chapter.8まで)

スマートコントラクトを構築するための言語solidity

言語をブラウザで遊びながら学ぶCryptoZombie

前回の学習記録は4月末なので3が月半ほど空いてしまった。

 

tenomeuonome.hateblo.jp

 

思い出しついでにLesson2以降をやっていきます。

あんまり細かく記録してくとなかなか進まないのでサクサクいきましょう。

 

目次

 

Lesson2 / Chapter1

茶番なので飛ばします。

 

Lesson2 / Chapter2

MappingとAddressesを学ぶ。

アドレス

仮想通貨のアカウントのこと。

Mappings(マッピング)

基本的にはキーとバリューのセット。

mapping(address => uint) public accountBalance;

↑アカウントアドレスに残高を格納

mapping(uint => string) userIdToName;

↑ユーザIDにユーザ名を格納

 

Lesson2 / Chapter3

Msg.senderを学ぶ。

solidityにはすべての関数で使用できるグローバル変数が用意してあり、

msg.senderもその一つ。

Solidityでは常に外部の呼び出し元から関数を実行しなければならない。

msg.senderを介して処理を行う。

-----

mapping( address => uint) favoriteNumber;

↓favoriteNumberに外部からmappingを更新

function setMyNumber(uint _myNumber) public{

  favoriteNumber[msg.sender] = _myNumber;

}

↓favoriteNumberに外部からmappingを参照

function whatIsMyNumber() public view returns (uint) {

  return favoriteNumber[msg.sender];

}

-----

 

Lesson2 / Chapter4

Requireを学ぶ。

requireはある条件を満たさない場合はエラーを投げて実行を止めることができる。

-----

function sayHiToVitalik(string _name) public returns (string) {

   ↓_nameが"Vitalik"と一致しなければエラー出力して処理を終わる。

  require(keccak256(_name) == keccak256("Vitalik"));

  return "Hi!";

}

-----

 

Lesson2 / Chapter5

継承を学ぶ。

あるcontractを継承して新しいcontractを定義する。

継承先contractからは継承元のcontractの情報にアクセスできる。

-----

↓継承元contract

contract Doge {

  function catchphrase) public returns (string) {

    return "So Wow CryptoDoge";

  }

}

↓継承先contract

contract BabyDoge is Doge {

  function anotherCatchphrase() public returns (string) {

    return "Such Moon BabyDoge";

  }

}

-----

 

Lesson2 / Chapter6

Importを学ぶ。

ファイルを分けて管理する場合に、他ファイルを参照する場合に使用する。

-----

import "./someothercontract.sol";

↑someotherconract.solを参照

contract newContract is SomeOtherContract {

}

-----

 

Lesson2 / Chapter7, 8

storagememoryを学ぶ。

storage

ブロックチェーン上に永久に格納される変数。

memory

一時的な変数で、関数の呼び出しが終われば消える。

-----

contract SandwichFactory {

  struct Sandwich {

    string name;

    string status;

  }

  Sandwich[] sandwiches;

 

  function eatSandwich( uint _index) public {

    Sandwich storage mySandwich = sandwiches[_index];

    mySandwich.status = "Eaten!";

    ↑storage内のsandwiches配列のstatusを更新する。

 

    Sandwich memory anotherSandwich = sandwiches[_index + 1];

    anotherSandwich.status = "Eaten!";

    ↑memory内を更新するだけなのでstorageには影響しない。

 

    sandwiches[_index + 1] = anotherSandwich;

    ↑であればstorageを更新する。

  }

}

-----

 

遅くなったので続きは後日。

 

続く。