本文主要是介绍【区块链】Ubuntu以太坊ganache和truffle增加一个新合约,并完成部署,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在contracts下新建一个文件mathControl.sol
pragma solidity >=0.4.22 <0.9.0;contract MathContract {function add(uint a,uint b) public pure returns(uint){return a+b;}function sub(uint a,uint b) public pure returns(uint) {return a-b;}function mul(uint a,uint b) public pure returns(uint) {return a*b;}
}
在migrations下新建一个部署合约的js文件:2_initial_migration.js
//const Migrations = artifacts.require("Migrations");
var Math=artifacts.require("./MathContract.sol");module.exports = function (deployer) {deployer.deploy(Math);
};
在test目录下新建一个执行智能合约的js文件:mathcontract.js
var MathContract=artifacts.require("MathContract")contract('MathContract',function(accounts){it("first",function(){return MathContract.deployed().then(function(instance){console.log(instance.address)instance.add(1,1).then(function(result) {console.log(result)assert.equal(result,2,"add prompt");})instance.sub(5,1).then(function(result) {console.log(result)assert.equal(result,4,"sub prompt");})instance.mul(5,2).then(function(result) {console.log(result)assert.equal(result,10,"mul prompt");})})})it("sencode",function(){return MathContract.deployed().then(function(instance){console.log(instance.address)instance.add(1,1).then(function(result) {console.log(result.toNumber())assert.equal(result,2,"add prompt");})instance.sub(5,1).then(function(result) {console.log(result.toNumber())assert.equal(result,4,"sub prompt");})instance.mul(5,2).then(function(result) {console.log(result.toNumber())assert.equal(result,10,"mul prompt");})})})})
合约编译:
truffle compile
合约部署:
truffle migrate
合约调用:
truffle test ./test/mathcontract.js
运行结果:
这篇关于【区块链】Ubuntu以太坊ganache和truffle增加一个新合约,并完成部署的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!