Skip to content

Commit 1a51d77

Browse files
committed
add batch transfers to permit2 and update diagram
1 parent 3c33e07 commit 1a51d77

File tree

6 files changed

+235
-43
lines changed

6 files changed

+235
-43
lines changed

lib/solmate

patterns/permit2/Permit2Vault.sol

+73-5
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ contract Permit2Vault {
2121
_reentrancyGuard = false;
2222
}
2323

24-
// Deposit some amount of an ERC20 token into this contract
25-
// using Permit2.
24+
// Deposit some amount of an ERC20 token from the caller
25+
// into this contract using Permit2.
2626
function depositERC20(
2727
IERC20 token,
2828
uint256 amount,
@@ -34,7 +34,7 @@ contract Permit2Vault {
3434
tokenBalancesByUser[msg.sender][token] += amount;
3535
// Transfer tokens from the caller to ourselves.
3636
PERMIT2.permitTransferFrom(
37-
// The permit message.
37+
// The permit message. Spender will be inferred as the caller (us).
3838
IPermit2.PermitTransferFrom({
3939
permitted: IPermit2.TokenPermissions({
4040
token: token,
@@ -58,13 +58,63 @@ contract Permit2Vault {
5858
);
5959
}
6060

61+
// Deposit multiple ERC20 tokens from the caller
62+
// into this contract using Permit2.
63+
function depositBatchERC20(
64+
IERC20[] calldata tokens,
65+
uint256[] calldata amounts,
66+
uint256 nonce,
67+
uint256 deadline,
68+
bytes calldata signature
69+
) external nonReentrant {
70+
require(tokens.length == amounts.length, 'array mismatch');
71+
// The batch form of `permitTransferFrom()` takes an array of
72+
// transfer details, which we will all direct to ourselves.
73+
IPermit2.SignatureTransferDetails[] memory transferDetails =
74+
new IPermit2.SignatureTransferDetails[](tokens.length);
75+
// Credit the caller and populate the transferDetails.
76+
for (uint256 i; i < tokens.length; ++i) {
77+
tokenBalancesByUser[msg.sender][tokens[i]] += amounts[i];
78+
transferDetails[i] = IPermit2.SignatureTransferDetails({
79+
to: address(this),
80+
requestedAmount: amounts[i]
81+
});
82+
}
83+
PERMIT2.permitTransferFrom(
84+
// The permit message. Spender will be inferred as the caller (us).
85+
IPermit2.PermitBatchTransferFrom({
86+
permitted: _toTokenPermissionsArray(tokens, amounts),
87+
nonce: nonce,
88+
deadline: deadline
89+
}),
90+
// The transfer recipients and amounts.
91+
transferDetails,
92+
// The owner of the tokens, which must also be
93+
// the signer of the message, otherwise this call
94+
// will fail.
95+
msg.sender,
96+
// The packed signature that was the result of signing
97+
// the EIP712 hash of `permit`.
98+
signature
99+
);
100+
}
101+
61102
// Return ERC20 tokens deposited by the caller.
62103
function withdrawERC20(IERC20 token, uint256 amount) external nonReentrant {
63104
tokenBalancesByUser[msg.sender][token] -= amount;
64105
// TODO: In production, use an ERC20 compatibility library to
65106
// execute thie transfer to support non-compliant tokens.
66107
token.transfer(msg.sender, amount);
67108
}
109+
110+
function _toTokenPermissionsArray(IERC20[] calldata tokens, uint256[] calldata amounts)
111+
private pure returns (IPermit2.TokenPermissions[] memory permissions)
112+
{
113+
permissions = new IPermit2.TokenPermissions[](tokens.length);
114+
for (uint256 i; i < permissions.length; ++i) {
115+
permissions[i] = IPermit2.TokenPermissions({ token: tokens[i], amount: amounts[i] });
116+
}
117+
}
68118
}
69119

70120
// Minimal Permit2 interface, derived from
@@ -80,8 +130,18 @@ interface IPermit2 {
80130

81131
// The permit2 message.
82132
struct PermitTransferFrom {
83-
// Permitted token and amount.
84-
TokenPermissions permitted;
133+
// Permitted token and maximum amount.
134+
TokenPermissions permitted;// deadline on the permit signature
135+
// Unique identifier for this permit.
136+
uint256 nonce;
137+
// Expiration for this permit.
138+
uint256 deadline;
139+
}
140+
141+
// The permit2 message for batch transfers.
142+
struct PermitBatchTransferFrom {
143+
// Permitted tokens and maximum amounts.
144+
TokenPermissions[] permitted;
85145
// Unique identifier for this permit.
86146
uint256 nonce;
87147
// Expiration for this permit.
@@ -103,6 +163,14 @@ interface IPermit2 {
103163
address owner,
104164
bytes calldata signature
105165
) external;
166+
167+
// Consume a batch permit2 message and transfer tokens.
168+
function permitTransferFrom(
169+
PermitBatchTransferFrom calldata permit,
170+
SignatureTransferDetails[] calldata transferDetails,
171+
address owner,
172+
bytes calldata signature
173+
) external;
106174
}
107175

108176
// Minimal ERC20 interface.

patterns/permit2/README.md

+27-8
Original file line numberDiff line numberDiff line change
@@ -45,18 +45,20 @@ Finally, let's dive into the Permit2 approach, which echoes elements from both p
4545

4646
1. Alice calls `approve()` on an ERC20 to grant an infinite allowance to the canonical Permit2 contract.
4747
2. Alice signs an off-chain "permit2" message that signals that the protocol contract is allowed to *transfer* tokens on her behalf.
48-
3. Alice calls an interaction function on the protocol contract, passing in the signed permit2 message as a parameter.
48+
3. The next step will vary depending on UX choices:
49+
1. In the simple case, Alice can just submit a transaction herself, including the signed permit2 message as part of an interaction with the protocol contract.
50+
2. If the protocol contract allows it, Alice can transmit her signed permit2 message to a relayer service that will submit interaction the transaction on Alice's behalf.
4951
4. The protocol contract calls `permitTransferFrom()` on the Permit2 contract, which in turn uses its allowance (granted in 1.) to call `transferFrom()` on the ERC20 contract, moving the tokens held by Alice.
5052

51-
It might seem like a regression to require the user to grant an explicit allowance first. But rather than granting it to the protocol directly, the user will instead grant it to the canonical Permit2 contract. This means that if the user has already done this before, say to interact with another protocol that integrated Permit2, every other protocol can skip that step! 🎉
53+
It might seem like a regression to require the user to grant an explicit allowance first. But rather than granting it to the protocol directly, the user will instead grant it to the canonical Permit2 contract. This means that if the user has already done this before, say to interact with another protocol that integrated Permit2, *every other protocol can skip that step*.
5254

5355
Instead of directly calling `transferFrom()` on the ERC20 token to perform a transfer, a protocol will call `permitTransferFrom()` on the canonical Permit2 contract. Permit2 sits between the protocol and the ERC20 token, tracking and validating permit2 messages, then ultimately using its allowance to perform the `transferFrom()` call directly on the ERC20. This indirection is what allows Permit2 to extend EIP-2612-like benefits to every existing ERC20 token! 🎉
5456

55-
Also, like EIP-2612 permit messages, permit2 messages expire to limit the the attack window of an exploit.
57+
Also, like EIP-2612 permit messages, permit2 messages expire to limit the the attack window of an exploit. It's much also easier to secure the small Permit2 contract than the contracts of individual defi protocols, so having an infinite allowance there is less of a concern.
5658

5759
## Integrating Permit2
5860

59-
For a frontend integrating Permit2, it will need to collect a user signature that will be passed into the transaction. The Permit2 message struct (`PermitTransferFrom`) signed by these signatures must comply with the [EIP-712](https://eips.ethereum.org/EIPS/eip-712) standard (for which [we have a general guide](../eip712-signed-messages/)), using the Permit2 domain and type hashes defined [here](https://github.com/Uniswap/permit2/blob/main/src/EIP712.sol) and [here](https://github.com/Uniswap/permit2/blob/main/src/libraries/PermitHash.sol). Be aware that the `spender` field for the EIP-712 Permit2 object needs to be set to the contract address that will be consuming it.
61+
For a frontend integrating Permit2, it will need to collect a user signature that will be passed into the transaction. The Permit2 message struct (`PermitTransferFrom`) signed by these signatures must comply with the [EIP-712](https://eips.ethereum.org/EIPS/eip-712) standard (for which [we have a general guide](../eip712-signed-messages/)), using the Permit2 domain and type hashes defined [here](https://github.com/Uniswap/permit2/blob/main/src/EIP712.sol) and [here](https://github.com/Uniswap/permit2/blob/main/src/libraries/PermitHash.sol). Be aware that the `spender` field for the EIP-712 Permit2 object needs to be set to the contract address that will be consuming it and directly calling the Permit2 contract functions.
6062

6163
The smart contract integration is actually fairly easy! Any function that needs to move tokens held by a user just needs to accept any unknown permit message details and the corresponding EIP-712 user signature. To actually move the tokens, we will call `permitTransferFrom()` on the canonical Permit2 contract. That function is declared as:
6264

@@ -76,23 +78,40 @@ The parameters for this function are:
7678
- `amount` - *Maximum* amount that can be transferred when consuming this permit.
7779
- `nonce` - A unique number, chosen by our app, to identify this permit. Once a permit is consumed, any other permit using that nonce will be invalid.
7880
- `deadline` - The latest possible block timestamp for when this permit is valid.
79-
- `transferDetails` - A struct containing the transfer recipient and transfer amount, which can be less than the amount the user signed for.
81+
- `transferDetails` - A struct detailing where permitted token should be transfered to and how much.
82+
- `to` - Who receives the permitted token.
83+
- `requestedAmount`: How much should be transferred. This can be less than the amount that the user signed in `permit.permitted`.
8084
- `owner` - Who signed the permit and also holds the tokens. Often, in simple use-cases where the caller and the user are one and the same, this should be set to the caller (`msg.sender`). But in more exotic integrations, [you may need more sophisticated checks](https://docs.uniswap.org/contracts/permit2/reference/signature-transfer#security-considerations).
8185
- `signature` - The corresponding EIP-712 signature for the permit2 message, signed by `owner`. If the recovered address from signature verification does not match `owner`, the call will fail.
8286

8387
> 🛈 Note that the `PermitTransferFrom` struct does not include the `spender` field found in the [EIP-712 typehash definition for the permit message](https://github.com/Uniswap/permit2/blob/main/src/libraries/PermitHash.sol#L21). It will be populated with our contract's address (the direct caller of `permitTransferFrom()`) during processing. This is why the `spender` field of the EIP-712 object the user signs must be the address of this contract.
8488
89+
90+
### Batch Transfers
91+
92+
If you need to transfer multiple tokens, the good news is Permit2 also supports batch transfers via an overloaded implementation of `permitTransferFrom()`:
93+
94+
```solidity
95+
function permitTransferFrom(
96+
PermitBatchTransferFrom memory permit,
97+
SignatureTransferDetails[] calldata transferDetails,
98+
address owner,
99+
bytes calldata signature
100+
) external;
101+
```
102+
103+
Instead of having the user sign a `PermitTransferFrom` message struct, you'll need the user to sign a `PermitBatchTransferFrom` message struct, inside which the `permitted` field is now an *array* of `TokenPermissions` structs instead of a single item. This version of `permitTransferFrom()` also accepts an array of `SignatureTransferDetails`, meaning each token permission can be directed towards different recipients.
104+
85105
### Advanced Integrations
86106
This guide covers the basic functionality offered by Permit2 but there's more you can do with it!
87-
- [Custom Witness Data](https://docs.uniswap.org/contracts/permit2/reference/signature-transfer#single-permitwitnesstransferfrom) - You can append custom data to the permit2 message, which means the Permit2 signature validation will extend to that data as well.
88-
- [Batch Transfers](https://docs.uniswap.org/contracts/permit2/reference/signature-transfer#batched-permittransferfrom) - A batched permit2 message for performing multiple transfers, secured by a single signature.
107+
- [Custom Witness Data](https://docs.uniswap.org/contracts/permit2/reference/signature-transfer#single-permitwitnesstransferfrom) - You can append custom data to the permit2 message, which means the Permit2 signature validation will extend to that data as well. Extremely useful to add validation to the rest of the interaction when employing the relayer approach.
89108
- [Smart Nonces](https://docs.uniswap.org/contracts/permit2/reference/signature-transfer#nonce-schema) - Under the hood, nonces are actually written as bit fields in an storage slot indexed by the upper 248 bits. You can save a signficant amount of gas by carefully choosing nonce values that reuse storage slots.
90109
- [Callback signatures](https://github.com/Uniswap/permit2/blob/main/src/libraries/SignatureVerification.sol#L43) - Permit2 supports [EIP-1271](https://eips.ethereum.org/EIPS/eip-1271) callback signatures, which allow smart contracts to also sign permit2 messages.
91110
- [Permit2 Allowances](https://docs.uniswap.org/contracts/permit2/reference/allowance-transfer) - For protocols that need more flexibility, Permit2 supports a more conventional allowance model that gets the added benefit of expiration times.
92111

93112
## The Demo
94113

95-
The provided [example code](./Permit2Vault.sol) is a simple vault that users can deposit ERC20 tokens into using Permit2, which they can later withdraw. Because it's multi-user, it needs to initiate the transfer in order to reliably credit which account owns which balance. Normally this requires granting an allowance to the vault contract and then having the vault perform the `transferFrom()` on the token itself, but Permit2 allows us to skip that hassle!
114+
The provided [example code](./Permit2Vault.sol) is a simple vault that users can deposit ERC20 tokens into using Permit2, which they can later withdraw. Because it's multi-user, it needs to initiate the transfer in order to reliably credit which account owns which balance. Normally this requires granting an allowance to the vault contract and then having the vault perform the `transferFrom()` on the token itself, but Permit2 allows us to skip that hassle! The demo provides examples for both single and batch transfers.
96115

97116
The [tests](../../test/Permit2Vault.t.sol) deploy a local, bytecode fork of the mainnet Permit2 contract to test an instance of the vault against. The EIP-712 hashing and signature generation is written in solidity/foundry as well, but should normally be performed off-chain at the frontend/backend level in your language of choice.
98117

4.91 KB
Loading

0 commit comments

Comments
 (0)