叫嚣着学只能合约好几个月了,不管怎么样今天必须把简单东西过一遍,军令状!!!!
这种贴代码的我实在是不想贴在我的笔记上,就放在CSDN上吧。
分为三部分,首先是创建一个智能合约,这个合约只有个名字
智能合约用的就是solidity
// the file is for creating smart contract
pragma solidity ^0.5.0;
contract Marketplace {
string public name;
constructor() public {
name = "Dapp University Marketplace";
}
}
接着要把合约部署到ganache中,也就是上链,当然,上链只能有一次,这应该知道吧。这里用的就是js了
//the file is for deploy smart contract to ganache
const Marketplace = artifacts.require("Marketplace");
module.exports = function(deployer){
deployer.deploy(Marketplace );
};
最后尝试着调用这个合约。调用的时候要检查这个合约的地址,因为我们的ganache是通过网络挂在PC上的,还检查了这个合约的名字,这里也是JS
//it's for calling smartcontract
const Marketplace = artifacts.require('./Marketplace.sol') //import the contract into the test file, of course the smartcontact is defined in this file
contract('Marketplace', (accounts) =>{
let marketplace
before(async () => {
marketplace = await Marketplace.deployed()//deployed这个函数是异步的,await关键字为了将异步变为同步
})
describe('deployment', async() => { //mocha which is a framework of js
it('deploys successfully', async()=> {
const address = await marketplace.address
assert.notEqual(address, 0x0) //chai for assert
assert.notEqual(address, null)
assert.notEqual(address, '')
assert.notEqual(address, undefined)
})
it('has a name', async() => {
const name = await marketplace.name()
assert.equal(name, 'Dapp University Marketplace')
})
})
})
注意这个await关键字。因为合约的部署是异步的,这很好理解,上链的什么东西都很慢的,异步肯定是最好的,但是我还想等结果怎么办,await,我理解这个await就是让异步看起来像同步
有没有巨简单
这里有个问题,调用addres应该是成员变量,或者是隐藏的成员,所以是marketplace.address,但是在调用name的时候为什么是函数的形式?明明合约中只有一个构造函数。难道带()才是成员变量吗?