solidity helloworld

【ブロックチェーン プログラミング】solidityで初めてのHelloWorld !!

  • 2023年6月18日
  • IT
IT solidity helloworld
keyboard

ブロックチェーン技術の中でも注目されているsolidityプログラミングに挑戦してみませんか?

この記事では、

初めてsolidityを使用してHelloWorldプログラムを作成する手順を詳しく解説しています。

ブロックチェーンの基礎知識がない方でも、わかりやすくステップバイステップで説明しているので安心して取り組むことができます。

solidityは、

イーサリアム(Ethereum)というブロックチェーンプラットフォーム上でスマートコントラクトを作成するためのプログラミング言語です。

HelloWorldプログラムはプログラミング初心者にとっておなじみの課題ですが、

solidityを使ってHelloWorldを作成することで、

ブロックチェーンの仕組みやsolidityの基本的な構文を学ぶことができます。

記事では、

まずsolidityの基本的な概念から説明し、

必要な開発環境のセットアップ方法も解説しています。

その後、実際にHelloWorldプログラムを作成する手順をステップバイステップで説明していきます。

プログラムのコーディング方法やコンパイル、

デプロイの方法まで、実践的な知識を身につけることができます。

この記事を通じて、solidityを使ったブロックチェーンプログラミングの基礎をしっかりと学び、

将来のブロックチェーン開発に役立ててください。

HelloWorldから始めて、新たな技術の世界に飛び込んでみましょう!


[getPhpFile() file=’Appeal_01′ html_file=’Appeal_05.html’]

ブロックチェーンプログラミングの入門:solidityでHelloWorldを作ろう!

この入門ガイドでは

ブロックチェーンのプログラミング言語であるSolidityを使用して、HelloWorldプログラムを作成する方法を紹介します。

Solidityは、イーサリアムプラットフォーム上でスマートコントラクトを実装するためのプログラミング言語です。


HelloWorldは、
プログラミングの初心者向けの簡単なプログラムであり、

特定のプログラミング言語やフレームワークの学習やテストによく使われます。
HelloWorldプログラムは、
コンピュータ上で実行される最も基本的なプログラムであり、

画面に「Hello, World!」というメッセージを表示するだけの単純な機能を持っています。

まず、Truffleを使って「Hello World」コントラクトを作成します。

Ethereumのブロックチェーンが必要ですが

開発用のローカルにプライベートなブロックチェーンを用意(Ganache)します。

そのブロックチェーン上にデプロイ(配置)して

実際にブロックチェーン上で動きを確認します。


ブロックチェーンプログラミングの世界への第一歩として、

ぜひこのガイドを活用してみてください。

関連記事

今回の目的は 明確です Solidityの開発を進めるための 開発環境の構築です 早速始めたく思います。 この記事を必要とする方はPCがメインです モバイルでは見にくい部分があることを […]

brockchain dev

solidityとは?初心者向け解説とHelloWorldプログラムの重要性


solidityとは、ブロックチェーン上でスマートコントラクトを構築するための

言語であることは以前の記事で紹介しています。

ぜひ、一読ください。

また、「HelloWorld」の初心者向けプログラムを経験することは大変重要です、

いきなり難しい書籍などで勉強するのではなく

慣れるまでは、簡単なソースから入り、

solidityの開発者が必要とするような

実務者向けのソース、書籍で勉強すればいいのです

簡単なソースなど”だけ”、

また、難しい玄人向けの書籍”だけ”

など極端な勉強では

すぐに壁にぶつかり、継続できないことにもなりかねません。

おすすめとして、初心者向けの書籍などと

玄人向けの書籍などの両方で勉強を進めましょう。

関連記事

プログラミング言語の「solidity」は WEB3.0を語る上で避けては通れない技術です 特に現在のWEB3.0のサービスでは スマートコントラクト機能が必須であり […]

programing

HelloWorldを通じてsolidityの基礎概念を学ぼう


実際にHelloWorldの表示するプログラムで

動きを体験しましょう。

この章を進める前に、先にローカルの環境のセットアップ

済ましておいてください。


プロジェクトの作成

truffle initで通常はプロジェクトを作成するのですが

最新のバージョンではtruffle initでは作成されないファイルが多いです

Truffle unbox <target project> コマンドを利用し

用意されたプロジェクトを利用します。

//プロジェクトのフォルダを作成する
$ mkdir testProject
//移動
$ cd testProject
//unbox
$ Truffle unbox

Starting unbox...
=================

✓ Preparing to download box
✓ Downloading
✓ Cleaning up temporary files
✓ Setting up box

Unbox successful, sweet!

Commands:

  Compile: truffle compile
  Migrate: truffle migrate
  Test:    truffle test

$ ls -la
total 8
drwxr-xr-x   6 XXXXXXXXX  staff   192  6 22 20:55 .
drwxr-x---+ 47 XXXXXXXXX  staff  1504  6 22 20:55 ..
drwxr-xr-x   5 XXXXXXXXX  staff   160  6 22 20:55 contracts
drwxr-xr-x   4 XXXXXXXXX  staff   128  6 22 20:55 migrations
drwxr-xr-x   4 XXXXXXXXX  staff   128  6 22 20:55 test
-rw-r--r--   1 XXXXXXXXX  staff   354  6 22 20:55 truffle-config.js

Truffle unbox コマンドで何もプロジェクトを指定しない場合は

metacoinのプロジェクトが利用されます。

プライベートネットワークの設定

プライベートネットワークに接続するための設定を

「truffle-config.js」 に設定します

下記はvi コマンドを利用して編集します

何も設定しない場合はnetworkの設定は

networks: {
 development: {
 host: “localhost”,
 port: 8545,
 network_id: “*”, // Match any network id
 gas: 5000000
}

のように

hostにはlocalhostが

portには8545が指定されています。

これを

portに7545を指定して変更します。

$ vi truffle-config.js 
module.exports = {
  networks: {
    development: {
      host: "localhost",
//portを7545に変更する
      port: 7545,
      network_id: "*", // Match any network id
      gas: 5000000
    }
  },
  compilers: {
    solc: {
      settings: {
        optimizer: {
          enabled: true, // Default: false
          runs: 200      // Default: 200
        },
      }
    }
  }
};

プライベートネットワークの起動

Ganacheを起動させて、プライベートネットワークを起動させます

インストールしたGanacheを起動させてください

すると下記画面が表示されます

Ganache

「NEW WORKSPACE」を選択します。

すると下記画面が表示されるため

ganache network select

「ADD PROJECT」をクリックして

先ほど修正した「truffle-config.js」を指定します。

そのご、画面右上の「START」ボタンをクリックしましょう

ganache network start

プライベートネットワーク接続確認

現状で一旦プライベートネットワークに接続します

「truffle console」コマンドで接続してみます

$ truffle console
This version of µWS is not compatible with your Node.js build:

Error: Cannot find module '../binaries/uws_darwin_arm64_108.node'
Require stack:
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/node_modules/ganache/node_modules/@trufflesuite/uws-js-unofficial/src/uws.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/node_modules/ganache/dist/node/core.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/build/console.bundled.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/node_modules/original-require/index.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/build/cli.bundled.js
Falling back to a NodeJS implementation; performance may be degraded.


> Something went wrong while attempting to connect to the network at http://localhost:7545. Check your network configuration.
CONNECTION ERROR: Couldn't connect to node http://localhost:7545.
Truffle v5.9.0 (core: 5.9.0)
Node v18.12.1

いつものFalling部分は無視します

しかし、「CONNECTION ERROR: Couldn’t connect to node http://localhost:7545.」

の表記が

$ cat /etc/hosts
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1	localhost
255.255.255.255	broadcasthost
::1             localhost

うーんあっているのですが

念の為「truffle-config.js」を再度修正します。

$ vi truffle-config.js 

module.exports = {
  networks: {
    development: {
//ここをループバックアドレス 127.0.0.1へ修正
      host: "127.0.0.1",
      port: 7545,
      network_id: "*", // Match any network id
      gas: 5000000
    }
  },
  compilers: {
    solc: {
      settings: {
        optimizer: {
          enabled: true, // Default: false
          runs: 200      // Default: 200
        },
      }
    }
  }
};
~                                                                               
~                  

再接続

$ truffle console
This version of µWS is not compatible with your Node.js build:

Error: Cannot find module '../binaries/uws_darwin_arm64_108.node'
Require stack:
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/node_modules/ganache/node_modules/@trufflesuite/uws-js-unofficial/src/uws.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/node_modules/ganache/dist/node/core.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/build/console.bundled.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/node_modules/original-require/index.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/build/cli.bundled.js
Falling back to a NodeJS implementation; performance may be degraded.


truffle(development)> 

相変わらず、Fallingは出ますが

コンソールからネットワークに繋がりました。

コントラクト作成

「truffle create contract 」コマンドでコントラクトを作成します。

今回は「HelloWorld」で作成しましょう

truffle(development)> truffle create contract HelloWorld
truffle(development)> 

一旦コンソールを抜けます

「.exit」で抜けることが可能です。

$ cd contracts
$ ls
ConvertLib.sol	HelloWorld.sol	MetaCoin.sol	Migrations.sol

contractsフォルダの配下に

「HelloWorld.sol」が作成されています。

「HelloWorld.sol」の内容を修正します。

なにも修正しないとこのような感じです

$ vi HelloWorld.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract HelloWorld {
  constructor() public {
  }
}

下記の内容で修正します。

今回は簡単にメッセージに「Hello World」を設定して

画面に出力される実装を入れました。

細かな内容は今後の記事で説明します

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract HelloWorld {
  string _message;
  constructor() public {
    _message = 'Hello World';
  }
  function getMessage() public view returns(string memory){
    return _message;
  }
}

コンパイル 〜 マイグレーション

「truffle compile」のコマンドでコンパイルを実施します。

$ truffle compile

Compiling your contracts...
===========================
> Compiling ./contracts/HelloWorld.sol
> Artifacts written to /Users/xxxxxxxx/testProject/build/contracts
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

「truffle create migration」コマンドでマグレーションのファイルを作成します

$ truffle create migration HelloWorld
$ cd ../
$ cd migrations
$ ls
1687439183_hello_world.js	2_deploy_contracts.js
1_initial_migration.js

「1687439183_hello_world.js」が存在しますね

_hello_world.js以外の部分には環境ごとに異なった数値が入ります。

次に「1687439183_hello_world.js」に記述します。

$ vi 1687439183_hello_world.js
//requireメソッド呼び出しを追加
const HelloWorld = artifacts.require("HelloWorld");
module.exports = function(_deployer) {
  // Use deployer to state migration tasks.
//deployメソッド呼び出しを追加
 _deployer.deploy(HelloWorld)
};

デプロイ

migrateコマンドで作成したプログラムをデプロイを実施

$ truffle migrate
This version of µWS is not compatible with your Node.js build:

Error: Cannot find module '../binaries/uws_darwin_arm64_108.node'
Require stack:
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/node_modules/ganache/node_modules/@trufflesuite/uws-js-unofficial/src/uws.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/node_modules/ganache/dist/node/core.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/build/migrate.bundled.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/node_modules/original-require/index.js
- /opt/homebrew/Cellar/truffle/5.9.0/libexec/lib/node_modules/truffle/build/cli.bundled.js
Falling back to a NodeJS implementation; performance may be degraded.



Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.


Starting migrations...
======================
> Network name:    'development'
> Network id:      5777
> Block gas limit: 6721975 (0x6691b7)


1_initial_migration.js
======================

   Deploying 'Migrations'
   ----------------------
   > transaction hash:    0xba639d8860916262e30fecccef95cfed99d0a9c0db18019aaeb911b9b44ea786
   > Blocks: 0            Seconds: 0
   > contract address:    0x9ea4a09be911350502DDa7d2085eC3Ca1Ddc965E
   > block number:        1
   > block timestamp:     1687521423
   > account:             0xbD2F6f8B3Fa5AC28677209d0d223D3a145A74563
   > balance:             99.99942764725
   > gas used:            169586 (0x29672)
   > gas price:           3.375 gwei
   > value sent:          0 ETH
   > total cost:          0.00057235275 ETH

   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:       0.00057235275 ETH


2_deploy_contracts.js
=====================

   Deploying 'ConvertLib'
   ----------------------
   > transaction hash:    0xaae61befc43d2a09c9bb0095d34c653f0c90d0cc1fa080df7ca8b4d025b6da09
   > Blocks: 0            Seconds: 0
   > contract address:    0x9ed119888811797201148f26a84b83455a968767
   > block number:        3
   > block timestamp:     1687521424
   > account:             0xbD2F6f8B3Fa5AC28677209d0d223D3a145A74563
   > balance:             99.998996952724562397
   > gas used:            88560 (0x159f0)
   > gas price:           3.17606086 gwei
   > value sent:          0 ETH
   > total cost:          0.0002812719497616 ETH


   Linking
   -------
   * Contract: MetaCoin <--> Library: ConvertLib (at address: 0x9ed119888811797201148f26a84b83455a968767)

   Deploying 'MetaCoin'
   --------------------
   > transaction hash:    0xe451a4ff7c8eb3d525db350cb5cebc0d9aa3b648cb3a053a68344352a4edc174
   > Blocks: 0            Seconds: 0
   > contract address:    0x1f94D09cB671F030972Ab5946eA156fcF9D9B567
   > block number:        4
   > block timestamp:     1687521424
   > account:             0xbD2F6f8B3Fa5AC28677209d0d223D3a145A74563
   > balance:             99.998364296375521243
   > gas used:            204493 (0x31ecd)
   > gas price:           3.093779978 gwei
   > value sent:          0 ETH
   > total cost:          0.000632656349041154 ETH

   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:     0.000913928298802754 ETH


1687439183_hello_world.js
=========================

   Deploying 'HelloWorld'
   ----------------------
   > transaction hash:    0x1e300f3e93504716056ac30a5989235e9be44a4837c0d7c994cd3e429fa45b40
   > Blocks: 0            Seconds: 0
   > contract address:    0xB6937b8D14e17D1F2b487F21a6E853042e96aE92
   > block number:        6
   > block timestamp:     1687521424
   > account:             0xbD2F6f8B3Fa5AC28677209d0d223D3a145A74563
   > balance:             99.997803829031418084
   > gas used:            160197 (0x271c5)
   > gas price:           2.95912127 gwei
   > value sent:          0 ETH
   > total cost:          0.00047404235009019 ETH

   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:     0.00047404235009019 ETH

Summary
=======
> Total deployments:   4
> Final cost:          0.001960323398892944 ETH

Fallingは相変わらず出力されますが無視・・・で

「1687439183_hello_world.js」からの内容に

「Deploying」の文字がありますね

たのプログラムもあるため、4つDeployが走っていますが

エラーなく完了しています。

HelloWorldメッセージ確認

では、実際にtruffle consoleを使って

稼働確認をします。

truffle(development)> HelloWorld.isDeployed();
true
truffle(development)> let helloWorld = await HelloWorld.deployed();
undefined
truffle(development)> helloWorld.getMessage();
'Hello World'

HelloWorld.isDeployed();

デプロイされているか確認しているコマンドです。

let helloWorld = await HelloWorld.deployed();

helloWorldを宣言し、HelloWorldのデプロイされたobjectを設定

helloWorld.getMessage();

getMessageメソッドを呼び出し

‘Hello World’が表示されることで正しく実行されていることを確認できました。


HelloWorldプログラム完成!次なるステップへの道案内と学習リソース


さて、「HelloWorld」を表示させることで、簡単な流れはつかめましたね

この後は、solidityの言語の仕様の理解

solidityを利用したプログラミング作成

DappsなどのWEB3.0のアプリケーション開発

といった流れになるでしょう?

引き続き、記事を紹介はしていきますが

solidityの技術者として

実際に実務についてバリバリ開発したい人もいることでしょう?

ぜひ、おすすめのプログラミングスクールを利用して

将来のsolidity技術者を目指し、

明るい将来を手にしてください。



おすすめプログラミングスクールへ

solidity helloworld
最新情報をチェックしよう!