HelloWorld程序
安装工具
- 安装Node.js 地址
- 安装truffle框架
npm install -g truffle
项目建立
mkdir my-contract
cd my-contract
truffle init # 初始化操作或者使用 git clone https://github.com/truffle-box/bare-box
新建HelloWorld合约与部署
- 在
contracts
文件夹下新建HelloWorld.sol
文件,并写入下面solidity代码:
pragma solidity >=0.4.21 <0.7.0;
contract HelloWorld{
//没有传参的函数,pure
function test() pure public returns(string memory){
return "Hello World";
}
//没有传参的函数
function test2() public returns(string memory){
return "yorick";
}
//有参数的函数
function echo(string memory s) public returns(string memory){
return s;
}
}
- 在migrations文件夹下新建 2_deploy_HelloWorld.js文件,并修改成如下代码:
var HelloWorld = artifacts.require("./HelloWorld.sol");
module.exports = function(deployer) {
deployer.deploy(HelloWorld);
};
部署测试
truffle develop
compile
migrate
let contract
contract=HelloWorld.deployed().then(instance=>contract=instance)
contract.test()
contract.test2.call()
contract.echo.call("Hello Solidity")
具体输出结果如下:
root@debian:/home/yorick/Products/my-contract/bare-box# truffle develop
Truffle Develop started at http://127.0.0.1:9545/
Accounts:
(0) 0x00a2eaab0689a0abebb98554c2fccb3c1023a481
(1) 0x0ad2211462372241a03520ca3d1be8b65539c3f0
(2) 0x08fef4b74825fea9cad02140ef2769682aae1179
(3) 0xfe9a20f3f1f47f64ee6fb2482a2c32a96a1c67ea
(4) 0xfa194cb79a083ae6aa43468ed0f12742df7a3168
(5) 0x6994b9231cebf72430285a7e162de3c19e2ccea9
(6) 0x42f421b7219d3b3f94604aac58edab3ce668bca3
(7) 0x9d5f1423cab0f8dec859e2fd58b103deedca4c06
(8) 0x827790948874f9c954eabe42df1c27fb5ad51647
(9) 0xc25deae3ebb575fd5040658c796c263f305b2836
Private Keys:
(0) b9c8ca70657320ebed6ae651dba3487c26647ba2b6617271c8db169081b3e09e
(1) 7fbd43f6fe4861577e6fd4045b82126f1fa965c26b998650ebc8a8044c41b488
(2) d6fa8e3b126850e339b3666c0a1189a2e4733a0f5f0655308a92071ac10db82c
(3) f0e51b61cac56138c374528c006c51dd169f561257705eafe7ab08387c16a892
(4) 423f05a1afdd3ad9173dd84da224c6910db4b89d8fb99f09ef7d2d375d9217fe
(5) abf9db11af0f587ce9e63b39b3ced8e2aa214ef1d714a5055a802466df4a4c5a
(6) 11440f3642c18e9a3e0585cf7ed0cea1e590a03cded9970868b71b0513d04e9d
(7) 3a4c1aa26cb60e976fcd571e2e0f188cd0696ad5e3d469f6b2771cf7715e16fe
(8) 5cff65cd60f5e4a37d7ad6b0dee9006d67ca0b2108af926565896fd21d20dd17
(9) 6d08cf5eebd39621c58d26eab7eb253f1a9568dcaf290d9c404aadb276da3677
Mnemonic: vivid scheme turkey garden ugly height shrimp satoshi ice core auction mystery
⚠️ Important ⚠️ : This mnemonic was created for you by Truffle. It is not secure.
Ensure you do not use it on production blockchains, or else you risk losing funds.
truffle(develop)> compile
Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.
truffle(develop)> migrate
Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.
Starting migrations...
======================
> Network name: 'develop'
> Network id: 5777
> Block gas limit: 6721975 (0x6691b7)
1_initial_migration.js
======================
Replacing 'Migrations'
----------------------
> transaction hash: 0xe44cc681f586db8dc97467de17b446a4c115b1202baa99d052197497acd21832
> Blocks: 0 Seconds: 0
> contract address: 0x86bE880263bf806EBc791273f6137D7CfFd2D8d5
> block number: 1
> block timestamp: 1590225783
> account: 0x00a2EAAB0689A0aBEbb98554C2fCCb3C1023a481
> balance: 99.9967165
> gas used: 164175 (0x2814f)
> gas price: 20 gwei
> value sent: 0 ETH
> total cost: 0.0032835 ETH
> Saving migration to chain.
> Saving artifacts
-------------------------------------
> Total cost: 0.0032835 ETH
2_deploy_HelloWorld.js
======================
Replacing 'HelloWorld'
----------------------
> transaction hash: 0xb75ea083e36acff1fd8f1ee1c45d753fef3c262004b0f7cb86dd873a992d7b14
> Blocks: 0 Seconds: 0
> contract address: 0xebb7D75E0388a9dE7003c8dEb6DDBa9ea313cB76
> block number: 3
> block timestamp: 1590225783
> account: 0x00a2EAAB0689A0aBEbb98554C2fCCb3C1023a481
> balance: 99.99125192
> gas used: 230888 (0x385e8)
> gas price: 20 gwei
> value sent: 0 ETH
> total cost: 0.00461776 ETH
> Saving migration to chain.
> Saving artifacts
-------------------------------------
> Total cost: 0.00461776 ETH
Summary
=======
> Total deployments: 2
> Final cost: 0.00790126 ETH
truffle(develop)> let contract;
undefined
truffle(develop)> contract=HelloWorld.deployed().then(instance=>contract=instance)
TruffleContract {
constructor: [Function: TruffleContract] {
_constructorMethods: {
configureNetwork: [Function: configureNetwork],
setProvider: [Function: setProvider],
new: [Function: new],
at: [AsyncFunction: at],
deployed: [AsyncFunction: deployed],
defaults: [Function: defaults],
hasNetwork: [Function: hasNetwork],
isDeployed: [Function: isDeployed],
detectNetwork: [AsyncFunction: detectNetwork],
setNetwork: [Function: setNetwork],
setNetworkType: [Function: setNetworkType],
setWallet: [Function: setWallet],
resetAddress: [Function: resetAddress],
link: [Function: link],
clone: [Function: clone],
addProp: [Function: addProp],
toJSON: [Function: toJSON],
decodeLogs: [Function: decodeLogs]
},
_properties: {
contract_name: [Object],
contractName: [Object],
gasMultiplier: [Object],
timeoutBlocks: [Object],
autoGas: [Object],
numberFormat: [Object],
abi: [Object],
metadata: [Function: metadata],
network: [Function: network],
networks: [Function: networks],
address: [Object],
transactionHash: [Object],
links: [Function: links],
events: [Function: events],
binary: [Function: binary],
deployedBinary: [Function: deployedBinary],
unlinked_binary: [Object],
bytecode: [Object],
deployedBytecode: [Object],
sourceMap: [Object],
deployedSourceMap: [Object],
source: [Object],
sourcePath: [Object],
legacyAST: [Object],
ast: [Object],
compiler: [Object],
schema_version: [Function: schema_version],
schemaVersion: [Function: schemaVersion],
updated_at: [Function: updated_at],
updatedAt: [Function: updatedAt],
userdoc: [Function: userdoc],
devdoc: [Function: devdoc],
networkType: [Object],
immutableReferences: [Object]
},
_property_values: {},
_json: {
contractName: 'HelloWorld',
abi: [Array],
metadata: '{"compiler":{"version":"0.5.16+commit.9c3226ce"},"language":"Solidity","output":{"abi":[{"constant":false,"inputs":[{"internalType":"string","name":"s","type":"string"}],"name":"echo","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"test","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[],"name":"test2","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"}],"devdoc":{"methods":{}},"userdoc":{"methods":{}}},"settings":{"compilationTarget":{"/home/yorick/Products/my-contract/bare-box/contracts/HelloWorld.sol":"HelloWorld"},"evmVersion":"istanbul","libraries":{},"optimizer":{"enabled":false,"runs":200},"remappings":[]},"sources":{"/home/yorick/Products/my-contract/bare-box/contracts/HelloWorld.sol":{"keccak256":"0x53039e0501c41b48d343a6d62be39087c228b8bf7282613d9dae8a92a8772985","urls":["bzz-raw://04c8cd75b30c91bbfb356abf599e449d5506080d6bd7e26816bfa16990fc7834","dweb:/ipfs/QmVGqq36hLjnjoBNRKcUCvvUoPyBFcd3fh53EMwdhLj3NT"]}},"version":1}',
bytecode: '0x608060405234801561001057600080fd5b50610339806100206000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c806366e41cb714610046578063f15da729146100c9578063f8a8fd6d146101fd575b600080fd5b61004e610280565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561008e578082015181840152602081019050610073565b50505050905090810190601f1680156100bb5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b610182600480360360208110156100df57600080fd5b81019080803590602001906401000000008111156100fc57600080fd5b82018360208201111561010e57600080fd5b8035906020019184600183028401116401000000008311171561013057600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506102bd565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101c25780820151818401526020810190506101a7565b50505050905090810190601f1680156101ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102056102c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561024557808201518184015260208101905061022a565b50505050905090810190601f1680156102725780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60606040518060400160405280600681526020017f796f7269636b0000000000000000000000000000000000000000000000000000815250905090565b6060819050919050565b60606040518060400160405280600b81526020017f48656c6c6f20576f726c6400000000000000000000000000000000000000000081525090509056fea265627a7a72315820f0db4324091c927864802f3c27328db42efdc0ceb8bf85cb444ae1baf007e2ba64736f6c63430005100032',
deployedBytecode: '0x608060405234801561001057600080fd5b50600436106100415760003560e01c806366e41cb714610046578063f15da729146100c9578063f8a8fd6d146101fd575b600080fd5b61004e610280565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561008e578082015181840152602081019050610073565b50505050905090810190601f1680156100bb5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b610182600480360360208110156100df57600080fd5b81019080803590602001906401000000008111156100fc57600080fd5b82018360208201111561010e57600080fd5b8035906020019184600183028401116401000000008311171561013057600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506102bd565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101c25780820151818401526020810190506101a7565b50505050905090810190601f1680156101ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102056102c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561024557808201518184015260208101905061022a565b50505050905090810190601f1680156102725780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60606040518060400160405280600681526020017f796f7269636b0000000000000000000000000000000000000000000000000000815250905090565b6060819050919050565b60606040518060400160405280600b81526020017f48656c6c6f20576f726c6400000000000000000000000000000000000000000081525090509056fea265627a7a72315820f0db4324091c927864802f3c27328db42efdc0ceb8bf85cb444ae1baf007e2ba64736f6c63430005100032',
immutableReferences: undefined,
sourceMap: '34:251:0:-;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;34:251:0;;;;;;;',
deployedSourceMap: '34:251:0:-;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;34:251:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;136:69;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;23:1:-1;8:100;33:3;30:1;27:10;8:100;;;99:1;94:3;90:11;84:18;80:1;75:3;71:11;64:39;52:2;49:1;45:10;40:15;;8:100;;;12:14;136:69:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;207:76;;;;;;13:2:-1;8:3;5:11;2:2;;;29:1;26;19:12;2:2;207:76:0;;;;;;;;;;21:11:-1;8;5:28;2:2;;;46:1;43;36:12;2:2;207:76:0;;35:9:-1;28:4;12:14;8:25;5:40;2:2;;;58:1;55;48:12;2:2;207:76:0;;;;;;100:9:-1;95:1;81:12;77:20;67:8;63:35;60:50;39:11;25:12;22:29;11:107;8:2;;;131:1;128;121:12;8:2;207:76:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;30:3:-1;22:6;14;1:33;99:1;93:3;85:6;81:16;74:27;137:4;133:9;126:4;121:3;117:14;113:30;106:37;;169:3;161:6;157:16;147:26;;207:76:0;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;23:1:-1;8:100;33:3;30:1;27:10;8:100;;;99:1;94:3;90:11;84:18;80:1;75:3;71:11;64:39;52:2;49:1;45:10;40:15;;8:100;;;12:14;207:76:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;56:78;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;23:1:-1;8:100;33:3;30:1;27:10;8:100;;;99:1;94:3;90:11;84:18;80:1;75:3;71:11;64:39;52:2;49:1;45:10;40:15;;8:100;;;12:14;56:78:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;136:69;168:13;186:15;;;;;;;;;;;;;;;;;;;136:69;:::o;207:76::-;253:13;278:1;271:8;;207:76;;;:::o;56:78::-;92:13;110:20;;;;;;;;;;;;;;;;;;;56:78;:::o',
source: 'pragma solidity >=0.4.21 <0.7.0;\n' +
'\n' +
'contract HelloWorld{\n' +
'\tfunction test() pure public returns(string memory){\n' +
'\t\treturn "Hello World";\n' +
'\t}\n' +
'\tfunction test2() public returns(string memory){\n' +
'\t\treturn "yorick";\n' +
'\t}\n' +
'\tfunction echo(string memory s) public returns(string memory){\n' +
'\t\treturn s;\n' +
'\t}\n' +
'}\n',
sourcePath: '/home/yorick/Products/my-contract/bare-box/contracts/HelloWorld.sol',
ast: [Object],
legacyAST: [Object],
compiler: [Object],
networks: [Object],
schemaVersion: '3.1.0',
updatedAt: '2020-05-23T09:23:04.286Z',
networkType: 'ethereum',
devdoc: [Object],
userdoc: [Object]
},
configureNetwork: [Function: bound configureNetwork],
setProvider: [Function: bound setProvider],
new: [Function: bound new] {
estimateGas: [Function: bound estimateDeployment]
},
at: [Function: bound at] AsyncFunction,
deployed: [Function: bound deployed] AsyncFunction,
defaults: [Function: bound defaults],
hasNetwork: [Function: bound hasNetwork],
isDeployed: [Function: bound isDeployed],
detectNetwork: [Function: bound detectNetwork] AsyncFunction,
setNetwork: [Function: bound setNetwork],
setNetworkType: [Function: bound setNetworkType],
setWallet: [Function: bound setWallet],
resetAddress: [Function: bound resetAddress],
link: [Function: bound link],
clone: [Function: bound clone],
addProp: [Function: bound addProp],
toJSON: [Function: bound toJSON],
decodeLogs: [Function: bound decodeLogs],
class_defaults: {
from: '0x00a2EAAB0689A0aBEbb98554C2fCCb3C1023a481',
gas: 6721975,
gasPrice: 20000000000
},
interfaceAdapter: Web3InterfaceAdapter { web3: [Web3Shim] },
web3: Web3Shim {
currentProvider: [Getter/Setter],
_requestManager: [RequestManager],
givenProvider: null,
providers: [Object],
_provider: [HttpProvider],
setProvider: [Function],
BatchRequest: [Function: bound Batch],
extend: [Function],
version: '1.2.1',
utils: [Object],
eth: [Eth],
shh: [Shh],
bzz: [Bzz],
networkType: 'ethereum'
},
currentProvider: HttpProvider {
host: 'http://127.0.0.1:9545/',
httpAgent: [Agent],
timeout: 0,
headers: undefined,
connected: true,
send: [Function],
_alreadyWrapped: true
},
network_id: '5777',
ens: { enabled: false, registryAddress: null }
},
methods: {
'test()': [Function] {
call: [Function],
sendTransaction: [Function],
estimateGas: [Function],
request: [Function]
},
'test2()': [Function] {
call: [Function],
sendTransaction: [Function],
estimateGas: [Function],
request: [Function]
},
'echo(string)': [Function] {
call: [Function],
sendTransaction: [Function],
estimateGas: [Function],
request: [Function]
}
},
abi: [
{
constant: true,
inputs: [],
name: 'test',
outputs: [Array],
payable: false,
stateMutability: 'pure',
type: 'function',
signature: '0xf8a8fd6d'
},
{
constant: false,
inputs: [],
name: 'test2',
outputs: [Array],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
signature: '0x66e41cb7'
},
{
constant: false,
inputs: [Array],
name: 'echo',
outputs: [Array],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
signature: '0xf15da729'
}
],
address: '0xebb7D75E0388a9dE7003c8dEb6DDBa9ea313cB76',
transactionHash: undefined,
contract: Contract {
currentProvider: [Getter/Setter],
_requestManager: RequestManager {
provider: [HttpProvider],
providers: [Object],
subscriptions: {}
},
givenProvider: null,
providers: {
WebsocketProvider: [Function: WebsocketProvider],
HttpProvider: [Function: HttpProvider],
IpcProvider: [Function: IpcProvider]
},
_provider: HttpProvider {
host: 'http://127.0.0.1:9545/',
httpAgent: [Agent],
timeout: 0,
headers: undefined,
connected: true,
send: [Function],
_alreadyWrapped: true
},
setProvider: [Function],
BatchRequest: [Function: bound Batch],
extend: [Function: ex] {
formatters: [Object],
utils: [Object],
Method: [Function: Method]
},
clearSubscriptions: [Function],
options: { address: [Getter/Setter], jsonInterface: [Getter/Setter] },
defaultAccount: [Getter/Setter],
defaultBlock: [Getter/Setter],
methods: {
test: [Function: bound _createTxObject],
'0xf8a8fd6d': [Function: bound _createTxObject],
'test()': [Function: bound _createTxObject],
test2: [Function: bound _createTxObject],
'0x66e41cb7': [Function: bound _createTxObject],
'test2()': [Function: bound _createTxObject],
echo: [Function: bound _createTxObject],
'0xf15da729': [Function: bound _createTxObject],
'echo(string)': [Function: bound _createTxObject]
},
events: { allEvents: [Function: bound ] },
_address: '0xebb7D75E0388a9dE7003c8dEb6DDBa9ea313cB76',
_jsonInterface: [ [Object], [Object], [Object] ]
},
test: [Function] {
call: [Function],
sendTransaction: [Function],
estimateGas: [Function],
request: [Function]
},
test2: [Function] {
call: [Function],
sendTransaction: [Function],
estimateGas: [Function],
request: [Function]
},
echo: [Function] {
call: [Function],
sendTransaction: [Function],
estimateGas: [Function],
request: [Function]
},
sendTransaction: [Function],
send: [Function],
allEvents: [Function],
getPastEvents: [Function]
}
truffle(develop)> contract.test()
'Hello World'
truffle(develop)> contract.test2.call()
'yorick'
truffle(develop)> contract.echo.call("Hello Solidity")
'Hello Solidity'
通过zeppelin-solidity建立标准代币
项目建立
mkdir BLC
cd BLC
truffle init # 或者使用 git clone https://github.com/truffle-box/bare-box
npm init # 生成package.json管理包工具
npm install zeppelin-solidity # 添加外部包
当引入zeppelin-solidity外部包后,可以发现在package.json中新增加如下代码:
"dependencies": {
"zeppelin-solidity": "^1.12.0"
}
新建solidity分发代币合约并部署
在contracts文件夹下,新建BloggerCoin.sol文件。并写如下代码:
pragma solidity >=0.4.21 <0.7.0;
//引入外部包的文件,若编译版本不同注意修改为当前solidity编译版本 通过 truffle version查看当前solidity的编译版本
import "zeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
contract BloggerCoin is StandardToken{
string public name = "BloggerCoin";
string public symbol = "BLC";
uint8 public decimals = 4;
uint public initMoney = 1000;
constructor() public{
balances[msg.sender] = initMoney;
}
}
在migrations文件夹下,新建2_deploy_BloggerCoin.js文件,并写如下代码:
var BloggerCoin = artifacts.require("./BloggerCoin.sol");
module.exports = function(deployer) {
deployer.deploy(BloggerCoin);
};
测试
truffle develop #开启truffle
compile #编译
migrate #部署
let contract #创建变量
contract = BloggerCoin.deployed().then(instance=>contract=instance) #给变量赋值
# 测试合约内的属性和方法
contract.name()
contract.symbol()
contract.balanceOf("地址")
contract.transfer("目的地址",代币数量)