编写智能合约保存为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)