Truffle 外部脚本

 

Truffle中,可以运行与合约交互的外部脚本。

 

命令

要运行外部脚本,可执行以下操作:

$ truffle exec <path/to/file.js>

在脚本中,可以启动合约,与合约进行交互等。可以把在truffle控制台中手动执行的操作,自动化执行。

 

文件结构

为了让外部脚本正确运行,Truffle要求它导出一个函数,该函数接受一个参数作为回调:

module.

exports = function

(callback) { // perform actions }

可以在这个脚本中做任何想做的事情,只要在脚本完成时调用回调。回调函数接受一个错误作为它的第一个也是唯一的参数。

如果提供了错误,执行将停止,进程将返回一个非零的退出代码。

示例

在项目根目录下,创建script.js文件,内容如下:

module.

exports = function

(callback) { web3.

eth.getBlock

(

'latest'

).

then

(console.log) }

该脚本将从所连接到的网络中,获取最新区块的信息。

执行脚本:

truffle exec script.js 

输出类似下面这样:

{ author: 

'0x596e8221a30bfe6e7eff67fee664a01c73ba3c56'

, difficulty:

'340282366920938463463374607431768211454'

, extraData:

'0xde830205058f5061726974792d457468657265756d86312e33362e30826c69'

, gasLimit:

'0x7a1200'

, gasUsed:

'0x5e61'

, hash:

'0x225a1e0b13fd20396af60d049ce9bb94c2f3f7df06c7db260880b62c91997004'

, logsBloom:

'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'

, miner:

'0x596e8221A30bFe6e7eFF67Fee664A01C73BA3C56'

, number: 13448162, parentHash:

'0x28d00fd7b66771130ed98de5073c7797ee293e7bee4b546793a4b79171555066'

, receiptsRoot:

'0x44617b5733ee59bde159af08ffd6edae36e0964f1724c333f3d1bef0808dee15'

, sealFields: [

'0x84175e95d7'

,

'0xb8412ed900e67f4a72925fb3b495efb3f547411f40d26e972cc0e8b2cf26e40cf84a545e0328199d4880b79c62670129a7db12ac58234bee0866c6376b46ab99e8a200'

], sha3Uncles:

'0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'

, signature:

'2ed900e67f4a72925fb3b495efb3f547411f40d26e972cc0e8b2cf26e40cf84a545e0328199d4880b79c62670129a7db12ac58234bee0866c6376b46ab99e8a200'

, size: 797, stateRoot:

'0xe1bbaacfb950361bec70f4ad53a2605e1ac1d2ff0bfd913fe063dc6c5f3252a0'

, step:

'392074711'

, timestamp: 1568298844, totalDifficulty:

'4525729278306228651801195598997744985609807728'

, transactions: [

'0xf1ae41eac6b32419bc62a6cde9cab4b4ca244899a3d49b4a2461bcf94f504176'

], transactionsRoot:

'0xf08c8097ea946f84ce9594ce73648fc0f9f683adef105a5db00c5f1f15e61c2c'

, uncles: [] }