Security Considerations (Full Text)
Security Considerations (Full Text)
This file accompanies the draft ERC “Serial-Numbered ERC-20 Tokens”. It is the full text of the draft’s “Security Considerations” section; the draft itself keeps only a summary of the subsections “Fragmentation and gas”, “Dust attacks” and “The acceptance check and failed payments”. A section name in quotation marks refers to a section of this file if there is one. Otherwise, the subsections of “Rationale” are given in full in rationale.md, and every other name refers to the section of that name in the draft. ERC and EIP numbers are not linked in this file.
Freezing follows units, not people
Freezing a slice affects whoever holds those units when the freeze takes effect. If a thief sells stolen units before they are frozen, the units that end up frozen or destroyed belong to the buyer or to the liquidity pool that took them, while the thief keeps the proceeds. A recipient cannot know in advance that the units it accepts will later be frozen. A thief who observes a pending freeze can also try to sell ahead of it. Issuers need a clear policy on how quickly and under which conditions slices are frozen and on how innocent recipients are treated, and integrators have to treat a token that implements the freezing extension as they would any token whose issuer can freeze funds.
Descriptions are the token’s own claims
The names and documents returned by freezeReasonInfo and classInfo are all supplied by the token contract itself, and no third party verifies them. How a token actually behaves is determined by the values that transferableBalanceOf and classAllows return and by the outcome of the transfers themselves; when what a name says disagrees with that, a wallet cannot detect it from the interface alone. As for powers, the interface answers only whether an address can freeze or unfreeze for a given reason (canFreeze and canUnfreeze), and that answer too is given by the token contract itself; it does not say who can destroy or forcibly transfer, or who can set classes. Two tokens that both conform to this proposal can give holders entirely different guarantees, and integrators must read a token’s own documentation and code before integrating it.
Wallets must treat these strings as untrusted input: limit their length, filter out control characters and easily confused characters, and not parse them as markup. When uri is a data URI, the description document is in the return value of the call itself, and wallets should limit its length. When uri points to an external resource, fetching it reveals the user’s network address to an external server, and the document can also become unavailable or be replaced. Even when the document is on-chain, the image in it can still point to an external resource, with the same problems; the image itself is untrusted content too, for example an SVG can contain scripts. Wallets should therefore not depend on the description document to complete their display. The properties in the document are likewise only the token’s own claims, and a wallet cannot use them to decide whether a unit can be transferred out. The result of classAllows can change over time or as a list changes, and callers should not cache it.
The arrays returned by freezeReasonsOf and classesOf have no upper bound on their length. An implementation that encodes parameters into the class, for example by using a different unlock time for every lock, can leave one account holding a great many different classes, and a third party can also increase that number by transferring in units of different classes. Contracts that call these functions on-chain must take this into account.
Number of reasons
A serial can be frozen for several reasons at the same time. The cost of determining whether a serial is frozen can grow with the number of reasons in use, and every transfer has to make that determination. Implementations should limit the number of reasons that can be in use at the same time, or use a storage layout whose cost does not grow with the number of reasons. “In use” counts only serials that are not destroyed, while destroyed serials still keep their frozen state: issuing, freezing and then destroying, over and over, can leave behind many reasons that are no longer in use but still have records. Limiting only the number of reasons in use does not limit the growth of these records; implementations should make sure that transfers and account-level queries do not need to scan them.
The interface separates the power to freeze by reason, but it does not by itself guarantee that one party cannot lift another party’s reason: who can unfreeze for which reason is up to the implementation. A party that relies on a reason, for example a pledgee, must confirm that the token’s implementation does not allow anyone else to lift it. A reason only prevents the holder from transferring the units out, so that party also needs to confirm who can destroy or forcibly transfer frozen units.
Selection order can be influenced
Units held by a shared contract, such as a pool or vault, are paid out according to the implementation’s selection rule. Under last-in-first-out, the most recently deposited units are the next to leave, so a depositor can make it likely that particular units are passed on to the next withdrawer; under first-in-first-out they would instead sit behind earlier deposits. Whoever designs a token on this proposal has to consider how the rule distributes units that may later be frozen.
Holders can choose which units to send
A holder can use transferSlices to name the units it sends, for example to pay others first with the units it believes might later be frozen. How far this is a new capability depends on whether holders can freely use several accounts (see “Transfers by serial are part of the core”). A recipient that cares which units it receives must check the serials reported by the SliceTransferred events and cannot look at the amount alone. This check can only be made off-chain: a contract cannot read events during execution, and this proposal has no function that makes a transfer by amount return the serials selected. A contract that needs to confirm on-chain which units it received needs to agree on a separate way of interacting with the payer, for example having the payer transfer in specified serials with transferSlices, and to bear the cost of checking its holding with queries such as sliceAt.
Fragmentation and gas
The cost of a transfer grows with the number of slices it moves. An account that collects many small payments and then sends a large amount pays for every slice involved, and in the extreme a single transfer can exceed the gas available to a transaction. An attacker can provoke this deliberately by sending many very small transfers to a victim, which is most damaging for contracts that cannot split their outgoing transfers. The attacker pays gas for every slice it sends in, which limits the number of slices it can create; but each time these slices later change hands, the holder at that time pays again, and the attacker’s cost does not limit that part (see “Dust attacks”). Possible mitigations include: a minimum transfer amount (which constrains ERC-20 compatibility for small values, and only raises the value the attacker gives up without stopping fragmentation, see “The core sets no minimum transfer amount”); coalescing of adjacent slices; storage structures that move many slices at sub-linear cost; and having holders split a large outgoing transfer over several transactions. On a token that supports the acceptance check, a receiving contract can also refuse incoming transfers; an implementation can also let accounts set a receive limit for themselves (see “The acceptance check and failed payments”). A holder can use defragmentation to replace scattered slices with one consecutive slice (see “Costs of defragmentation”). On a token that does not open defragmentation, non-adjacent slices cannot become one slice; when a holding really needs to be defragmented, the issuer can exchange it (see “Consecutive issuance and no renumbering on transfer”). Contracts that forward a fixed amount of gas with token transfers are not safe to use with these tokens.
Under “Events”, when the serials a transfer moves together form k non-adjacent slices, the contract has to emit at least k SliceTransferred events; finding the transferable units and recording them in the recipient’s holding each have a cost of their own as well. Two accounts with the same balance and the same transferable balance can therefore pay very different costs for paying out the same amount. For accounts that receive payments over a long period, such as merchants, pools and vaults, integrators should evaluate on the target chain how much one transaction can actually transfer out of the account. A contract such as a vault should be measured through its own withdrawal entry point, with the accounting, the permission checks and the transfer counted in the same transaction; for a withdrawal that can only be completed in one go, the criterion is that the full amount requested succeeds in one transaction. The selection rule is up to the implementation (see clause 2 of “Transfers”). An implementation’s selection rule should not pay out recently received small slices first; it can, for example, prefer a single slice that is enough to pay the whole amount, and an implementation that stores a holding as a stack can look at the slice at the bottom first when the slice at the top cannot pay it. The sender then moves fewer slices, the recipient receives fewer fragments, and small scattered slices stay where they are and do not burden everyday transfers. The price is that these slices remain in the holding the whole time, the cost of locating by serial and of account-level queries still grows with them, and an account that receives many payments might also face a large transfer that needs to draw on them. Such a rule likewise affects which units are paid to whom (see “Selection order can be influenced”). A selection rule changes which accounts accumulate scattered slices; it cannot eliminate fragmentation: an account that keeps receiving many payments of non-adjacent units still sees its number of slices grow.
Slices that are not transferable can impose a cost even when they are not moved. Under clause 4 of “Transferable balance”, a transfer by amount has to skip serials that are not transferable. If an implementation leaves these slices on the selection path, every transfer pays for every slice it skips, rather than paying only once when the slice is moved. This cost can be driven up by a third party: someone who holds units of a class that is subject to a flow rule can split those units into many very small non-adjacent slices and transfer them to one of the class’s permitted recipients; if the units still belong to that class once they are in the permitted recipient’s hands, every later transfer by that recipient to an address the class does not allow has to skip these slices. Freezing gives rise to a similar situation: an account first receives many small scattered amounts of units, and those serials are then frozen. When enough slices are skipped, a transfer that does not exceed the transferable balance might not fit in one transaction. Implementations should take slices that are not transferable off the selection path, for example by moving skipped frozen slices into separate storage, or by storing holdings separately by class and skipping a whole group when the flow rule does not allow the transfer. Slices that were moved aside can become transferable again after they are unfrozen or their class changes, and the implementation needs to be able to bring them back; the cost of doing so still grows with the number of slices. Not providing burning by holders does not prevent this, because transferSlices alone can create non-adjacent slices; on a token that provides burning by holders, an account that received small scattered amounts can clean up by burning those of them that are not frozen and whose class allows burning; frozen units and units whose class does not allow burning cannot be cleaned up this way. This is also partly why, when units still belong to their original class after they arrive, permitted recipients should only be terminal accounts (see “Destination-dependent flow rules and contracts”).
transferSlices moves only the slices the caller names, so a holder can use it to transfer the units out of a fragmented account over several transactions. It cannot prevent fragmentation, and it does not help contracts that can only call transfer.
The functions that name units by serial, that is, transferSlices, forcedTransferSlice and destroySlice, have to locate those serials in the account’s holding; transferSlices has to locate each slice it names separately. In an implementation that locates them by scanning, the cost grows with the number of slices the account holds, and that number can be inflated deliberately: a holder can split its own holding into a very large number of slices beforehand, and a third party can send many very small transfers to an account (see “Dust attacks”). After a freeze the holder cannot move the frozen units, but others can still transfer small scattered amounts of units to the account. In the extreme, a forced operation no longer fits in one transaction. The function signatures of this proposal carry no position hint. Implementations should use a storage layout in which the cost of locating serials is bounded, or, as the freezing extension allows, provide additional functions that take the position of the slice as a hint and verify it.
Dust attacks
A dust attack is the sending of very small amounts of units to someone else’s account. In an ordinary ERC-20 token, a received amount only makes the balance larger; the recipient bears no cost for it and can ignore it. This proposal changes that, because received units carry their own serials and history. A received amount that is not adjacent to the serials the recipient already holds adds a slice to its holding, and that slice stays in the holding until it is transferred out, burned or destroyed; even when it is transferred out, it is still a separate slice in the next holder’s hands, unless the serials on both sides of it happen to end up with the same holder. Received units might also be frozen later. The acceptance check is optional, and only contracts that implement the acceptance interface can refuse incoming transfers (see “Acceptance check”). So on a token that does not support the acceptance check, a sender of dust can impose these consequences on any address; on a token that supports it, the sender can impose them on any address without code and on any contract that does not implement this interface. An implementation can additionally let accounts set a receive limit for themselves (see “The acceptance check and failed payments”). A token that circulates publicly and will be held by contracts needs the acceptance check and such limits all the more. On a token that does not support the acceptance check, a contract that receives payments over a long period and cannot split its outgoing transfers can use transferSlices to pay only units of its own choosing, or can decline to integrate the token. By the attacker’s aim, the following cases can be distinguished.
Raising costs. The attacker sends many very small non-adjacent slices into an account, raising the cost of its later transfers, operations by serial and account-level queries, and in the extreme making a transfer or a forced operation no longer fit in one transaction (see “Fragmentation and gas” and “Balance includes units that cannot be transferred”). Beyond those two sections, there are a few further points.
- Dust is passed along with payments. If the selection rule pays out the most recently received units first, or the units with the highest serials first, and the dust was received only recently and has comparatively high serials, every later payment by the victim draws on the dust first, and even a small payment has to move several slices. The payee receives these same fragments, so its number of slices grows accordingly, and its later payments pass the fragments on in turn.
- A holder can avoid the dust by using
transferSlicesto pay only units of its own choosing, but this requires locating those serials in the holding first, and the cost of locating can itself grow with the number of slices (see “Fragmentation and gas”). On a token that provides burning by holders, a holder can clean up by burning the dust; once burned, these units can no longer be recovered, and the holder has no way of knowing beforehand whether the dust it received consists of units that will later be frozen. Burning removes slices rather than adding them, so when the units selected for burning happen to be the dust, cleaning up can be cheaper than it was for the attacker to send them in; when the dust is sandwiched between other slices, it has to be named withburnSlices, which needs locating as well. Frozen dust and dust whose class does not allow burning cannot be cleaned up this way and can only be disposed of by a party that has the right to do so. A wallet can display slices that are very small and not adjacent to the rest of the holding separately from the rest, and prompt the user to avoid or burn them. - The less a unit is worth, the cheaper dust is for the attacker. On a token with a large number of decimals, each slice of dust costs almost nothing but gas; with fewer decimals, the attacker also has to give the value of these units to the recipient. This should be considered when choosing the number of decimals, and “Finite serial space” needs to be considered as well.
- Some storage layouts make the cost of paying a fragmented account grow with its number of slices as well, for example when a received slice has to be inserted into an array sorted by serial. On such an implementation, dust also makes it more expensive for others to pay the victim.
Passing on history. Someone who holds stolen units, or units involved in a case, can split them into very small amounts before they are frozen and scatter them across a large number of unrelated addresses, including exchanges, well-known addresses and widely used contracts. The aim can be to cause compliance trouble for those addresses, to make a freeze hit innocent parties and thereby put pressure on the issuer, or simply to increase the work of disposal.
- The number of freezes needed does not change. The scattered units are still within the few slices of consecutive serials they were in originally, and one freeze per slice covers all of them, however many addresses they were scattered to (see “Consecutive issuance and no renumbering on transfer”).
- The recipient’s other units are not affected. History follows units, not accounts: receiving dust does not give the units the recipient already had the same history, and a freeze falls only on the dust, while the recipient’s other units remain transferable as usual.
- The work of disposal does increase. Forced transfer and destruction are carried out holder by holder, so the more widely the units are scattered, the more accounts have to be handled. Dust that stays in these accounts after it is frozen still counts toward
balanceOfandtotalSupply(see “Frozen units remain in the balance”), and can also raise the cost these accounts pay, when they transfer, for skipping units that are not transferable (see “Fragmentation and gas”). An issuer’s policy should state how very small amounts scattered to unrelated accounts are treated: whether they are frozen, whether they are disposed of after being frozen, under which conditions they are unfrozen, and how the recipients are treated. - Once units scattered into shared contracts such as pools and vaults are frozen, these contracts hold balance they cannot pay out. Who bears the loss depends on how the contract pays out and on the outcome of the freeze. Once units are in a shared contract they are mixed with the other deposits; depositors hold pro-rata shares that correspond to no particular serials, and the contract can only pay out transferable units (see “Freezing follows units, not people” and “Balance includes units that cannot be transferred”).
- Contracts that pay out by shares of
balanceOf, for example theburnof a Uniswap v2 pool (the amount paid out is the share multiplied bybalanceOf(address(this))) and an ERC-4626 vault that uses the defaulttotalAssets(which by default returnsasset.balanceOf(address(this))): while the freeze lasts, the frozen units still count inbalanceOf, and those who leave receive their full amount out of the transferable units, by a share that includes the frozen part, so those who leave first bear no loss; when the transferable units cannot cover the next payout, that exit fails as a whole, and in a v2 pool not even the other token can be withdrawn. After the frozen units are destroyed or forcibly transferred out, the contract’sbalanceOfdrops accordingly, and the loss is shared pro rata by those who are still in the contract at that time, and not by those who have already left; if the transferable units have all been paid out before then, those who stayed receive nothing. - Contracts that pay out by their own accounts, for example a Uniswap v3 pool, which pays the amounts recorded for each position, and the
PoolManagerof v4, which pays from its own balance: a payout does not readbalanceOf, during the freeze and after a disposal alike, a disposal spreads no loss, and those who cannot be paid are the last to withdraw. In thePoolManager, all pools that contain the token share one balance, so all of these pools are affected. - If the frozen units are in the end unfrozen, nobody loses in either kind of contract, and those who stayed were only unable to withdraw for a time. At the time of the freeze it is not known whether the outcome will be an unfreeze or a disposal, so leaving first never costs anything; a freeze therefore triggers a rush to leave first, and the time between freezing and disposal is its window.
- Contracts that pay out by shares of
- Exchanges and compliance screening should assess an account’s exposure by serial, that is, which units and how many units come from a source of concern, rather than treating the whole account as suspect because it once received units from a certain address. A very small amount received unsolicited does not by itself show that the recipient took part in anything.
Tracking markers. The attacker knows the serials it sent and can recognize them wherever they later go. In the account model, an address’s transfers are public anyway; what dust adds for the attacker is that after these units enter a contract that mixes many people’s funds, such as a pool or an exchange, it can still tell from the serials paid out where they went. If the selection rule pays out the most recently received units first, the victim’s next payment is likely to carry these markers; the selection rule of a shared contract also determines to whom these markers are paid (see “Selection order can be influenced”). A holder who cares about this can use transferSlices to pay only units of its own choosing, or burn the dust (see also “Reduced fungibility and privacy”).
Through flow rules. Under a flow rule that restricts destinations by payee address (see “Examples of classes”), the constrained units can only be transferred to permitted recipients, so dust of this kind can only land on permitted recipients (see “Fragmentation and gas” and “Destination-dependent flow rules and contracts”). An implementation that encodes parameters into the class can also let a third party lengthen the return value of classesOf by transferring in units of many different classes (see “Descriptions are the token’s own claims”).
Zero-value transfers. ERC-20 requires a transfer of zero value to emit a Transfer event as well, and address poisoning exploits such events to forge entries in the victim’s history that transferred nothing at all. This proposal emits no SliceTransferred event for a zero-value Transfer (see “Events”), so a wallet that displays history by SliceTransferred events does not show these entries; a very small real transfer sent from a look-alike address still has a SliceTransferred event, so wallets should not let users copy a payee address from the transaction history.
The acceptance check and failed payments
On a token that supports the acceptance check, a receiving contract can make transfers paid to it fail. This is what the acceptance check is for, and it also has the following consequences.
Payers.
- A contract that pushes payments to addresses named by others can be blocked by a payee. Examples are an auction that refunds the previous bidder when it receives a new bid, or a transaction that pays a series of addresses one by one: if one of the payees refuses, the whole transaction fails. This situation has long existed when native currency is transferred to contracts, and it exists on tokens with account blacklists as well. Such contracts should let payees withdraw for themselves, or record a payment when it fails, rather than letting the whole operation fail.
- A receiving contract can change its answer at any time, including just ahead of a pending payment. The result of a query or a simulation made in advance does not guarantee that the transfer that follows succeeds.
- A payment for which both the balance and the transferable balance are sufficient can still fail. When a recipient refuses by number of slices, a payer with a fragmented holding can be refused when it pays by amount, and its holding might have been fragmented precisely by dust that others scattered on it. The payer can name longer slices with
transferSlices, or clean up the dust first. A recipient that refuses by number of slices should be aware that what it rejects might be normal payments.
Receiving contracts.
- A receiving contract is arbitrary code of the payee. It can consume a large amount of gas, which the payer bears; wallets should estimate gas for every transaction individually. An implementation can limit the gas forwarded to it, read only the first 32 bytes of the return data, and not copy overlong return data into memory.
- The query that determines whether the payee is a receiving contract is taken as “not a receiving contract” when it fails or answers “no”, and the transfer proceeds as usual. A payer that can, by lowering the gas, make this query fail or make it answer “no”, while the rest of the transfer succeeds, has bypassed the acceptance check. An example of the latter case: the
supportsInterfaceof a receiving contract queries another contract and returnsfalsewhen the subcall fails for lack of gas. That is why clause 5 of “Acceptance check” requires the contract to revert when it could not forward 30,000 gas to a query, whether or not the query returned successfully. An implementation needs to check the available gas before every query and cannot look only at whether the call succeeded. - A receiving contract’s answer can change over time, and the contract might also be upgradeable. A receiving contract that always refuses can only receive incoming transfers it pulls itself, and units delivered by restricted issuance and by forced operations.
- The read-only call prevents reentrancy and misplaced events; it does not prevent a receiving contract from reading the state of other contracts. If the external state a receiving contract depends on can be manipulated by the payer, its decision can be manipulated too.
- When a receiving contract hands the decision to another contract, for example a checker contract shared by several receiving contracts, it also hands the question of whether it can be paid to whoever controls that contract. A shared checker contract should not be upgradeable and should have no administrator.
What the acceptance check does not stop. The acceptance check protects only contracts that implement the acceptance interface, and only on tokens that support it; whether a token supports it can be queried with ERC-165, but this is the token’s own declaration and does not guarantee its behavior. Addresses without code cannot implement the interface, and a contract that is already deployed and cannot be upgraded cannot implement it after the fact; an address that has set a delegation under EIP-7702 has code, and when its delegation target implements the interface, it can refuse; whether this is available depends on whether the chain it is on and the wallet it uses support such a delegation. An account that cannot refuse can only deal with dust through the selection rule, transferSlices and burning (see “Fragmentation and gas” and “Dust attacks”), or through limits set by accounts themselves that the implementation provides (see below). Incoming transfers that the recipient pulls itself are not checked: if a contract lets anyone trigger it to pull, for example through a deposit function with no minimum deposit, dust can come in through that function, and such a contract needs to set limits in its own entry points. Restricted issuance and forced operations are not subject to the acceptance check either, so an issuer can still hand out very small amounts to a recipient that refuses.
Limits set by accounts themselves. This proposal specifies no way for addresses without code to refuse; an implementation can provide one itself (see clause 6 of “Transferable balance”). One suggested approach is a receive limit for accounts: every account sets a number for itself on the token, namely how many units, at least, an incoming transfer has to contain per slice on average, and the token rejects an incoming transfer that falls short of it; the number of slices is the number of SliceTransferred events of that incoming transfer. The threshold is counted per slice because the recipient’s cost is counted per slice: for every additional slice sent into the account, the sender has to give up at least that many units, and those units belong to the recipient; a threshold on the amount of each transfer cannot achieve this, because an incoming transfer whose amount meets the threshold can still consist of many very small slices. A limit of this kind raises the price; it does not block: anyone willing to pay that price can still send in fragments, and a normal payment from a payer whose holding was fragmented by dust is rejected as well. The threshold of accounts that have never set one can be decided by the issuer. When it is zero, only accounts that have set a limit themselves are protected; when it is not zero, every account has a threshold without doing anything, and the price is that small transfers paid to accounts that have never set one fail, payers that know only ERC-20 do not expect such failures, and a contract that is already deployed and cannot call the setter function cannot change its own threshold. A party that can change the threshold of accounts that have never set one can make all of those accounts refuse small amounts together; deployments should put this power under the same controls as the right to freeze (see “Powers of the authorized party”).
An implementation can also provide other limits set by accounts, for example a list of trusted senders, or letting an address without code register a checker contract. An implementation that provides registration should attend to three points. First, the call to the checker contract should be read-only, on the same grounds as for the acceptance interface. Second, a checker contract without code should be treated as refusing, not as accepting; a wallet therefore needs to confirm that there is code at the address before registering it. Third, a party that can register on behalf of another account can thereby keep that account from being paid, which has the same effect as blocking an address from receiving payments; deployments should put this power under the same controls as the right to freeze (see “Powers of the authorized party”).
Costs of defragmentation
This subsection applies to tokens that open defragmentation.
- The cost of a freeze grows with defragmentation records. Without defragmentation, the cost of freezing a slice does not depend on how many holders the units have since been divided among. With defragmentation, a freeze propagates once more for every defragmentation record it passes through, and the number of records depends on how many times the holders of these units have defragmented. Whoever holds stolen units can divide them among many accounts and defragment once in each, or defragment the same units again and again, so that one freeze has to pass through many records. Each of these defragmentations costs its caller gas as well. An implementation should make creating a 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 (clause 7 of “Defragmentation”). A defragmentation whose serials all lie inside one slice that
sliceAtreports removes no slice and only leaves a record; an implementation can refuse it. An implementation in which only listed accounts can defragment is not affected. - A freeze might take several transactions. A freeze of any serial a unit has had propagates to the serial it has now, so defragmenting ahead of a freeze does not make the freeze miss. But when a freeze passes through too many records, it does not fit in one transaction. The authorized party can split the slice into several calls; when a unit has been consolidated many times, it can also freeze the serial the unit has now, and such a freeze passes only through the records created after that serial was looked up. The serial a unit has now can be found by calling
consolidatedSpanAtstep by step, or computed from theSliceConsolidatedevents. Between these calls, units that are not yet frozen can still be transferred away; a transfer does not change the serials of the units it moves, and a defragmentation performed in the course of a transfer leaves a record as well, so the later calls still freeze them. The authorized party should first estimate the cost of a freeze with a read-only call. - Cost and limit of a defragmentation. A defragmentation pays the storage cost of the record it leaves, and the number of slices one defragmentation can handle is limited by the gas available to a transaction. An account with very many slices has to defragment over several transactions, each of which yields one new slice.
- Defragmenting on behalf of another account. After serials change, calls that name units by their old serials fail, for example a
transferSlicesorburnSlicesthat has been signed and is not yet included. An implementation that provides a function for defragmenting on behalf of another account therefore must restrict who can call it, or open it only for accounts that hold more than a certain number of slices; otherwise anyone can make other holders’ transfers by serial fail. ThedefragmentSlicesForof the “On-behalf defragmentation extension” and a defragmentation performed for someone else in the course of a transfer (clause 4 of “Transfers”) are both defragmentations of this kind; the restriction on the former can be queried withcanDefragmentFor. A party that needs certain units to keep their serials, for example a contract that registers collateral by serial, can freeze these units: frozen units cannot be consolidated. An ordinary holder usually cannot freeze its own units, and on a token that lets others defragment for it, it cannot assume that only it will renumber its own units. - Defragmenting in the course of a transfer. On a token that does this, defragmentations are as frequent as transfers, and the records a freeze has to pass through grow accordingly (see the first item of this subsection); the cost falls on whoever happens to deposit, withdraw or swap. On the reference implementation, a defragmentation costs more per slice it handles than a transfer does per slice it moves, so it cannot rescue a transfer that already does not fit in one transaction, and can only keep the number of slices down in advance. A caller does not know beforehand whether a transfer will also defragment, but this affects only calls that name units by their old serials and are not yet included, which fail rather than move the wrong units; the simulation a wallet runs to estimate gas already includes the cost of the defragmentation, and the state can be different at inclusion, as it can for any transfer. Implementations should document the conditions under which they defragment in the course of a transfer (clause 4 of “Transfers”).
- Serials kept off-chain. After a defragmentation, a list of serials kept off-chain is not updated automatically. A party that screens the units it receives by serial (see “Holders can choose which units to send”) has to follow the
SliceConsolidatedevents, or useconsolidatedSpanAt, to translate the serials on its list into the serials the units have now; the new serials alone do not show where the units come from. - Serial space. Each defragmentation consumes as many new serials as the number of units consolidated, whatever the number of slices, so any holder can use it to exhaust the serial space and bring issuance to a stop. Limits that do not depend on gas are described in “Finite serial space”.
Balance includes units that cannot be transferred
When the freezing extension is implemented, balanceOf includes frozen units; when the classification extension is implemented, it also includes units that can only be transferred to some addresses. Contracts that derive reserves, collateral value or withdrawable amounts from balanceOf can overestimate what is available and have to use transferableBalanceOf instead. Computing transferableBalanceOf can require iterating over an account’s slices and may be expensive to call on-chain; the same can be true of frozenBalanceOf, freezeReasonsOf and classesOf. The number of slices of an account can be raised by a third party that transfers in small scattered amounts of units (see “Dust attacks”), so the cost of these queries is not entirely under the account’s own control.
Classes do not represent different rights
balanceOf and totalSupply add up the units of all classes, and integrators that know only ERC-20 will price, collateralize and exchange them as one and the same asset. Classes should therefore only be used to distinguish where units can go and where they come from. Making assets with different rights, for example several bonds with different maturity dates or yields, into several classes of one token does not violate the interface, but integrators will treat them at the same price, and holders of the worse class can profit from that. Such assets should each use a contract of their own.
Even when all classes carry the same rights, units that are subject to a flow rule are of less use to their holder than units of the default class, and the same is true of frozen units (see “Balance includes units that cannot be transferred” and “Destination-dependent flow rules and contracts”).
Destination-dependent flow rules and contracts
Under a flow rule that restricts destinations by payee address (see “Examples of classes”), whether a unit can be transferred out depends on the destination. A liquidity pool, a vault or any other contract that needs to pay arbitrary addresses, if it takes in such units, can end up holding balance it cannot pay out, and withdrawals can fail as a result.
An issuer has two ways to avoid this. One is to list only terminal accounts as permitted recipients, that is, accounts that do not need to transfer units onward to arbitrary addresses after receiving them. The other is to have units change to the default class when they arrive at a permitted recipient (see “Permitted recipients” in “Examples of classes”). A permitted recipient then receives unrestricted units that it can pay on to anyone, and so does not have to be a terminal account; the practice described in “Fragmentation and gas”, of transferring small scattered amounts of restricted units to a permitted recipient to raise the cost of its transfers, no longer works either; the scattered units themselves are still dust (see “Dust attacks”). The price is that once units have changed to the default class, the issuer can no longer constrain where they go. When units still belong to their original class once they are in a permitted recipient’s hands, the issuer should use the first way.
Powers of the authorized party
A party that can freeze units holds substantial power over holders, and a party that can destroy or forcibly transfer units holds even more; a compromise of their keys allows arbitrary units to be frozen and then destroyed or transferred away. The freezing extension involves four powers, and their abuse harms different parties and to different degrees. A freeze stops a holder from transferring its units out, but it can be lifted. Unfreezing harms the party that the freeze protects: stolen units, pledged units or the units named in a court order can be transferred away again. A forced transfer hands units to someone else. A destruction cannot be undone, because issuing again produces new serials. On a token where others can defragment for an account, this is a fifth power: it changes neither balances nor holders and is weaker than the other four, but whoever holds it can make the target account’s calls by serial fail, add defragmentation records and so raise the cost of freezes, and consume serials (see “Costs of defragmentation”).
Deployments are advised to place these functions behind multi-party control and to grant the four powers separately, so that one of them falling into the wrong hands does not hand over the others as well, for example by letting an address responsible for emergencies only freeze, while unfreezing and disposal go through a multisig; and to leave a delay between freezing and disposal so that mistaken freezes can be contested. This proposal does not require such an assignment: how the powers are granted is up to the implementation, and a small issuer might have only one multisig.
Every change of frozen state and every forced operation has an event (SliceFrozen, SliceUnfrozen and SliceForciblyTransferred), and the events all carry the address that initiated the call (operator). The operator of a freeze event is the address that initiated that call, which is not necessarily the party that first froze the units: freezing serials again that are already frozen emits an event with another operator.
The delay between freezing and disposal protects holders whose own units were frozen by mistake. When the frozen units are in a shared contract that pays out by shares of balanceOf, the delay has a side effect: those who leave first during the delay take their full amount, and if the outcome is disposal, the whole loss falls on those who stay, so the delay is a window for leaving first (see “Dust attacks”). A deployment can, in the same transaction that freezes these units, forcibly transfer them to a dedicated escrow address. A forced transfer does not change frozen state (clause 5 of “Forced transfer and destruction”), so the units remain frozen for the original reasons at the escrow address, and the delay and any contest take place there. Doing so has the following costs and limits.
- The contract’s
balanceOfdrops at the moment of the transfer out, and the loss is at once shared pro rata by those who are in the contract at that time, and not by those who have already left. The delay protects the units, not the depositors’ positions: when a contest succeeds, the units should not simply be transferred back to the contract, for example back to a Uniswap v2 pool, where anyone can take the amount above the reserves withskim; making the depositors whole according to their shares at the moment of the transfer out has to be handled outside this proposal. - The transfer to the escrow address uses the power of forced transfer without a delay. A deployment that needs a delay therefore has to divide forced transfers into two tiers: a transfer to the escrow address can be executed at once, while a transfer from the escrow address to any other address, or a destruction, has to go through the delay.
- It is of use only for contracts that pay out by
balanceOf. A contract that pays out by its own accounts, for example a Uniswap v3 pool or thePoolManagerof v4, does not read its balance when it pays, and transferring the units out spreads no loss. - It removes only the window after the freeze. Before the freezing transaction is included, whoever observes it can still leave first (see “Freezing follows units, not people”).
Who can freeze and unfreeze, and how a holder contests a freeze, is the policy of the deployment and depends on the issuer and the jurisdiction; this proposal does not specify it (see “Design of the freezing extension”). A holder can obtain four things from the interface: the reasons for which its units are frozen (freezeReasonsOf); the name and description document of each of these reasons (freezeReasonInfo); the address that initiated a freeze (the operator of the SliceFrozen event); and whether a given address can freeze or unfreeze for a given reason (canFreeze and canUnfreeze). What these two queries provide is limited: they do not list the addresses that have the right, and do not say who can destroy or forcibly transfer; their return values can change without an event; and an address for which they return true can be a contract, in which case who can freeze or unfreeze through that contract depends on that contract. The rest has to come from the reason’s description document: the specification recommends that every reason in use have a description document that states who can freeze for it and who can release it (authority), and to whom and in what way a holder can contest a freeze (contest), see clause 7 of “Freeze queries”; a deployment should also state there the conditions of release (release) and how long after a freeze, at the least, units can be destroyed or forcibly transferred (disposal). The innocent recipients described in “Freezing follows units, not people” are the ones who need this route most. This information is likewise the token’s own claim (see “Descriptions are the token’s own claims”); the addresses given in authority can be checked with canFreeze and canUnfreeze.
A party that can set classes or change flow rules holds a power close to that of freezing: changing units to a class that does not allow transfer to anyone, or emptying a class’s list of permitted recipients, has the same effect as a freeze. Unlike a freeze, a change to a flow rule emits no event (see clause 4 of “Flow rules”). The name and uri of a reason or a class, and the return values of canFreeze and canUnfreeze, can also change without an event. Holders can discover these changes only by querying. Deployments should put these powers under the same controls as the right to freeze.
The declaration of an interface does not say which powers a token actually has. On a token that declares the freezing extension, the destruction and forced transfer functions might revert for every caller, or might be usable at any time. A token that does not declare the freezing extension can still freeze, destroy or transfer units with functions outside this proposal, and an upgradeable contract can also add them later. “Freeze first, then dispose” is only a recommendation in this proposal: a token that declares the freezing extension might also destroy or transfer away units without freezing them, and unless the token’s own documentation and code guarantee it, holders and integrators cannot assume that a visible freeze comes before disposal. Integrators must read the token’s own code.
External calls and event attribution
Indexers attribute SliceTransferred and SliceForciblyTransferred events by the order of events (see “Events” and clause 7 of “Forced transfer and destruction”). An implementation that calls an external contract between the events of one operation, for example notifying the recipient after emitting SliceTransferred and before emitting the corresponding Transfer, or making a callback between Transfer and SliceForciblyTransferred, gives the called contract the opportunity to reenter and complete another transfer. Once the events of that other transfer are interleaved, events are attributed wrongly, and the contract also violates the ordering requirements stated in those two places. Implementations should complete their state updates and emit all events of the operation before calling any external contract, or prevent reentrancy. Functions that notify the recipient on transfer, such as those defined by ERC-1363, should call the recipient only after all of these events have been emitted. The queries and the call to the recipient under “Acceptance check” are not such a case: they are read-only, and the called contract can neither emit events nor complete another transfer, so they can take place before the events are emitted; for their timing relative to the changes of holder, see clause 6 of “Acceptance check”.
Reduced fungibility and privacy
Units are distinguishable by design. The complete history of every unit is public, and markets can price units differently according to that history, for instance by avoiding units that passed through a particular address. Issuers and users have to accept this as an inherent property of the token.
Finite serial space
Serials are never reused, so the total number of units ever issued, including those later destroyed, is limited by the integer width the implementation uses for serials. Tokens with frequent mint-and-burn cycles consume this space continuously and have to size it, or choose their number of decimals, accordingly.
Consolidated serials are likewise never used again: each defragmentation consumes as many new serials as the number of units consolidated, whatever the number of slices. On a token that opens defragmentation, any holder can defragment the same units again and again, without first having to create fragments; the units needed can even be borrowed with a flash loan and returned after being defragmented repeatedly within one transaction. Once the serials run out, issuance and defragmentation both fail permanently; transfers, destruction and freezing are not affected.
Conditions such as a minimum number of slices per defragmentation cannot limit this consumption: one large slice plus a few slices of dust meets the condition and still consumes the full amount. Nor is the cost of gas a reliable limit, least of all on chains where gas is cheap.
A token that opens defragmentation needs a limit that does not depend on gas; how to do it is left to the implementation. One possible way is to reserve part of the serial space for issuance, which defragmentation cannot use, so that an attack can at most bring defragmentation to a stop; and to provide that a unit is consolidated at most once in a fixed period, for example by recording the value of serialsIssued() before the first defragmentation of each period and defragmenting, within that period, only units whose serials are below it. The serials consumed in each period then do not exceed the circulating supply, and the time needed to exhaust the remaining space depends only on the circulating supply and the length of the period, not on gas or on borrowed units. The price is that units that have just been consolidated temporarily cannot be defragmented again, and an attacker can also send dust made of such units, so that the victim cannot defragment it within the current period; the length of the period has to be weighed against that. On a token where only listed accounts can defragment, the consumption is decided by the listed accounts.