5.10 测试合约及交易

优质
小牛编辑
117浏览
2023-12-01

测试合同和交易

通常,您需要采取低级别策略来测试和调试合约及交易。本节介绍一些可以使用的调试工具和实践。为了在不产生实际影响的情况下测试合约和交易,你最好在一个私人的块上测试它。这可以通过配置备用网络ID(选择唯一的整数)和/或禁用peer来实现。测试时推荐您使用备用数据目录和端口,这使得您甚至不会意外与现场运行的节点冲突(假设使用默认值运行)。使用带有性能分析的VM调试模式开启你的geth,推荐最高的日志记录级别:

geth --datadir ~/dapps/testing/00/ --port 30310 --rpcport 8110 --networkid 4567890 --nodiscover --maxpeers 0 --vmdebug --verbosity 6 --pprof --pprofport 6110 console 2>> ~/dapp/testint/00/00.log

Before you can submit any transactions, you need mine some ether on your private chain and for that you need an account. See the sections on Mining and Accounts

在您提交任何交易之前,您需要在您的私链上挖取一些ether,因此您需要一个帐户。请参阅采矿账户部分。

// create account. will prompt for password
personal.newAccount("mypassword");
// name your primary account, will often use it
primary = eth.accounts[0];
// check your balance (denominated in ether)
balance = web3.fromWei(eth.getBalance(primary), "ether");
// assume an existing unlocked primary account
primary = eth.accounts[0];

// mine 10 blocks to generate ether

// starting miner
miner.start(8);
// sleep for 10 blocks.
admin.sleepBlocks(10);
// then stop mining (just not to burn heat in vain)
miner.stop()  ;
balance = web3.fromWei(eth.getBalance(primary), "ether");

创建事务后,可以强制处理它们,具体如下:

miner.start(1);
admin.sleepBlocks(1);
miner.stop()  ;

你可以查看你的待处理交易:

// shows transaction pool
txpool.status
// number of pending txs
eth.getBlockTransactionCount("pending");
// print all pending txs
eth.getBlock("pending", true).transactions

如果您提交合约创建事务,您可以检查所需的代码是否已经插入到当前块链中:

txhash = eth.sendTansaction({from:primary, data: code})
//... mining
contractaddress = eth.getTransactionReceipt(txhash);
eth.getCode(contractaddress)