开发Dapp流程 1.vue前端生成项目, 写好前端页面 2.安装truffle npm install -g truffle npm install -g ethereumjs-testrpc 3.下载ganache软件 https://www.trufflesuite.com/ganache# 4.在谷歌浏览器下载MetaMast小狐狸插件, 加入应项目中生成的私匙 4.在根目录初始化truffle truffle init 5.配置truffle-config.js module.exports = { contracts_build_directory: "./src/contract", // 输入目录 网络 networks: { development: { host: "127.0.0.1", // Localhost (default: none) port: 7545, // Standard Ethereum port (default: none) network_id: "*", // Any network (default: none) }, } }; 6.migrations目录文件是钱包那边给的, contracts目录文件也是钱包那边给的sol文件 7.静态文件引入web3.js与, truffle-contract.js (用package.josn 也可以引入) 8.web3.js初始化, 在app.vue中 window.addEventListener('load', async () => { var web3Provider; if (window.ethereum) { web3Provider = window.ethereum; try { // 请求用户授权 await window.ethereum.enable(); } catch (error) { // 用户不授权时 console.error('User denied account access'); } } else if (window.web3) { // 老版 MetaMask Legacy dapp browsers... web3Provider = window.web3.currentProvider; } else { web3Provider = new Web3.providers.HttpProvider('http://localhost:7545'); } window.web3 = new Web3(web3Provider); new Vue({ i18n, router, store, render: h => h(App), }).$mount('#app'); }); 9.启动truffle truffle develop compile migrate 10. 如何使用, 如MetaCoin.js import MetaCoin from '@/contract/MetaCoin.json'; let adoptionInstance = null; const Contracts = { contract: null, // 初始化 init() { return new Promise((resolve, reject) => { if (adoptionInstance) { resolve(); return; } this.contract = TruffleContract(MetaCoin); this.contract.at('0x80fa9638580fD0c325e27FD84845Eb0957Da32C0'); // 项目生成合约地址 this.contract.setProvider(window.web3.currentProvider); this.contract .deployed() .then(instance => { adoptionInstance = instance; resolve(); }) .catch(err => { reject(err); }); }); }, // 投资买入, MetaCoin.json中的方法 buy(address, params) { return new Promise((resolve, reject) => { adoptionInstance .buy(address, params) .then(res => { resolve(res); }) .catch(err => { reject(err); }); }); }, }; export default Contracts; 11.获取帐户地址 /** * 获取帐号 */ export function getAccounts() { return new Promise((resolve, reject) => { window.web3.eth.getAccounts((error, accounts) => { if (error) { console.log(error); reject(error); } var account = accounts[0]; resolve(account); }); }); }