Update docs

This commit is contained in:
github-actions
2023-09-19 19:19:10 +00:00
commit dbe796d542
624 changed files with 107720 additions and 0 deletions

View File

@ -0,0 +1,145 @@
const { BN } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const BitMap = artifacts.require('$BitMaps');
contract('BitMap', function () {
const keyA = new BN('7891');
const keyB = new BN('451');
const keyC = new BN('9592328');
beforeEach(async function () {
this.bitmap = await BitMap.new();
});
it('starts empty', async function () {
expect(await this.bitmap.$get(0, keyA)).to.equal(false);
expect(await this.bitmap.$get(0, keyB)).to.equal(false);
expect(await this.bitmap.$get(0, keyC)).to.equal(false);
});
describe('setTo', function () {
it('set a key to true', async function () {
await this.bitmap.$setTo(0, keyA, true);
expect(await this.bitmap.$get(0, keyA)).to.equal(true);
expect(await this.bitmap.$get(0, keyB)).to.equal(false);
expect(await this.bitmap.$get(0, keyC)).to.equal(false);
});
it('set a key to false', async function () {
await this.bitmap.$setTo(0, keyA, true);
await this.bitmap.$setTo(0, keyA, false);
expect(await this.bitmap.$get(0, keyA)).to.equal(false);
expect(await this.bitmap.$get(0, keyB)).to.equal(false);
expect(await this.bitmap.$get(0, keyC)).to.equal(false);
});
it('set several consecutive keys', async function () {
await this.bitmap.$setTo(0, keyA.addn(0), true);
await this.bitmap.$setTo(0, keyA.addn(1), true);
await this.bitmap.$setTo(0, keyA.addn(2), true);
await this.bitmap.$setTo(0, keyA.addn(3), true);
await this.bitmap.$setTo(0, keyA.addn(4), true);
await this.bitmap.$setTo(0, keyA.addn(2), false);
await this.bitmap.$setTo(0, keyA.addn(4), false);
expect(await this.bitmap.$get(0, keyA.addn(0))).to.equal(true);
expect(await this.bitmap.$get(0, keyA.addn(1))).to.equal(true);
expect(await this.bitmap.$get(0, keyA.addn(2))).to.equal(false);
expect(await this.bitmap.$get(0, keyA.addn(3))).to.equal(true);
expect(await this.bitmap.$get(0, keyA.addn(4))).to.equal(false);
});
});
describe('set', function () {
it('adds a key', async function () {
await this.bitmap.$set(0, keyA);
expect(await this.bitmap.$get(0, keyA)).to.equal(true);
expect(await this.bitmap.$get(0, keyB)).to.equal(false);
expect(await this.bitmap.$get(0, keyC)).to.equal(false);
});
it('adds several keys', async function () {
await this.bitmap.$set(0, keyA);
await this.bitmap.$set(0, keyB);
expect(await this.bitmap.$get(0, keyA)).to.equal(true);
expect(await this.bitmap.$get(0, keyB)).to.equal(true);
expect(await this.bitmap.$get(0, keyC)).to.equal(false);
});
it('adds several consecutive keys', async function () {
await this.bitmap.$set(0, keyA.addn(0));
await this.bitmap.$set(0, keyA.addn(1));
await this.bitmap.$set(0, keyA.addn(3));
expect(await this.bitmap.$get(0, keyA.addn(0))).to.equal(true);
expect(await this.bitmap.$get(0, keyA.addn(1))).to.equal(true);
expect(await this.bitmap.$get(0, keyA.addn(2))).to.equal(false);
expect(await this.bitmap.$get(0, keyA.addn(3))).to.equal(true);
expect(await this.bitmap.$get(0, keyA.addn(4))).to.equal(false);
});
});
describe('unset', function () {
it('removes added keys', async function () {
await this.bitmap.$set(0, keyA);
await this.bitmap.$set(0, keyB);
await this.bitmap.$unset(0, keyA);
expect(await this.bitmap.$get(0, keyA)).to.equal(false);
expect(await this.bitmap.$get(0, keyB)).to.equal(true);
expect(await this.bitmap.$get(0, keyC)).to.equal(false);
});
it('removes consecutive added keys', async function () {
await this.bitmap.$set(0, keyA.addn(0));
await this.bitmap.$set(0, keyA.addn(1));
await this.bitmap.$set(0, keyA.addn(3));
await this.bitmap.$unset(0, keyA.addn(1));
expect(await this.bitmap.$get(0, keyA.addn(0))).to.equal(true);
expect(await this.bitmap.$get(0, keyA.addn(1))).to.equal(false);
expect(await this.bitmap.$get(0, keyA.addn(2))).to.equal(false);
expect(await this.bitmap.$get(0, keyA.addn(3))).to.equal(true);
expect(await this.bitmap.$get(0, keyA.addn(4))).to.equal(false);
});
it('adds and removes multiple keys', async function () {
// []
await this.bitmap.$set(0, keyA);
await this.bitmap.$set(0, keyC);
// [A, C]
await this.bitmap.$unset(0, keyA);
await this.bitmap.$unset(0, keyB);
// [C]
await this.bitmap.$set(0, keyB);
// [C, B]
await this.bitmap.$set(0, keyA);
await this.bitmap.$unset(0, keyC);
// [A, B]
await this.bitmap.$set(0, keyA);
await this.bitmap.$set(0, keyB);
// [A, B]
await this.bitmap.$set(0, keyC);
await this.bitmap.$unset(0, keyA);
// [B, C]
await this.bitmap.$set(0, keyA);
await this.bitmap.$unset(0, keyB);
// [A, C]
expect(await this.bitmap.$get(0, keyA)).to.equal(true);
expect(await this.bitmap.$get(0, keyB)).to.equal(false);
expect(await this.bitmap.$get(0, keyC)).to.equal(true);
});
});
});

View File

@ -0,0 +1,332 @@
// SPDX-License-Identifier: MIT
// This file was procedurally generated from scripts/generate/templates/Checkpoints.t.js.
pragma solidity ^0.8.20;
import {Test} from "forge-std/Test.sol";
import {SafeCast} from "../../../contracts/utils/math/SafeCast.sol";
import {Checkpoints} from "../../../contracts/utils/structs/Checkpoints.sol";
contract CheckpointsTrace224Test is Test {
using Checkpoints for Checkpoints.Trace224;
// Maximum gap between keys used during the fuzzing tests: the `_prepareKeys` function with make sure that
// key#n+1 is in the [key#n, key#n + _KEY_MAX_GAP] range.
uint8 internal constant _KEY_MAX_GAP = 64;
Checkpoints.Trace224 internal _ckpts;
// helpers
function _boundUint32(uint32 x, uint32 min, uint32 max) internal view returns (uint32) {
return SafeCast.toUint32(bound(uint256(x), uint256(min), uint256(max)));
}
function _prepareKeys(uint32[] memory keys, uint32 maxSpread) internal view {
uint32 lastKey = 0;
for (uint256 i = 0; i < keys.length; ++i) {
uint32 key = _boundUint32(keys[i], lastKey, lastKey + maxSpread);
keys[i] = key;
lastKey = key;
}
}
function _assertLatestCheckpoint(bool exist, uint32 key, uint224 value) internal {
(bool _exist, uint32 _key, uint224 _value) = _ckpts.latestCheckpoint();
assertEq(_exist, exist);
assertEq(_key, key);
assertEq(_value, value);
}
// tests
function testPush(uint32[] memory keys, uint224[] memory values, uint32 pastKey) public {
vm.assume(values.length > 0 && values.length <= keys.length);
_prepareKeys(keys, _KEY_MAX_GAP);
// initial state
assertEq(_ckpts.length(), 0);
assertEq(_ckpts.latest(), 0);
_assertLatestCheckpoint(false, 0, 0);
uint256 duplicates = 0;
for (uint256 i = 0; i < keys.length; ++i) {
uint32 key = keys[i];
uint224 value = values[i % values.length];
if (i > 0 && key == keys[i - 1]) ++duplicates;
// push
_ckpts.push(key, value);
// check length & latest
assertEq(_ckpts.length(), i + 1 - duplicates);
assertEq(_ckpts.latest(), value);
_assertLatestCheckpoint(true, key, value);
}
if (keys.length > 0) {
uint32 lastKey = keys[keys.length - 1];
if (lastKey > 0) {
pastKey = _boundUint32(pastKey, 0, lastKey - 1);
vm.expectRevert();
this.push(pastKey, values[keys.length % values.length]);
}
}
}
// used to test reverts
function push(uint32 key, uint224 value) external {
_ckpts.push(key, value);
}
function testLookup(uint32[] memory keys, uint224[] memory values, uint32 lookup) public {
vm.assume(values.length > 0 && values.length <= keys.length);
_prepareKeys(keys, _KEY_MAX_GAP);
uint32 lastKey = keys.length == 0 ? 0 : keys[keys.length - 1];
lookup = _boundUint32(lookup, 0, lastKey + _KEY_MAX_GAP);
uint224 upper = 0;
uint224 lower = 0;
uint32 lowerKey = type(uint32).max;
for (uint256 i = 0; i < keys.length; ++i) {
uint32 key = keys[i];
uint224 value = values[i % values.length];
// push
_ckpts.push(key, value);
// track expected result of lookups
if (key <= lookup) {
upper = value;
}
// find the first key that is not smaller than the lookup key
if (key >= lookup && (i == 0 || keys[i - 1] < lookup)) {
lowerKey = key;
}
if (key == lowerKey) {
lower = value;
}
}
// check lookup
assertEq(_ckpts.lowerLookup(lookup), lower);
assertEq(_ckpts.upperLookup(lookup), upper);
assertEq(_ckpts.upperLookupRecent(lookup), upper);
}
}
contract CheckpointsTrace208Test is Test {
using Checkpoints for Checkpoints.Trace208;
// Maximum gap between keys used during the fuzzing tests: the `_prepareKeys` function with make sure that
// key#n+1 is in the [key#n, key#n + _KEY_MAX_GAP] range.
uint8 internal constant _KEY_MAX_GAP = 64;
Checkpoints.Trace208 internal _ckpts;
// helpers
function _boundUint48(uint48 x, uint48 min, uint48 max) internal view returns (uint48) {
return SafeCast.toUint48(bound(uint256(x), uint256(min), uint256(max)));
}
function _prepareKeys(uint48[] memory keys, uint48 maxSpread) internal view {
uint48 lastKey = 0;
for (uint256 i = 0; i < keys.length; ++i) {
uint48 key = _boundUint48(keys[i], lastKey, lastKey + maxSpread);
keys[i] = key;
lastKey = key;
}
}
function _assertLatestCheckpoint(bool exist, uint48 key, uint208 value) internal {
(bool _exist, uint48 _key, uint208 _value) = _ckpts.latestCheckpoint();
assertEq(_exist, exist);
assertEq(_key, key);
assertEq(_value, value);
}
// tests
function testPush(uint48[] memory keys, uint208[] memory values, uint48 pastKey) public {
vm.assume(values.length > 0 && values.length <= keys.length);
_prepareKeys(keys, _KEY_MAX_GAP);
// initial state
assertEq(_ckpts.length(), 0);
assertEq(_ckpts.latest(), 0);
_assertLatestCheckpoint(false, 0, 0);
uint256 duplicates = 0;
for (uint256 i = 0; i < keys.length; ++i) {
uint48 key = keys[i];
uint208 value = values[i % values.length];
if (i > 0 && key == keys[i - 1]) ++duplicates;
// push
_ckpts.push(key, value);
// check length & latest
assertEq(_ckpts.length(), i + 1 - duplicates);
assertEq(_ckpts.latest(), value);
_assertLatestCheckpoint(true, key, value);
}
if (keys.length > 0) {
uint48 lastKey = keys[keys.length - 1];
if (lastKey > 0) {
pastKey = _boundUint48(pastKey, 0, lastKey - 1);
vm.expectRevert();
this.push(pastKey, values[keys.length % values.length]);
}
}
}
// used to test reverts
function push(uint48 key, uint208 value) external {
_ckpts.push(key, value);
}
function testLookup(uint48[] memory keys, uint208[] memory values, uint48 lookup) public {
vm.assume(values.length > 0 && values.length <= keys.length);
_prepareKeys(keys, _KEY_MAX_GAP);
uint48 lastKey = keys.length == 0 ? 0 : keys[keys.length - 1];
lookup = _boundUint48(lookup, 0, lastKey + _KEY_MAX_GAP);
uint208 upper = 0;
uint208 lower = 0;
uint48 lowerKey = type(uint48).max;
for (uint256 i = 0; i < keys.length; ++i) {
uint48 key = keys[i];
uint208 value = values[i % values.length];
// push
_ckpts.push(key, value);
// track expected result of lookups
if (key <= lookup) {
upper = value;
}
// find the first key that is not smaller than the lookup key
if (key >= lookup && (i == 0 || keys[i - 1] < lookup)) {
lowerKey = key;
}
if (key == lowerKey) {
lower = value;
}
}
// check lookup
assertEq(_ckpts.lowerLookup(lookup), lower);
assertEq(_ckpts.upperLookup(lookup), upper);
assertEq(_ckpts.upperLookupRecent(lookup), upper);
}
}
contract CheckpointsTrace160Test is Test {
using Checkpoints for Checkpoints.Trace160;
// Maximum gap between keys used during the fuzzing tests: the `_prepareKeys` function with make sure that
// key#n+1 is in the [key#n, key#n + _KEY_MAX_GAP] range.
uint8 internal constant _KEY_MAX_GAP = 64;
Checkpoints.Trace160 internal _ckpts;
// helpers
function _boundUint96(uint96 x, uint96 min, uint96 max) internal view returns (uint96) {
return SafeCast.toUint96(bound(uint256(x), uint256(min), uint256(max)));
}
function _prepareKeys(uint96[] memory keys, uint96 maxSpread) internal view {
uint96 lastKey = 0;
for (uint256 i = 0; i < keys.length; ++i) {
uint96 key = _boundUint96(keys[i], lastKey, lastKey + maxSpread);
keys[i] = key;
lastKey = key;
}
}
function _assertLatestCheckpoint(bool exist, uint96 key, uint160 value) internal {
(bool _exist, uint96 _key, uint160 _value) = _ckpts.latestCheckpoint();
assertEq(_exist, exist);
assertEq(_key, key);
assertEq(_value, value);
}
// tests
function testPush(uint96[] memory keys, uint160[] memory values, uint96 pastKey) public {
vm.assume(values.length > 0 && values.length <= keys.length);
_prepareKeys(keys, _KEY_MAX_GAP);
// initial state
assertEq(_ckpts.length(), 0);
assertEq(_ckpts.latest(), 0);
_assertLatestCheckpoint(false, 0, 0);
uint256 duplicates = 0;
for (uint256 i = 0; i < keys.length; ++i) {
uint96 key = keys[i];
uint160 value = values[i % values.length];
if (i > 0 && key == keys[i - 1]) ++duplicates;
// push
_ckpts.push(key, value);
// check length & latest
assertEq(_ckpts.length(), i + 1 - duplicates);
assertEq(_ckpts.latest(), value);
_assertLatestCheckpoint(true, key, value);
}
if (keys.length > 0) {
uint96 lastKey = keys[keys.length - 1];
if (lastKey > 0) {
pastKey = _boundUint96(pastKey, 0, lastKey - 1);
vm.expectRevert();
this.push(pastKey, values[keys.length % values.length]);
}
}
}
// used to test reverts
function push(uint96 key, uint160 value) external {
_ckpts.push(key, value);
}
function testLookup(uint96[] memory keys, uint160[] memory values, uint96 lookup) public {
vm.assume(values.length > 0 && values.length <= keys.length);
_prepareKeys(keys, _KEY_MAX_GAP);
uint96 lastKey = keys.length == 0 ? 0 : keys[keys.length - 1];
lookup = _boundUint96(lookup, 0, lastKey + _KEY_MAX_GAP);
uint160 upper = 0;
uint160 lower = 0;
uint96 lowerKey = type(uint96).max;
for (uint256 i = 0; i < keys.length; ++i) {
uint96 key = keys[i];
uint160 value = values[i % values.length];
// push
_ckpts.push(key, value);
// track expected result of lookups
if (key <= lookup) {
upper = value;
}
// find the first key that is not smaller than the lookup key
if (key >= lookup && (i == 0 || keys[i - 1] < lookup)) {
lowerKey = key;
}
if (key == lowerKey) {
lower = value;
}
}
// check lookup
assertEq(_ckpts.lowerLookup(lookup), lower);
assertEq(_ckpts.upperLookup(lookup), upper);
assertEq(_ckpts.upperLookupRecent(lookup), upper);
}
}

View File

@ -0,0 +1,158 @@
require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const { VALUE_SIZES } = require('../../../scripts/generate/templates/Checkpoints.opts.js');
const { expectRevertCustomError } = require('../../helpers/customError.js');
const { expectRevert } = require('@openzeppelin/test-helpers');
const $Checkpoints = artifacts.require('$Checkpoints');
// The library name may be 'Checkpoints' or 'CheckpointsUpgradeable'
const libraryName = $Checkpoints._json.contractName.replace(/^\$/, '');
const first = array => (array.length ? array[0] : undefined);
const last = array => (array.length ? array[array.length - 1] : undefined);
contract('Checkpoints', function () {
beforeEach(async function () {
this.mock = await $Checkpoints.new();
});
for (const length of VALUE_SIZES) {
describe(`Trace${length}`, function () {
beforeEach(async function () {
this.methods = {
at: (...args) => this.mock.methods[`$at_${libraryName}_Trace${length}(uint256,uint32)`](0, ...args),
latest: (...args) => this.mock.methods[`$latest_${libraryName}_Trace${length}(uint256)`](0, ...args),
latestCheckpoint: (...args) =>
this.mock.methods[`$latestCheckpoint_${libraryName}_Trace${length}(uint256)`](0, ...args),
length: (...args) => this.mock.methods[`$length_${libraryName}_Trace${length}(uint256)`](0, ...args),
push: (...args) => this.mock.methods[`$push(uint256,uint${256 - length},uint${length})`](0, ...args),
lowerLookup: (...args) => this.mock.methods[`$lowerLookup(uint256,uint${256 - length})`](0, ...args),
upperLookup: (...args) => this.mock.methods[`$upperLookup(uint256,uint${256 - length})`](0, ...args),
upperLookupRecent: (...args) =>
this.mock.methods[`$upperLookupRecent(uint256,uint${256 - length})`](0, ...args),
};
});
describe('without checkpoints', function () {
it('at zero reverts', async function () {
// Reverts with array out of bound access, which is unspecified
await expectRevert.unspecified(this.methods.at(0));
});
it('returns zero as latest value', async function () {
expect(await this.methods.latest()).to.be.bignumber.equal('0');
const ckpt = await this.methods.latestCheckpoint();
expect(ckpt[0]).to.be.equal(false);
expect(ckpt[1]).to.be.bignumber.equal('0');
expect(ckpt[2]).to.be.bignumber.equal('0');
});
it('lookup returns 0', async function () {
expect(await this.methods.lowerLookup(0)).to.be.bignumber.equal('0');
expect(await this.methods.upperLookup(0)).to.be.bignumber.equal('0');
expect(await this.methods.upperLookupRecent(0)).to.be.bignumber.equal('0');
});
});
describe('with checkpoints', function () {
beforeEach('pushing checkpoints', async function () {
this.checkpoints = [
{ key: '2', value: '17' },
{ key: '3', value: '42' },
{ key: '5', value: '101' },
{ key: '7', value: '23' },
{ key: '11', value: '99' },
];
for (const { key, value } of this.checkpoints) {
await this.methods.push(key, value);
}
});
it('at keys', async function () {
for (const [index, { key, value }] of this.checkpoints.entries()) {
const at = await this.methods.at(index);
expect(at._value).to.be.bignumber.equal(value);
expect(at._key).to.be.bignumber.equal(key);
}
});
it('length', async function () {
expect(await this.methods.length()).to.be.bignumber.equal(this.checkpoints.length.toString());
});
it('returns latest value', async function () {
expect(await this.methods.latest()).to.be.bignumber.equal(last(this.checkpoints).value);
const ckpt = await this.methods.latestCheckpoint();
expect(ckpt[0]).to.be.equal(true);
expect(ckpt[1]).to.be.bignumber.equal(last(this.checkpoints).key);
expect(ckpt[2]).to.be.bignumber.equal(last(this.checkpoints).value);
});
it('cannot push values in the past', async function () {
await expectRevertCustomError(
this.methods.push(last(this.checkpoints).key - 1, '0'),
'CheckpointUnorderedInsertion',
[],
);
});
it('can update last value', async function () {
const newValue = '42';
// check length before the update
expect(await this.methods.length()).to.be.bignumber.equal(this.checkpoints.length.toString());
// update last key
await this.methods.push(last(this.checkpoints).key, newValue);
expect(await this.methods.latest()).to.be.bignumber.equal(newValue);
// check that length did not change
expect(await this.methods.length()).to.be.bignumber.equal(this.checkpoints.length.toString());
});
it('lower lookup', async function () {
for (let i = 0; i < 14; ++i) {
const value = first(this.checkpoints.filter(x => i <= x.key))?.value || '0';
expect(await this.methods.lowerLookup(i)).to.be.bignumber.equal(value);
}
});
it('upper lookup & upperLookupRecent', async function () {
for (let i = 0; i < 14; ++i) {
const value = last(this.checkpoints.filter(x => i >= x.key))?.value || '0';
expect(await this.methods.upperLookup(i)).to.be.bignumber.equal(value);
expect(await this.methods.upperLookupRecent(i)).to.be.bignumber.equal(value);
}
});
it('upperLookupRecent with more than 5 checkpoints', async function () {
const moreCheckpoints = [
{ key: '12', value: '22' },
{ key: '13', value: '131' },
{ key: '17', value: '45' },
{ key: '19', value: '31452' },
{ key: '21', value: '0' },
];
const allCheckpoints = [].concat(this.checkpoints, moreCheckpoints);
for (const { key, value } of moreCheckpoints) {
await this.methods.push(key, value);
}
for (let i = 0; i < 25; ++i) {
const value = last(allCheckpoints.filter(x => i >= x.key))?.value || '0';
expect(await this.methods.upperLookup(i)).to.be.bignumber.equal(value);
expect(await this.methods.upperLookupRecent(i)).to.be.bignumber.equal(value);
}
});
});
});
}
});

View File

@ -0,0 +1,99 @@
const { expectEvent } = require('@openzeppelin/test-helpers');
const { expectRevertCustomError } = require('../../helpers/customError');
const DoubleEndedQueue = artifacts.require('$DoubleEndedQueue');
/** Rebuild the content of the deque as a JS array. */
const getContent = deque =>
deque.$length(0).then(bn =>
Promise.all(
Array(bn.toNumber())
.fill()
.map((_, i) => deque.$at(0, i)),
),
);
contract('DoubleEndedQueue', function () {
const bytesA = '0xdeadbeef'.padEnd(66, '0');
const bytesB = '0x0123456789'.padEnd(66, '0');
const bytesC = '0x42424242'.padEnd(66, '0');
const bytesD = '0x171717'.padEnd(66, '0');
beforeEach(async function () {
this.deque = await DoubleEndedQueue.new();
});
describe('when empty', function () {
it('getters', async function () {
expect(await this.deque.$empty(0)).to.be.equal(true);
expect(await getContent(this.deque)).to.have.ordered.members([]);
});
it('reverts on accesses', async function () {
await expectRevertCustomError(this.deque.$popBack(0), 'QueueEmpty', []);
await expectRevertCustomError(this.deque.$popFront(0), 'QueueEmpty', []);
await expectRevertCustomError(this.deque.$back(0), 'QueueEmpty', []);
await expectRevertCustomError(this.deque.$front(0), 'QueueEmpty', []);
});
});
describe('when not empty', function () {
beforeEach(async function () {
await this.deque.$pushBack(0, bytesB);
await this.deque.$pushFront(0, bytesA);
await this.deque.$pushBack(0, bytesC);
this.content = [bytesA, bytesB, bytesC];
});
it('getters', async function () {
expect(await this.deque.$empty(0)).to.be.equal(false);
expect(await this.deque.$length(0)).to.be.bignumber.equal(this.content.length.toString());
expect(await this.deque.$front(0)).to.be.equal(this.content[0]);
expect(await this.deque.$back(0)).to.be.equal(this.content[this.content.length - 1]);
expect(await getContent(this.deque)).to.have.ordered.members(this.content);
});
it('out of bounds access', async function () {
await expectRevertCustomError(this.deque.$at(0, this.content.length), 'QueueOutOfBounds', []);
});
describe('push', function () {
it('front', async function () {
await this.deque.$pushFront(0, bytesD);
this.content.unshift(bytesD); // add element at the beginning
expect(await getContent(this.deque)).to.have.ordered.members(this.content);
});
it('back', async function () {
await this.deque.$pushBack(0, bytesD);
this.content.push(bytesD); // add element at the end
expect(await getContent(this.deque)).to.have.ordered.members(this.content);
});
});
describe('pop', function () {
it('front', async function () {
const value = this.content.shift(); // remove first element
expectEvent(await this.deque.$popFront(0), 'return$popFront', { value });
expect(await getContent(this.deque)).to.have.ordered.members(this.content);
});
it('back', async function () {
const value = this.content.pop(); // remove last element
expectEvent(await this.deque.$popBack(0), 'return$popBack', { value });
expect(await getContent(this.deque)).to.have.ordered.members(this.content);
});
});
it('clear', async function () {
await this.deque.$clear(0);
expect(await this.deque.$empty(0)).to.be.equal(true);
expect(await getContent(this.deque)).to.have.ordered.members([]);
});
});
});

View File

@ -0,0 +1,178 @@
const { expectEvent } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const zip = require('lodash.zip');
const { expectRevertCustomError } = require('../../helpers/customError');
function shouldBehaveLikeMap(keys, values, zeroValue, methods, events) {
const [keyA, keyB, keyC] = keys;
const [valueA, valueB, valueC] = values;
async function expectMembersMatch(map, keys, values) {
expect(keys.length).to.equal(values.length);
await Promise.all(keys.map(async key => expect(await methods.contains(map, key)).to.equal(true)));
expect(await methods.length(map)).to.bignumber.equal(keys.length.toString());
expect((await Promise.all(keys.map(key => methods.get(map, key)))).map(k => k.toString())).to.have.same.members(
values.map(value => value.toString()),
);
// To compare key-value pairs, we zip keys and values, and convert BNs to
// strings to workaround Chai limitations when dealing with nested arrays
expect(
await Promise.all(
[...Array(keys.length).keys()].map(async index => {
const entry = await methods.at(map, index);
return [entry[0].toString(), entry[1].toString()];
}),
),
).to.have.same.deep.members(
zip(
keys.map(k => k.toString()),
values.map(v => v.toString()),
),
);
// This also checks that both arrays have the same length
expect((await methods.keys(map)).map(k => k.toString())).to.have.same.members(keys.map(key => key.toString()));
}
it('starts empty', async function () {
expect(await methods.contains(this.map, keyA)).to.equal(false);
await expectMembersMatch(this.map, [], []);
});
describe('set', function () {
it('adds a key', async function () {
const receipt = await methods.set(this.map, keyA, valueA);
expectEvent(receipt, events.setReturn, { ret0: true });
await expectMembersMatch(this.map, [keyA], [valueA]);
});
it('adds several keys', async function () {
await methods.set(this.map, keyA, valueA);
await methods.set(this.map, keyB, valueB);
await expectMembersMatch(this.map, [keyA, keyB], [valueA, valueB]);
expect(await methods.contains(this.map, keyC)).to.equal(false);
});
it('returns false when adding keys already in the set', async function () {
await methods.set(this.map, keyA, valueA);
const receipt = await methods.set(this.map, keyA, valueA);
expectEvent(receipt, events.setReturn, { ret0: false });
await expectMembersMatch(this.map, [keyA], [valueA]);
});
it('updates values for keys already in the set', async function () {
await methods.set(this.map, keyA, valueA);
await methods.set(this.map, keyA, valueB);
await expectMembersMatch(this.map, [keyA], [valueB]);
});
});
describe('remove', function () {
it('removes added keys', async function () {
await methods.set(this.map, keyA, valueA);
const receipt = await methods.remove(this.map, keyA);
expectEvent(receipt, events.removeReturn, { ret0: true });
expect(await methods.contains(this.map, keyA)).to.equal(false);
await expectMembersMatch(this.map, [], []);
});
it('returns false when removing keys not in the set', async function () {
const receipt = await methods.remove(this.map, keyA);
expectEvent(receipt, events.removeReturn, { ret0: false });
expect(await methods.contains(this.map, keyA)).to.equal(false);
});
it('adds and removes multiple keys', async function () {
// []
await methods.set(this.map, keyA, valueA);
await methods.set(this.map, keyC, valueC);
// [A, C]
await methods.remove(this.map, keyA);
await methods.remove(this.map, keyB);
// [C]
await methods.set(this.map, keyB, valueB);
// [C, B]
await methods.set(this.map, keyA, valueA);
await methods.remove(this.map, keyC);
// [A, B]
await methods.set(this.map, keyA, valueA);
await methods.set(this.map, keyB, valueB);
// [A, B]
await methods.set(this.map, keyC, valueC);
await methods.remove(this.map, keyA);
// [B, C]
await methods.set(this.map, keyA, valueA);
await methods.remove(this.map, keyB);
// [A, C]
await expectMembersMatch(this.map, [keyA, keyC], [valueA, valueC]);
expect(await methods.contains(this.map, keyA)).to.equal(true);
expect(await methods.contains(this.map, keyB)).to.equal(false);
expect(await methods.contains(this.map, keyC)).to.equal(true);
});
});
describe('read', function () {
beforeEach(async function () {
await methods.set(this.map, keyA, valueA);
});
describe('get', function () {
it('existing value', async function () {
expect(await methods.get(this.map, keyA).then(r => r.toString())).to.be.equal(valueA.toString());
});
it('missing value', async function () {
const key = web3.utils.toHex(keyB);
await expectRevertCustomError(methods.get(this.map, keyB), 'EnumerableMapNonexistentKey', [
key.length == 66 ? key : web3.utils.padLeft(key, 64, '0'),
]);
});
});
describe('tryGet', function () {
it('existing value', async function () {
const result = await methods.tryGet(this.map, keyA);
expect(result['0']).to.be.equal(true);
expect(result['1'].toString()).to.be.equal(valueA.toString());
});
it('missing value', async function () {
const result = await methods.tryGet(this.map, keyB);
expect(result['0']).to.be.equal(false);
expect(result['1'].toString()).to.be.equal(zeroValue.toString());
});
});
});
}
module.exports = {
shouldBehaveLikeMap,
};

View File

@ -0,0 +1,149 @@
const { BN, constants } = require('@openzeppelin/test-helpers');
const { mapValues } = require('../../helpers/iterate');
const EnumerableMap = artifacts.require('$EnumerableMap');
const { shouldBehaveLikeMap } = require('./EnumerableMap.behavior');
const getMethods = ms => {
return mapValues(
ms,
m =>
(self, ...args) =>
self.methods[m](0, ...args),
);
};
// Get the name of the library. In the transpiled code it will be EnumerableMapUpgradeable.
const library = EnumerableMap._json.contractName.replace(/^\$/, '');
contract('EnumerableMap', function (accounts) {
const [accountA, accountB, accountC] = accounts;
const keyA = new BN('7891');
const keyB = new BN('451');
const keyC = new BN('9592328');
const bytesA = '0xdeadbeef'.padEnd(66, '0');
const bytesB = '0x0123456789'.padEnd(66, '0');
const bytesC = '0x42424242'.padEnd(66, '0');
beforeEach(async function () {
this.map = await EnumerableMap.new();
});
// AddressToUintMap
describe('AddressToUintMap', function () {
shouldBehaveLikeMap(
[accountA, accountB, accountC],
[keyA, keyB, keyC],
new BN('0'),
getMethods({
set: '$set(uint256,address,uint256)',
get: '$get(uint256,address)',
tryGet: '$tryGet(uint256,address)',
remove: '$remove(uint256,address)',
length: `$length_${library}_AddressToUintMap(uint256)`,
at: `$at_${library}_AddressToUintMap(uint256,uint256)`,
contains: '$contains(uint256,address)',
keys: `$keys_${library}_AddressToUintMap(uint256)`,
}),
{
setReturn: `return$set_${library}_AddressToUintMap_address_uint256`,
removeReturn: `return$remove_${library}_AddressToUintMap_address`,
},
);
});
// UintToAddressMap
describe('UintToAddressMap', function () {
shouldBehaveLikeMap(
[keyA, keyB, keyC],
[accountA, accountB, accountC],
constants.ZERO_ADDRESS,
getMethods({
set: '$set(uint256,uint256,address)',
get: `$get_${library}_UintToAddressMap(uint256,uint256)`,
tryGet: `$tryGet_${library}_UintToAddressMap(uint256,uint256)`,
remove: `$remove_${library}_UintToAddressMap(uint256,uint256)`,
length: `$length_${library}_UintToAddressMap(uint256)`,
at: `$at_${library}_UintToAddressMap(uint256,uint256)`,
contains: `$contains_${library}_UintToAddressMap(uint256,uint256)`,
keys: `$keys_${library}_UintToAddressMap(uint256)`,
}),
{
setReturn: `return$set_${library}_UintToAddressMap_uint256_address`,
removeReturn: `return$remove_${library}_UintToAddressMap_uint256`,
},
);
});
// Bytes32ToBytes32Map
describe('Bytes32ToBytes32Map', function () {
shouldBehaveLikeMap(
[keyA, keyB, keyC].map(k => '0x' + k.toString(16).padEnd(64, '0')),
[bytesA, bytesB, bytesC],
constants.ZERO_BYTES32,
getMethods({
set: '$set(uint256,bytes32,bytes32)',
get: `$get_${library}_Bytes32ToBytes32Map(uint256,bytes32)`,
tryGet: `$tryGet_${library}_Bytes32ToBytes32Map(uint256,bytes32)`,
remove: `$remove_${library}_Bytes32ToBytes32Map(uint256,bytes32)`,
length: `$length_${library}_Bytes32ToBytes32Map(uint256)`,
at: `$at_${library}_Bytes32ToBytes32Map(uint256,uint256)`,
contains: `$contains_${library}_Bytes32ToBytes32Map(uint256,bytes32)`,
keys: `$keys_${library}_Bytes32ToBytes32Map(uint256)`,
}),
{
setReturn: `return$set_${library}_Bytes32ToBytes32Map_bytes32_bytes32`,
removeReturn: `return$remove_${library}_Bytes32ToBytes32Map_bytes32`,
},
);
});
// UintToUintMap
describe('UintToUintMap', function () {
shouldBehaveLikeMap(
[keyA, keyB, keyC],
[keyA, keyB, keyC].map(k => k.add(new BN('1332'))),
new BN('0'),
getMethods({
set: '$set(uint256,uint256,uint256)',
get: `$get_${library}_UintToUintMap(uint256,uint256)`,
tryGet: `$tryGet_${library}_UintToUintMap(uint256,uint256)`,
remove: `$remove_${library}_UintToUintMap(uint256,uint256)`,
length: `$length_${library}_UintToUintMap(uint256)`,
at: `$at_${library}_UintToUintMap(uint256,uint256)`,
contains: `$contains_${library}_UintToUintMap(uint256,uint256)`,
keys: `$keys_${library}_UintToUintMap(uint256)`,
}),
{
setReturn: `return$set_${library}_UintToUintMap_uint256_uint256`,
removeReturn: `return$remove_${library}_UintToUintMap_uint256`,
},
);
});
// Bytes32ToUintMap
describe('Bytes32ToUintMap', function () {
shouldBehaveLikeMap(
[bytesA, bytesB, bytesC],
[keyA, keyB, keyC],
new BN('0'),
getMethods({
set: '$set(uint256,bytes32,uint256)',
get: `$get_${library}_Bytes32ToUintMap(uint256,bytes32)`,
tryGet: `$tryGet_${library}_Bytes32ToUintMap(uint256,bytes32)`,
remove: `$remove_${library}_Bytes32ToUintMap(uint256,bytes32)`,
length: `$length_${library}_Bytes32ToUintMap(uint256)`,
at: `$at_${library}_Bytes32ToUintMap(uint256,uint256)`,
contains: `$contains_${library}_Bytes32ToUintMap(uint256,bytes32)`,
keys: `$keys_${library}_Bytes32ToUintMap(uint256)`,
}),
{
setReturn: `return$set_${library}_Bytes32ToUintMap_bytes32_uint256`,
removeReturn: `return$remove_${library}_Bytes32ToUintMap_bytes32`,
},
);
});
});

View File

@ -0,0 +1,129 @@
const { expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
function shouldBehaveLikeSet(values, methods, events) {
const [valueA, valueB, valueC] = values;
async function expectMembersMatch(set, values) {
const contains = await Promise.all(values.map(value => methods.contains(set, value)));
expect(contains.every(Boolean)).to.be.equal(true);
const length = await methods.length(set);
expect(length).to.bignumber.equal(values.length.toString());
// To compare values we convert to strings to workaround Chai
// limitations when dealing with nested arrays (required for BNs)
const indexedValues = await Promise.all(
Array(values.length)
.fill()
.map((_, index) => methods.at(set, index)),
);
expect(indexedValues.map(v => v.toString())).to.have.same.members(values.map(v => v.toString()));
const returnedValues = await methods.values(set);
expect(returnedValues.map(v => v.toString())).to.have.same.members(values.map(v => v.toString()));
}
it('starts empty', async function () {
expect(await methods.contains(this.set, valueA)).to.equal(false);
await expectMembersMatch(this.set, []);
});
describe('add', function () {
it('adds a value', async function () {
const receipt = await methods.add(this.set, valueA);
expectEvent(receipt, events.addReturn, { ret0: true });
await expectMembersMatch(this.set, [valueA]);
});
it('adds several values', async function () {
await methods.add(this.set, valueA);
await methods.add(this.set, valueB);
await expectMembersMatch(this.set, [valueA, valueB]);
expect(await methods.contains(this.set, valueC)).to.equal(false);
});
it('returns false when adding values already in the set', async function () {
await methods.add(this.set, valueA);
const receipt = await methods.add(this.set, valueA);
expectEvent(receipt, events.addReturn, { ret0: false });
await expectMembersMatch(this.set, [valueA]);
});
});
describe('at', function () {
it('reverts when retrieving non-existent elements', async function () {
await expectRevert.unspecified(methods.at(this.set, 0));
});
});
describe('remove', function () {
it('removes added values', async function () {
await methods.add(this.set, valueA);
const receipt = await methods.remove(this.set, valueA);
expectEvent(receipt, events.removeReturn, { ret0: true });
expect(await methods.contains(this.set, valueA)).to.equal(false);
await expectMembersMatch(this.set, []);
});
it('returns false when removing values not in the set', async function () {
const receipt = await methods.remove(this.set, valueA);
expectEvent(receipt, events.removeReturn, { ret0: false });
expect(await methods.contains(this.set, valueA)).to.equal(false);
});
it('adds and removes multiple values', async function () {
// []
await methods.add(this.set, valueA);
await methods.add(this.set, valueC);
// [A, C]
await methods.remove(this.set, valueA);
await methods.remove(this.set, valueB);
// [C]
await methods.add(this.set, valueB);
// [C, B]
await methods.add(this.set, valueA);
await methods.remove(this.set, valueC);
// [A, B]
await methods.add(this.set, valueA);
await methods.add(this.set, valueB);
// [A, B]
await methods.add(this.set, valueC);
await methods.remove(this.set, valueA);
// [B, C]
await methods.add(this.set, valueA);
await methods.remove(this.set, valueB);
// [A, C]
await expectMembersMatch(this.set, [valueA, valueC]);
expect(await methods.contains(this.set, valueB)).to.equal(false);
});
});
}
module.exports = {
shouldBehaveLikeSet,
};

View File

@ -0,0 +1,79 @@
const EnumerableSet = artifacts.require('$EnumerableSet');
const { mapValues } = require('../../helpers/iterate');
const { shouldBehaveLikeSet } = require('./EnumerableSet.behavior');
const getMethods = ms => {
return mapValues(
ms,
m =>
(self, ...args) =>
self.methods[m](0, ...args),
);
};
// Get the name of the library. In the transpiled code it will be EnumerableSetUpgradeable.
const library = EnumerableSet._json.contractName.replace(/^\$/, '');
contract('EnumerableSet', function (accounts) {
beforeEach(async function () {
this.set = await EnumerableSet.new();
});
// Bytes32Set
describe('EnumerableBytes32Set', function () {
shouldBehaveLikeSet(
['0xdeadbeef', '0x0123456789', '0x42424242'].map(e => e.padEnd(66, '0')),
getMethods({
add: '$add(uint256,bytes32)',
remove: '$remove(uint256,bytes32)',
contains: '$contains(uint256,bytes32)',
length: `$length_${library}_Bytes32Set(uint256)`,
at: `$at_${library}_Bytes32Set(uint256,uint256)`,
values: `$values_${library}_Bytes32Set(uint256)`,
}),
{
addReturn: `return$add_${library}_Bytes32Set_bytes32`,
removeReturn: `return$remove_${library}_Bytes32Set_bytes32`,
},
);
});
// AddressSet
describe('EnumerableAddressSet', function () {
shouldBehaveLikeSet(
accounts,
getMethods({
add: '$add(uint256,address)',
remove: '$remove(uint256,address)',
contains: '$contains(uint256,address)',
length: `$length_${library}_AddressSet(uint256)`,
at: `$at_${library}_AddressSet(uint256,uint256)`,
values: `$values_${library}_AddressSet(uint256)`,
}),
{
addReturn: `return$add_${library}_AddressSet_address`,
removeReturn: `return$remove_${library}_AddressSet_address`,
},
);
});
// UintSet
describe('EnumerableUintSet', function () {
shouldBehaveLikeSet(
[1234, 5678, 9101112].map(e => web3.utils.toBN(e)),
getMethods({
add: '$add(uint256,uint256)',
remove: '$remove(uint256,uint256)',
contains: '$contains(uint256,uint256)',
length: `$length_${library}_UintSet(uint256)`,
at: `$at_${library}_UintSet(uint256,uint256)`,
values: `$values_${library}_UintSet(uint256)`,
}),
{
addReturn: `return$add_${library}_UintSet_uint256`,
removeReturn: `return$remove_${library}_UintSet_uint256`,
},
);
});
});