Solidity 数字格式化库: solpretty

Solidity 数字格式化库: The solpretty

电报联系方式

Contracts中的数字通常非常庞大,使得人眼阅读变得非常困难。solprettyTools能够使这些数字呈现出漂亮的格式化,使其更加易于理解和阅读。

solpretty 在 Foundry 工程下使用:

使用 Foundry install 安装 solpretty:

forge install devtooligan/solpretty

solpretty 用法

pp 格式化

solpretty 提供了 pp 函数:

  • pp(uint256 value)
  • pp(uint256 value, uint256 fixedDecimals)
  • pp(uint256 value, uint256 fixedDecimals, uint256 displayDecimals)
  • pp(uint256 value, uint256 fixedDecimals, uint256 displayDecimals, uint256 fixedWidth)
  • pp(uint256 value, memory SolPrettyOptions)

不同的参数,用来支持不同的格式化显示效果, pp 函数返回的是格式化后的在字符串。

例如(注释字符串为 pp 函数返回结果):

import {pp} from “solpretty/SolPretty.sol”;

pp(123123123123) // -> “123,123,123,123” // default
pp(123123123123, 6) // -> “123,123.123123” // fixedDecimals = 6
pp(123123123123, 6, 2) // -> “123,123.12” // displayDecimals = 2
pp(123123123123, 6, 0, 15) // -> ” 123,123″ // fixedWidth = 15

还可以自定义选项:

SolPrettyOptions memory solPrettyOptions = getDefaultOptions();

SolPrettyOptions.fixedDecimals = 6;
SolPrettyOptions.fixedWidth = 20;
SolPrettyOptions.decimalDelimeter = bytes1(“*”);
SolPrettyOptions.integerDelimeter = bytes1(” “);

pp(123123123123, solPrettyOptions); // -> ” 123 123*123123″

//
struct SolPrettyOptions {
uint256 fixedDecimals; // default 0
uint256 displayDecimals; // default type(uint256).max
bytes1 decimalDelimter; // default “.”
bytes1 fractionalDelimiter; // default ” ”
uint256 fractionalGroupingSize; // default 0
bytes1 integerDelimiter; // default “,”
uint256 integerGroupingSize; // default 3
uint256 fixedWidth; // default 0 (automatic)
}

concat

solpretty还提供了两种字符串拼接方法,以便更好地处理合约中的字符串操作:

  1. Using concat(string memory left, string memory right) 方法进行字符串拼接。
  2. Using concat(string[] memory parts) 方法进行字符串数组拼接。

这些方法可以帮助开发者更有效地处理字符串相关操作,提高合约的可读性和可维护性。

import {pp, SolPretty} from “solpretty/SolPretty.sol”;
using SolPretty for string;

pp(1234).concat(” Alice’s balance”); // -> “1,234 Alice’s Balance”;

// 字符串数组拼接
string[] memory strings = new string[](3);
strings[0] = “a”;
strings[1] = “b”;
strings[2] = “c”;
concat(strings); // -> “abc”

log 打印

solpretty 支持把格式好的字符串打印输出:

  • log(string memory message)
  • log(string[] memory messages)

For example.

using SolPretty for string;

log(“hoagies”); // console2.log(“hoagies”);
pp(1234).log(); // console2.log(“1,234″)
pp(1234).concat(” Alice’s balance”).log(); // console2.log(“1,234 Alice’s balance”)

开发联系:DEXDAO

 

© 版权声明

Related posts

No comments

No comments...