見出し画像

Solidity勉強メモ

この本を買ったので、進めてみる。
ちょっと古い本なので、環境とかの違いをまとめる。

環境

OS
Windows10

Geth

>geth version
Geth
Version: 1.10.8-stable
Git Commit: 26675454bf93bf904be7a43cce6b3f550115ff90
Git Commit Date: 20210824
Architecture: amd64
Go Version: go1.16.4
Operating System: windows
GOPATH=
GOROOT=go

npm

>npm version
{
 greeter: '1.0.0',
 npm: '6.14.6',
 ares: '1.16.0',
 brotli: '1.0.7',
 cldr: '37.0',
 http_parser: '2.9.3',
 icu: '67.1',
 llhttp: '2.1.2',
 modules: '72',
 napi: '6',
 nghttp2: '1.41.0',
 node: '12.18.4',
 openssl: '1.1.1g',
 tz: '2019c',
 unicode: '13.0',
 uv: '1.38.0',
 v8: '7.8.279.23-node.39',
 zlib: '1.2.11'
}

Truffle

>truffle version
Truffle v5.4.9 (core: 5.4.9)
Solidity - ^0.8.0 (solc-js)
Node v12.18.4
Web3.js v1.5.2

Parityが使えない

今は下記になっていて、しかもアーカイブ状態。これは使わないほうが良いのかもしれない。
https://github.com/openethereum/parity-ethereum

こちらの記事を発見。やっぱりうまくいってなくて、Gethを選択したよう。

Gethはこれ。インストーラーからインストールする

バージョンを確認する

>geth version
Geth
Version: 1.10.8-stable
Git Commit: 26675454bf93bf904be7a43cce6b3f550115ff90
Git Commit Date: 20210824
Architecture: amd64
Go Version: go1.16.4
Operating System: windows
GOPATH=
GOROOT=go

Gethのデータディレクトリを作成する

>mkdir mygeth1

Gethアカウントを作成する。

>geth account new --datadir /mygeth1
INFO [09-19|23:43:08.474] Maximum peer count                       ETH=50 LES=0 total=50
Your new account is locked with a password. Please give a password. Do not forget this password.
Password:
Repeat password:

Your new key was generated

Public address of the key:   0x8306acAE091E1d115716a7e2E7Ef329EAd2029eB
Path of the secret key file: \mygeth1\keystore\UTC--2021-09-19T14-43-25.165720700Z--8306acae091e1d115716a7e2e7ef329ead2029eb

- You can share your public address with anyone. Others need it to interact with you.
- You must NEVER share the secret key with anyone! The key controls access to your funds!
- You must BACKUP your key file! Without the key, it's impossible to access account funds!
- You must REMEMBER your password! Without the password, it's impossible to decrypt the key!

genesis.jsonの構成ファイルを作成する。mygeth1配下にgenesis.jsonとして下記を作る

>geth init genesis.json
Fatal: Failed to read genesis file: open genesis.json: The system cannot find the file specified.

geth initでエラーが起きた。
まずはgenesis.jsonを手で置く。
allocのアドレスは、うえで作ったaccountのPublic address of the keyを設定する。

{
   "config": {
     "chainId": 10024,
     "homesteadBlock": 0,
     "eip150Block": 0,
     "eip155Block": 0,
     "eip158Block": 0,
     "byzantiumBlock": 0,
     "constantinopleBlock": 0,
     "petersburgBlock": 0,
     "clique": {
       "period": 5,
       "epoch": 30000
     }
   },
   "difficulty": "1",
   "gasLimit": "8000000",
   "extradata": "",
   "alloc": {
       "0x8306acAE091E1d115716a7e2E7Ef329EAd2029eB": { "balance": "9000000" }
   }
 }

次に、geth init。できたようだ

>geth init genesis.json
INFO [09-20|00:21:07.147] Maximum peer count                       ETH=50 LES=0 total=50
INFO [09-20|00:21:07.183] Set global gas cap                       cap=50,000,000
INFO [09-20|00:21:07.186] Allocated cache and file handles         database=C:\Users\syund\AppData\Local\Ethereum\geth\chaindata cache=16.00MiB handles=16
INFO [09-20|00:21:07.204] Writing custom genesis block
INFO [09-20|00:21:07.206] Persisted trie from memory database      nodes=1 size=142.00B time=0s gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-20|00:21:07.212] Successfully wrote genesis state         database=chaindata hash=07edec..60d964
INFO [09-20|00:21:07.215] Allocated cache and file handles         database=C:\Users\syund\AppData\Local\Ethereum\geth\lightchaindata cache=16.00MiB handles=16
INFO [09-20|00:21:07.228] Writing custom genesis block
INFO [09-20|00:21:07.231] Persisted trie from memory database      nodes=1 size=142.00B time="536.2µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-20|00:21:07.239] Successfully wrote genesis state         database=lightchaindata hash=07edec..60d964

実際には、一度allocにユーザーを入れ忘れて、下記URLを参考に一度削除してやり直した。

起動させる。後ろのほうのパラメータは「--」をつけていたらなぜかエラーになったので消した。設定としては効いているみたい。謎。あと、古いコマンドらしくrpc, rpcaddr, rpccorsdomain, rpcapiが怒られてる。

>geth --datadir "\mygeth1" --networkid 8956 --ipcdisable --port 30307 --rpc --rpcapi "eth,web3,personal,net,miner,admin,debug" --rpcport 8507 --allow-insecure-unlock --rpcaddr "localhost" --nodiscover --rpccorsdomain "*" console --mine minerthreads=1 etherbase=0x8306acAE091E1d115716a7e2E7Ef329EAd2029eB
INFO [09-20|00:28:25.757] Maximum peer count                       ETH=50 LES=0 total=50
WARN [09-20|00:28:25.793] The flag --rpc is deprecated and will be removed June 2021, please use --http
WARN [09-20|00:28:25.796] The flag --rpcaddr is deprecated and will be removed June 2021, please use --http.addr
WARN [09-20|00:28:25.800] The flag --rpcport is deprecated and will be removed June 2021, please use --http.port
WARN [09-20|00:28:25.803] The flag --rpccorsdomain is deprecated and will be removed June 2021, please use --http.corsdomain
WARN [09-20|00:28:25.806] The flag --rpcapi is deprecated and will be removed June 2021, please use --http.api
INFO [09-20|00:28:25.812] Set global gas cap                       cap=50,000,000
INFO [09-20|00:28:25.814] Allocated trie memory caches             clean=154.00MiB dirty=256.00MiB
INFO [09-20|00:28:25.818] Allocated cache and file handles         database=C:\mygeth1\geth\chaindata cache=512.00MiB handles=8192
INFO [09-20|00:28:25.891] Opened ancient database                  database=C:\mygeth1\geth\chaindata\ancient readonly=false
INFO [09-20|00:28:25.897] Initialised chain configuration          config="{ChainID: 1 Homestead: 1150000 DAO: 1920000 DAOSupport: true EIP150: 2463000 EIP155: 2675000 EIP158: 2675000 Byzantium: 4370000 Constantinople: 7280000 Petersburg: 7280000 Istanbul: 9069000, Muir Glacier: 9200000, Berlin: 12244000, London: 12965000, Engine: ethash}"
INFO [09-20|00:28:25.908] Disk storage enabled for ethash caches   dir=C:\mygeth1\geth\ethash count=3
INFO [09-20|00:28:25.912] Disk storage enabled for ethash DAGs     dir=C:\Users\syund\AppData\Local\Ethash count=2
INFO [09-20|00:28:25.916] Initialising Ethereum protocol           network=8956 dbversion=8
INFO [09-20|00:28:25.930] Loaded most recent local header          number=0 hash=d4e567..cb8fa3 td=17,179,869,184 age=52y5mo2w
INFO [09-20|00:28:25.935] Loaded most recent local full block      number=0 hash=d4e567..cb8fa3 td=17,179,869,184 age=52y5mo2w
INFO [09-20|00:28:25.939] Loaded most recent local fast block      number=0 hash=d4e567..cb8fa3 td=17,179,869,184 age=52y5mo2w
INFO [09-20|00:28:25.943] Loaded local transaction journal         transactions=0 dropped=0
INFO [09-20|00:28:25.948] Regenerated local transaction journal    transactions=0 accounts=0
INFO [09-20|00:28:25.952] Gasprice oracle is ignoring threshold set threshold=2
INFO [09-20|00:28:25.955] Starting peer-to-peer node               instance=Geth/v1.10.8-stable-26675454/windows-amd64/go1.16.4
INFO [09-20|00:28:25.976] New local node record                    seq=2 id=8b96b70ae8bbd974 ip=127.0.0.1 udp=0 tcp=30307
INFO [09-20|00:28:25.980] HTTP server started                      endpoint=127.0.0.1:8507 prefix= cors=* vhosts=localhost
INFO [09-20|00:28:25.981] Started P2P networking                   self="enode://8999676de60aba134d9a5ab3703497a3bac8db4431172b6c699ab90d7112342594e78f92927c5eb7bb96077abb33e0e27c5e7f45ca6d27e096fac5ccdeb63bc7@127.0.0.1:30307?discport=0"
INFO [09-20|00:28:25.986] Transaction pool price threshold updated price=1,000,000,000
INFO [09-20|00:28:25.997] Updated mining threads                   threads=0
INFO [09-20|00:28:25.999] Transaction pool price threshold updated price=1,000,000,000
INFO [09-20|00:28:26.003] Etherbase automatically configured       address=0x8306acAE091E1d115716a7e2E7Ef329EAd2029eB
INFO [09-20|00:28:26.007] Commit new mining work                   number=1 sealhash=c50eb8..4fc76c uncles=0 txs=0 gas=0 fees=0 elapsed="532µs"
Welcome to the Geth JavaScript console!

instance: Geth/v1.10.8-stable-26675454/windows-amd64/go1.16.4
coinbase: 0x8306acae091e1d115716a7e2e7ef329ead2029eb
at block: 0 (Thu Jan 01 1970 09:00:00 GMT+0900 (JST))
datadir: C:\mygeth1
modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

To exit, press ctrl-d
>

WARNが出たパラメータを修正した。これでWARNが出なくなった。

geth --datadir "\mygeth1" --networkid 8956 --ipcdisable --port 30307 --http --http.api "eth,web3,personal,net,miner,admin,debug" --http.port 8507 --allow-insecure-unlock --http.addr "localhost" --nodiscover --http.corsdomain "*" console --mine minerthreads=1 etherbase=0x8306acAE091E1d115716a7e2E7Ef329EAd2029eB

「ブロックチェーン実践入門」だとこのままgeth2を作って2つのノードを繋いでいたけど、一旦ここまでにしておいて困ったら作る。

Ownable.solが見つからない

project:/contracts/Greeter.sol:3:1: ParserError: Source "openzeppelin/contracts/ownership/Ownable.sol" not found

openzeppelinのバージョンが新しくなってて、npm initもOwnableの場所も変わってる。
npm initはこれ

npm install @openzeppelin/contracts

import文はこれ

import "@openzeppelin/contracts/access/Ownable.sol";

情報元はこれ
https://docs.openzeppelin.com/contracts/4.x/access-control

solidityのバージョンエラー

Error: Truffle is currently using solc 0.5.16, but one or more of your contracts specify "pragma solidity ^0.8.0".

solidityのバージョンの違いっぽい。プログラムでの宣言をこうする

pragma solidity ^0.8.0;

あとtruffle-config.jsに設定を追加する

  // Configure your compilers
 compilers: {
   solc: {
     version: "^0.8.0"
     // version: "0.5.1",    // Fetch exact version from solc-bin (default: truffle's version)
     // docker: true,        // Use "0.5.1" you've installed locally with docker (default: false)
     // settings: {          // See the solidity docs for advice about optimization and evmVersion
     //  optimizer: {
     //    enabled: false,
     //    runs: 200
     //  },
     //  evmVersion: "byzantium"
     // }
   }
 },

情報元はこれ。

Unhandled Rejection (Error): This contract object doesn't have address set yet, please set an address first.

5.3 Ganacheへのデプロイで、npm run startしたらこのエラーが面が出た。MetaMaskが本物のアカウントでイーサリアム メインネットに接続してるのが原因だった。Ganacheで表示されているアカウントでログインをし直して、ネットワークをGoerliテストネットワークにしたら動いた。It's working! 嬉しい。(でも実はネットワークをGoerliテストネットワークにするのは間違えてた)

画像1

ETHが無くてGreetingの文が変えられない

Greetingの文を変えようと思ったら、Ganacheのユーザの所持ETHが0でガス代が払えなくて変えられない。このアカウントにETH入れるのはどうやればいいんだ?Gethで最初に作ったユーザーは自前のイーサリアムネットワークのETH持ってるけど、Ganacheのユーザーは持ってないんだな。Ganacheのaccountsタブに並んでるユーザーでMetaMaskに入ってみても0ETHだし、どうやったらいいかわからない。Ganacheの画面では100ETHって書いてあるのになぁ。

と思ったら、MetaMaskの接続先を切り替えるのを忘れていた。MetaMaskの「イーサリアムメインネット」を「localhost 8545」に切り替えるとETH持ってた。

画像2

メッセージが更新できない

ブラウザのコンソールを見たら、こんなエラーが出ていた

Uncaught (in promise) Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
   at ABICoder.push../node_modules/web3-eth-abi/lib/index.js.ABICoder.decodeParametersWith (index.js:366)
   at ABICoder.push../node_modules/web3-eth-abi/lib/index.js.ABICoder.decodeParameters (index.js:351)
   at Contract.push../node_modules/web3-eth-contract/lib/index.js.Contract._decodeMethodReturn (index.js:536)
   at Method.outputFormatter (index.js:871)
   at Method.push../node_modules/web3-core-method/lib/index.js.Method.formatOutput (index.js:177)
   at sendTxCallback (index.js:727)
   at cb (util.js:702)
   at Item.push../node_modules/process/browser.js.Item.run (browser.js:167)
   at drainQueue (browser.js:131)

戻り値が正しくないよ。ABIがおかしいんじゃないの?もしくは(いろいろな理由)って言われてる。

truffle compileとかtruffle migrateとかしてもエラーがなくならない。

→ よく調べたら、truffle-config.jsのcontracts_build_directoryの設定を間違えて、違うディレクトリにContext.jsonとかができてた。設定を直してbuildとかをやり直したら動いた。

GanacheでTransactionosを見たら、更新来てた

画像3

別のユーザーで更新エラーになる確認をしようと思ったら、MetaMaskでもうエラーが出てる。なるほどそうなるのか。

画像4

それでも「確認」ボタンを押して進めたら、ブラウザコンソールにエラーが出た。なるほどそうなるのか(2回目)

inpage.js:1 MetaMask - RPC Error: Error: [ethjs-query] while formatting outputs from RPC '{"value":{"code":-32603,"data":{"message":"VM Exception while processing transaction: revert Ownable: caller is not the owner","code":-32000,"data":{"0x2f02bdca7f9e27adfbfa07e9d2482f33588f131fffcf3ddfef0770424eb5b336":{"error":"revert","program_counter":519,"return":"0x08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000204f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572","reason":"Ownable: caller is not the owner"},"stack":"RuntimeError: VM Exception while processing transaction: revert Ownable: caller is not the owner\n    at Function.RuntimeError.fromResults (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\lib\\utils\\runtimeerror.js:94:13)\n    at BlockchainDouble.processBlock (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\lib\\blockchain_double.js:627:24)\n    at runMicrotasks (<anonymous>)\n    at processTicksAndRejections (internal/process/task_queues.js:93:5)","name":"RuntimeError"}}}}' 

truffle-hdwallet-providerでエラー

>npm install truffle-hdwallet-provider --save-dev
npm WARN deprecated truffle-hdwallet-provider@1.0.17: WARNING: This package has been renamed to @truffle/hdwallet-provider.
npm WARN deprecated mkdirp-promise@5.0.1: This package is broken and no longer maintained. 'mkdirp' itself supports promises now, please switch to that.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated uuid@2.0.1: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated uuid@3.3.2: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.

よく見たら、最初に「パッケージの名前が @truffle/hdwallet-provider に変わったよ」って書いてあった。なので

npm install @truffle/hdwallet-provider --save-dev

ってやったらエラー無く入れることができた。(ワーニングはめちゃくちゃ出る)

>npm install @truffle/hdwallet-provider --save-dev
npm WARN deprecated ethereumjs-tx@2.1.2: New package name format for new versions: @ethereumjs/tx. Please update.
npm WARN deprecated ethereumjs-common@1.5.2: New package name format for new versions: @ethereumjs/common. Please update.
npm WARN deprecated ethereumjs-tx@1.3.7: New package name format for new versions: @ethereumjs/tx. Please update.
npm WARN deprecated ethereumjs-block@1.7.1: New package name format for new versions: @ethereumjs/block. Please update.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated eth-json-rpc-errors@2.0.2: Package renamed: https://www.npmjs.com/package/eth-rpc-errors
npm WARN deprecated ethereumjs-vm@2.6.0: New package name format for new versions: @ethereumjs/vm. Please update.
npm WARN deprecated safe-event-emitter@1.0.1: Renamed to @metamask/safe-event-emitter
npm WARN deprecated eth-json-rpc-errors@1.1.1: Package renamed: https://www.npmjs.com/package/eth-rpc-errors
npm WARN deprecated ethereumjs-block@2.2.2: New package name format for new versions: @ethereumjs/block. Please update.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated har-validator@5.1.5: this library is no longer supported

> secp256k1@4.0.2 install C:\Users\syund\eclipse-workspace\greeter\node_modules\secp256k1
> node-gyp-build || exit 0


> keccak@3.0.2 install C:\Users\syund\eclipse-workspace\greeter\node_modules\keccak
> node-gyp-build || exit 0

npm WARN @babel/plugin-transform-runtime@7.15.0 requires a peer of @babel/core@^7.0.0-0 but none is installed. You must install peer dependencies yourself.
npm WARN babel-plugin-polyfill-regenerator@0.2.2 requires a peer of @babel/core@^7.0.0-0 but none is installed. You must install peer dependencies yourself.
npm WARN babel-plugin-polyfill-corejs3@0.2.4 requires a peer of @babel/core@^7.0.0-0 but none is installed. You must install peer dependencies yourself.
npm WARN babel-plugin-polyfill-corejs2@0.2.2 requires a peer of @babel/core@^7.0.0-0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/helper-define-polyfill-provider@0.2.3 requires a peer of @babel/core@^7.4.0-0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/helper-compilation-targets@7.15.4 requires a peer of @babel/core@^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN greeter@1.0.0 No description
npm WARN greeter@1.0.0 No repository field.

+ @truffle/hdwallet-provider@1.5.0
added 264 packages from 333 contributors and audited 265 packages in 47.423s

7 packages are looking for funding
 run `npm fund` for details

found 3 low severity vulnerabilities
 run `npm audit fix` to fix them, or `npm audit` for details

export MNEMONIC

windowsなのでこうですね。ダブルクォーテーションで囲む必要はない。

>set MNEMONIC=word1 word2 .........

truffle-config.jsの設定

なんとなく「goerli → rinkeby」にしたので、こうなった

設定の初めのほう

const mnemonic = process.env["MNEMONIC"];
const project_id = process.env["INFURA_PROJECT_ID"];
const rinkeby_infura_url = "https://rinkeby.infura.io/v3/" + project_id;

networksの中

    rinkeby: {
     provider: function() { 
       return new HDWalletProvider(mnemonic, rinkeby_infura_url);
     },
     network_id: 4,
     gas: 4500000,
     gasPrice: 10000000000,

   },

Parityを使ったgoerliへのデプロイ

色々あって、「Parity → geth」、「goerli → rinkeby」になった。なので、こうやってノード起動。あ、mygethrinkebyディレクトリは事前に作成。でも何も入ってないから、いらないのかもしれない。

geth --rinkeby --datadir "\mygethrinkeby"

こんな感じで、毎秒1行くらいのペースでずっとログが流れ続ける。

INFO [09-21|22:21:52.504] Imported new block receipts              count=257  elapsed=36.171ms  number=134,491 hash=bb7456..9ca475 age=4y5mo1w  size=161.96KiB
INFO [09-21|22:21:52.594] Imported new block headers               count=384  elapsed=47.323ms  number=134,976 hash=177c00..75b439 age=4y5mo1w
INFO [09-21|22:21:52.666] Imported new block headers               count=192  elapsed=20.425ms  number=135,168 hash=b8f378..b6f5e5 age=4y5mo1w
INFO [09-21|22:21:52.741] Imported new block receipts              count=449  elapsed=57.887ms  number=134,940 hash=0f58d0..787711 age=4y5mo1w  size=282.68KiB
INFO [09-21|22:21:52.866] Imported new block headers               count=384  elapsed=34.853ms  number=135,552 hash=f332ab..98dcc3 age=4y5mo1w
INFO [09-21|22:21:55.185] State sync in progress                   synced=1.06% state=894.49MiB accounts=82321@21.72MiB slots=3,300,265@695.42MiB codes=31724@177.36MiB eta=3h14m28.496s
INFO [09-21|22:21:56.785] Looking for peers                        peercount=2 tried=37 static=0
INFO [09-21|22:22:01.527] Imported new block headers               count=192  elapsed=19.802ms  number=135,744 hash=57ba0d..beb100 age=4y5mo1w
INFO [09-21|22:22:01.672] Imported new block receipts              count=228  elapsed=179.325ms number=135,168 hash=b8f378..b6f5e5 age=4y5mo1w  size=143.54KiB
INFO [09-21|22:22:01.696] Imported new block receipts              count=124  elapsed=18.55ms   number=135,292 hash=99c50f..430554 age=4y5mo1w  size=77.98KiB
INFO [09-21|22:22:01.749] Imported new block receipts              count=432  elapsed=47.049ms  number=135,724 hash=e71b6f..476783 age=4y5mo1w  size=271.83KiB
INFO [09-21|22:22:01.788] Imported new block headers               count=2048 elapsed=195.694ms number=137,792 hash=a724e9..ba3515 age=4y5mo1w
I

デプロイでHDWalletエラー

>truffle migrate --network rinkeby

Compiling your contracts...
===========================
√ Fetching solc version list from solc-bin. Attempt #1
> Compiling @openzeppelin\contracts\access\Ownable.sol
> Compiling @openzeppelin\contracts\utils\Context.sol
> Compiling .\contracts\Greeter.sol
> Compiling .\contracts\Migrations.sol
√ Fetching solc version list from solc-bin. Attempt #1
> Compilation warnings encountered:

   Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "SPDX-License-Identifier: <SPDX-License>" to each source file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more information.
--> project:/contracts/Greeter.sol


> Artifacts written to C:\<作業パス>\greeter\client\src\contracts
> Compiled successfully using:
  - solc: 0.8.7+commit.e28d00a7.Emscripten.clang

Error: Unknown arguments format passed to new HDWalletProvider. Please check your configuration and try again
   at Object.getOptions (C:\<作業パス>\greeter\node_modules\@truffle\hdwallet-provider\src\constructor\getOptions.ts:143:11)
   at new HDWalletProvider (C:\<作業パス>\greeter\node_modules\@truffle\hdwallet-provider\src\index.ts:68:9)
   途中省略
Truffle v5.4.9 (core: 5.4.9)
Node v12.18.4

だめだ、解決できない。

というか、ページを読み進めたら次にInfuraを使ってrinkebyにデプロイするのがあったから、もうそっちでやる。

なんとかできたようだ。本に書いてある設定ではうまくいかなかったので、下記を参考に設定を変更した。

const HDWalletProvider = require('@truffle/hdwallet-provider');
const mnemonic = process.env["MNEMONIC"];

const project_id = process.env["INFURA_PROJECT_ID"];
const rinkeby_infura_url = "https://rinkeby.infura.io/v3/" + project_id;

// 途中省略

    rinkeby: {
     provider: function() { 
       return new HDWalletProvider(mnemonic, rinkeby_infura_url);
     },
     network_id: 4,
     gas: 4500000,
     gasPrice: 10000000000,

   },

できたー!って、なんでこんなメッセージになってるの?わからん。

画像5

動かそうと思ったら動かない。Ownableで弾かれる。これ別の人のやつなのでは?

ログをよく見たら、デプロイしてる風のログがない。「Network up to date.」って、そんだけ。

>truffle migrate --network development

Compiling your contracts...
===========================
√ Fetching solc version list from solc-bin. Attempt #1
> Compiling .\contracts\Greeter.sol
> Compiling .\contracts\Greeter.sol
> Compiling .\contracts\Migrations.sol
√ Fetching solc version list from solc-bin. Attempt #1
> Compilation warnings encountered:

   Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "SPDX-License-Identifier: <SPDX-License>" to each source file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more information.
--> project:/contracts/Greeter.sol


> Artifacts written to C:\<作業パス>\greeter\client\src\contracts
> Compiled successfully using:
  - solc: 0.8.7+commit.e28d00a7.Emscripten.clang

Network up to date.

アカウントがGanacheのものだからか?とか思って切り替えたり、下記を参考にビルド時に出力されるjsonファイル(greeter\client\src\contracts 配下のもの)を消して再度ビルドしたりしたら、デプロイできた!

>truffle migrate --network rinkeby

Compiling your contracts...
===========================
√ Fetching solc version list from solc-bin. Attempt #1
> Compiling @openzeppelin\contracts\access\Ownable.sol
> Compiling @openzeppelin\contracts\utils\Context.sol
> Compiling .\contracts\Greeter.sol
> Compiling .\contracts\Migrations.sol
√ Fetching solc version list from solc-bin. Attempt #1
> Compilation warnings encountered:

   Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "SPDX-License-Identifier: <SPDX-License>" to each source file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more information.
--> project:/contracts/Greeter.sol


> Artifacts written to C:\<作業パス>\greeter\client\src\contracts
> Compiled successfully using:
  - solc: 0.8.7+commit.e28d00a7.Emscripten.clang

Migrations dry-run (simulation)
===============================
> Network name:    'rinkeby-fork'
> Network id:      4
> Block gas limit: 29970705 (0x1c95111)


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

  Deploying 'Migrations'
  ----------------------
  > block number:        9337994
  > block timestamp:     1632325966
  > account:             0x4eF9663aFfb340585A3dF42F253aC65765EbFDb0
  > balance:             2.99766146
  > gas used:            233854 (0x3917e)
  > gas price:           10 gwei
  > value sent:          0 ETH
  > total cost:          0.00233854 ETH

  -------------------------------------
  > Total cost:          0.00233854 ETH


2_deploy_greeter.js
===================

  Deploying 'Greeter'
  -------------------
  > block number:        9337996
  > block timestamp:     1632325982
  > account:             0x4eF9663aFfb340585A3dF42F253aC65765EbFDb0
  > balance:             2.99175825
  > gas used:            562808 (0x89678)
  > gas price:           10 gwei
  > value sent:          0 ETH
  > total cost:          0.00562808 ETH

  -------------------------------------
  > Total cost:          0.00562808 ETH


Summary
=======
> Total deployments:   2
> Final cost:          0.00796662 ETH

Starting migrations...
======================
> Network name:    'rinkeby'
> Network id:      4
> Block gas limit: 29999943 (0x1c9c347)


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

  Deploying 'Migrations'
  ----------------------
  > transaction hash:    0xac05c799a82cdeb21e74b4d5ddd9c55964a9636673960a1b04ca40860e793474
  > Blocks: 1            Seconds: 9
  > contract address:    0x82D235ca4f4Dc7cDe248b06e627cf920C73d774b
  > block number:        9337995
  > block timestamp:     1632326000
  > account:             0x4eF9663aFfb340585A3dF42F253aC65765EbFDb0
  > balance:             2.99749846
  > gas used:            250154 (0x3d12a)
  > gas price:           10 gwei
  > value sent:          0 ETH
  > total cost:          0.00250154 ETH


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


2_deploy_greeter.js
===================

  Deploying 'Greeter'
  -------------------
  > transaction hash:    0x8b6c0283f06f624d8089832d3659cde60c02184d269a4e3d29274448558de58c
  > Blocks: 0            Seconds: 9
  > contract address:    0xDbc27c6f8ad8d97fFB432B742F120E7d95152897
  > block number:        9337997
  > block timestamp:     1632326030
  > account:             0x4eF9663aFfb340585A3dF42F253aC65765EbFDb0
  > balance:             2.99109225
  > gas used:            594708 (0x91314)
  > gas price:           10 gwei
  > value sent:          0 ETH
  > total cost:          0.00594708 ETH


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


Summary
=======
> Total deployments:   2
> Final cost:          0.00844862 ETH

吐かれたコードを消さないと動かないなんて、いつの時代だよって感じだけど、とりあえず動いたからよかった。参考にしたのはこれ。


Ethascanで見たらなぜかdeployが2回走ってるけど、それはいったん置いておくか。あーいや、MigrationsとGreeterの2つをデプロイしてるのか。Migrationsってなんだっけ。まあいいか。

画像6

画面からメッセージを更新して・・・

画像8

更新トランザクションきた!

画像7

geth経由でのrinkebyへのデプロイはできなかったけど、infura経由でできたから良しとする。


===== ここから6章 =====

受取人の編集でOwnableの導入する。4章と同じようにnpm installするパッケージやimport文を変更する。pragmaのsolidityのバージョンを^0.8.0に変更し、truffle-config.jsにバージョン指定を追加する。

test動かしたら、なんかWARNING出た。Warning: Visibility for constructor is ignored. If you want the contract to be non-deployable, making it "abstract" is sufficient.

調べたら、コンストラクタにpublicとかexternalとか、もうつけなくていいらしい。何故なのかはわからない。どこからでも呼べちゃうのでいいんだろうか。

>truffle test
Using network 'test'.


Compiling your contracts...
===========================
√ Fetching solc version list from solc-bin. Attempt #1
> Compiling .\contracts\Fundraiser.sol
> Compiling .\contracts\Fundraiser.sol
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\Migrations.sol
√ Fetching solc version list from solc-bin. Attempt #1
> Compilation warnings encountered:

   Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "SPDX-License-Identifier: <SPDX-License>" to each source file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more information.
--> project:/contracts/Fundraiser.sol

,Warning: Visibility for constructor is ignored. If you want the contract to be non-deployable, making it "abstract" is sufficient.
 --> project:/contracts/Fundraiser.sol:12:5:
  |
12 |     constructor(
  |     ^ (Relevant source part starts here and spans across multiple lines).

,Warning: Visibility for constructor is ignored. If you want the contract to be non-deployable, making it "abstract" is sufficient.
 --> project:/contracts/Migrations.sol:12:3:
  |
12 |   constructor() public {
  |   ^ (Relevant source part starts here and spans across multiple lines).


> Artifacts written to C:\Users\syund\AppData\Local\Temp\test--15668-2gKNAXS9e7vQ
> Compiled successfully using:
  - solc: 0.8.7+commit.e28d00a7.Emscripten.clang

 Contract: Fundraiser
   initialization
     √ gets the beneficiary name (73ms)
     √ gets the beneficiary url (60ms)
     √ gets the beneficiary imageURL (71ms)
     √ gets the beneficiary description (50ms)
     √ gets the beneficiary (65ms)
     √ gets the owner (50ms)


 6 passing (2s)

Fundraiser.solとMigrations.solのコンストラクタについてるpublicを消したらWARNINGが消えた。

SafeMath

コンパイラーのチェックに含められたから、無くすよって書いてある(ように読める)

本と一致させるために一応導入しようとすると、例のごとくimportする場所が変わってる。下記に変更されている。

import "@openzeppelin/contracts/utils/math/SafeMath.sol";

参考にしたのはこれ

イベントってなんだろう。やりたいことは、サブスクライバが自分に関係があるかもしれないイベントを絞り込みやすくすることらしい。

サブスクライバって誰?今でいうと寄付者のこと?どうやってイベントを絞り込むの?Ethescanとか?読み進めたらわかるのかなぁ。

Contract # addressが見つからない

資金の引き出しで追加するこれがエラーになる

            const currentContractBalance = await web3.eth.getBalance(fundraiser.address);

エラーはこれ。2時間くらい格闘したけど解決できず。ここからは机上で理解するだけにするか。

>truffle test
Using network 'test'.


Compiling your contracts...
===========================
√ Fetching solc version list from solc-bin. Attempt #1
> Compiling .\contracts\Fundraiser.sol
> Compiling .\contracts\Fundraiser.sol
> Compiling .\contracts\Migrations.sol
√ Fetching solc version list from solc-bin. Attempt #1
> Artifacts written to C:\Users\syund\AppData\Local\Temp\test--9832-1Dlnm5p7ZkdZ
> Compiled successfully using:
  - solc: 0.8.7+commit.e28d00a7.Emscripten.clang


 1) Uncaught error outside test suite

 0 passing (2ms)
 1 failing

 1) Uncaught error outside test suite:
    Uncaught TypeError: Cannot read property 'address' of undefined
     at Suite.<anonymous> (test\fundraiser_test.js:173:81)
     at Suite.<anonymous> (test\fundraiser_test.js:172:9)
     at C:\Users\syund\eclipse-workspace\fundraiser\test\fundraiser_test.js:143:5
     at Suite.template (C:\Users\syund\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\testing\Test.js:328:1)
     at Suite.<anonymous> (C:\Users\syund\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\testing\Test.js:333:1)
     at global.contract (C:\Users\syund\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\testing\Test.js:332:1)
     at Object.<anonymous> (test\fundraiser_test.js:3:1)
     at Module._compile (internal/modules/cjs/loader.js:1137:30)
     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
     at Module.load (internal/modules/cjs/loader.js:985:32)
     at Function.Module._load (internal/modules/cjs/loader.js:878:14)
     at Module.require (internal/modules/cjs/loader.js:1025:19)
     at require (internal/modules/cjs/helpers.js:72:18)
     at Array.forEach (<anonymous>)
     
UnhandledRejections detected
Promise {
 <rejected> TypeError: Cannot read property 'address' of undefined
     at Suite.<anonymous> (test\fundraiser_test.js:173:81)
     at Suite.<anonymous> (test\fundraiser_test.js:172:9)
     at C:\Users\syund\eclipse-workspace\fundraiser\test\fundraiser_test.js:143:5
     at Suite.template (C:\Users\syund\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\testing\Test.js:328:1)
     at Suite.<anonymous> (C:\Users\syund\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\testing\Test.js:333:1)
     at global.contract (C:\Users\syund\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\testing\Test.js:332:1)
     at Object.<anonymous> (test\fundraiser_test.js:3:1)
     at Module._compile (internal/modules/cjs/loader.js:1137:30)
     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
     at Module.load (internal/modules/cjs/loader.js:985:32)
     at Function.Module._load (internal/modules/cjs/loader.js:878:14)
     at Module.require (internal/modules/cjs/loader.js:1025:19)
     at require (internal/modules/cjs/helpers.js:72:18)
     at Array.forEach (<anonymous>) {
   uncaught: true
 }
} TypeError: Cannot read property 'address' of undefined
   at Suite.<anonymous> (test\fundraiser_test.js:173:81)
   at Suite.<anonymous> (test\fundraiser_test.js:172:9)
   at C:\Users\syund\eclipse-workspace\fundraiser\test\fundraiser_test.js:143:5
   at Suite.template (C:\Users\syund\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\testing\Test.js:328:1)
   at Suite.<anonymous> (C:\Users\syund\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\testing\Test.js:333:1)
   at global.contract (C:\Users\syund\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\testing\Test.js:332:1)
   at Object.<anonymous> (test\fundraiser_test.js:3:1)
   at Module._compile (internal/modules/cjs/loader.js:1137:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
   at Module.load (internal/modules/cjs/loader.js:985:32)
   at Function.Module._load (internal/modules/cjs/loader.js:878:14)
   at Module.require (internal/modules/cjs/loader.js:1025:19)
   at require (internal/modules/cjs/helpers.js:72:18)
   at Array.forEach (<anonymous>) {
 uncaught: true
}




参考URL



いいなと思ったら応援しよう!