Notes on the Reference Implementation
Notes on the Reference Implementation
This file accompanies the draft ERC “Serial-Numbered ERC-20 Tokens”. Its content was the section “Reference Implementation” of the draft. Section names in quotation marks refer to sections of the draft.
The code is in contracts/ in this directory and the tests are in test/; README.md describes the layout of the directory, how to run the tests and the code size of the combinations.
The core contract ERC8527 implements ERC-20 and the core interface, and keeps defragmentation closed by default. The freezing extension, the classification extension, an example class that restricts destinations by payee address, the acceptance check, burning, tidying (tidySlices) and the module that opens defragmentation are each a separate contract, which a token inherits as needed. Who can freeze, force transfers, and define and set classes is decided by authorization functions that the token implements itself. The storage of holdings sits behind an abstraction layer and has two interchangeable implementations: a slice stack (last-in-first-out) and a sorted array in ascending order of start. Both use one storage slot per slice; they serve to compare the gas of different data structures.
A class has to be defined, and so have a name, before it can be used. The example class is defined through an internal function of its own, _defineAllowlistClass, and other classes through _defineClass; whether a class carries a list of permitted recipients is decided by its most recent definition.
Each account’s holding is divided into several piles: a default pile, a frozen pile, and one pile for each non-default class. Units received are put into the pile that matches their frozen state and class at that time. A transfer by amount takes first from the non-default class piles that this transfer can use and then from the default pile; the slice stack takes from the slice received last, and the sorted array takes from the slice with the largest serials; this is the default selection rule, and the slice stack has a second rule that chooses among the slices received most recently, described below. Freezing and setting a class act on serials, and the contract does not know who holds those units, so units already received stay in their original pile after they are frozen or their class is changed. When selection meets such a slice, it moves the slice to the pile where it belongs, at most 32 slices per transfer, and skips the rest in place. When the usable piles are exhausted and the amount is still not met, it then checks the unusable piles in place and takes the transferable units in them, for example units that were moved into the frozen pile and unfrozen afterwards.
tidySlices(account, pile, maxMoves) performs only this moving between piles: it moves the misplaced slices in the pile pile of account to the piles where they belong, at most maxMoves slices per call, and returns how many slices it moved. A slice that was moved into the frozen pile and unfrozen afterwards is moved back only when the function is called on the frozen pile. Anyone can call it. It emits no events and changes neither balances nor the result of any query by serial, but it does change the order that sliceAt reports, and with it which units a later transfer by amount selects. It reads a pile from the slice with the largest index downward, and before it reaches a misplaced slice it first has to read past the slices with larger indexes that are in place; these reads do not count toward maxMoves.
The functions that take a position hint are forcedTransferSliceAt(from, to, start, amount, pile, index) and destroySliceAt(from, start, amount, pile, index). The caller gives the pile that holds the serials and the index in that pile of the slice that contains them; both can be read beforehand with serialPositionOf(account, serial). The contract only checks whether this slice contains the specified slice and does not search; when the position is no longer valid, the call reverts and changes no state. The remaining checks and the events are the same as for forcedTransferSlice and destroySlice. On the slice stack, units transferred in by others do not change the indexes of existing slices, so a position read after the freeze usually stays valid; tidySlices, the holder’s own outgoing transfers, and the move of the pile’s last slice into the vacated position when a whole slice is taken can each invalidate it.
The number of freezes covering a serial and the class of a serial are each stored as a step function of the serial, that is, an ordered array of breakpoints, on which queries by serial use binary search. In addition the contract keeps a bounding slice, that is, the smallest slice that covers all frozen serials and all serials of non-default classes. For a serial outside this slice, a transfer establishes by reading one storage slot that the serial is not frozen and is of the default class, without a binary search; when only one of the two extensions has restrictions and they form a single slice, serials inside the bounding slice need no search either.
There are two rules for selection by amount, chosen by a deployment parameter of the slice stack that cannot be changed after deployment. When the parameter is 0, the default rule applies: the contract always takes from the first slice of a pile in selection order, which on the slice stack is the slice received last. When the parameter is W (at least 1), “best fit in a bounded window” applies, with window size W. This rule is available only on the slice stack; the sorted array always uses the default rule. The contract has no function for querying the parameter, so a token has to state its value in its own documentation. When r units remain to be paid, the contract looks at up to W of the most recent slices in the pile: if some are at least r long, it picks the shortest of them; if none is, it picks the longest; among slices of equal length it picks the one nearest the top of the stack. It takes from the end of the picked slice with the largest serials, and when the amount is not yet met it picks again in the window as it then is. What is compared is the length recorded in the pile, not the transferable length, so a picked slice might pay less than r because part of it is not transferable, in which case the contract goes on picking. When a slice in the middle of the window is taken whole, the slice at the top of the stack moves into its position, so the order of the slices inside the window gets shuffled, while the slices below the window stay in the order in which they were received. Every pile applies this rule on its own, and the order of the piles is the same as under the default rule. Burning by amount selects by the same rule; transferSlices, burnSlices, forced operations and defragmentation name serials and are not affected by it. Each additional slice in the window is one more slice read for every pick, so a transfer that pays out many slices costs more and fewer slices can be paid out in one transaction.
The core contract keeps defragmentation closed by default: defragmentSlices reverts with ERC8527ConsolidationClosed() for every caller, and for an issued serial consolidatedSpanAt reports that the whole span from it to the last issued serial is not consolidated. A token that inherits ERC8527Consolidation opens defragmentation. The conditions that clause 7 of “Defragmentation” leaves up to the implementation are expressed by three internal functions of this module that a token can override: who can call (by default any holder), how many groups of slices a defragmentation has to include at least (by default 1), and how many slices an account has to exceed before it can defragment (by default 0, that is, no limit). Groups are counted as slices that are not adjacent to one another: a slice that starts where the previous one ends belongs to the previous group, so splitting one slice into several adjacent slices and naming them separately does not make up the number of groups. The module provides no function for defragmenting on behalf of another account.
The checks of a defragmentation are made in this order: permission to call, the account’s slice threshold, the form of the arguments and whether the serials are issued, whether the serials are held by the caller, the number of groups, freezes and classes. So when the serials named include some that are not held by the caller and some that are frozen, the call reverts with ERC8527NotHeld. When several slices contain frozen serials or serials of a different class, ERC8527NotConsolidatable reports the first of them.
Defragmentation records are stored by old serial: each record takes one storage slot and holds the start of the old slice, the start of its successors and the length; in addition there is a 256-ary bitmap tree keyed by old start, which is used to find all the records that intersect a slice. Slices of one defragmentation that are adjacent to one another become one record. The tree is expanded only where it branches: when a subtree above the lowest level holds a single old start, none of the words inside it is written and one storage slot records that start; only when a second old start falls into the same subtree is it expanded, down to the level at which the two starts separate. The cost of adding a record therefore does not grow with the number of existing records, and when the old serials are scattered, a record usually adds only the record itself and one such slot to storage. Transfers, transferSlices and forced operations do not read the defragmentation records.
consolidatedSpanAt first finds the record that contains the serial queried. It joins to it the records that follow immediately in both the old serials and the successors and reports them together, but at most 32 more records, so the number of records one query reads is bounded. When more records follow one another, the span it returns is shorter than the longest one (clause 10 of “Defragmentation”).
The propagation of freezes and unfreezes is done in the freezing extension: it first handles the slice named in the call, then finds the successors generation by generation, merges adjacent successors and handles them slice by slice. The contract first emits the event for the slice named in the call and then one event for each slice of successors, in ascending order of serial; successors of different generations that are adjacent share one event. The cost of propagation grows with the number of records it passes through, and is higher when the successors are scattered than when they are consecutive. When the contract also implements the classification extension, a defragmentation first checks that the serials named are of the same class; when that class is not zero, it emits one SliceClassified event for the whole slice of new serials, after all the SliceConsolidated events of the defragmentation.
A token that inherits ERC8527Acceptance supports the acceptance check; a token that does not inherit it makes no call to recipients. In the places that “Acceptance check” leaves up to the implementation, the reference implementation does the following:
- Determining a receiving contract. When
tohas no code, no call is made. Whentohas code, it queriessupportsInterface(0x01ffc9a7),supportsInterface(0xffffffff)andsupportsInterface(0x3fbf9755)in that order, each withSTATICCALLand forwarding 30,000 gas. The three return values are evaluated in the same way as in theERC165Querycontract that accompanies ERC-165; in addition, a call that returns fewer than 32 bytes of data is treated as failed. - Gas for the queries (clause 5). Before each query, when less than 34,000 gas remains, the operation reverts with
ERC8527AcceptanceQueryOutOfGas(to)and the query is not made. This value guarantees that the callee receives 30,000 gas. An incoming transfer that is not exempt therefore has to leave room for this gas whenevertohas code, including whentoturns out not to be a receiving contract. - Timing (clause 6). The queries and the call take place after all changes of holder are complete and before the
Transferevent is emitted. During the call the receiving contract reads the token state as it is after the incoming transfer, and a payer who is refused pays the gas of the whole movement. - Gas for the call (clause 7). The gas forwarded to
acceptsERC8527Transferis not limited, and only the first 32 bytes of the return data are read. - Issuance and forced operations (clause 9). Restricted issuance and forced operations do not query receiving contracts. Issuance that any caller can execute is for the token itself to provide; for this the contract offers the internal functions
_mintAcceptedand_requireIssuanceAccepted, which ask the recipient after the issuance.
The reference implementation does not implement ERC-1363.
The reference implementation falls short of this proposal’s recommendations in the following places:
- Clause 4 of “Transferable balance” recommends that the cost of skipping serials that are not transferable not grow with the number of slices of those serials. The reference implementation achieves this only in the amortized sense: k slices that were frozen or had their class changed after they were received take about k/32 transfers before all of them are moved away, and each of these transfers pays for the slices not yet moved away. When k is large enough, the first transfer does not fit in one transaction, and after it reverts no slice has been moved away either. In that case anyone can move them away by calling
tidySlicesseveral times. On the slice stack, the cost of each call depends onmaxMovesand on the number of in-place slices that have to be read before a misplaced slice is reached, and does not depend on k. Tidying in batches makes progress only if every call can, within the gas of one transaction, reach and move away at least one misplaced slice: if a large number of in-place slices lie on top of a misplaced slice, for example because many small payments were received afterwards, a call runs out of gas before it reaches that slice, and even withmaxMovesequal to 1 the next call still starts from the same place. On the sorted array, every call has to rewrite all the slices in the destination pile that come after the slice moved in, and once the frozen pile holds more than a certain number of slices, a single tidying call does not fit in one transaction either, so on the sorted array the k that does not fit in one transaction is essentially unchanged. Units that were moved into the frozen pile and unfrozen afterwards are not moved back to their original pile by transfers; taking them means skipping in place the slices in the frozen pile that are still frozen, until someone callstidySliceson the frozen pile. - “Fragmentation and gas” recommends that the cost of locating serials be bounded, or that functions taking a position hint be provided in addition. The reference implementation provides the latter, but the cost is bounded only on the slice stack: on the sorted array, even when no search is needed, taking out a slice in the middle means shifting all the slices after it, and the number of writes grows with the number of slices. The cost of
forcedTransferSlice,destroySliceandtransferSliceswithout a hint still grows with the number of slices: the slice stack scans the whole pile to locate by serial, and the sorted array locates by binary search but has to shift slices in the same way when taking one out.transferSliceshas no version with a hint. - “Fragmentation and gas” recommends that the selection rule not let recently received small slices be paid out first. Under the default rule, the slice stack of the reference implementation pays out the slice received last first, and the sorted array pays out the slice with the largest serials first, so the dust an account receives is usually the first to be used in its subsequent payments and is passed on to the payee. The second rule prefers, inside the window, a slice that is long enough to pay the whole amount, but it picks the shortest of these, so when the amount paid does not exceed the dust slice, the dust is still what gets used.
- “Costs of defragmentation” recommends making the creation of a defragmentation record cost no less than a freeze passing through it, for example by requiring a defragmentation to include at least a certain number of slices. In the defragmentation module the default minimum number of groups is 1 and the default slice threshold is 0, that is, neither is limited, and a holder can defragment the same slice again and again; a token that opens defragmentation has to set these two numbers itself. Groups are counted as slices that are not adjacent to one another, while the slice stack merges only with the slice on top, so adjacent serials might be stored as several slices; a defragmentation of a single group can therefore still remove slices, and a minimum of 2 refuses such defragmentations as well.
- “Finite serial space” recommends that a token that opens defragmentation limit the consumption of serials by means that do not depend on gas. The defragmentation module has no such limit: defragmentation can use serials right up to the issuance cap, and serials just obtained from a defragmentation can be consolidated again at once. A token that opens defragmentation has to add one itself.
- “The acceptance check and failed payments” recommends providing a receive limit for accounts. The reference implementation does not provide one, so an address without code cannot refuse incoming transfers on it.
In addition, on every freeze, unfreeze or setting of a class, the reference implementation rebuilds the whole step function in memory, at a cost that grows linearly with the number of existing breakpoints.
To keep tokens within the contract code size limit, the parts of the freezing extension, the classification extension and defragmentation that transfers do not use are in four libraries: the freeze operations ERC8527FreezeOps, the class operations ERC8527ClassOps, the defragmentation records ERC8527Consolidations, and ERC8527StackBatch, which takes several slices out of the slice stack at once during defragmentation. The libraries are deployed separately and a token links their addresses when it is deployed, so all the tokens on a chain that use them can share one deployment of each. With them, every combination on the slice stack is within the limit as long as the deployment parameters of defragmentation keep their defaults (the margins are small: one test combination that overrides these parameters is 121 bytes over the limit); on the sorted array, the combinations that have both the freezing and the classification extensions together with defragmentation or the acceptance check still exceed it. To save code, classesOf, classInfo, freezeReasonsOf, freezeReasonInfo and frozenSpanAt are declared external and pass the library’s return data straight to the caller, so a token that inherits these contracts can override them but cannot call them internally or through super. Freezing, unfreezing, setting a class, forced operations and defragmentation call a library and cost somewhat more than the same code compiled into the token would; transfers make no library calls. No compiler setting was tuned for size. The sizes of the combinations and of the libraries are listed in README.md.