-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy patherc7715Mapping.ts
More file actions
573 lines (529 loc) · 15.8 KB
/
Copy patherc7715Mapping.ts
File metadata and controls
573 lines (529 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
import type {
Erc20TokenAllowancePermission as RpcErc20TokenAllowancePermission,
Erc20TokenPeriodicPermission as RpcErc20TokenPeriodicPermission,
Erc20TokenStreamPermission as RpcErc20TokenStreamPermission,
Erc20TokenRevocationPermission as RpcErc20TokenRevocationPermission,
NativeTokenAllowancePermission as RpcNativeTokenAllowancePermission,
NativeTokenPeriodicPermission as RpcNativeTokenPeriodicPermission,
NativeTokenStreamPermission as RpcNativeTokenStreamPermission,
PermissionRequest,
PermissionTypes as RpcPermissionTypes,
Rule,
TokenApprovalRevocationPermission as RpcTokenApprovalRevocationPermission,
} from '@metamask/7715-permission-types';
import { getAddress, hexToNumber, isAddress, toHex, type Hex } from 'viem';
import { isDefined, toHexOrThrow } from '../utils';
import type {
Erc20TokenAllowancePermission,
Erc20TokenPeriodicPermission,
Erc20TokenRevocationPermission,
Erc20TokenStreamPermission,
GetGrantedExecutionPermissionsResult,
GetSupportedExecutionPermissionsResult,
NativeTokenAllowancePermission,
NativeTokenPeriodicPermission,
NativeTokenStreamPermission,
PermissionRequestParameter,
PermissionTypes as DeveloperPermissionTypes,
RpcGetGrantedExecutionPermissionsResult,
RpcGetSupportedExecutionPermissionsResult,
TokenApprovalRevocationPermission,
} from './erc7715Types';
// =============================================================================
// Developer → RPC (request formatting)
// =============================================================================
/**
* Converts a developer permission request to RPC format for wallet submission.
*
* @param parameters the permission request parameters
* @returns the permission request in RPC format
*/
export function permissionRequestToRpc(
parameters: PermissionRequestParameter,
): PermissionRequest<RpcPermissionTypes> {
const { chainId, from, expiry, redeemer, payee } = parameters;
const converter = getPermissionRequestToRpcConverter(
parameters.permission.type,
);
const rules: Rule[] = [];
if (isDefined(expiry)) {
rules.push({
type: 'expiry',
data: {
timestamp: expiry,
},
});
}
if (isDefined(redeemer)) {
if (redeemer.length === 0) {
throw new Error(
'Invalid redeemers: must specify at least one redeemer address',
);
}
const addresses: Hex[] = [];
for (const addr of redeemer) {
if (!isAddress(addr)) {
throw new Error('Invalid redeemers: must be a valid address');
}
addresses.push(getAddress(addr));
}
rules.push({
type: 'redeemer',
data: { addresses },
});
}
if (isDefined(payee)) {
if (payee.length === 0) {
throw new Error(
'Invalid payees: must specify at least one payee address',
);
}
const payeeAddresses: Hex[] = [];
for (const addr of payee) {
if (!isAddress(addr)) {
throw new Error('Invalid payees: must be a valid address');
}
payeeAddresses.push(getAddress(addr));
}
rules.push({
type: 'payee',
data: { addresses: payeeAddresses },
});
}
const optionalFields = {
...(from ? { from } : {}),
};
return {
...optionalFields,
chainId: toHex(chainId),
permission: converter(parameters.permission),
to: parameters.to,
rules,
};
}
type PermissionRequestToRpcConverter = (
permission: DeveloperPermissionTypes,
) => RpcPermissionTypes;
/**
* Get the permission request to RPC converter for the given permission type.
*
* @param permissionType the permission type
* @returns the permission request to RPC converter for the given permission type
*/
function getPermissionRequestToRpcConverter(
permissionType: string,
): PermissionRequestToRpcConverter {
switch (permissionType) {
case 'native-token-stream':
return (permission) =>
nativeTokenStreamPermissionToRpc(
permission as NativeTokenStreamPermission,
);
case 'erc20-token-stream':
return (permission) =>
erc20TokenStreamPermissionToRpc(
permission as Erc20TokenStreamPermission,
);
case 'native-token-periodic':
return (permission) =>
nativeTokenPeriodicPermissionToRpc(
permission as NativeTokenPeriodicPermission,
);
case 'native-token-allowance':
return (permission) =>
nativeTokenAllowancePermissionToRpc(
permission as NativeTokenAllowancePermission,
);
case 'erc20-token-periodic':
return (permission) =>
erc20TokenPeriodicPermissionToRpc(
permission as Erc20TokenPeriodicPermission,
);
case 'erc20-token-allowance':
return (permission) =>
erc20TokenAllowancePermissionToRpc(
permission as Erc20TokenAllowancePermission,
);
case 'erc20-token-revocation':
return (permission) =>
erc20TokenRevocationPermissionToRpc(
permission as Erc20TokenRevocationPermission,
);
case 'token-approval-revocation':
return (permission) =>
tokenApprovalRevocationPermissionToRpc(
permission as TokenApprovalRevocationPermission,
);
default:
throw new Error(`Unsupported permission type: ${permissionType}`);
}
}
/**
* Convert native token stream permission to RPC format.
*
* @param permission the native token stream permission
* @returns the native token stream permission in RPC format
*/
function nativeTokenStreamPermissionToRpc(
permission: NativeTokenStreamPermission,
): RpcNativeTokenStreamPermission {
const {
data: {
initialAmount,
justification,
maxAmount,
startTime,
amountPerSecond,
},
isAdjustmentAllowed,
} = permission;
const optionalFields = {
...(isDefined(initialAmount) && {
initialAmount: toHexOrThrow(initialAmount, 'initialAmount'),
}),
...(isDefined(maxAmount) && {
maxAmount: toHexOrThrow(maxAmount, 'maxAmount'),
}),
...(isDefined(startTime) && {
startTime: Number(startTime),
}),
...(justification ? { justification } : {}),
};
return {
type: 'native-token-stream',
data: {
amountPerSecond: toHexOrThrow(amountPerSecond, 'amountPerSecond'),
...optionalFields,
},
isAdjustmentAllowed,
};
}
/**
* Convert ERC20 token stream permission to RPC format.
*
* @param permission the erc20 token stream permission
* @returns the erc20 token stream permission in RPC format
*/
function erc20TokenStreamPermissionToRpc(
permission: Erc20TokenStreamPermission,
): RpcErc20TokenStreamPermission {
const {
data: {
tokenAddress,
amountPerSecond,
initialAmount,
startTime,
maxAmount,
justification,
},
isAdjustmentAllowed,
} = permission;
const optionalFields = {
...(isDefined(initialAmount) && {
initialAmount: toHexOrThrow(initialAmount, 'initialAmount'),
}),
...(isDefined(maxAmount) && {
maxAmount: toHexOrThrow(maxAmount, 'maxAmount'),
}),
...(isDefined(startTime) && {
startTime: Number(startTime),
}),
...(justification ? { justification } : {}),
};
return {
type: 'erc20-token-stream',
data: {
tokenAddress: toHexOrThrow(tokenAddress, 'tokenAddress'),
amountPerSecond: toHexOrThrow(amountPerSecond, 'amountPerSecond'),
...optionalFields,
},
isAdjustmentAllowed,
};
}
/**
* Convert native token periodic permission to RPC format.
*
* @param permission the native token periodic permission
* @returns the native token periodic permission in RPC format
*/
function nativeTokenPeriodicPermissionToRpc(
permission: NativeTokenPeriodicPermission,
): RpcNativeTokenPeriodicPermission {
const {
data: { periodAmount, periodDuration, startTime, justification },
isAdjustmentAllowed,
} = permission;
const optionalFields = {
...(isDefined(startTime) && {
startTime: Number(startTime),
}),
...(justification ? { justification } : {}),
};
return {
type: 'native-token-periodic',
data: {
periodAmount: toHexOrThrow(periodAmount, 'periodAmount'),
periodDuration: Number(periodDuration),
...optionalFields,
},
isAdjustmentAllowed,
};
}
/**
* Convert ERC20 token periodic permission to RPC format.
*
* @param permission the erc20 token periodic permission
* @returns the erc20 token periodic permission in RPC format
*/
function erc20TokenPeriodicPermissionToRpc(
permission: Erc20TokenPeriodicPermission,
): RpcErc20TokenPeriodicPermission {
const {
data: {
tokenAddress,
periodAmount,
periodDuration,
startTime,
justification,
},
isAdjustmentAllowed,
} = permission;
const optionalFields = {
...(isDefined(startTime) && {
startTime: Number(startTime),
}),
...(justification ? { justification } : {}),
};
return {
type: 'erc20-token-periodic',
data: {
tokenAddress: toHexOrThrow(tokenAddress, 'tokenAddress'),
periodAmount: toHexOrThrow(periodAmount, 'periodAmount'),
periodDuration: Number(periodDuration),
...optionalFields,
},
isAdjustmentAllowed,
};
}
/**
* Convert native token fixed allowance permission to RPC format.
*
* @param permission the native token fixed allowance permission
* @returns the native token fixed allowance permission in RPC format
*/
function nativeTokenAllowancePermissionToRpc(
permission: NativeTokenAllowancePermission,
): RpcNativeTokenAllowancePermission {
const {
data: { allowanceAmount, startTime, justification },
isAdjustmentAllowed,
} = permission;
const optionalFields = {
...(isDefined(startTime) && {
startTime: Number(startTime),
}),
...(justification ? { justification } : {}),
};
return {
type: 'native-token-allowance',
data: {
allowanceAmount: toHexOrThrow(allowanceAmount, 'allowanceAmount'),
...optionalFields,
},
isAdjustmentAllowed,
};
}
/**
* Convert ERC-20 token fixed allowance permission to RPC format.
*
* @param permission the ERC-20 token fixed allowance permission
* @returns the ERC-20 token fixed allowance permission in RPC format
*/
function erc20TokenAllowancePermissionToRpc(
permission: Erc20TokenAllowancePermission,
): RpcErc20TokenAllowancePermission {
const {
data: { tokenAddress, allowanceAmount, startTime, justification },
isAdjustmentAllowed,
} = permission;
const optionalFields = {
...(isDefined(startTime) && {
startTime: Number(startTime),
}),
...(justification ? { justification } : {}),
};
return {
type: 'erc20-token-allowance',
data: {
tokenAddress: toHexOrThrow(tokenAddress, 'tokenAddress'),
allowanceAmount: toHexOrThrow(allowanceAmount, 'allowanceAmount'),
...optionalFields,
},
isAdjustmentAllowed,
};
}
/**
* Convert ERC20 token revocation permission to RPC format.
*
* @param permission the erc20 token revocation permission
* @returns the erc20 token revocation permission in RPC format
*/
function erc20TokenRevocationPermissionToRpc(
permission: Erc20TokenRevocationPermission,
): RpcErc20TokenRevocationPermission {
const {
data: { justification },
isAdjustmentAllowed,
} = permission;
const data = {
...(justification ? { justification } : {}),
};
return {
type: 'erc20-token-revocation',
data,
isAdjustmentAllowed,
};
}
/**
* Convert token approval revocation permission to RPC format.
*
* @param permission the token approval revocation permission
* @returns the token approval revocation permission in RPC format
*/
function tokenApprovalRevocationPermissionToRpc(
permission: TokenApprovalRevocationPermission,
): RpcTokenApprovalRevocationPermission {
const {
data: {
erc20Approve,
erc721Approve,
erc721SetApprovalForAll,
permit2ApproveZero,
permit2Lockdown,
permit2InvalidateNonces,
justification,
},
isAdjustmentAllowed,
} = permission;
const data = {
erc20Approve,
erc721Approve,
erc721SetApprovalForAll,
permit2ApproveZero,
permit2Lockdown,
permit2InvalidateNonces,
...(justification ? { justification } : {}),
};
return {
type: 'token-approval-revocation',
data,
isAdjustmentAllowed,
};
}
// =============================================================================
// RPC → Developer friendly types (response conversion)
// =============================================================================
/**
* Converts RPC permission responses to developer-friendly types.
* Converts chainId from hex to number, and token amounts from hex to bigint.
*
* @param result the RPC permission responses
* @returns the developer-friendly permission responses
*/
export function permissionResponsesFromRpc(
result: RpcGetGrantedExecutionPermissionsResult,
): GetGrantedExecutionPermissionsResult {
return result.map((permission) => ({
...permission,
chainId: hexToNumber(permission.chainId),
permission: permissionTypeFromRpc(permission.permission),
rules: normalizeRulesFromRpc(permission.rules),
}));
}
/**
* Checksums addresses in `redeemer` and `payee` rules; other rules are returned unchanged.
*
* @param rules - Rules from the wallet RPC response.
* @returns The same list with normalized addresses, or null/undefined if that was the input.
*/
function normalizeRulesFromRpc(
rules: Rule[] | null | undefined,
): Rule[] | null | undefined {
if (rules === undefined || rules === null) {
return rules;
}
return rules.map((rule) => {
if (rule.type !== 'redeemer' && rule.type !== 'payee') {
return rule;
}
const rawAddresses = (rule.data as { addresses?: unknown } | undefined)
?.addresses;
if (!Array.isArray(rawAddresses)) {
return rule;
}
return {
type: rule.type,
data: {
addresses: rawAddresses.map((addr) => getAddress(addr as Hex)),
},
};
});
}
/**
* Converts RPC permission type data to developer-friendly types.
* Converts hex amount fields to bigint.
*
* @param permission the RPC permission
* @returns the developer-friendly permission
*/
export function permissionTypeFromRpc(
permission: RpcPermissionTypes,
): DeveloperPermissionTypes {
const convertedData: Record<string, unknown> = { ...permission.data };
if ('amountPerSecond' in convertedData && convertedData.amountPerSecond) {
convertedData.amountPerSecond = BigInt(
convertedData.amountPerSecond as `0x${string}`,
);
}
if ('periodAmount' in convertedData && convertedData.periodAmount) {
convertedData.periodAmount = BigInt(
convertedData.periodAmount as `0x${string}`,
);
}
if ('initialAmount' in convertedData && convertedData.initialAmount) {
convertedData.initialAmount = BigInt(
convertedData.initialAmount as `0x${string}`,
);
}
if ('maxAmount' in convertedData && convertedData.maxAmount) {
convertedData.maxAmount = BigInt(convertedData.maxAmount as `0x${string}`);
}
if ('allowanceAmount' in convertedData && convertedData.allowanceAmount) {
convertedData.allowanceAmount = BigInt(
convertedData.allowanceAmount as `0x${string}`,
);
}
return {
...permission,
data: convertedData,
} as DeveloperPermissionTypes;
}
/**
* Converts RPC supported permissions result to developer-friendly types.
* Converts chain IDs from hex to numbers.
*
* @param result the RPC supported permissions result
* @returns the developer-friendly supported permissions result
*/
export function rpcSupportedPermissionsToDeveloper(
result: RpcGetSupportedExecutionPermissionsResult,
): GetSupportedExecutionPermissionsResult {
const converted: GetSupportedExecutionPermissionsResult = {};
for (const [permissionType, permissionInfo] of Object.entries(result)) {
converted[permissionType] = {
chainIds: permissionInfo.chainIds.map((chainId) => hexToNumber(chainId)),
ruleTypes: permissionInfo.ruleTypes,
};
}
return converted;
}