智能合约
Remix IDE
是开发以太坊智能合约的在线IDE工具,部署简单的智能合约非常方便。
http://remix.ethereum.org
truffle
一个世界级的智能合约开发框架,专为智能合约而生。
- 管理智能合约的生命周期
- 自动化合约测试
- 可编程,可部署,可发布智能合约
- 不用过多的关注网络管理
- 强大的交互式控制台
安装truffle:
npm i truffle -g
在指定文件夹下初始化合约:
truffle init
合约目录结构:
- contracts/ :存放solidity智能合约文件
- migrations/ :truffle使用migration system来控制合约的部署
- test/ :测试文件存放位置
- truffle-config.js:配置文件
配置truffle-config.js文件:
打开开发配置,下方advance高级配置可以指定扣钱的账户,如不指定,默认是第一个登录的账号扣钱,这里我们是account2,导入的ganache账户。打开优化配置。
/ * Use this file to configure your truffle project. It's seeded with some * common settings for different networks and features like migrations, * compilation, and testing. Uncomment the ones you need or modify * them to suit your project as necessary. * * More information about configuration can be found at: * * https://trufflesuite.com/docs/truffle/reference/configuration * * Hands-off deployment with Infura * -------------------------------- * * Do you have a complex application that requires lots of transactions to deploy? * Use this approach to make deployment a breeze 🏖️: * * Infura deployment needs a wallet provider (like @truffle/hdwallet-provider) * to sign transactions before they're sent to a remote public node. * Infura accounts are available for free at 🔍: https://infura.io/register * * You'll need a mnemonic - the twelve word phrase the wallet uses to generate * public/private key pairs. You can store your secrets 🤐 in a .env file. * In your project root, run `$ npm install dotenv`. * Create .env (which should be .gitignored) and declare your MNEMONIC * and Infura PROJECT_ID variables inside. * For example, your .env file will have the following structure: * * MNEMONIC = <Your 12 phrase mnemonic> * PROJECT_ID = <Your Infura project id> * * Deployment with Truffle Dashboard (Recommended for best security practice) * -------------------------------------------------------------------------- * * Are you concerned about security and minimizing rekt status 🤔? * Use this method for best security: * * Truffle Dashboard lets you review transactions in detail, and leverages * MetaMask for signing, so there's no need to copy-paste your mnemonic. * More details can be found at 🔎: * * https://trufflesuite.com/docs/truffle/getting-started/using-the-truffle-dashboard/ */ // require('dotenv').config(); // const { MNEMONIC, PROJECT_ID } = process.env; // const HDWalletProvider = require('@truffle/hdwallet-provider'); module.exports = { / * Networks define how you connect to your ethereum client and let you set the * defaults web3 uses to send transactions. If you don't specify one truffle * will spin up a managed Ganache instance for you on port 9545 when you * run `develop` or `test`. You can ask a truffle command to use a specific * network from the command line, e.g * * $ truffle test --network <network-name> */ networks: { // Useful for testing. The `development` name is special - truffle uses it by default // if it's defined here and no other network is specified at the command line. // You should run a client (like ganache, geth, or parity) in a separate terminal // tab if you use this network and you must also set the `host`, `port` and `network_id` // options below to some value. // development: { host: "127.0.0.1", // Localhost (default: none) port: 8545, // Standard Ethereum port (default: none) network_id: "*", // Any network (default: none) }, // // An additional network, but with some advanced options… // advanced: { // port: 8777, // Custom port // network_id: 1342, // Custom network // gas: , // Gas sent with each transaction (default: ~) // gasPrice: , // 20 gwei (in wei) (default: 100 gwei) // from: <address>, // Account to send transactions from (default: accounts[0]) // websocket: true // Enable EventEmitter interface for web3 (default: false) // }, // // Useful for deploying to a public network. // Note: It's important to wrap the provider as a function to ensure truffle uses a new provider every time. // goerli: { // provider: () => new HDWalletProvider(MNEMONIC, `https://goerli.infura.io/v3/${PROJECT_ID}`), // network_id: 5, // Goerli's id // confirmations: 2, // # of confirmations to wait between deployments. (default: 0) // timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) // skipDryRun: true // Skip dry run before migrations? (default: false for public nets ) // }, // // Useful for private networks // private: { // provider: () => new HDWalletProvider(MNEMONIC, `https://network.io`), // network_id: 2111, // This network is yours, in the cloud. // production: true // Treats this network as if it was a public net. (default: false) // } }, // Set default mocha options here, use special reporters, etc. mocha: { // timeout: }, // Configure your compilers compilers: { solc: { version: "0.8.18", // Fetch exact version from solc-bin (default: truffle's version) // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) settings: { // See the solidity docs for advice about optimization and evmVersion optimizer: { enabled: false, runs: 200 }, evmVersion: "byzantium" } } }, // Truffle DB is currently disabled by default; to enable it, change enabled: // false to enabled: true. The default storage location can also be // overridden by specifying the adapter settings, as shown in the commented code below. // // NOTE: It is not possible to migrate your contracts to truffle DB and you should // make a backup of your artifacts to a safe location before enabling this feature. // // After you backed up your artifacts you can utilize db by running migrate as follows: // $ truffle migrate --reset --compile-all // // db: { // enabled: false, // host: "127.0.0.1", // adapter: { // name: "indexeddb", // settings: { // directory: ".db" // } // } // } };
在contracts下建立StudentStorage.sol文件。
solidity
数据位置
solidity数据存储位置有三类:storage,memory,calldata。不同存储位置的gas成本不同。storage类型的数据存在链上,类似计算机的硬盘,消耗gas多,memory和calldata类型的临时存储在内存里,消耗gas少。
- storage:合约里的状态变量默认都是storage,存储在链上。
- memory:函数里的参数和临时变量一般用memory。存储在内存中,不上链。
- calldata:和memory类似,存储在内存中,不上链。与memory不通点在于calldata不能修改,一般用于函数的参数。
作用域:
变量的作用域:Solidity中变量按作用域划分有三种:
状态变量:状态变量是数据存储在链上的变量,所有合约内函数都可以访问,gas消耗高。状态变量在合约内,函数外声明。可以在函数里更改状态变量的值。
局部变量:局部变量是仅在函数执行过程中有效的变量,函数脱出后,变量无效。局部变量的素具存储在内存,不上链,gas低,声明在函数内。
和全局变量:全局变量是全局范围工作的变量,都是solidity预留关键字。他们可以在函数内不声明直接使用(类似于msg.sender,block.number)
作用域类型
- public 公共状态变量可以在内部访问,也可以通过消息访问。对于公共状态变量,将生成一个自动getter函数。
- internal 内部状态变量只能从当前合约或其派生合约内访问,类似于继承。
- private:私有状态变量只能从当前合约内部访问,派生合约也不能访问。
函数可以指定为以下:
external:外部合约函数是合约接口的一部分,这意味着可以从其他合约或通过事务调用他们,但是内部无法调用。
public:外部和内部都可以调用。
internal:只能从当前合约或当前合约的派生合约中访问,外部无法访问,由于它们没有通过合约的ABI向外部公开,所以他们可以接受内部类型的参数,比如映射或存储引用。
private:私有函数类似于内部函数,但在派生合约中不可见。
智能合约脚本:
// SPDX-License-Identifier: GPL-3.0 //源码遵循协议,MIT... pragma solidity >=0.4.16 <0.9.0; //限定solidity编译器版本 contract StudentStorage{ //名称与文件名一致 //创建两个状态变量,存储在链上,默认storage类型 uint age; //默认uint256 string name; //函数形参使用memory/calldata类型,临时内存,基本类型可以不用设置,uint不用设置了 function setData(string memory _name,uint _age) public{ //string memory a; //局部变量 name=_name; age=_age; } //view视图函数,只访问不修改状态变量,pure纯函数,不访问也不修改,两者可以节省gas,如果不加会花很多gas function getData() public view returns (string memory,uint) { return (name,age); } }
view视图函数,只访问不修改状态变量,pure纯函数,不访问也不修改,两者可以节省gas,如果不加会花很多gas。必须写分号,不然报错
执行编译:
truffle compile
编译结束,会出现一个build文件夹生成StudentStorage.json。
在migration文件夹下创建并编写部署脚本1_deploy.js:
const Contracts = artifacts.require("StudentStorage.sol")//引入合约 module.exports=function(deployer){ deployer.deploy(Contracts) }
部署合约,会先执行truffle compile,然后再部署:
truffle migrate
与此同时,对应的account2消耗了gas。
下面我们可以测试一下,一次在终端输入:
truffle console
const object = await StudentStorage.deployed()
object
能够看到部署的智能合约对象,下面设置值
object.setData("xiaoming",18)
读取值:
object.getData()
此时我们如果直接通过object.name,或者object.age直接访问,是不能读取到的,改为公共属性即可。
// SPDX-License-Identifier: GPL-3.0 //源码遵循协议,MIT... pragma solidity >=0.4.16 <0.9.0; //限定solidity编译器版本 contract StudentStorage{ //名称与文件名一致 //创建两个状态变量,存储在链上,默认storage类型 uint public age; //默认uint256 string public name; //函数形参使用memory/calldata类型,临时内存,基本类型可以不用设置,uint不用设置了 function setData(string memory _name,uint _age) public{ //string memory a; //局部变量 name=_name; age=_age; } //view视图函数,只访问不修改状态变量,pure纯函数,不访问也不修改,两者可以节省gas,如果不加会花很多gas function getData() public view returns (string memory,uint) { return (name,age); } }
按照上述重新部署,再次访问obj.age,发现会返回一个函数,所有设置了public的变量,都会自动生成一个对应的getter方法
我们重新设值,然后访问使用obj.age()或obj.name()方法访问,就可以访问到了。所以想要外部调用使用public/external,不想的话就internal/private。
脚本测试:
- mocha测试
- truffle脚本
这里使用truffle脚本。合约根目录下创建scripts文件夹,创建编写test.js文件。
const Contracts = artifacts.require("StudentStorage.sol") module.exports=async function(callback){ const studentStorage = await Contracts.deployed() await studentStorage.setData("xiaoming",16) const res = await studentStorage.getData() console.log(res); console.log(await studentStorage.age()); console.log(await studentStorage.name()); callback() }
然后调用指令:
truffle exec ./scripts/test.js
即可查看返回的数据。
下面新建合约StudentListStorage.sol,并在migrations下创建并编写部署文件2_deploy.js
// SPDX-License-Identifier: GPL-3.0 //源码遵循协议,MIT... pragma solidity >=0.4.16 <0.9.0; //限定solidity编译器版本 contract StudentListStorage { //名称与文件名一致 //结构体 struct Student { uint id; string name; uint age; } //动态数组 Student[] public StudentList; function addListData(string memory _name, uint _age) public returns (uint) { uint count = StudentList.length; uint index = count + 1; StudentList.push(Student(index, _name, _age)); //添加数据 return StudentList.length; } function getListData() public view returns (Student[] memory) { Student[] memory list = StudentList; return list; } }
const Contracts = artifacts.require("StudentListStorage.sol")//引入合约 module.exports=function(deployer){ deployer.deploy(Contracts) }
重新部署:
truffle migrate --reset //能够覆盖上次的部署
创建test2.js
const Contracts = artifacts.require("StudentListStorage.sol") module.exports = async function (callback) { const studentListStorage = await Contracts.deployed() await studentListStorage.addListData("xiaoming", 16) const res = await studentListStorage.getListData() console.log(res); console.log(await studentListStorage.StudentList)//这里返回的是一个方法 // console.log(await studentListStorage.StudentList())//这里会报错 try { console.log(await studentListStorage.StudentList())//使用trycatch捕捉异常 } catch (error) { console.log(error); } console.log(await studentListStorage.StudentList(1))//必须添加索引 callback() }
直接访问合约的数组属性时,要添加索引
打通web3.js到智能合约
ABI非常类似于API,ABI定义了用于二进制合约交互的方法和结构,就像API一样,只是在较低的级别上。
连接智能合约:
new web3.eth.Contract(abi,address)
打包生成的build文件夹下的json文件就有已经生成的abi可以直接拿来使用,address(在networks下)指合约的地址,也在json文件中可以读取到。这里我们连接StudentListStorage合约,找到StudentListStorage.json。
创建web3.html文件并编写连接至智能合约:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input id="myname" type="text">
<input id="myage" type="number">
<button id="add">添加</button>
<ul id="list"></ul>
</body>
<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
<script type="module">
const abi = [
{
"inputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"name": "StudentList",
"outputs": [
{
"internalType": "uint256",
"name": "id",
"type": "uint256"
},
{
"internalType": "string",
"name": "name",
"type": "string"
},
{
"internalType": "uint256",
"name": "age",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function",
"constant": true
},
{
"inputs": [
{
"internalType": "string",
"name": "_name",
"type": "string"
},
{
"internalType": "uint256",
"name": "_age",
"type": "uint256"
}
],
"name": "addListData",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "getListData",
"outputs": [
{
"components": [
{
"internalType": "uint256",
"name": "id",
"type": "uint256"
},
{
"internalType": "string",
"name": "name",
"type": "string"
},
{
"internalType": "uint256",
"name": "age",
"type": "uint256"
}
],
"internalType": "struct StudentListStorage.Student[]",
"name": "",
"type": "tuple[]"
}
],
"stateMutability": "view",
"type": "function",
"constant": true
}
]
const address = "0x3aCeFa3b11F7138aF23a86aBf5c7d592971CC2A9"
var web3 = new Web3(Web3.givenProvider || "ws://localhost:8545");
//授权账号
const account = await web3.eth.requestAccounts()
console.log(account);
//连接智能合约
const StudentListStorage = await new web3.eth.Contract(abi, address)
console.log(StudentListStorage);
add.onclick=async function(){
await StudentListStorage.methods.addListData(myname.value,myage.value).send({
from:account[0]
})
getList()
}
getList()
async function getList(){
const res =await StudentListStorage.methods.getListData().call()
console.log(res)
list.innerHTML = res.map(item=>`<li>${item.id}--${item.name}--${item.age}</li>`).join("")
}
</script>
</html>
在调用方法时,如果是上链操作或者是消耗gas,那么需要加上.send({from}),如果只是访问,只需加上.call()
我们可以将扣费记录的账号也展示在页面上,使用 msg.sender 全局变量,在添加时传入即可:
// SPDX-License-Identifier: GPL-3.0 //源码遵循协议,MIT... pragma solidity >=0.4.16 <0.9.0; //限定solidity编译器版本 contract StudentListStorage { //名称与文件名一致 //结构体 struct Student { uint id; string name; uint age; address account; } //动态数组 Student[] public StudentList; function addListData(string memory _name, uint _age) public returns (uint) { uint count = StudentList.length; uint index = count + 1; StudentList.push(Student(index, _name, _age,msg.sender)); //添加数据 return StudentList.length; } function getListData() public view returns (Student[] memory) { Student[] memory list = StudentList; return list; } }
修改合约后,重新部署,重新配置abi和address:
truffle migrate
在读取中可以查到当前操作用户的地址。
到此这篇DAPP开发(三)——智能合约开发的文章就介绍到这了,更多相关内容请继续浏览下面的相关推荐文章,希望大家都能在编程的领域有一番成就!
版权声明:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权、违法违规、事实不符,请将相关资料发送至xkadmin@xkablog.com进行投诉反馈,一经查实,立即处理!
转载请注明出处,原文链接:https://www.xkablog.com/qkl-kf/7507.html