Truffle框架的初使用

本文链接:https://blog.csdn.net/Aaron_Kings/article/details/88358342
truffle使用
1、下载
1.1、nodejs
1.2、truffle
2、新建truffle项目
2.1、创建简单项目
2.2、编译合约文件
2.2.1、开启truffle框架私有链
2.2.2、编译合约文件
2.2.3、部署合约上链
2.2.4、获取合约实例
小结
1、下载
本机环境使用Win10专业版、Atom、Metamask,关于Atom、Metamask钱包的安装使用,可以浏览我的一篇博客:开发Solidity的IDE推荐。

1.1、nodejs
前往nodejs官网,选择下图左边的LTS版本下载,下载完成后傻瓜式安装。

1.2、truffle
npm install -g truffle
1
下载完成后查看版本信息:

truffle version
1
正常情况下返回如下信息:

Truffle v5.0.2 (core: 5.0.2)
Solidity v0.5.0 (solc-js)
Node v8.12.0

2、新建truffle项目
2.1、创建简单项目
新建个项目文件,如:demo1,在demo1的根目录下,运行cmd并输入如下命令

truffle init
1
运行完成后,在Atom中打开demo1,可以看到其项目结构如下:


contracts:存放合约文件,默认存在Migrations.sol文件
migrations:存放接口文件,默认存在1_initial_migrations.js文件
test:初始为空,存放测试用例文件

新建合约文件,在contracts中新建文件HelloWorld.sol文件。

pragma solidity ^ 0.5.0;
contract HelloWorld {
  function test() pure public returns (string memory) {
    return 'HelloWorld';
  }
}
1
2
3
4
5
6
2.2、编译合约文件
2.2.1、开启truffle框架私有链
在demo1的根目录下,执行下列命令:

truffle develop
1
正常情况下会开启truffle框架的私有链,端口为:localhost:9545(与以太坊私有链localhost:8545不同),并输出以下内容:


给出了10个默认账户和私钥,转账不需要密码,既为空就好:""

可以通过web3访问该私有链,如下:

truffle(develop)>web3.eth.getCoinbase()
‘0x9a37e2b824bb3fbd4429d0ceb2c7ef3471cb0fe3’

使用Metamask钱包连接当前私有链:


通过自定义RPC,连接localhost:9545,另外一定要注意network的id,可以输入networks命令进行查看,不然后面开发多个truffle项目时,会出现交易错误和转账错误,如:区块链项目开发常见错误-2-rpc error with payload,如果你之前忘记设置,一定先要重设账户后再重新添加。
但是连接后,账号中并没有以太币,我们可以通过web3的命令来转账,如下命令所示:

truffle(develop)>web3.eth.sendTransaction({from:"0x9A37E2b824bB3FBd4429D0CEb2c7ef3471cb0fE3",to:"0x2090500323e31d59e097ebb59aa8f410af3ce4d2",value:'10000000000000000000'})
from:“0x9A37E2b824bB3FBd4429D0CEb2c7ef3471cb0fE3”:当前私有链的矿工账户
to:"0x2090500323e31d59e097ebb59aa8f410af3ce4d2"这是我钱包中的账号
value:‘10000000000000000000’:转账金额

正常情况下返回以下内容,就是本次转账的哈希值以及区块地址,(并没有挖矿的过程,应该立刻就会返回如下内容):

{ transactionHash: ‘0x084c2c2e634def470ceb3e599da616cb9cc316d74500e718d0d5485d045ccebe’,
transactionIndex: 0,
blockHash: ‘0x7e49cba0be0cb19d16f3b442b6fc5531354d883f4ab8659f3774996a77430a85’,
blockNumber: 1,
from: ‘0x9a37e2b824bb3fbd4429d0ceb2c7ef3471cb0fe3’,
to: ‘0x2090500323e31d59e097ebb59aa8f410af3ce4d2’,
gasUsed: 21000,
cumulativeGasUsed: 21000,
contractAddress: null,
logs: [],
status: true,
logsBloom: ‘0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000’,
v: ‘0x1b’,
r: ‘0xdd5c45bb431a6b8e75bb5d09e5ccd6339d8ec4f0368603cea1d313a31681bcd6’,
s: ‘0x56f86f10732a059bbdf7e7572f9e912b34e59e90542351be9a76b5a71aee4a1a’ }

此时Metamask钱包中就会收到这笔ETH:

2.2.2、编译合约文件
合约已经编写完毕。那如何编译呢,平时使用solcjs进行编译合约,而在truffle中止需要输入如下命令:

truffle(develop)> compile

正常情况下,如果你的合约文件没有问题的话,是没有返回任何内容的(初学者建议使用我上面写的HelloWorld.sol文件),但是我们的项目中会出现一个新的文件夹:build,结构如下:


此时我们的合约文件就编译完成了,新生成的json文件包含与其相关的abi文件

上图不完整

2.2.3、部署合约上链
在migrations文件下新建文件2_deploy_helloworld.js,并在其中写入如下代码:

const HelloWorld = artifacts.require("./HelloWorld");
module.exports = function(deployer) {
  deployer.deploy(HelloWorld);
};
1
2
3
4
在命令行中输入如下命令,就已经部署成功:

truffle(develop)> migrate

正常情况下会返回如下内容:

⚠️ Important ⚠️
If you’re using an HDWalletProvider, it must be Web3 1.0 enabled or your migration will hang.
Starting migrations…
======================
Network name: ‘develop’
Network id: 4447
Block gas limit: 6721975
1_initial_migration.js
======================
Deploying ‘Migrations’
----------------------
transaction hash: 0x0a43458915fbea5485dc516fe2ae8d3262b3b907afaad9cb3a861fce24433d58
Blocks: 0 Seconds: 0
contract address: 0x6D8cB434D9E4f8B8872AAe6Eda5330873dB35D63
account: 0x9A37E2b824bB3FBd4429D0CEb2c7ef3471cb0fE3
balance: 89.99426112
gas used: 284844
gas price: 20 gwei
value sent: 0 ETH
total cost: 0.00569688 ETH
Saving artifacts
-------------------------------------
Total cost: 0.00569688 ETH
2_deploy_helloworld.js
======================
Replacing ‘HelloWorld’
----------------------
transaction hash: 0x0d7e7296125586234d0e01111854d236fff237760cb200c9ade74726ccfadb7f
Blocks: 0 Seconds: 0
contract address: 0x487B6C076809d7Db11C9B5fF75A4289f1A739914
account: 0x9A37E2b824bB3FBd4429D0CEb2c7ef3471cb0fE3
balance: 89.99153386
gas used: 136363
gas price: 20 gwei
value sent: 0 ETH
total cost: 0.00272726 ETH
Saving artifacts
-------------------------------------
Total cost: 0.00272726 ETH
Summary
=======
Total deployments: 2
Final cost: 0.00842414 ETH

2.2.4、获取合约实例
经过上述步骤我们已经将合约部署到了truffle私有链上,那么下面就要创建合约实例,来调用合约文件。在命令行中输入如下命令:

truffle(develop)> var helloWorld
undefined
truffle(develop)>HelloWorld.deployed().then((instance)=>{helloWorld=instance})
undefined

这样合约实例就创建成功了,查看合约实例,输入如下命令:

truffle(develop)> helloWorld
TruffleContract {
constructor:
{ [Function: TruffleContract]
_constructorMethods:
{ setProvider: [Function: setProvider],
new: [Function: new],
at: [Function: at],
deployed: [Function: deployed],
defaults: [Function: defaults],
hasNetwork: [Function: hasNetwork],
isDeployed: [Function: isDeployed],
detectNetwork: [Function: detectNetwork],
setNetwork: [Function: setNetwork],
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],
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] },
_property_values: {},
_json:
{ contractName: ‘HelloWorld’,
abi: [Array],
bytecode: ‘0x608060405234801561001057600080fd5b5061013f806100206000396000f3fe608060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063f8a8fd6d14610046575b600080fd5b34801561005257600080fd5b5061005b6100d6565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561009b578082015181840152602081019050610080565b50505050905090810190601f1680156100c85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60606040805190810160405280600a81526020017f48656c6c6f576f726c640000000000000000000000000000000000000000000081525090509056fea165627a7a72305820903d53a33c88326dd2f332c3a2be2ef8db8c54ce836e7652e83aaf0970f941170029’,
deployedBytecode: ‘0x608060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063f8a8fd6d14610046575b600080fd5b34801561005257600080fd5b5061005b6100d6565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561009b578082015181840152602081019050610080565b50505050905090810190601f1680156100c85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60606040805190810160405280600a81526020017f48656c6c6f576f726c640000000000000000000000000000000000000000000081525090509056fea165627a7a72305820903d53a33c88326dd2f332c3a2be2ef8db8c54ce836e7652e83aaf0970f941170029’,
sourceMap: ‘28:114:0:-;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;28:114:0;;;;;;;’,
deployedSourceMap: ‘28:114:0:-;;;;;;;;;;;;;;;;;;;;;;;;55:84;;8:9:-1;5:2;;;30:1;27;20:12;5:2;55:84:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;55:84:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;92:13;114:19;;;;;;;;;;;;;;;;;;;;55:84;::?’,
source: ‘pragma solidity ^ 0.5.0;\r\n\r\ncontract HelloWorld {\r\n\r\n function test() pure public returns (string memory) {\r\n return ‘HelloWorld’;\r\n }\r\n}\r\n’,
sourcePath: ‘D:/Desktop/Code/Truffle/demo1/contracts/HelloWorld.sol’,
ast: [Object],
legacyAST: [Object],
compiler: [Object],
networks: [Object],
schemaVersion: ‘3.0.1’,
updatedAt: ‘2019-03-08T14:20:37.002Z’,
devdoc: [Object],
userdoc: [Object] },
setProvider: [Function: bound setProvider],
new: { [Function: bound new] estimateGas: [Function: bound estimateDeployment] },
at: [Function: bound at],
deployed: [Function: bound deployed],
defaults: [Function: bound defaults],
hasNetwork: [Function: bound hasNetwork],
isDeployed: [Function: bound isDeployed],
detectNetwork: [Function: bound detectNetwork],
setNetwork: [Function: bound setNetwork],
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],
web3:
Web3 {
currentProvider: [Getter/Setter],
_requestManager: [Object],
givenProvider: null,
providers: [Object],
_provider: [Object],
setProvider: [Function],
BatchRequest: [Function: bound Batch],
extend: [Object],
version: ‘1.0.0-beta.37’,
utils: [Object],
eth: [Object],
shh: [Object],
bzz: [Object] },
class_defaults:
{ from: ‘0x9A37E2b824bB3FBd4429D0CEb2c7ef3471cb0fE3’,
gas: 6721975,
gasPrice: 20000000000 },
currentProvider:
HttpProvider {
host: ‘http://127.0.0.1:9545/’,
httpAgent: [Object],
timeout: 0,
headers: undefined,
connected: true,
send: [Function],
_alreadyWrapped: true },
network_id: ‘4447’ },
methods:
{ ‘test()’:
{ [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’ } ],
address: ‘0x487B6C076809d7Db11C9B5fF75A4289f1A739914’,
transactionHash: undefined,
contract:
Contract {
currentProvider: [Getter/Setter],
_requestManager: RequestManager { provider: [Object], 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: [Object],
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] },
events: { allEvents: [Function: bound ] },
_address: ‘0x487B6C076809d7Db11C9B5fF75A4289f1A739914’,
_jsonInterface: [ [Object] ] },
test:
{ [Function]
call: [Function],
sendTransaction: [Function],
estimateGas: [Function],
request: [Function] },
sendTransaction: [Function],
send: [Function],
allEvents: [Function],
getPastEvents: [Function] }

合约实例调用,我们在HelloWorld.sol文件中定义了一个test函数,接下来就调用它:

truffle(develop)> helloWorld.test()
‘HelloWorld’

至此,我们的智能合约就已经初步上链并可以调用了。

小结
通过简单的HelloWorld.sol文件的编写、编译、部署、调用来初步学习了truffle框架的使用,而truffle作为框架,还包括了前端界面的使用,接下来,我将编写truffle框架包含前端界面的使用。
————————————————
版权声明:本文为CSDN博主「白山茶瑰」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Aaron_Kings/article/details/88358342

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值