原文发布在 https://github.com/33357/smartcontract-apps这是一个面向中文社区,分析市面上智能合约应用的架构与实现的仓库。欢迎关注开源知识项目!
最省GAS链上排序 原理因为区块链机制的限制,智能合约的执行步骤越多,消耗的GAS也越多。传统的排序算法需要对数组进行遍历从而实现排序,这种操作消耗的GAS会随着数组长度成正比上涨。为了在链上实现排序并尽可能地减少GAS消耗,我们需要把计算量放到链下,把验证放到链上,从而实现既安全又节约GAS的链上排序功能。
实现uint256 public firstSortId;
uint256 public sortLength;
mapping(uint256 => uint256) private _sortMap;
function _addSort(
uint256 beforeSortId,
uint256 id
) internal {
if (beforeSortId == 0) {
if (firstSortId != 0) {
require(
firstSortId = id,
"Sort: sort error"
);
_sortMap[beforeSortId] = id;
} else {
require(
beforeSortId >= id &&
_sortMap[beforeSortId]
关注
打赏