

在 Etherscan 上提交智能合約原始碼認證
source link: https://www.frank.hk/blog/smart-contract-sourcecode-verification/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

這篇文章假設大家使用 hardhat 來進行智能合約開發。關於 hardhat 我有時間再詳細寫一寫懶人教學 😅。
大家如果常去 Etherscan 上查看智能合約 Smart Contract, 大概會看到兩種情況,第一種是如下這樣,在 Contract 下面看到是一堆「亂碼」,這堆「亂碼」其實是編譯過後的智能合約 ByteCode (字節碼),這明顯不是給人類閱讀的。
另一種則是如下圖所示,在 Contract Tab 旁邊能夠看到一個綠色的✓,下面能夠看到智能合約的原始代碼,並且可以直接在 Etherscan 上讀取,調用智能合約的 function。
明顯第二種合約給人的感覺會自信很多, 因為所有人都能夠清楚看到智能合約具體的運行邏輯,一切公開透明,不怕「黑箱作業」。
那麼如何做到在 Etherscan 上「開放原始碼」呢?
一種方法是手動在 Etherscan 上提交原始碼,透過提交智能合約的地址,選擇編譯器版本,上載智能合約的原始碼等等一系列步驟之後便可以做到。
但這種方法的壞處是非常麻煩,要確保選對編譯器版本,上載所有需要上載的檔案,包括一些第三方的 library。一旦上載的原始碼檔案出現錯漏,則無法完成認證。
有沒有更好的方法呢?
隆重介紹 @nomiclabs/hardhat-etherscan
使用 @nomiclabs/hardhat-etherscan 這個 npm package,能夠超級簡單的完成智能合約認證。這個 package 集成了 Etherscan 的 API,透過 API 的形式自動完成原始碼認證,免去了繁瑣的手動步驟。
首先我們需要在 Etherscan 上有一個賬戶,然後免費申請一個 API key。 按此前往。
在上述頁面中按下「ADD」即可申請一個全新的 API Key。得到這個 API Key 之後,將它放入你的 .env 檔案中。(假設你用 .env 檔案來保存環境變數)
安裝 @nomiclabs/hardhat-etherscan
, 使用 npm 或者 yarn 的方式安裝。這個應該不用多說了吧,是人都會了。
現在我們需要設定 hardhat.config.js
。
首先,要在 hardhat.config.js
頂部引入這個 package
然後,在 hardhat.config.js
添加如下設定:
在完成智能合約編譯後,透過以下指令即可驗證智能合約原始碼:
至此,打開 Etherscan ,就可以看到我們的智能合約已經認證成功啦。
DeployDemo.js 參考:
訂閱我的網站,接收更新以及其他有趣的消息 😙 。 訂閱不收費,走過路過別錯過。
Subscribe to my website, I will email you if any new posts or interesting stuff available.
如果你喜歡我的內容,請考慮用一杯咖啡支持我一下吧,非常感謝 🥰 。
If you like my contents, please support me via BuyMeCoffee, Thanks a lot.
其它相關文章
評論內容
暱稱 *
電郵(頭像及區分用途,保密且不會顯示) *
WRITTEN BY
Frank Shi
Frank, 居住在香港, 從事 IT 行業,並為這個行業投身了大半生的精力。 沒事喜歡寫寫程式,看看書,畫畫圖,可他並不是一個『宅男』,他很喜歡旅行,遠的去過約旦,近的去過深水埗,每到一個地方,都讓他對這個世界有不同的認識。他也很喜歡寫網誌,錄播客,發 Instagram,就這樣簡單而快樂的生活著。
Frank is an IT guy living in Hong Kong who was majoring in Biology Engineering back to college. Because of the endless love and passion to IT, he changed his direction to Information Technology and got a Master Degree in IT field. What he loves to do including coding, building stuff, gadgets, drawing, traveling and taking (sometimes boring ) photos.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK