本文转载自微信公众号《区块链研究实验室》,作者连三丰。转载本文请联系区块链研究实验室公众号。Truffle是一个开发环境(提供编译、部署、测试和构建的命令行工具),一个框架(提供各种包,方便编写测试、部署代码、构建客户端等),以及一个资产管道(发布软件包并使用其他人发布的软件包来构建基于以太坊的DApps。使用Truffle,您将获得:内置智能合约编译、链接、部署和二进制管理。使用Mocha和Chai进行自动合约测试。可配置构建管道支持自定义构建过程。脚本化部署和迁移框架。用于部署到许多公共和私有网络的网络管理。用于直接合约通信的交互式控制台。在开发过程中立即重建资产。外部脚本运行器,在Truffle环境中执行脚本。使用大多数Truffle命令,你需要在现有的Truffle项目上运行它们。所以第一步是创建一个Truffle项目,让我们开始yinstallingTruffle:$npminstall-gtruffleMakesureit'sinstalled:$truffleTrufflev3.2.1-developmentframeworkforEthereumUsage:truffle[options]Commands:initInitializenewEthereumprojectwithexamplecontractsandtests...Thencreatetheproject:$mkdirstorage_smart_contract_example$cdstorage_smart_contract_example$cdstorage_smart_contract_example$truffleinitcompile,youcanruncompilehere你可以运行Truffle,将这些合约部署到网络,并运行它们的相关单元测试。Truffle与本地开发区块链服务器捆绑在一起,该服务器会在您调用上述命令时自动启动。如果您想配置更高级的开发环境,我们建议您通过在命令行运行npminstall-gganache-cli来单独安装区块链服务器。ganache-cli:Truffle区块链服务器的命令行版本。您的交易历史和链条状态。Truffle项目的结构您创建的Truffle文件夹如下所示:1.ContractsConvertLib.solMetaCoin.solMigrations.so2.Migrations1_initial_migration.js2_deploy_contracts.js3.测试TestMetacoin.solmetacoin.js4.truffle-config.js5.truffle.js现在进一步研究代码,您会看到Truffle为我们创建了文件结构。转到合约文件夹并创建Storage.sol文件并在其中写入智能合约的代码。pragmasolidity^0.4.8;contractStorage{uint256storedData;functionset(uint256data){storedData=data;}functionget()constantreturns(uint256){returnstoredData;}}现在转到migrations/2_deploy_contracts.js并将其修改为如下所示:varStorage=artifacts.require("./Storage.sol");module.exports=function(deployer){deployer.deploy(Storage);};现在我们有了基本的设置,我们需要将它部署到区块链上面,让我们使用testrpc,它可以很好地用于测试开发目的。在单独的选项卡上,键入以下命令:$npminstall-gethereumjs-testrpc$testrpcEthereumJSTestRPCv3.0.3AvailableAccounts==================...然后返回选项卡运行truffle项目:$trufflecompile$trufflemigrate所以我们完成了部署合约,让我们检查一下我们是否能够调用合约函数。$truffleconsoletruffle(development)>Storage.deployed().then(instance=>instance.get.call()).then(result=>storeData=result){[String:'0']s:1,e:0,c:[0]}truffle(development)>storeData.toString()'0'现在让我们看看是否可以将storeData设置为值99。truffle(development)>Storage.deployed().then(instance=>instance.set.sendTransaction(99)).then(result=>newStorageData=result)'0xc5e2f9c9da4cf9f563c8e59073d5b6ca9458f112a6dcfc14aaea7c16a99422d4'truffle(development)>Storage.deployed().then(instance=>instance=then.get.call()).>storeData=result){[String:'99']s:1,e:1,c:[99]}truffle(development)>storeData.toString()'99'至此,我们已经成功部署并测试了松露项目合同。如果您有任何问题,请在留言区留言。
