Skip to content

Commit 3f326d8

Browse files
authored
Merge pull request #24 from dragonfly-xyz/pattern/bitmap-nonces
Pattern: Bitmap Nonces
2 parents 1d725a9 + bda49ab commit 3f326d8

File tree

5 files changed

+1436
-1
lines changed

5 files changed

+1436
-1
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ This repo is an ongoing collection of useful, and occasionally clever, solidity/
1515
- Contracts with upgradeable logic.
1616
- [Big Data Storage (SSTORE2)](./patterns/big-data-storage)
1717
- Cost efficient on-chain storage of multi-word data accessible to contracts.
18+
- [Bitmap Nonces](./patterns/bitmap-nonces/)
19+
- Efficiently tracking the state of many operations identifiable by a unique nonce.
1820
- [Commit + Reveal](./patterns/commit-reveal)
1921
- A two-step process for performing partially obscured on-chain actions that can't be front or back runned.
2022
- [EIP712 Signed Messages](./patterns/eip712-signed-messages)
@@ -52,7 +54,7 @@ This repo is an ongoing collection of useful, and occasionally clever, solidity/
5254
- [Read-Only Delegatecall](./patterns/readonly-delegatecall)
5355
- Execute arbitrary delegatecalls in your contract in a read-only manner, without side-effects.
5456
- [Reentrancy](./patterns/reentrancy)
55-
- Explaining reentrancy vulnerabilities and patterns for addressing them.
57+
- Explaining reentrancy vulnerabilities and patterns for addressing them (Checks-Effects-Interactions and reentrancy guards).
5658
- [Separate Allowance Targets](./patterns/separate-allowance-targets/)
5759
- Avoid having to migrate user allowances between upgrades with a dedicated approval contract.
5860
- [Stack-Too-Deep Workarounds](./patterns/stack-too-deep/)

patterns/bitmap-nonces/README.md

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# Bitmap Nonces
2+
3+
- [📜 Example Code](./TransferRelay.sol)
4+
- [🐞 Tests](../../test/TransferRelay.t.sol)
5+
6+
What do filling a stop-loss order, executing a governance proposal, or meta transactions have in common? They're all operations meant to be consumed once and only once. You'll find these kinds of operations across many major protocols. This single-use guarantee needs to be enforced on-chain to prevent replay attacks. To do this, many protocols will derive some unique identifier (nonce) for the operation then map that identifier to a storage slot dedicated to that operation which holds a status flag indicating whether its been consumed or not.
7+
8+
## The Naive Approach
9+
10+
Take the following example of a contract that executes off-chain signed messages to transfer (compliant) ERC20 tokens on behalf of the signer after a given time:
11+
12+
```solidity
13+
contract TransferRelay {
14+
struct Message {
15+
address from;
16+
address to;
17+
uint256 validAfter;
18+
IERC20 token;
19+
uint256 amount;
20+
uint256 nonce;
21+
}
22+
23+
mapping (address => mapping (uint256 => bool)) public isSignerNonceConsumed;
24+
25+
function executeTransferMessage(
26+
Message calldata mess,
27+
uint8 v,
28+
bytes32 r,
29+
bytes32 s
30+
)
31+
external
32+
{
33+
require(mess.from != address(0), 'bad from');
34+
require(mess.validAfter < block.timestamp, 'not ready');
35+
require(!isSignerNonceConsumed[mess.from][mess.nonce], 'already consumed');
36+
{
37+
bytes32 messHash = keccak256(abi.encode(block.chainid, address(this), mess));
38+
require(ecrecover(messHash, v, r, s) == mess.from, 'bad signature');
39+
}
40+
// Mark the message consumed.
41+
isSignerNonceConsumed[mess.from][mess.nonce] = true;
42+
// Perform the transfer.
43+
mess.token.transferFrom(address(mess.from), mess.to, mess.amount);
44+
}
45+
}
46+
```
47+
48+
We expect the signer to choose a `nonce` value that is unique across all their messages. Our contract uses this `nonce` value to uniquely identify the message and record its status in the `isSignerNonceConsumed` mapping. Pretty straight-forward and intuitive... but we can do better!
49+
50+
## Examining Gas costs
51+
52+
Let's look at the gas cost associated with marking a message consumed. Because every `Message.nonce` maps to a unique storage slot, we will write to an **empty** slot each time a message gets consumed. Writing to an empty storage slot costs 20k(\*) gas. For context, this can represent 15% of the total gas cost for a simple AMM swap. Especially for high frequency defi operations, the costs can add up. In contrast, writing to a *non-empty* storage slot only costs 3k(\*) gas. Bitmap nonces can minimize how often we write to empty slots, cutting down this cost down by 85% for most operations.
53+
54+
*(\*) Not accounting for EIP-2929 cold/warm state access costs.*
55+
56+
## One More Time, With Bitmap Nonces
57+
58+
If we think about it, we don't need a whole 32-byte word, or even a whole 8-bit boolean to represent whether a message was consumed. We only need one bit (`0` or `1`). So if we wanted to minimize the frequency of writes to empty slots, instead of mapping nonces to an *entire* storage slot, we could map nonces to bit positions within a storage slot. Each storage slot in the EVM is a 32-byte word so we can fit the status of 256 operations inside a single storage slot before we have to move on to the next.
59+
60+
![nonces slot usage](./nonces-slots.drawio.svg)
61+
62+
The addressing is done by mapping the upper 248 bits of the `nonce` to a unique slot (similar to before), then map the lower 8 bits to a bit offset inside that slot. If the user assigns nonces to operations incrementally (1, 2, 3, ...) instead of randomly then they will only write to a new slot every 255 operations.
63+
64+
Let's apply bitmap nonces to our contract:
65+
66+
```solidity
67+
contract TransferRelay {
68+
// ...
69+
70+
mapping (address => mapping (uint248 => uint256)) public signerNonceBitmap;
71+
72+
function executeTransferMessage(
73+
Message calldata mess,
74+
uint8 v,
75+
bytes32 r,
76+
bytes32 s
77+
)
78+
external
79+
{
80+
require(mess.from != address(0), 'bad from');
81+
require(mess.validAfter < block.timestamp, 'not ready');
82+
require(!_getSignerNonceState(mess.from, mess.nonce), 'already consumed');
83+
{
84+
bytes32 messHash = keccak256(abi.encode(block.chainid, address(this), mess));
85+
require(ecrecover(messHash, v, r, s) == mess.from, 'bad signature');
86+
}
87+
// Mark the message consumed.
88+
_setSignerNonce(mess.from, mess.nonce);
89+
// Perform the transfer.
90+
mess.token.transferFrom(address(mess.from), mess.to, mess.amount);
91+
}
92+
93+
function _getSignerNonceState(address signer, uint256 nonce) private view returns (bool) {
94+
uint256 bitmap = signerNonceBitmap[signer][uint248(nonce >> 8)];
95+
return bitmap & (1 << (nonce & 0xFF)) != 0;
96+
}
97+
98+
function _setSignerNonce(address signer, uint256 nonce) private {
99+
signerNonceBitmap[signer][uint248(nonce >> 8)] |= 1 << (nonce & 0xFF);
100+
}
101+
}
102+
```
103+
104+
## Final Thoughts
105+
106+
- You can find bitmap nonces being used in major protocols such as Uniswap's [Permit2](https://github.com/Uniswap/permit2/blob/cc56ad0f3439c502c246fc5cfcc3db92bb8b7219/src/SignatureTransfer.sol#L142) and 0x's [Exchange Proxy](https://github.com/0xProject/protocol/blob/e66307ba319e8c3e2a456767403298b576abc85e/contracts/zero-ex/contracts/src/features/nft_orders/ERC721OrdersFeature.sol#L662).
107+
- There is no reason you couldn't track operations that have more than 2 states using bitmap nonces. You would just simply increase the number of bits in a word assigned to each operation and adjust the mapping formula accordingly.
108+
- The full, working example can be found [here](./TransferRelay.sol) with complete tests demonstrating its usage and gas savings [here](../../test/TransferRelay.sol).
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// SPDX-License-Identifier: MIT
2+
pragma solidity ^0.8.23;
3+
4+
// Minimal ERC20 interface.
5+
interface IERC20 {
6+
function transferFrom(address from, address to, uint256 amount) external returns (bool);
7+
}
8+
9+
// Allows anyone to execute an ERC20 token transfer on someone else's behalf.
10+
// Payers grant an allowance to this contract on every ERC20 they wish to send.
11+
// Then they sign an off-chain message (hash of the `Message` struct) indicating
12+
// recipient, amount, and time. Afterwards, anyone can submit the message to this
13+
// contract's `executeTransferMessage()` function which consumes the message and
14+
// executes the transfer. Messages are marked consumed using bitmap nonces rather
15+
// than traditional, dedicated nonce slots.
16+
contract TransferRelay {
17+
struct Message {
18+
address from;
19+
address to;
20+
uint256 validAfter;
21+
IERC20 token;
22+
uint256 amount;
23+
uint256 nonce;
24+
}
25+
26+
mapping (address => mapping (uint248 => uint256)) public signerNonceBitmap;
27+
28+
// Consume a signed transfer message and transfer tokens specified within (if valid).
29+
function executeTransferMessage(
30+
Message calldata mess,
31+
uint8 v,
32+
bytes32 r,
33+
bytes32 s
34+
)
35+
external
36+
{
37+
require(mess.from != address(0), 'bad from');
38+
require(mess.validAfter < block.timestamp, 'not ready');
39+
require(!_getSignerNonceState(mess.from, mess.nonce), 'already consumed');
40+
{
41+
bytes32 messHash = keccak256(abi.encode(block.chainid, address(this), mess));
42+
require(ecrecover(messHash, v, r, s) == mess.from, 'bad signature');
43+
}
44+
// Mark the message consumed.
45+
_setSignerNonce(mess.from, mess.nonce);
46+
// Perform the transfer.
47+
mess.token.transferFrom(address(mess.from), mess.to, mess.amount);
48+
}
49+
50+
function _getSignerNonceState(address signer, uint256 nonce) private view returns (bool) {
51+
uint256 bitmap = signerNonceBitmap[signer][uint248(nonce >> 8)];
52+
return bitmap & (1 << (nonce & 0xFF)) != 0;
53+
}
54+
55+
function _setSignerNonce(address signer, uint256 nonce) private {
56+
signerNonceBitmap[signer][uint248(nonce >> 8)] |= 1 << (nonce & 0xFF);
57+
}
58+
}

0 commit comments

Comments
 (0)