ethers js を使用して堅牢なコントラクトをデプロイする方法


メタマスクがインストールされていて、シード フレーズを知っていると仮定すると、「ethers」と「fs」を使用してコントラクトを展開する手順は次のとおりです.
  • コントラクトを .bin および .abi ファイルにコンパイルします
  • ロード 'ethers' と 'fs'
  • 'ethers' の 'provider'、'Wallet'、および 'connect' メソッドを使用して 'signer' オブジェクトを作成します
  • 「ContractFactory」メソッドから契約インスタンスを作成します
  • deploy メソッドを promise として使用する
  • ここでは、たとえば web3 プロバイダーとして「getblock」を使用しました ( https://getblock.io/docs/get-started/auth-with-api-key/ を参照).他の選択肢は「quicknode」、「alchemy」、「infura」です.

  • コードを BSC テストネットにデプロイしますが、同じ手順が、Avalanche Contract Chain (C-Chain)、Binance Smart Chain (BSC) メインネット、Fantom Opera、Polygon など、他の Ethereum Virtual Machine(EVM) 互換チェーンにも適用されます.等

    コントラクト展開用の nodejs スクリプトは次のとおりです.

    //load 'ethers' and 'fs'
    
    ethers = require('ethers');
    fs = require('fs');
    
    //Read bin and abi file to object; names of the solcjs-generated files renamed
    bytecode = fs.readFileSync('storage.bin').toString();
    abi = JSON.parse(fs.readFileSync('storage.abi').toString());
    
    //to create 'signer' object;here 'account'
    const mnemonic = "<see-phrase>" // seed phrase for your Metamask account
    const provider = new ethers.providers.WebSocketProvider("wss://bsc.getblock.io/testnet/?api_key=<your-api-key>");
    const wallet = ethers.Wallet.fromMnemonic(mnemonic);
    const account = wallet.connect(provider);
    
    const myContract = new ethers.ContractFactory(abi, bytecode, account);
    
    //Using 'deploy method 'in 'async-await' 
    async function main() {
    // If your contract requires constructor args, you can specify them here
    const contract = await myContract.deploy();
    
    console.log(contract.address);
    console.log(contract.deployTransaction);
    }
    
    main();
    


    上記のコードでは、「アカウント」は ethers ドキュメントの「署名者」です

    ethers.ContractFactory( interface , bytecode [ , signer ] )
    


    契約を展開する際に問題が発生した場合は、遠慮なく話し合いで質問してください.