• 以太坊私链部署智能合约


    编写智能合约保存为test.sol

    # 返回输入的平方
    pragma solidity ^0.7.5;
    
    contract test{
        function multiply(uint256 input) public returns(uint256 res){
            return input * input;
        }
    }

    安装solc,用于编译 .sol文件

    npm install -g solc

    编译,生成两个文件:.abi 和 .bin

    solcjs test.sol --bin --abi --optimize -o ./

    部署智能合约

    # 在节点控制台输入abi = "此处为生成的.abi文件中的内容"
    abi = [{"inputs":[{"internalType":"uint256","name":"input","type":"uint256"}],"name":"multiply","outputs":[{"internalType":"uint256","name":"res","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]
    
    contract = eth.contract(abi)
    
    # bytecode = "0x此处为.bin文件中的内容"
    bytecode = "0x6080604052348015600f57600080fd5b5060948061001e6000396000f3fe6080                                                                  604052348015600f57600080fd5b506004361060285760003560e01c8063c6888fa114602d575b60                                                                  0080fd5b604760048036036020811015604157600080fd5b50356059565b60408051918252519081                                                                  900360200190f35b80029056fea26469706673582212209edf68a7757d17f0de352322d58f19264a                                                                  f9a5ec3493dfb6e71a3d0a69d4317264736f6c63430007050033"
    
    initializer = {from: web3.eth.accounts[0], data: bytecode, gas:300000};
    
    # 这里需要先解锁账户
    personal.unlockAccount(eth.accounts[0],"你的密码")
    
    token = contract.new(initializer)
    
    # 然后启动挖矿,对合约地址进行确认,而后可以停止挖矿
    miner.start(1)

    与合约交互

    # 获取合约地址
    token.address
    # "0xe5a8779a4fae7946a7c1c5ea7760b78d2c0b94dc"
    
    abi = [{"inputs":[{"internalType":"uint256","name":"input","type":"uint256"}],"name":"multiply","outputs":[{"internalType":"uint256","name":"res","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]
    
    # 获取合约对象
    MyContract = eth.contract(abi)
    
    # 实例化合约
    myContract = MyContract.at("0xe5a8779a4fae7946a7c1c5ea7760b78d2c0b94dc")
    
    # 调用, 返回结果:25
    myContract.multiply.call(5)

    作者:mhly

    博客:https://www.cnblogs.com/mhly

    本文采用BY-NC-SA许可协议,转载请注明出处

  • 相关阅读:
    JS中关于clientWidth offsetWidth scrollWidth 等的含义
    javascript中数组concat()join()split()
    我的大数据学习路线(持续更新)
    java多线程-学习笔记
    java多线程-线程交互&互斥&同步
    java多线程-关键人物程咬金
    java多线程-军队战争
    java多线程-两个演员线程
    pytorch-Flatten操作
    龙良曲pytorch学习笔记_迁移学习
  • 原文地址:https://www.cnblogs.com/mhly/p/14024985.html
Copyright © 2020-2023  润新知