📜  如何在以太坊上简单地部署智能合约?

📅  最后修改于: 2022-05-13 01:55:19.036000             🧑  作者: Mango

如何在以太坊上简单地部署智能合约?

智能合约是驻留在区块链上的代码块。它就像一个以太坊账户,但外部账户和智能合约之间有一个关键的区别。与智能合约不同,外部账户可以连接到多个以太坊网络(Rinkebey、Kovan、main 等),而智能合约仅特定于一个单独的网络(部署它的网络)。部署智能合约时,它会在网络上创建一个实例(合约账户)。可以在网络或多个网络上创建智能合约的多个实例。智能合约的部署是通过使用字节码向网络发送交易来完成的。

部署到本地网络

模拟器可用于在本地网络上部署智能合约,例如。 Ganache-cli。它会处理一切,用户不必担心交易所需的安全性和 gas 数量,因为一切都发生在本地测试网络上。所要做的就是将 ganache 提供程序作为参数传递给 web3 实例(web3 促进了区块链网络和 js 应用程序之间的连接)。

部署到本地测试网络

部署到实际的以太坊网络

在将智能合约部署到实际的以太坊网络之前,请确保帐户中有一些以太币。部署合约就像发送交易一样,它需要一些 gas 来处理。与在本地网络上部署不同,交易需要一些时间才能完成(15 秒到 5 分钟之间的任何时间)。 Web3 用于与网络交互的方式与在本地部署中完成的方式相同,除了自定义将传递到 web3 实例的提供程序。可以使用 Infura,而不是创建我们自己的连接到以太坊网络的节点。它是一个公共 API,可以访问已经托管在以太坊网络上的 Infura 节点。只需注册 Infura 并获得一个端点,该端点将在代码中用于部署智能合约。

部署到实际的以太坊网络



example.sol-下面是用于测试的示例 Solidity 代码。它所做的只是设置一个公共变量作为发件人的地址。

Solidity
// Solidity program to implement
// the above approach
pragma solidity ^0.8.4;
 
// Creating a contract named Example
contract Example
{
    // Public variable of type address
    address public manager;
 
    // Constructor function to set manager
    // as address of sender
     constructor()
     {
        manager = msg.sender;
     }
}


Javascript
// Javascript file to implement
// the above approach
const path = require("path");
const fs = require("fs");
const solc = require("solc");
 
// remember to change line 8 to your
// own file path. Make sure you have your
// own file name or contract name in line
// 13, 28 and 30 as well.
 
const examplePath = path.resolve(__dirname, "contracts", "example.sol");
const source = fs.readFileSync(examplePath, "utf-8");
 
var input = {
    language: 'Solidity',
    sources: {
        'example.sol': {
            content: source
        }
    },
    settings: {
        outputSelection: {
            '*': {
                '*': ['*']
            }
        }
    }
};
 
var output = JSON.parse(solc.compile(JSON.stringify(input)));
 
var interface = output.contracts["example.sol"]["example"].abi;
 
var bytecode = output.contracts['example.sol']["example"].evm.bytecode.object;
 
module.exports = { interface, bytecode };


Javascript
const HDWalletProvider = require("truffle-hdwallet-provider");
 
// Web3 constructor function.
const Web3 = require("web3");
 
// Get bytecode and ABI after compiling
// solidity code.
const { interface, bytecode } = require("file-path");
 
const provider = new HDWalletProvider(
  "mnemonic phrase",
  // Remember to change this to your own phrase!
  "-"
  // Remember to change this to your own endpoint!
);
 
// Create an instance of Web3 and pass the
// provider as an argument.
const web3 = new Web3(provider);
 
const deploy = async () => {
  // Get access to all accounts linked to mnemonic
  // Make sure you have metamask installed.
  const accounts = await web3.eth.getAccounts();
 
  console.log("Attempting to deploy from account", accounts[0]);
 
  // Pass initial gas and account to use in the send function
  const result = await new web3.eth.Contract(interface)
    .deploy({ data: bytecode })
    .send({ gas: "1000000", from: accounts[0]});
 
  console.log("Contract deployed to", result.options.address);
};
 
deploy();
 
// The purpose of creating a function and
// calling it at the end -
// so that we can use async await instead
// of using promises


步骤 1-通过运行以下命令安装所需的依赖项-

npm i solc@0.8.4 truffle-hdwallet-provider@1.0.17 web3@1.3.5

确保为以下脚本安装相同版本以成功运行。

第 2 步 -注册 Infura 并在特定的以太坊网络上创建一个项目以访问端点。端点将需要在已经托管在以太坊网络上的 infura 节点上部署智能合约。在 infura 上创建一个项目

  • 单击创建一个新项目。
  • 给它一个名字。
  • 选择要在其上部署智能合约的网络。
  • 在 infura 上最多可以免费创建 3 个项目。

在 Infura 上创建项目在 infura 上创建一个项目

第 3 步– 访问字节码和 ABI(编译智能合约)。 Solidity 编译器提供了大量代码作为输出,如果需要,可以将输出打印到控制台。仅从以下脚本的输出中提取相关部分(与部署相关),即字节码和接口。

Compile.js-下面是 javascript 文件。



Javascript

// Javascript file to implement
// the above approach
const path = require("path");
const fs = require("fs");
const solc = require("solc");
 
// remember to change line 8 to your
// own file path. Make sure you have your
// own file name or contract name in line
// 13, 28 and 30 as well.
 
const examplePath = path.resolve(__dirname, "contracts", "example.sol");
const source = fs.readFileSync(examplePath, "utf-8");
 
var input = {
    language: 'Solidity',
    sources: {
        'example.sol': {
            content: source
        }
    },
    settings: {
        outputSelection: {
            '*': {
                '*': ['*']
            }
        }
    }
};
 
var output = JSON.parse(solc.compile(JSON.stringify(input)));
 
var interface = output.contracts["example.sol"]["example"].abi;
 
var bytecode = output.contracts['example.sol']["example"].evm.bytecode.object;
 
module.exports = { interface, bytecode };

第 4 步– 从 chrome 网上商店向 google chrome 添加 Metamask 扩展。

元掩码扩展

步骤 5 – 一旦可以访问字节码和接口,所需要做的就是使用之前安装的 truffle-hdwallet-provider 创建一个具有自己的助记词和 infura 端点的提供程序。创建一个 web3 实例并将提供程序作为参数传递。最后,使用以字节码为参数的 deploy 方法来部署智能合约。

部署.js

Javascript

const HDWalletProvider = require("truffle-hdwallet-provider");
 
// Web3 constructor function.
const Web3 = require("web3");
 
// Get bytecode and ABI after compiling
// solidity code.
const { interface, bytecode } = require("file-path");
 
const provider = new HDWalletProvider(
  "mnemonic phrase",
  // Remember to change this to your own phrase!
  "-"
  // Remember to change this to your own endpoint!
);
 
// Create an instance of Web3 and pass the
// provider as an argument.
const web3 = new Web3(provider);
 
const deploy = async () => {
  // Get access to all accounts linked to mnemonic
  // Make sure you have metamask installed.
  const accounts = await web3.eth.getAccounts();
 
  console.log("Attempting to deploy from account", accounts[0]);
 
  // Pass initial gas and account to use in the send function
  const result = await new web3.eth.Contract(interface)
    .deploy({ data: bytecode })
    .send({ gas: "1000000", from: accounts[0]});
 
  console.log("Contract deployed to", result.options.address);
};
 
deploy();
 
// The purpose of creating a function and
// calling it at the end -
// so that we can use async await instead
// of using promises

输出:

Contract is deployed to 0x8716443863c87ee791C1ee15289e61503Ad4443c

现在合约已部署在网络上,可以使用 remix IDE 测试其功能,或者可以创建一个接口与网络上的智能合约进行交互。

使用 Remix IDE 与已部署的智能合约交互

Remix 可用于连接到实际的以太坊网络并与已部署的智能合约进行交互。这是与已部署的智能合约交互的最简单方法,而无需制作花哨的前端。

步骤 1-在 Chrome 浏览器中打开 Remix IDE,复制已部署智能合约的 Solidity 代码并将其粘贴到 IDE 中的 Ballot.sol 文件中。通过单击侧边栏上的“S”图标切换到solidity 编译器并编译它。

打开混音IDE

第 2 步 -从侧边栏导航到部署和运行事务,然后从环境下拉列表中选择注入的 web3。它是由 metamask 注入浏览器的 web3 实例。它还可以访问所有帐户。

部署和运行事务

第 3 步 -在“地址”字段中复制已部署的智能合约的地址,而不是部署智能合约。在您输入有效地址之前,此按钮将被禁用。单击按钮后,可以看到智能合约中的功能列表。可以使用这些函数按钮与已部署的智能合约进行交互。由于“example.sol”只有一个变量,manager。单击此按钮将提供部署它的帐户的地址作为输出。

输出