LoginSignup
2
2

More than 5 years have passed since last update.

じゃんけんアプリにEthereumを組み込んでみた

Posted at

はじめに

じゃんけんに勝つと1ETHをもらえるものを作りました。
イメージはこんな感じです。

ローカル環境のgethで作成したアカウントをそれぞれこのように分けてます。
account[0]→master
account[1]→player
account[2]→pc 

アプリの作り方

じゃんけん部は割愛するとしてgethと繋げる部分としてまずweb3を読み込みます。

index.html
<script type="text/javascript" src="../web3/bignumber.js/bignumber.min.js"></script>

<script type="text/javascript" src="../web3/dist/web3.js"></script>

var web3 = new Web3();
    web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

    if(!web3.isConnected()){
      alert("not connected! gethを立ち上げてください");
      console.log("not connected");
    }else{
      console.log("connected");
    }

アカウント、残高の表示

function watchBalance() {
      var add00 = String(web3.eth.accounts[0]);
      var add01 = String(web3.eth.accounts[1]);
      var add02 = String(web3.eth.accounts[2]);
      $("#add00").text(add00);
      $("#add01").text(add01);
      $("#add02").text(add02);

      var add00_balance = web3.eth.getBalance(add00);
      var add01_balance = web3.eth.getBalance(add01);
      var add02_balance = web3.eth.getBalance(add02);
      var add00_balance_eth = web3.fromWei(add00_balance, 'ether');
      var add01_balance_eth = web3.fromWei(add01_balance, 'ether');
      var add02_balance_eth = web3.fromWei(add02_balance, 'ether');

      $("#add00_balance").text(add00_balance_eth +" ETH");
      $("#add01_balance").text(add01_balance_eth +" ETH");
      $("#add02_balance").text(add02_balance_eth +" ETH");
    }

勝利時のトランザクション処理

function win(){
  var _sendTransaction = web3.eth.sendTransaction({
          from: web3.eth.accounts[2], 
          to: web3.eth.accounts[1], 
          value: 1000000000000000000
        },)
}

この処理をじゃんけん勝ったときに追加すればOKです。

アプリの使い方

gethの起動

'''
geth --rpc --rpcport 8545 --rpcapi "web3,eth,net,personal" --rpccorsdomain "*" --rpcaddr "0.0.0.0" --datadir "~/eth_testnet" --nodiscover --networkid 10 --unlock 0,1,2 console 2>> ~/eth_testnet/geth.log
'''

アカウントをアンロックしないとトランザクション処理時にエラーになるので、geth立ち上げ時にアカウントロックを解除します。

アカウントロック例

Unlocking account 0 | Attempt 1/3
Passphrase: pass
Unlocking account 0 | Attempt 2/3
Passphrase: 
Unlocking account 0 | Attempt 3/3
Passphrase: 

マイニングスタートしてじゃんけんをする
miner start()

終わりに

今回はローカル環境だったので次はテストネット上のdappsに挑戦じゃー!

2
2
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
2
2