当前位置: 首页 > article >正文

合约编译部署基本流程

文章目录

    • 合约编译部署基本流程
      • 项目参考
      • 准备Infura Project
      • 准备私钥
      • 准备测试币
      • 准备项目
      • 执行项目
    • 详细
      • 合约
      • index.js
      • package.json

合约编译部署基本流程

项目参考

https://github.com/Dapp-Learning-DAO/Dapp-Learning/blob/main/basic/01-web3js-deploy/README-cn.md

准备Infura Project

https://developer.metamask.io/

本项目发送交易到 Infura , 需要创建相应的 Infura Project, 可以获取相应的PROJECT ID。

在这里插入图片描述
注册登录,完成步骤。
在这里插入图片描述点击设置看到api,就是需要的项目id。

在这里插入图片描述
下面需要勾选以太坊的测试网络。

准备私钥

在MetaMask的账户详情中可以显示私钥。

在这里插入图片描述

准备测试币

准备测试币。可参考上一篇

准备项目

替换准备的私钥和项目id。
在这里插入图片描述

执行项目

node index.js

在这里插入图片描述

然后查看infura,发现会有请求。

在这里插入图片描述部署成功会显示合约地址,根据合约地址可以在以太坊测试网络上查看到相应的信息。

在这里插入图片描述

详细

合约

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

contract Incrementer {
    uint256 public number;

    constructor(uint256 _initialNumber) {
        number = _initialNumber;
    }

    function increment(uint256 _value) public {
        number = number + _value;
    }

    function reset() public {
        number = 0;
    }

    function getNumber() public view returns (uint256) {
        return number;
    }
}

index.js

let { Web3 } = require('web3');
let solc = require('solc');
let fs = require('fs');

// Get privatekey from environment
require('dotenv').config();
let privatekey = process.env.PRIVATE_KEY;
console.log("privatekey:", privatekey);
if (privatekey.slice(0, 2) !== '0x') privatekey = '0x' + privatekey;

// Load contract
const source = fs.readFileSync('Incrementer.sol', 'utf8');

// compile solidity
const input = {
  language: 'Solidity',
  sources: {
    'Incrementer.sol': {
      content: source,
    },
  },
  settings: {
    outputSelection: {
      '*': {
        '*': ['*'],
      },
    },
  },
};

const compiledCode = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = compiledCode.contracts['Incrementer.sol']['Incrementer'];

// Get bin & abi
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;

// Create web3 with sepolia provider,you can change sepolia to other testnet
const web3 = new Web3('https://sepolia.infura.io/v3/' + process.env.INFURA_ID);

// Create account from privatekey
const accounts = web3.eth.accounts.wallet.add(privatekey);

/*
   -- Deploy Contract --
*/
const Deploy = async () => {
  // Create contract instance
  const deployContract = new web3.eth.Contract(abi);

  // Create Tx
  const deployTx = deployContract.deploy({
    data: '0x' + bytecode,
    arguments: [0], // Pass arguments to the contract constructor on deployment(_initialNumber in Incremental.sol)
  });

  // optionally, estimate the gas that will be used for development and log it
  const gas = await deployTx.estimateGas({
    from: accounts,
  });
  console.log('estimated gas:', gas);

  try {
    // Deploy the contract to the Ganache network
    // Your deployed contrac can be viewed at: https://sepolia.etherscan.io/address/${tx.options.address}
    // You can change sepolia in above url to your selected testnet.
    const tx = await deployTx.send({
      from: accounts[0].address,
      gas,
      // gasPrice: 10000000000,
    });
    console.log('Contract deployed at address: ' + tx.options.address);
  } catch (error) {
    console.error(error);
  }
};

// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
Deploy()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

package.json

{
  "name": "Example01-deploy-contract",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.3.1",
    "solc": "0.8.0",
    "web3": "^4.0.3"
  }
}

http://www.kler.cn/a/592168.html

相关文章:

  • Spring(8)——MyBatis入门(2)
  • pycharm运行OpenCV项目踩坑记录
  • 3D开发工具HOOPS SDK:赋能CAM软件开发的利器
  • 以太网安全管理实验——ARP欺骗
  • Deepseek本地部署及本地知识库搭建(保姆级截图)
  • VIVO手机如何实现证件照换底色?证件照换底色技巧分享
  • 【RabbitMQ】RabbitMQ的基本架构是什么?包括哪些核心组件?
  • NIC数据包的接收与发送
  • 【STL】string类用法介绍及部分接口的模拟实现
  • pnpm创建vite
  • 蓝桥杯第13届真题2
  • C++项目:高并发内存池_上
  • 【云原生之kubernetes实战】在k8s环境中高效部署minio对象存储(详细教程)
  • pytorch 笔记:张量索引的维度扩展规则
  • python二级每日十题
  • JS逆向_腾讯点选_VMP补环境
  • (五)Reactor核心-前置知识4
  • (六)Reactive-Stream 响应式流
  • 霍尔传感器与电流互感器的区别
  • 男女搭配(数学思维)