見出し画像

AnimeLootの派生Lootを作る過程で詰まったところなどまとめる

Solidityの勉強を本一冊したところで、AnimeLootの派生Lootを作っていこうと色々頑張ってるので、詰まったところをまとめていきます。まだ公開に至ってないので随時増やしていきます。

勉強した軌跡はこちら。

前提

・OS Windows 10
・Node v12.18.4
・Truffle v5.4.9 (core: 5.4.9)
・Solidity - ^0.8.0 (solc-js)
・Web3.js v1.5.2
・Ganache v2.5.4
・Geth 1.10.8 → 1.10.9

最初に纏め

・デプロイする方式はRemixIDE経由。GethだとGethの同期が上手くできない。Infura経由だとタイムアウトで止まってしまう。

・ソースをverifyするのは、EthereumはRemixIDEのプラグインでそのままverifyできる。Polygonはflattenしたものを手動でverifyする。

勧誘

ここにソースを置いておくので、一緒に試行錯誤してくれる人を募集しています。まだ開発途中なので、随時更新していきます

色々やってるDiscordはこちら


rinkebyテストネットワークにdeployできない

ETIMEDOUTというエラーが出てdeployできない。そして、そのエラーが出るまでに数時間かかる。issueでも上がってるみたいです。

GitHubでrinkebyを呼び出している設定ファイルを色々調べて、これにしたらdeployが動き始めました。でも数時間経ってからETIMEOUTというエラーが出ます。

    rinkeby: {
     provider: function() {
       const networkCheckTimeout = 10000;
       const rinkeby_infura_url = "wss://rinkeby.infura.io/ws/v3/" + rinkeby_infura_project_id;

       return new HDWalletProvider(mnemonic, rinkeby_infura_url);
     },
     network_id: 4,
     gas: 8500000,
     gasPrice: 1000000000,  // 1 gwei (in wei) (default: 100 gwei)
     confirmations: 2,
     skipDryRun: true,
     websocket: true,
     timeoutBlocks: 50000,
     networkCheckTimeout: 1000000000,
   },

どうしてもわからなかったので、もともと動いていたサンプルコードを改変する形で進めました。そしたら動きました。そして、一度だけ動いてまた動かなくなりました。つらい。

Gethからrinkebyテストネットワークにdeployする

infura経由がうまくいかないので、gethを通じてdeployする方法を試します。参考にしたのはこちら

gethを起動するところにあるbootnodesってなんだろうって思って調べたら、ここにありました。


lightモードだとうまく動かなかったので、fastモードでやりました。bootnodesは別に指定しなくても普通に動いてくれました。

>geth --rinkeby --datadir "./fast" --syncmode "fast" --rpc --rpcapi="db,eth,net,web3,personal,web3" --cache=1024  --rpcport 8545 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --port "35555"
INFO [09-30|12:10:56.387] Starting Geth on Rinkeby testnet...
INFO [09-30|12:10:56.423] Maximum peer count                       ETH=50 LES=0 total=50
WARN [09-30|12:10:56.426] The flag --rpc is deprecated and will be removed June 2021, please use --http
WARN [09-30|12:10:56.429] The flag --rpcaddr is deprecated and will be removed June 2021, please use --http.addr
WARN [09-30|12:10:56.433] The flag --rpcport is deprecated and will be removed June 2021, please use --http.port
WARN [09-30|12:10:56.436] The flag --rpccorsdomain is deprecated and will be removed June 2021, please use --http.corsdomain
WARN [09-30|12:10:56.440] The flag --rpcapi is deprecated and will be removed June 2021, please use --http.api
INFO [09-30|12:10:56.451] Set global gas cap                       cap=50,000,000
INFO [09-30|12:10:56.454] Allocated trie memory caches             clean=153.00MiB dirty=256.00MiB
INFO [09-30|12:10:56.458] Allocated cache and file handles         database=C:\Users\syund\eclipse-workspace\geth\fast\geth\chaindata cache=512.00MiB handles=8192
INFO [09-30|12:10:57.226] Opened ancient database                  database=C:\Users\syund\eclipse-workspace\geth\fast\geth\chaindata\ancient readonly=false
INFO [09-30|12:10:57.271] Persisted trie from memory database      nodes=355 size=50.43KiB time=0s gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-30|12:10:57.296] Initialised chain configuration          config="{ChainID: 4 Homestead: 1 DAO: <nil> DAOSupport: true EIP150: 2 EIP155: 3 EIP158: 3 Byzantium: 1035301 Constantinople: 3660663 Petersburg: 4321234 Istanbul: 5435345, Muir Glacier: <nil>, Berlin: 8290928, London: 8897988, Engine: clique}"
INFO [09-30|12:10:58.524] Initialising Ethereum protocol           network=4 dbversion=8
INFO [09-30|12:10:58.552] Loaded most recent local header          number=9,373,589 hash=1b6492..e50d68 td=15,824,958 age=1d6h41m
INFO [09-30|12:10:58.557] Loaded most recent local full block      number=0         hash=6341fd..67e177 td=1          age=4y6mo1w
INFO [09-30|12:10:58.561] Loaded most recent local fast block      number=9,373,589 hash=1b6492..e50d68 td=15,824,958 age=1d6h41m
INFO [09-30|12:10:58.567] Loaded last fast-sync pivot marker       number=9,375,539
INFO [09-30|12:10:58.700] Upgrading chain index                    type=bloombits percentage=16
INFO [09-30|12:10:58.701] Loaded local transaction journal         transactions=0 dropped=0
INFO [09-30|12:10:58.709] Regenerated local transaction journal    transactions=0 accounts=0
INFO [09-30|12:10:58.720] Allocated fast sync bloom                size=511.00MiB
INFO [09-30|12:10:58.725] Gasprice oracle is ignoring threshold set threshold=2
INFO [09-30|12:10:58.730] Starting peer-to-peer node               instance=Geth/v1.10.8-stable-26675454/windows-amd64/go1.16.4
INFO [09-30|12:10:58.805] New local node record                    seq=7 id=682102485c6f7a94 ip=127.0.0.1 udp=35555 tcp=35555
INFO [09-30|12:10:58.811] Started P2P networking                   self=enode://ee0604e5e3ae33ae59841d172825eb52ae879ffe860969d42f45c39a47452cf9b274dc0751c7e41b9dc96976213226f3c13f18a9e4814a8a4b7db71f03144eeb@127.0.0.1:35555
INFO [09-30|12:10:58.812] IPC endpoint opened                      url=\\.\pipe\geth.ipc
ERROR[09-30|12:10:58.823] Unavailable modules in HTTP API list     unavailable=[db] available="[admin debug web3 eth txpool personal clique miner net]"
INFO [09-30|12:10:58.829] HTTP server started                      endpoint=127.0.0.1:8545 prefix= cors=* vhosts=localhost
INFO [09-30|12:11:06.725] Initializing state bloom                 items=8,130,214 errorrate=0.000 elapsed=8.000s
INFO [09-30|12:11:06.835] Upgrading chain index                    type=bloombits percentage=17
INFO [09-30|12:11:08.358] New local node record                    seq=8 id=682102485c6f7a94 ip=58.70.122.165 udp=35555 tcp=35555
INFO [09-30|12:11:09.450] Looking for peers                        peercount=0 tried=18 static=0
INFO [09-30|12:11:14.731] Initializing state bloom                 items=16,658,077 errorrate=0.000 elapsed=16.006s
INFO [09-30|12:11:15.086] Upgrading chain index                    type=bloombits percentage=19
INFO [09-30|12:11:20.117] Looking for peers                        peercount=0 tried=38 static=0
INFO [09-30|12:11:22.736] Initializing state bloom                 items=25,482,340 errorrate=0.000 elapsed=24.012s
INFO [09-30|12:11:23.154] Upgrading chain index                    type=bloombits percentage=20
INFO [09-30|12:11:28.801] Block synchronisation started
INFO [09-30|12:11:30.255] Looking for peers                        peercount=1 tried=37 static=0
INFO [09-30|12:11:30.741] Initializing state bloom                 items=29,616,622 errorrate=0.000 elapsed=32.016s
INFO [09-30|12:11:31.211] Upgrading chain index                    type=bloombits percentage=22
INFO [09-30|12:11:32.494] Disabling direct-ancient mode            origin=9,373,589 ancient=9,076,735
INFO [09-30|12:11:33.633] Imported new block headers               count=192 elapsed=20.306ms number=9,373,781 hash=629a58..bf8984 age=1d5h53m
INFO [09-30|12:11:33.945] Downloader queue stats                   receiptTasks=183 blockTasks=184 itemSize=7.26KiB throttle=8192
INFO [09-30|12:11:33.949] Imported new block headers               count=192 elapsed=19.108ms number=9,373,973 hash=07cfdb..a586fc age=1d5h5m
INFO [09-30|12:11:33.956] Imported new block receipts              count=1   elapsed=5.691ms  number=9,373,590 hash=36274a..d10984 age=1d6h41m size=46.86KiB
INFO [09-30|12:11:34.267] Imported new block headers               count=192 elapsed=19.552ms number=9,374,165 hash=c1a1d0..cb5443 age=1d4h17m
INFO [09-30|12:11:34.333] Imported new block receipts              count=7   elapsed="988.4µs" number=9,373,597 hash=a78034..402a61 age=1d6h40m size=130.02KiB
INFO [09-30|12:11:34.586] Imported new block headers               count=192 elapsed=17.950ms  number=9,374,357 hash=822c53..eb1fa6 age=1d3h29m
INFO [09-30|12:11:35.990] Imported new block receipts              count=40  elapsed=7.601ms   number=9,373,637 hash=231506..eb10cf age=1d6h30m size=1.02MiB
I​

下のURLに表示されるブロックの数字と、コンソール上にたまに出てくるブロックの数字がだいたい一緒になるまで待ちます。

待っている間に、truffle-config.jsを設定します。fromはmy_test_addressという環境変数からとってくる設定にしました。


   geth: {
     host: "127.0.0.1",     // Localhost (default: none)
     port: 8545,            // Standard Ethereum port (default: none)
     network_id: "*",       // Any network (default: none)
     from: my_test_address,
     gas: 8500000,
     gasPrice: 10000000000,
   },

次にgethにアカウント情報を設定します。参考URLはこちら

色々やってるうちに入れたので忘れてしまいましたが、「geth account import」でやった気がします。

次にアカウントがあることを確認して、パスワードを設定します。

>geth account update 0
INFO [09-30|13:43:13.912] Maximum peer count                       ETH=50 LES=0 total=50
INFO [09-30|13:43:13.947] Set global gas cap                       cap=50,000,000
WARN [09-30|13:43:13.951] -------------------------------------------------------------------
WARN [09-30|13:43:13.955] Referring to accounts by order in the keystore folder is dangerous!
WARN [09-30|13:43:13.958] This functionality is deprecated and will be removed in the future!
WARN [09-30|13:43:13.961] Please use explicit addresses! (can search via `geth account list`)
WARN [09-30|13:43:13.965] -------------------------------------------------------------------
Unlocking account 0 | Attempt 1/3
Password:
INFO [09-30|13:43:23.722] Unlocked account                         address=<インポートしたアドレス>
Please give a new password. Do not forget this password.
Password:
Repeat password:

>

次に、truffleコンソールでimportしました。gethのコマンドで入れるのとtruffle consoleで入れるのと二重になってる感があります。が、gethのほうだけだと動かなかったので両方必要なのかもしれません。

https://web3js.readthedocs.io/en/v1.5.2/web3-eth-personal.html#id31

>truffle consone --network geth
truffle(geth)> web3.eth.personal.importRawKey('<アカウントの秘密鍵>', '<このアカウントに設定するパスワード>');
'<インポートされたアカウント名が表示される>'
truffle(geth)>

続いて、Geth経由でのデプロイで使えるようにアンロックします。3つ目の1800は、アンロックする秒数です。

truffle(geth)> web3.eth.personal.unlockAccount('<アカウントのAddress>', '<このアカウントに設定したパスワード>', 1800);
true


参考にしたURL

次に、アカウントをアンロックできるオプションを追加してGethを起動します。rpcapiのパラメータで渡しているdbがエラーになっているのが気になりますが、動いています。

>geth --rinkeby --datadir "./fast" --syncmode "fast" --rpc --rpcapi="db,eth,net,web3,personal,web3" --cache=1024  --rpcport 8545 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --port "35555" --allow-insecure-unlock
INFO [09-30|14:05:56.540] Starting Geth on Rinkeby testnet...
INFO [09-30|14:05:56.575] Maximum peer count                       ETH=50 LES=0 total=50
WARN [09-30|14:05:56.578] The flag --rpc is deprecated and will be removed June 2021, please use --http
WARN [09-30|14:05:56.582] The flag --rpcaddr is deprecated and will be removed June 2021, please use --http.addr
WARN [09-30|14:05:56.585] The flag --rpcport is deprecated and will be removed June 2021, please use --http.port
WARN [09-30|14:05:56.587] The flag --rpccorsdomain is deprecated and will be removed June 2021, please use --http.corsdomain
WARN [09-30|14:05:56.592] The flag --rpcapi is deprecated and will be removed June 2021, please use --http.api
INFO [09-30|14:05:56.597] Set global gas cap                       cap=50,000,000
INFO [09-30|14:05:56.600] Allocated trie memory caches             clean=153.00MiB dirty=256.00MiB
INFO [09-30|14:05:56.603] Allocated cache and file handles         database=C:\Users\syund\eclipse-workspace\geth\fast\geth\chaindata cache=512.00MiB handles=8192
INFO [09-30|14:05:58.521] Opened ancient database                  database=C:\Users\syund\eclipse-workspace\geth\fast\geth\chaindata\ancient readonly=false
INFO [09-30|14:05:58.531] Persisted trie from memory database      nodes=355 size=50.43KiB time=0s gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-30|14:05:58.538] Initialised chain configuration          config="{ChainID: 4 Homestead: 1 DAO: <nil> DAOSupport: true EIP150: 2 EIP155: 3 EIP158: 3 Byzantium: 1035301 Constantinople: 3660663 Petersburg: 4321234 Istanbul: 5435345, Muir Glacier: <nil>, Berlin: 8290928, London: 8897988, Engine: clique}"
INFO [09-30|14:05:58.976] Initialising Ethereum protocol           network=4 dbversion=8
INFO [09-30|14:05:58.994] Loaded most recent local header          number=9,379,359 hash=3abbf7..2a7c8a td=15,833,161 age=8h33m15s
INFO [09-30|14:05:58.999] Loaded most recent local full block      number=0         hash=6341fd..67e177 td=1          age=4y6mo1w
INFO [09-30|14:05:59.003] Loaded most recent local fast block      number=9,379,359 hash=3abbf7..2a7c8a td=15,833,161 age=8h33m16s
INFO [09-30|14:05:59.009] Loaded last fast-sync pivot marker       number=9,381,306
INFO [09-30|14:05:59.056] Loaded local transaction journal         transactions=0 dropped=0
INFO [09-30|14:05:59.060] Regenerated local transaction journal    transactions=0 accounts=0
INFO [09-30|14:05:59.076] Allocated fast sync bloom                size=511.00MiB
INFO [09-30|14:05:59.079] Gasprice oracle is ignoring threshold set threshold=2
WARN [09-30|14:05:59.081] Unclean shutdown detected                booted=2021-09-30T13:39:59+0900 age=26m
WARN [09-30|14:05:59.084] Unclean shutdown detected                booted=2021-09-30T13:40:20+0900 age=25m39s
WARN [09-30|14:05:59.089] Unclean shutdown detected                booted=2021-09-30T13:41:25+0900 age=24m34s
WARN [09-30|14:05:59.093] Unclean shutdown detected                booted=2021-09-30T13:42:01+0900 age=23m58s
WARN [09-30|14:05:59.097] Unclean shutdown detected                booted=2021-09-30T13:45:09+0900 age=20m50s
WARN [09-30|14:05:59.101] Unclean shutdown detected                booted=2021-09-30T13:45:55+0900 age=20m4s
WARN [09-30|14:05:59.106] Unclean shutdown detected                booted=2021-09-30T13:47:10+0900 age=18m49s
WARN [09-30|14:05:59.109] Unclean shutdown detected                booted=2021-09-30T13:47:43+0900 age=18m16s
WARN [09-30|14:05:59.113] Unclean shutdown detected                booted=2021-09-30T13:48:02+0900 age=17m57s
INFO [09-30|14:05:59.116] Starting peer-to-peer node               instance=Geth/v1.10.8-stable-26675454/windows-amd64/go1.16.4
INFO [09-30|14:05:59.152] New local node record                    seq=26 id=682102485c6f7a94 ip=127.0.0.1 udp=35555 tcp=35555
INFO [09-30|14:05:59.159] Started P2P networking                   self=enode://ee0604e5e3ae33ae59841d172825eb52ae879ffe860969d42f45c39a47452cf9b274dc0751c7e41b9dc96976213226f3c13f18a9e4814a8a4b7db71f03144eeb@127.0.0.1:35555
INFO [09-30|14:05:59.161] IPC endpoint opened                      url=\\.\pipe\geth.ipc
ERROR[09-30|14:05:59.170] Unavailable modules in HTTP API list     unavailable=[db] available="[admin debug web3 eth txpool personal clique miner net]"
INFO [09-30|14:05:59.175] HTTP server started                      endpoint=127.0.0.1:8545 prefix= cors=* vhosts=localhost
INFO [09-30|14:06:07.012] New local node record                    seq=27 id=682102485c6f7a94 ip=58.70.122.165 udp=35555 tcp=35555
INFO [09-30|14:06:07.080] Initializing state bloom                 items=10,535,701 errorrate=0.000 elapsed=8.000s
INFO [09-30|14:06:09.485] Looking for peers                        peercount=0 tried=29 static=0
INFO [09-30|14:06:15.083] Initializing state bloom                 items=21,376,256 errorrate=0.000 elapsed=16.004s
INFO [09-30|14:06:19.702] Looking for peers                        peercount=0 tried=42 static=0
I

アンロックを再度行います。

>truffle consone --network geth
truffle(geth)> web3.eth.personal.unlockAccount('<アカウントのAddress>', '<このアカウントに設定したパスワード>', 1800);
true


truffle migrateで「"Migrations" exceeded the block limit」が起きる

ようやくデプロイできるかと思ったら。

Migrations dry-run (simulation)
===============================
> Network name:    'geth-fork'
> Network id:      4
> Block gas limit: 4700000 (0x47b760)


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

  Deploying 'Migrations'
  ----------------------

Error:  *** Deployment Failed ***

"Migrations" exceeded the block limit (with a gas value you set).
  * Block limit:  4700000 (0x47b760)
  * Gas sent:     8500000 (0x81b320)
  * Try:
     + Sending less gas.
     + Setting a higher network block limit if you are on a
       private network or test client (like ganache).

Gasの設定値を引き下げたら出なくなりました。

"Migrations" could not deploy due to insufficient funds

デプロイするためのETHを持ってないよって言われました。おかしい。MetaMask上は持ってるのに?Gethのsyncが終わってないかもと思って確認しましたが、最新まで追い付いています。

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

  Deploying 'Migrations'
  ----------------------

Error:  *** Deployment Failed ***

"Migrations" could not deploy due to insufficient funds
  * Account:  <使っているアカウントのaddress>
  * Balance:  0 wei
  * Message:  sender doesn't have enough funds to send tx. The upfront cost is: 8000000000000000 and the sender's account only has: 0
  * Try:
     + Using an adequately funded account
     + If you are using a local Geth node, verify that your node is synced.

うーん・・・どこかでrinkebyじゃなくてメインネット見てるとか?コンソールで確認しましたが、network idは4(Rinkeby)になっています。

truffle(geth)> web3.eth.net.getId();
4

わからないので、ここでアカウントを生成します。

>geth account new
INFO [09-30|14:55:54.518] 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:   <生成されたパスワード>
Path of the secret key file: C:\Users\syund\AppData\Local\Ethereum\keystore\<ファイル名>

MetaMaskにインポートします。MetaMaskのインポートから、JSONファイルをインポートします。

RinebyテストネットのEthをもらいます

Ethが増えたことを確認します。今回はMetaMaskで。

画像5

アンロックします

truffle(geth)> web3.eth.personal.unlockAccount('<アカウントのAddress>', '<このアカウントに設定したパスワード>', 1800);
true

truffle-config.jsで使用するアカウントとして環境変数にセットします

set MY_TEST_ADDRESS=<アカウントのAddress>

デプロイします。・・・やはり同じエラーが出ました。うーん・・・いや、Eth持ってるよ???

Migrations dry-run (simulation)
===============================
> Network name:    'geth-fork'
> Network id:      4
> Block gas limit: 4700000 (0x47b760)


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

  Deploying 'Migrations'
  ----------------------

Error:  *** Deployment Failed ***

"Migrations" could not deploy due to insufficient funds
  * Account:  0x1BBBab246B5f4E50D9e1c2574B93Afe8D57741C7
  * Balance:  0 wei
  * Message:  sender doesn't have enough funds to send tx. The upfront cost is: 8000000000000000 and the sender's account only has: 0
  * Try:
     + Using an adequately funded account
     + If you are using a local Geth node, verify that your node is synced.

gethにattachして確認してもやっぱり0

>geth attach http://127.0.0.1:8545
Welcome to the Geth JavaScript console!

> web3.eth.getBalance("0x1bbbab246b5f4e50d9e1c2574b93afe8d57741c7");
0

でもこれで、原因がgethだということがわかりました。gethのソフトウェアをバージョンアップしてみます。1.10.9に上げてみました。

アップデートしたらrpcが使えなくなってgethを起動できなくなったので、コマンドを修正します。今だったらlightモードでも動くのかもしれませんが、fastモードでもそんなに同期には時間がかからないのでこのままいきます。

geth --rinkeby --datadir "./fast" --syncmode "fast" --http --http.api="db,eth,net,web3,personal,web3" --cache=1024  --http.port 8545 --http.addr 127.0.0.1 --http.corsdomain "*" --port "35555" --allow-insecure-unlock


そして再びgetBalanceしたら・・・・見れた!Gethのバージョンのせいだったのかー!

>geth attach http://127.0.0.1:8545
Welcome to the Geth JavaScript console!

instance: Geth/v1.10.9-stable-eae3b194/windows-amd64/go1.17
coinbase: 0x4ef9663affb340585a3df42f253ac65765ebfdb0
at block: 9383206 (Thu Sep 30 2021 21:34:41 GMT+0900 (JST))
modules: eth:1.0 net:1.0 personal:1.0 rpc:1.0 web3:1.0

To exit, press ctrl-d or type exit
> eth.getBalance("0x1BBBab246B5f4E50D9e1c2574B93Afe8D57741C7");
3000000000000000000
>

デプロイできた!

3_deploy_AnimeLootPhysicalCharacteristics.js
============================================

  Deploying 'AnimeLootPhysicalCharacteristics2'
  ---------------------------------------------
  > transaction hash:    0x88b22aba19cf1e101b9ee0f0ccde1055be1011c289aa31a2353e4ac6aa2e8761
  > Blocks: 1            Seconds: 16
  > contract address:    0xC2b4372317059Bb3b0fbA09CD9a072E4FAC04186
  > block number:        9383242
  > block timestamp:     1633005821
  > account:             0x1BBBab246B5f4E50D9e1c2574B93Afe8D57741C7
  > balance:             2.983404675
  > gas used:            67066 (0x105fa)
  > gas price:           45 gwei
  > value sent:          0 ETH
  > total cost:          0.00301797 ETH


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


Summary
=======
> Total deployments:   3
> Final cost:          0.013252725 ETH


​AnimeLootがないとテスト出来ないけどどうしたらいいの?

AnimeLoot作ればいいじゃないかってことで、AnimeLootのソースを持ってきてローカルで動かすようにしました。そのままだと1つのファイルにいろいろなのが混ざっているので、別々に分けたりしました。

AnimeLoot.solの最初の部分はこんな感じになりました。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Base64.sol";

contract AnimeLoot is ERC721Enumerable, ReentrancyGuard, Ownable {

Base64については下に書いてあります。

Base64って何なの?

AnimeLootのソースの中で実態がわからなかったものがBase64です。色々調べたら、多分これということがわかりました。

ちょっと、大丈夫なのかはわからないです。


Etherscan上でAPIを叩けるようにする

なんとかrinkebyテストネットにデプロイすることができました。早速見てみると・・・ByteCodeしかない!勝手にアップされるんじゃないのか。

画像1

コードを入れる必要があるようです。今回はtruffle-plugin-verifyを使ってみます。参考にしたのはこれ。まずはパッケージを入れます。

>npm install -D truffle-plugin-verify
npm WARN deprecated querystring@0.2.1: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
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 @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/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-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-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-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 greeter@1.0.0 No repository field.

+ truffle-plugin-verify@0.5.15
added 9 packages from 8 contributors and audited 293 packages in 7.236s

9 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

次にtruffle-configに設定を入れます。

const etherscan_api_key = process.env["ETHERSCAN_API_KEY"];

module.exports = {
    // 何かの設定
   
 api_keys: {
   etherscan: etherscan_api_key
 },

 plugins: [
   'truffle-plugin-verify'
 ],


次にEtherscanでアカウントを作ります。

https://etherscan.io/register

ログインしてキーを作ります。

画像5

環境変数にセットします

>set ETHERSCAN_API_KEY=<取得したキー>

verifyを動かします

>truffle run verify AnimeLootPhysicalCharacteristics --network rinkeby --debug
DEBUG logging is turned ON
Running truffle-plugin-verify v0.5.15
Verifying AnimeLootPhysicalCharacteristics
Reading artifact file at C:\Users\syund\eclipse-workspace\greeter\client\src\contracts\AnimeLootPhysicalCharacteristics.json
Retrieving constructor parameters from https://api-rinkeby.etherscan.io/api?apiKey=DA4SJYUNDGW1RAP8E687Z7VSTXT3885YMG&module=account&action=txlist&address=0x7f1551278C9b9010679B4394231d657640E45dAa&page=1&sort=asc&offset=1
Constructor parameters retrieved: 0x
Sending verify request with POST arguments:
{

<途中省略>

 "codeformat": "solidity-standard-json-input",
 "contractname": "/contracts/AnimeLootPhysicalCharacteristics.sol:AnimeLootPhysicalCharacteristics",
 "compilerversion": "v0.8.8+commit.dddeac2f",
 "constructorArguements": ""
}
Checking status of verification request zwhltmrif2xv6l2jbm4kegbki5xetjpcbbeufvw8ibi2uig6j2
Pass - Verified: https://rinkeby.etherscan.io/address/0x7f1551278C9b9010679B4394231d657640E45dAa#code
Successfully verified 1 contract(s).

コードがアップされて、APIが叩けるようになりました!

https://rinkeby.etherscan.io/address/0x7f1551278C9b9010679B4394231d657640E45dAa#code

画像3

画像4


上からしばらくして、infura経由からGeth経由に変更して再度コードをアップしようと思ったら、network idが*だとだめだと。

>truffle run verify AnimeLootPhysicalCharacteristics2 --network geth --debug
DEBUG logging is turned ON
Running truffle-plugin-verify v0.5.15
Etherscan has no support for network geth with id *


truffle-config.jsを修正します。network_idを*から4に。

    geth: {
     host: "127.0.0.1",     // Gethを起動している場所。127.0.0.1はローカル。
     port: 8545,            // Gethを起動するときのポート
     network_id: 4,       // *だとtruffle-plugin-verifyでコードがあげられない
     from: my_test_address,
     gas: 4698712,
     gasPrice: 45000000000,
     skipDryRun: false,
   },


そして再びverify。こんどは成功。

>truffle run verify AnimeLootPhysicalCharacteristics2 --network geth --debug
DEBUG logging is turned ON
Running truffle-plugin-verify v0.5.15
Verifying AnimeLootPhysicalCharacteristics2
Reading artifact file at C:\Users\syund\eclipse-workspace\AnimeLootPhysicalCharacteristics\client\src\contracts\AnimeLootPhysicalCharacteristics2.json
Retrieving constructor parameters from https://api-rinkeby.etherscan.io/api?apiKey=DA4SJYUNDGW1RAP8E687Z7VSTXT3885YMG&module=account&action=txlist&address=0xC2b4372317059Bb3b0fbA09CD9a072E4FAC04186&page=1&sort=asc&offset=1
Constructor parameters retrieved: 0x
Sending verify request with POST arguments:
{
 "apikey": "<APIキー>",
 "module": "contract",
 "action": "verifysourcecode",
 "contractaddress": "0xC2b4372317059Bb3b0fbA09CD9a072E4FAC04186",
 "sourceCode": "{\"language\":\"Solidity\",\"sources\":{\"/contracts/AnimeLootPhysicalCharacteristics.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\r\\npragma solidity ^0.8.0;\\r\\n\\r\\ncontract AnimeLootPhysicalCharacteristics2 {\\r\\n    \\r\\n    constructor() {}\\r\\n\\r\\n}\\r\\n\"}},\"settings\":{\"remappings\":[],\"optimizer\":{\"enabled\":true,\"runs\":200},\"evmVersion\":\"london\",\"libraries\":{}}}",
 "codeformat": "solidity-standard-json-input",
 "contractname": "/contracts/AnimeLootPhysicalCharacteristics.sol:AnimeLootPhysicalCharacteristics2",
 "compilerversion": "v0.8.7+commit.e28d00a7",
 "constructorArguements": ""
}
Checking status of verification request 9n32sfqsn3wmg4knapc5vzmviwvfxw6pjyqhng25i2t8j4jnf3
Pass - Verified: https://rinkeby.etherscan.io/address/0xC2b4372317059Bb3b0fbA09CD9a072E4FAC04186#code
Successfully verified 1 contract(s).

コードがアップされました。

https://rinkeby.etherscan.io/address/0xC2b4372317059Bb3b0fbA09CD9a072E4FAC04186#code

画像6


Gethを起動すると「Aborting/resuming state snapshots all the time」が出続ける

gethの起動コマンドのオプションに「--snapshot=false」を追加すると解決しました。参考はこちら

https://ethereum.stackexchange.com/questions/94289/aborting-resuming-state-snapshots-all-the-time

Web版RemixIDEを使う

どうしてもGethやinfuraでのデプロイが安定してできないので、RemixIDEを使ってみます。参考URLはこちら

とりあえず、この記事を参考にするとBSCのメインネットで独自トークンが発行できました。RemixIDEすごいかもしれない。

画像7

AnimeLootを開発するために環境を整えます。

■GitHubのアクセストークンを設定する

RemixIDEの左下の歯車から設定できます。

GitHubのアクセストークンはこちらから。

GitHubにあげてみたのがこちら。

https://gist.github.com/syunduel/7a034dc9da152fc68d1984d679c930b9

いや、なんか思ってたのと違う。ディレクトリ構成は保存されないのね。というか、これしかないとEtherscanにソース貼れないのでは?

ローカルファイルシステムと連動させたほうが良いのかもしれない。

■ローカルホストと同期する

参考にしたのはこちら

すんなり入りました

>npm install -g @remix-project/remixd
npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
C:\Users\syund\AppData\Roaming\npm\remixd -> C:\Users\syund\AppData\Roaming\npm\node_modules\@remix-project\remixd\bin\remixd.js
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules\@remix-project\remixd\node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ @remix-project/remixd@0.5.2
added 186 packages from 130 contributors in 23.928s

起動してみます。接続できました。でもなんだか「https://remix.ethereum.org」はやめとけって言われています。

>remixd -s "F:\work\AnimeLootPhysicalCharacteristics"  -u https://remix.ethereum.org
[INFO] you are using the latest version 0.5.2
[WARN] You may now only use IDE at https://remix.ethereum.org to connect to that instance
[WARN] Any application that runs on your computer can potentially read from and write to all files in the directory.
[WARN] Symbolic links are not forwarded to Remix IDE

[INFO] Tue Oct 05 2021 22:40:07 GMT+0900 (GMT+09:00) remixd is listening on 127.0.0.1:65520
[INFO] Tue Oct 05 2021 22:40:07 GMT+0900 (GMT+09:00) slither is listening on 127.0.0.1:65523

ちょっと調べてみましたが、良い方法が見つからなかったのでこのままにしておきます。

Web版RemixIDEを起動してlocalhostを選択すると、ローカルのファイルが見えました。

画像8

次に、RemixIDEでコンパイルしたファイルの置き場所を変更したいです。が、その方法は見つかりませんでした。

コンパイルはコンパイルしたいファイルを開いてからコンパイルって感じですね。無事にできました。

画像9

■RemixIDEでデプロイしたスマートコントラクトにソースをアップする(Ethereum)

参考にしたのはこちら。プラグインがあるんですね。

https://medium.com/remix-ide/verify-contracts-on-remix-with-sourcify-2912004d9c84

プラグインから「ETHERSCAN - CONTRACT VERIFICATION」を探してinstallします。

画像10

左に追加されたETHERSCANのアイコンをクリックします。Etherscanで作成した「API KEY」を保存します。

「Verify Contract」をクリックすると、ソースがアップできました。

画像11

画像12


■RemixIDEでデプロイしたスマートコントラクトにソースをアップする(Polygon)

Ethereumと同じように出来るかと思いきや、プラグインが対応しているのはEthereumだけで、PolygonとBSCには対応していないようです。

Hardhatを使う方法と、multisolを使う方法があるようです。

Hardhatはinfura経由でちょっと嫌なので、multisolを使ってみます。

Windowsなのでバイナリをダウンロードします

https://github.com/paulrberg/multisol

適当なところに置きます

画像13

呼び出してみます。なんかエラーが出ました。

>E:\app\multisol\multisol-1.1.0-x86_x64-pc-windows-gnu.exe contracts\AnimeLootPhysicalCharacteristics.sol
Couldn't get an absolute path to the contract: "IERC721.sol"

解決方法を探してみましたが、見つけられませんでした。。。


truffleで上げようとしてみます。truffle-config.jsに設定を追加します。

        
   mumbai: {
     provider: function() { 
       return new HDWalletProvider(mnemonic_polygon, mumbai_infura_url_wss);
     },
     network_id: 80001,
     gas: 5000000,
     gasPrice: 45000000000,
     confirmations: 2,
     skipDryRun: true,
     websocket: true,
     timeoutBlocks: 50000,
     networkCheckTimeout: 1000000
   },

コマンド打ってみます。ないよって言われました。見ているjsonが、Remixでコンパイルしたjsと違うのが気になります。

>truffle run verify AnimeLootPhysicalCharacteristics --network mumbai --debug
DEBUG logging is turned ON
Running truffle-plugin-verify v0.5.15
Verifying AnimeLootPhysicalCharacteristics
Reading artifact file at F:\work\AnimeLootPhysicalCharacteristics\client\src\contracts\AnimeLootPhysicalCharacteristics.json
No instance of contract AnimeLootPhysicalCharacteristics found for network id 80001
Failed to verify 1 contract(s): AnimeLootPhysicalCharacteristics

ディレクトリを合わせてみます。truffle-config.jsのビルドdirを変更します

  contracts_build_directory: "./contracts/artifacts",

同じエラーです。ダメみたいです。何をもってデプロイされているかどうかを見ているのかがわかりません。中身を見ても、特にIDらしきものは入っていません。

デプロイするのはRemixでやりたい、でもRemixで作ったコードでverifyができない。うーん。。。

flattenする方法を見つけたのでやってみます。



Sol Managerを入れます

https://sourceforge.net/projects/solmgr/files/solmgr/0.1.6/solmgr-0.1.6-bin.zip/download?use_mirror=master&download=

・・・なんかすごい大変そうだぞ。別の方法を探そう

Remixにflattenプラグインがあるらしいので試してみます。

コンパイルしてから巻物みたいなメニューを開いてFlattenすると、ファイルが出来ました

画像14

ダウンロードもできました

画像15

これをあげてみます。設定はこれでいきます

画像16

flattenしたコードの中身を貼り付けます

画像17

verifyすると・・・エラーになりました。うーんContextが見つけられないのか。何故なのか。

画像18

ソースコードで明示的にContextをインポートしたら、verifyできました!

画像19

画像20

claimもできました!ただ、Polygonのテストネットは反応が遅くて、claim押してから1分くらい経ってからMetaMaskが反応してました。あと、ガス代も足さないとガス不足(out of Gas)でエラーになりました

画像21

画像22














この記事が気に入ったらサポートをしてみませんか?