Update docs

This commit is contained in:
github-actions
2022-11-08 14:30:45 +00:00
parent 1643a5673b
commit 6db3408885
193 changed files with 16530 additions and 45158 deletions

View File

@ -1,6 +1,8 @@
#!/usr/bin/env node
const cp = require('child_process');
const fs = require('fs');
const path = require('path');
const format = require('./format-lines');
function getVersion (path) {
@ -14,16 +16,31 @@ function getVersion (path) {
}
for (const [ file, template ] of Object.entries({
'utils/math/SafeCast.sol': './templates/SafeCast',
'mocks/SafeCastMock.sol': './templates/SafeCastMock',
// SafeCast
'utils/math/SafeCast.sol': './templates/SafeCast.js',
'mocks/SafeCastMock.sol': './templates/SafeCastMock.js',
// EnumerableSet
'utils/structs/EnumerableSet.sol': './templates/EnumerableSet.js',
'mocks/EnumerableSetMock.sol': './templates/EnumerableSetMock.js',
// EnumerableMap
'utils/structs/EnumerableMap.sol': './templates/EnumerableMap.js',
'mocks/EnumerableMapMock.sol': './templates/EnumerableMapMock.js',
// Checkpoints
'utils/Checkpoints.sol': './templates/Checkpoints.js',
'mocks/CheckpointsMock.sol': './templates/CheckpointsMock.js',
})) {
const path = `./contracts/${file}`;
const version = getVersion(path);
const script = path.relative(path.join(__dirname, '../..'), __filename);
const input = path.join(path.dirname(script), template);
const output = `./contracts/${file}`;
const version = getVersion(output);
const content = format(
'// SPDX-License-Identifier: MIT',
(version ? version + ` (${file})\n` : ''),
require(template).trimEnd(),
...(version ? [ version + ` (${file})` ] : []),
`// This file was procedurally generated from ${input}.`,
'',
require(template),
);
fs.writeFileSync(path, content);
fs.writeFileSync(output, content);
cp.execFileSync('prettier', ['--write', output]);
}

View File

@ -0,0 +1,299 @@
const format = require('../format-lines');
const VALUE_SIZES = [ 224, 160 ];
const header = `\
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SafeCast.sol";
/**
* @dev This library defines the \`History\` struct, for checkpointing values as they change at different points in
* time, and later looking up past values by block number. See {Votes} as an example.
*
* To create a history of checkpoints define a variable type \`Checkpoints.History\` in your contract, and store a new
* checkpoint for the current transaction block using the {push} function.
*
* _Available since v4.5._
*/
`;
const types = opts => `\
struct ${opts.historyTypeName} {
${opts.checkpointTypeName}[] ${opts.checkpointFieldName};
}
struct ${opts.checkpointTypeName} {
${opts.keyTypeName} ${opts.keyFieldName};
${opts.valueTypeName} ${opts.valueFieldName};
}
`;
/* eslint-disable max-len */
const operations = opts => `\
/**
* @dev Pushes a (\`key\`, \`value\`) pair into a ${opts.historyTypeName} so that it is stored as the checkpoint.
*
* Returns previous value and new value.
*/
function push(
${opts.historyTypeName} storage self,
${opts.keyTypeName} key,
${opts.valueTypeName} value
) internal returns (${opts.valueTypeName}, ${opts.valueTypeName}) {
return _insert(self.${opts.checkpointFieldName}, key, value);
}
/**
* @dev Returns the value in the oldest checkpoint with key greater or equal than the search key, or zero if there is none.
*/
function lowerLookup(${opts.historyTypeName} storage self, ${opts.keyTypeName} key) internal view returns (${opts.valueTypeName}) {
uint256 len = self.${opts.checkpointFieldName}.length;
uint256 pos = _lowerBinaryLookup(self.${opts.checkpointFieldName}, key, 0, len);
return pos == len ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos).${opts.valueFieldName};
}
/**
* @dev Returns the value in the most recent checkpoint with key lower or equal than the search key.
*/
function upperLookup(${opts.historyTypeName} storage self, ${opts.keyTypeName} key) internal view returns (${opts.valueTypeName}) {
uint256 len = self.${opts.checkpointFieldName}.length;
uint256 pos = _upperBinaryLookup(self.${opts.checkpointFieldName}, key, 0, len);
return pos == 0 ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1).${opts.valueFieldName};
}
`;
const legacyOperations = opts => `\
/**
* @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one
* before it is returned, or zero otherwise.
*/
function getAtBlock(${opts.historyTypeName} storage self, uint256 blockNumber) internal view returns (uint256) {
require(blockNumber < block.number, "Checkpoints: block not yet mined");
uint32 key = SafeCast.toUint32(blockNumber);
uint256 len = self.${opts.checkpointFieldName}.length;
uint256 pos = _upperBinaryLookup(self.${opts.checkpointFieldName}, key, 0, len);
return pos == 0 ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1).${opts.valueFieldName};
}
/**
* @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one
* before it is returned, or zero otherwise. Similar to {upperLookup} but optimized for the case when the searched
* checkpoint is probably "recent", defined as being among the last sqrt(N) checkpoints where N is the number of
* checkpoints.
*/
function getAtProbablyRecentBlock(${opts.historyTypeName} storage self, uint256 blockNumber) internal view returns (uint256) {
require(blockNumber < block.number, "Checkpoints: block not yet mined");
uint32 key = SafeCast.toUint32(blockNumber);
uint256 len = self.${opts.checkpointFieldName}.length;
uint256 low = 0;
uint256 high = len;
if (len > 5) {
uint256 mid = len - Math.sqrt(len);
if (key < _unsafeAccess(self.${opts.checkpointFieldName}, mid)._blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
uint256 pos = _upperBinaryLookup(self.${opts.checkpointFieldName}, key, low, high);
return pos == 0 ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1).${opts.valueFieldName};
}
/**
* @dev Pushes a value onto a History so that it is stored as the checkpoint for the current block.
*
* Returns previous value and new value.
*/
function push(${opts.historyTypeName} storage self, uint256 value) internal returns (uint256, uint256) {
return _insert(self.${opts.checkpointFieldName}, SafeCast.toUint32(block.number), SafeCast.toUint224(value));
}
/**
* @dev Pushes a value onto a History, by updating the latest value using binary operation \`op\`. The new value will
* be set to \`op(latest, delta)\`.
*
* Returns previous value and new value.
*/
function push(
${opts.historyTypeName} storage self,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) internal returns (uint256, uint256) {
return push(self, op(latest(self), delta));
}
`;
const common = opts => `\
/**
* @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
*/
function latest(${opts.historyTypeName} storage self) internal view returns (${opts.valueTypeName}) {
uint256 pos = self.${opts.checkpointFieldName}.length;
return pos == 0 ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1).${opts.valueFieldName};
}
/**
* @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value
* in the most recent checkpoint.
*/
function latestCheckpoint(${opts.historyTypeName} storage self)
internal
view
returns (
bool exists,
${opts.keyTypeName} ${opts.keyFieldName},
${opts.valueTypeName} ${opts.valueFieldName}
)
{
uint256 pos = self.${opts.checkpointFieldName}.length;
if (pos == 0) {
return (false, 0, 0);
} else {
${opts.checkpointTypeName} memory ckpt = _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1);
return (true, ckpt.${opts.keyFieldName}, ckpt.${opts.valueFieldName});
}
}
/**
* @dev Returns the number of checkpoint.
*/
function length(${opts.historyTypeName} storage self) internal view returns (uint256) {
return self.${opts.checkpointFieldName}.length;
}
/**
* @dev Pushes a (\`key\`, \`value\`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,
* or by updating the last one.
*/
function _insert(
${opts.checkpointTypeName}[] storage self,
${opts.keyTypeName} key,
${opts.valueTypeName} value
) private returns (${opts.valueTypeName}, ${opts.valueTypeName}) {
uint256 pos = self.length;
if (pos > 0) {
// Copying to memory is important here.
${opts.checkpointTypeName} memory last = _unsafeAccess(self, pos - 1);
// Checkpoints keys must be increasing.
require(last.${opts.keyFieldName} <= key, "Checkpoint: invalid key");
// Update or push new checkpoint
if (last.${opts.keyFieldName} == key) {
_unsafeAccess(self, pos - 1).${opts.valueFieldName} = value;
} else {
self.push(${opts.checkpointTypeName}({${opts.keyFieldName}: key, ${opts.valueFieldName}: value}));
}
return (last.${opts.valueFieldName}, value);
} else {
self.push(${opts.checkpointTypeName}({${opts.keyFieldName}: key, ${opts.valueFieldName}: value}));
return (0, value);
}
}
/**
* @dev Return the index of the oldest checkpoint whose key is greater than the search key, or \`high\` if there is none.
* \`low\` and \`high\` define a section where to do the search, with inclusive \`low\` and exclusive \`high\`.
*
* WARNING: \`high\` should not be greater than the array's length.
*/
function _upperBinaryLookup(
${opts.checkpointTypeName}[] storage self,
${opts.keyTypeName} key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid).${opts.keyFieldName} > key) {
high = mid;
} else {
low = mid + 1;
}
}
return high;
}
/**
* @dev Return the index of the oldest checkpoint whose key is greater or equal than the search key, or \`high\` if there is none.
* \`low\` and \`high\` define a section where to do the search, with inclusive \`low\` and exclusive \`high\`.
*
* WARNING: \`high\` should not be greater than the array's length.
*/
function _lowerBinaryLookup(
${opts.checkpointTypeName}[] storage self,
${opts.keyTypeName} key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid).${opts.keyFieldName} < key) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
function _unsafeAccess(${opts.checkpointTypeName}[] storage self, uint256 pos)
private
pure
returns (${opts.checkpointTypeName} storage result)
{
assembly {
mstore(0, self.slot)
result.slot := add(keccak256(0, 0x20), pos)
}
}
`;
/* eslint-enable max-len */
// OPTIONS
const defaultOpts = (size) => ({
historyTypeName: `Trace${size}`,
checkpointTypeName: `Checkpoint${size}`,
checkpointFieldName: '_checkpoints',
keyTypeName: `uint${256 - size}`,
keyFieldName: '_key',
valueTypeName: `uint${size}`,
valueFieldName: '_value',
});
const OPTS = VALUE_SIZES.map(size => defaultOpts(size));
const LEGACY_OPTS = {
...defaultOpts(224),
historyTypeName: 'History',
checkpointTypeName: 'Checkpoint',
keyFieldName: '_blockNumber',
};
// GENERATE
module.exports = format(
header.trimEnd(),
'library Checkpoints {',
[
// Legacy types & functions
types(LEGACY_OPTS),
legacyOperations(LEGACY_OPTS),
common(LEGACY_OPTS),
// New flavors
...OPTS.flatMap(opts => [
types(opts),
operations(opts),
common(opts),
]),
],
'}',
);

View File

@ -0,0 +1,80 @@
const format = require('../format-lines');
const VALUE_SIZES = [ 224, 160 ];
const header = `\
pragma solidity ^0.8.0;
import "../utils/Checkpoints.sol";
`;
const legacy = () => `\
contract CheckpointsMock {
using Checkpoints for Checkpoints.History;
Checkpoints.History private _totalCheckpoints;
function latest() public view returns (uint256) {
return _totalCheckpoints.latest();
}
function latestCheckpoint() public view returns (bool, uint256, uint256) {
return _totalCheckpoints.latestCheckpoint();
}
function length() public view returns (uint256) {
return _totalCheckpoints.length();
}
function push(uint256 value) public returns (uint256, uint256) {
return _totalCheckpoints.push(value);
}
function getAtBlock(uint256 blockNumber) public view returns (uint256) {
return _totalCheckpoints.getAtBlock(blockNumber);
}
function getAtProbablyRecentBlock(uint256 blockNumber) public view returns (uint256) {
return _totalCheckpoints.getAtProbablyRecentBlock(blockNumber);
}
}
`;
const checkpoint = length => `\
contract Checkpoints${length}Mock {
using Checkpoints for Checkpoints.Trace${length};
Checkpoints.Trace${length} private _totalCheckpoints;
function latest() public view returns (uint${length}) {
return _totalCheckpoints.latest();
}
function latestCheckpoint() public view returns (bool, uint${256 - length}, uint${length}) {
return _totalCheckpoints.latestCheckpoint();
}
function length() public view returns (uint256) {
return _totalCheckpoints.length();
}
function push(uint${256 - length} key, uint${length} value) public returns (uint${length}, uint${length}) {
return _totalCheckpoints.push(key, value);
}
function lowerLookup(uint${256 - length} key) public view returns (uint${length}) {
return _totalCheckpoints.lowerLookup(key);
}
function upperLookup(uint${256 - length} key) public view returns (uint${length}) {
return _totalCheckpoints.upperLookup(key);
}
}
`;
// GENERATE
module.exports = format(
header,
legacy(),
...VALUE_SIZES.map(checkpoint),
);

View File

@ -0,0 +1,278 @@
const format = require('../format-lines');
const { fromBytes32, toBytes32 } = require('./conversion');
const TYPES = [
{ name: 'UintToUintMap', keyType: 'uint256', valueType: 'uint256' },
{ name: 'UintToAddressMap', keyType: 'uint256', valueType: 'address' },
{ name: 'AddressToUintMap', keyType: 'address', valueType: 'uint256' },
{ name: 'Bytes32ToUintMap', keyType: 'bytes32', valueType: 'uint256' },
];
/* eslint-disable max-len */
const header = `\
pragma solidity ^0.8.0;
import "./EnumerableSet.sol";
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[\`mapping\`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* \`\`\`
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* \`\`\`
*
* The following map types are supported:
*
* - \`uint256 -> address\` (\`UintToAddressMap\`) since v3.0.0
* - \`address -> uint256\` (\`AddressToUintMap\`) since v4.6.0
* - \`bytes32 -> bytes32\` (\`Bytes32ToBytes32Map\`) since v4.6.0
* - \`uint256 -> uint256\` (\`UintToUintMap\`) since v4.7.0
* - \`bytes32 -> uint256\` (\`Bytes32ToUintMap\`) since v4.7.0
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableMap.
* ====
*/
`;
/* eslint-enable max-len */
const defaultMap = () => `\
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct Bytes32ToBytes32Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
Bytes32ToBytes32Map storage map,
bytes32 key,
bytes32 value
) internal returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position \`index\` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - \`index\` must be strictly less than {length}.
*/
function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with \`key\`. O(1).
* Does not revert if \`key\` is not in the map.
*/
function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with \`key\`. O(1).
*
* Requirements:
*
* - \`key\` must be in the map.
*/
function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {get}, with a custom error message when \`key\` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
Bytes32ToBytes32Map storage map,
bytes32 key,
string memory errorMessage
) internal view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || contains(map, key), errorMessage);
return value;
}
`;
const customMap = ({ name, keyType, valueType }) => `\
// ${name}
struct ${name} {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
${name} storage map,
${keyType} key,
${valueType} value
) internal returns (bool) {
return set(map._inner, ${toBytes32(keyType, 'key')}, ${toBytes32(valueType, 'value')});
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(${name} storage map, ${keyType} key) internal returns (bool) {
return remove(map._inner, ${toBytes32(keyType, 'key')});
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(${name} storage map, ${keyType} key) internal view returns (bool) {
return contains(map._inner, ${toBytes32(keyType, 'key')});
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(${name} storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position \`index\` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - \`index\` must be strictly less than {length}.
*/
function at(${name} storage map, uint256 index) internal view returns (${keyType}, ${valueType}) {
(bytes32 key, bytes32 value) = at(map._inner, index);
return (${fromBytes32(keyType, 'key')}, ${fromBytes32(valueType, 'value')});
}
/**
* @dev Tries to returns the value associated with \`key\`. O(1).
* Does not revert if \`key\` is not in the map.
*/
function tryGet(${name} storage map, ${keyType} key) internal view returns (bool, ${valueType}) {
(bool success, bytes32 value) = tryGet(map._inner, ${toBytes32(keyType, 'key')});
return (success, ${fromBytes32(valueType, 'value')});
}
/**
* @dev Returns the value associated with \`key\`. O(1).
*
* Requirements:
*
* - \`key\` must be in the map.
*/
function get(${name} storage map, ${keyType} key) internal view returns (${valueType}) {
return ${fromBytes32(valueType, `get(map._inner, ${toBytes32(keyType, 'key')})`)};
}
/**
* @dev Same as {get}, with a custom error message when \`key\` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
${name} storage map,
${keyType} key,
string memory errorMessage
) internal view returns (${valueType}) {
return ${fromBytes32(valueType, `get(map._inner, ${toBytes32(keyType, 'key')}, errorMessage)`)};
}
`;
// GENERATE
module.exports = format(
header.trimEnd(),
'library EnumerableMap {',
[
'using EnumerableSet for EnumerableSet.Bytes32Set;',
'',
defaultMap(),
TYPES.map(details => customMap(details).trimEnd()).join('\n\n'),
],
'}',
);

View File

@ -0,0 +1,66 @@
const format = require('../format-lines');
const TYPES = [
{ name: 'UintToAddressMap', keyType: 'uint256', valueType: 'address' },
{ name: 'AddressToUintMap', keyType: 'address', valueType: 'uint256' },
{ name: 'Bytes32ToBytes32Map', keyType: 'bytes32', valueType: 'bytes32' },
{ name: 'UintToUintMap', keyType: 'uint256', valueType: 'uint256' },
{ name: 'Bytes32ToUintMap', keyType: 'bytes32', valueType: 'uint256' },
];
const header = `\
pragma solidity ^0.8.0;
import "../utils/structs/EnumerableMap.sol";
`;
const customSetMock = ({ name, keyType, valueType }) => `\
// ${name}
contract ${name}Mock {
using EnumerableMap for EnumerableMap.${name};
event OperationResult(bool result);
EnumerableMap.${name} private _map;
function contains(${keyType} key) public view returns (bool) {
return _map.contains(key);
}
function set(${keyType} key, ${valueType} value) public {
bool result = _map.set(key, value);
emit OperationResult(result);
}
function remove(${keyType} key) public {
bool result = _map.remove(key);
emit OperationResult(result);
}
function length() public view returns (uint256) {
return _map.length();
}
function at(uint256 index) public view returns (${keyType} key, ${valueType} value) {
return _map.at(index);
}
function tryGet(${keyType} key) public view returns (bool, ${valueType}) {
return _map.tryGet(key);
}
function get(${keyType} key) public view returns (${valueType}) {
return _map.get(key);
}
function getWithMessage(${keyType} key, string calldata errorMessage) public view returns (${valueType}) {
return _map.get(key, errorMessage);
}
}
`;
// GENERATE
module.exports = format(
header,
...TYPES.map(details => customSetMock(details)),
);

View File

@ -0,0 +1,253 @@
const format = require('../format-lines');
const { fromBytes32, toBytes32 } = require('./conversion');
const TYPES = [
{ name: 'Bytes32Set', type: 'bytes32' },
{ name: 'AddressSet', type: 'address' },
{ name: 'UintSet', type: 'uint256' },
];
/* eslint-disable max-len */
const header = `\
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* \`\`\`
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* \`\`\`
*
* As of v3.3.0, sets of type \`bytes32\` (\`Bytes32Set\`), \`address\` (\`AddressSet\`)
* and \`uint256\` (\`UintSet\`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
`;
/* eslint-enable max-len */
const defaultSet = () => `\
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the \`values\` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position \`index\` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - \`index\` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
`;
const customSet = ({ name, type }) => `\
// ${name}
struct ${name} {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(${name} storage set, ${type} value) internal returns (bool) {
return _add(set._inner, ${toBytes32(type, 'value')});
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(${name} storage set, ${type} value) internal returns (bool) {
return _remove(set._inner, ${toBytes32(type, 'value')});
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(${name} storage set, ${type} value) internal view returns (bool) {
return _contains(set._inner, ${toBytes32(type, 'value')});
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(${name} storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position \`index\` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - \`index\` must be strictly less than {length}.
*/
function at(${name} storage set, uint256 index) internal view returns (${type}) {
return ${fromBytes32(type, '_at(set._inner, index)')};
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(${name} storage set) internal view returns (${type}[] memory) {
bytes32[] memory store = _values(set._inner);
${type}[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
`;
// GENERATE
module.exports = format(
header.trimEnd(),
'library EnumerableSet {',
[
defaultSet(),
TYPES.map(details => customSet(details).trimEnd()).join('\n\n'),
],
'}',
);

View File

@ -0,0 +1,56 @@
const format = require('../format-lines');
const TYPES = [
{ name: 'Bytes32Set', type: 'bytes32' },
{ name: 'AddressSet', type: 'address' },
{ name: 'UintSet', type: 'uint256' },
];
const header = `\
pragma solidity ^0.8.0;
import "../utils/structs/EnumerableSet.sol";
`;
const customSetMock = ({ name, type }) => `\
// ${name}
contract Enumerable${name}Mock {
using EnumerableSet for EnumerableSet.${name};
event OperationResult(bool result);
EnumerableSet.${name} private _set;
function contains(${type} value) public view returns (bool) {
return _set.contains(value);
}
function add(${type} value) public {
bool result = _set.add(value);
emit OperationResult(result);
}
function remove(${type} value) public {
bool result = _set.remove(value);
emit OperationResult(result);
}
function length() public view returns (uint256) {
return _set.length();
}
function at(uint256 index) public view returns (${type}) {
return _set.at(index);
}
function values() public view returns (${type}[] memory) {
return _set.values();
}
}
`;
// GENERATE
module.exports = format(
header,
...TYPES.map(details => customSetMock(details)),
);

View File

@ -114,9 +114,9 @@ const toIntDownCast = length => `\
*
* _Available since v${version('toInt(int)', length)}._
*/
function toInt${length}(int256 value) internal pure returns (int${length}) {
require(value >= type(int${length}).min && value <= type(int${length}).max, "SafeCast: value doesn't fit in ${length} bits");
return int${length}(value);
function toInt${length}(int256 value) internal pure returns (int${length} downcasted) {
downcasted = int${length}(value);
require(downcasted == value, "SafeCast: value doesn't fit in ${length} bits");
}
`;
/* eslint-enable max-len */
@ -159,10 +159,10 @@ module.exports = format(
header.trimEnd(),
'library SafeCast {',
[
...LENGTHS.map(size => toUintDownCast(size)),
...LENGTHS.map(toUintDownCast),
toUint(256),
...LENGTHS.map(size => toIntDownCast(size)),
toInt(256).trimEnd(),
...LENGTHS.map(toIntDownCast),
toInt(256),
],
'}',
);

View File

@ -42,9 +42,9 @@ module.exports = format(
'using SafeCast for int256;',
'',
toUint(256),
...LENGTHS.map(size => toUintDownCast(size)),
...LENGTHS.map(toUintDownCast),
toInt(256),
...LENGTHS.map(size => toIntDownCast(size)),
...LENGTHS.map(toIntDownCast),
].flatMap(fn => fn.split('\n')).slice(0, -1),
'}',
);

View File

@ -0,0 +1,30 @@
function toBytes32 (type, value) {
switch (type) {
case 'bytes32':
return value;
case 'uint256':
return `bytes32(${value})`;
case 'address':
return `bytes32(uint256(uint160(${value})))`;
default:
throw new Error(`Conversion from ${type} to bytes32 not supported`);
}
}
function fromBytes32 (type, value) {
switch (type) {
case 'bytes32':
return value;
case 'uint256':
return `uint256(${value})`;
case 'address':
return `address(uint160(uint256(${value})))`;
default:
throw new Error(`Conversion from bytes32 to ${type} not supported`);
}
}
module.exports = {
toBytes32,
fromBytes32,
};