# 30个solidity示例2-First App **Published by:** [bvicii](https://paragraph.com/@startboy/) **Published on:** 2022-06-15 **URL:** https://paragraph.com/@startboy/30-solidity-2-first-app ## Content // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; //使用contract关键字声明一个合约Counter计数器 contract Counter { //申明一个unit类型状态变量count,状态变量是永久地存储在合约存储中的值 //对于 public 状态变量会自动生成一个 getter hanshu 函数,以便其他的合约读取他们的值 uint public count; // 获取当前count值 function get() public view returns (uint) { return count; } // count加1 function inc() public { count += 1; } // count减1 function dec() public { // This function will fail if count = 0 count -= 1; } } 部署合约请参考: https://mirror.xyz/startboy.eth/sH966iKNKdySO7isGMsBNbIwYhcpowkVOKhfmRkeql8测试一下合约:调用inc()方法//使用ethersjs调用合约测试 const Contract = new ethers.Contract( '0x36C4Cd42E5d68fa989bCa1b13FCB5566d4eA0306', [ 'function dec() public', 'function inc() public', 'function get() public view returns (uint)' ], account ) //加1(减1同理dec()) try { const tx = await Contract.inc( { 'gasLimit': 220000, 'gasPrice': ethers.utils.parseUnits('10', 'gwei'), }); await tx.wait(); } catch (e) { console.log("approve error 致命错误: ", e) } 试一下查询count(get方法): try { const count = await Contract.get(); console.log(ethers.utils.formatUnits(count, 0)); } catch (e) { console.log("call error : ", e) } 结果:这样的话一个简单的合约就部署并测试完成。关于ethersjs可以查看文档: https://docs.ethers.io/v5/ 相较于官方的web3.js 这个封装的更好使用简单易上手,当然如果你js也不会的话可能需要学一点js基础然后再找教程安装nodejs,并不复杂网上教程非常多 ## Publication Information - [bvicii](https://paragraph.com/@startboy/): Publication homepage - [All Posts](https://paragraph.com/@startboy/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@startboy): Subscribe to updates