# 编程日记：交互智能合约（2022-08-23）

By [Corror](https://paragraph.com/@corror) · 2022-08-25

---

编程学习
----

### 行动框架

1.  **编码**智能合约
    
    1.  用 Solidity 语言编码 .sol 合约
        
    2.  涉及：映射、自定义结构体、动态数组、以及函数。
        
2.  **编译**智能合约
    
    1.  安装 solc 包
        
    2.  通过 yarn 包管理器来运行 solc 包
        
    3.  将 .sol 合约编译成为 .abi 接口文件和 .bin 二进制文件。
        
3.  **部署**智能合约
    
    1.  准备阶段
        
        1.  安装 ethers.js 包
            
        2.  通过 `.JsonRpcProvider(url)` 方法，创建 provider
            
        3.  通过 provider 和 `.Wallet(privateKey, provider)` 方法，创建 signer。
            
        4.  通过 signer, .abi, .bin 创建 ContractFactory
            
    2.  部署阶段
        
        1.  通过 `.deploy()` 方法发起部署合约的交易
            
        2.  通过 `.deployContract.wait()` 方法等待交易被确认
            
4.  **交互**智能合约
    
    1.  函数调用：通过点表示法 (dot notation) `contract.`来调用 contract 中定义的函数。
        

### 做了什么？

1.  成了做到全盘理解 .abi 接口文件，知晓其每一个部分的具体含义。
    
2.  成功了解了 stateMutability 的本质，知晓了函数与区块链网络的四种交互方式。
    
3.  成功通过 `.` 点表示法，**在 .js 文件中，调用在 .sol 文件中声明的函数**。
    
4.  成功了解 Bignumber 出现的原因，以及将 BigNumber 的数值用字符串呈现的方法 `.toString()` 。
    
5.  **_td_** 查阅 BigNubmer 文档，了解为什么传递数值时，最好附上引号。
    

### 收获了什么？

#### stateMutability

来源：[stateMutability](https://pub.dev/documentation/web3dart/latest/contracts/StateMutability.html#values)

stateMutability 是指函数的状态，它决定了函数与区块链的交互方式。

stateMutability 决定了函数与区块链有四种交互方式：pure, view, nonpayable, payable. 其具体含义如下：

1.  pure: 函数与区块链网络没有交互，其运行方式只会受到函数输入的影响。
    
2.  view: 函数只读区块链网络，但不会写入区块链网络。
    
3.  nonpayable: 函数写入区块链网络，但不接收 Ether.
    
4.  payable: 函数写入区块链网络，同时也接收 Ether.
    

#### BigNumber

##### BigNumber 是什么？有什么用？

BigNumber 是一种对象，它能让任意大小的数值进行计算，同时还不会出现溢出报错的。

JavaScript 由于标准的要求，存在一个最大的数值上限，即 0.009 Ether 在 Wei 单位下的数值大小。

BigNumber 的出现，就能够为数值运算取消数值上限，从而在任意数值范围内都能够安全地进行运算。

##### 举例解释

情境1：

    uint16 number;
    

    console.log(number); // Expect output: 0
    

情境2：

    uint256 number;
    

    console.log(number); // Expect output: BigNumber { _hex: '0x00', _isBigNumber: true }
    console.log(number.toString()); // Expect output: 0
    

运行结果：

*   代码1中，`uint16` 下的 `nubmer` 不会溢出，因此会直接显示数值 `0`.
    
*   代码2中：
    
    *   `uint256` 下的 `number` 会溢出，因此会用 BigNumber 进行安全计算和数值显示。
        
    *   如果想要显示具体的值，可以通过 `.toString()` 方法，将 BigNumber 的数值转化为字符串显示。
        

#### String Interpolation 内插字符串

内插字符串 (string interpolation) 是指，用变量计算后的字符串代替变量显示出来，一般用 \`${变量名}\`表示。

举例如下：

    const variable;
    console.log(`The value is: ${variable}`); // Expect output: The value is: 1 (in form of string)

---

*Originally published on [Corror](https://paragraph.com/@corror/2022-08-23)*
