# 编程日记:交互智能合约(2022-08-23) **Published by:** [Corror](https://paragraph.com/@corror/) **Published on:** 2022-08-25 **URL:** https://paragraph.com/@corror/2022-08-23 ## Content 编程学习行动框架编码智能合约用 Solidity 语言编码 .sol 合约涉及:映射、自定义结构体、动态数组、以及函数。编译智能合约安装 solc 包通过 yarn 包管理器来运行 solc 包将 .sol 合约编译成为 .abi 接口文件和 .bin 二进制文件。部署智能合约准备阶段安装 ethers.js 包通过 .JsonRpcProvider(url) 方法,创建 provider通过 provider 和 .Wallet(privateKey, provider) 方法,创建 signer。通过 signer, .abi, .bin 创建 ContractFactory部署阶段通过 .deploy() 方法发起部署合约的交易通过 .deployContract.wait() 方法等待交易被确认交互智能合约函数调用:通过点表示法 (dot notation) contract.来调用 contract 中定义的函数。做了什么?成了做到全盘理解 .abi 接口文件,知晓其每一个部分的具体含义。成功了解了 stateMutability 的本质,知晓了函数与区块链网络的四种交互方式。成功通过 . 点表示法,在 .js 文件中,调用在 .sol 文件中声明的函数。成功了解 Bignumber 出现的原因,以及将 BigNumber 的数值用字符串呈现的方法 .toString() 。td 查阅 BigNubmer 文档,了解为什么传递数值时,最好附上引号。收获了什么?stateMutability来源:stateMutability stateMutability 是指函数的状态,它决定了函数与区块链的交互方式。 stateMutability 决定了函数与区块链有四种交互方式:pure, view, nonpayable, payable. 其具体含义如下:pure: 函数与区块链网络没有交互,其运行方式只会受到函数输入的影响。view: 函数只读区块链网络,但不会写入区块链网络。nonpayable: 函数写入区块链网络,但不接收 Ether.payable: 函数写入区块链网络,同时也接收 Ether.BigNumberBigNumber 是什么?有什么用?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) ## Publication Information - [Corror](https://paragraph.com/@corror/): Publication homepage - [All Posts](https://paragraph.com/@corror/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@corror): Subscribe to updates