# 30个solidity示例2-First App

By [bvicii](https://paragraph.com/@startboy) · 2022-06-15

---

    // 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](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)
     }
    

![](https://storage.googleapis.com/papyrus_images/98f4238530bc2f49d5c26a99bef9eb472240d248f7ecf10f0af3ef64dcd0f79b.png)

试一下查询count（get方法）：

     try {
         const count = await Contract.get();
    
         console.log(ethers.utils.formatUnits(count, 0));
     
     } catch (e) {
         console.log("call error : ", e)
     }
    

结果:

![](https://storage.googleapis.com/papyrus_images/f178267b73517914ea4d80f411a1e99499a6d12b70f14accd189abfa9386e9ec.png)

这样的话一个简单的合约就部署并测试完成。关于ethersjs可以查看文档：

[https://docs.ethers.io/v5/](https://docs.ethers.io/v5/)

相较于官方的web3.js 这个封装的更好使用简单易上手，当然如果你js也不会的话可能需要学一点js基础然后再找教程安装nodejs，并不复杂网上教程非常多

---

*Originally published on [bvicii](https://paragraph.com/@startboy/30-solidity-2-first-app)*
