-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathsignUserOperation.ts
More file actions
345 lines (315 loc) · 10.5 KB
/
Copy pathsignUserOperation.ts
File metadata and controls
345 lines (315 loc) · 10.5 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
import {
type Account,
type Address,
type Chain,
type Hex,
type LocalAccount,
type OneOf,
type Transport,
type UnionPartialBy,
type WalletClient,
concatHex,
decodeAbiParameters,
encodeAbiParameters,
encodePacked,
hashTypedData
} from "viem"
import type { UserOperation, WebAuthnAccount } from "viem/account-abstraction"
import { toOwner } from "../../utils/index.js"
import { getOxExports } from "../../utils/ox.js"
import type { EthereumProvider } from "../../utils/toOwner.js"
import {
EIP712_SAFE_OPERATION_TYPE_V06,
EIP712_SAFE_OPERATION_TYPE_V07,
type SafeVersion,
getDefaultAddresses,
getPaymasterAndData,
isWebAuthnAccount
} from "./toSafeSmartAccount.js"
export const concatSignatures = (
signatures: { signer: Address; data: Hex; dynamic: boolean }[]
) => {
signatures.sort((left, right) =>
left.signer.toLowerCase().localeCompare(right.signer.toLowerCase())
)
const SIGNATURE_LENGTH_BYTES = 65
let signatureBytes = "0x"
let dynamicBytes = ""
for (const sig of signatures) {
if (sig.dynamic) {
/*
A contract signature has a static part of 65 bytes and the dynamic part that needs to be appended
at the end of signature bytes.
The signature format is
Signature type == 0
Constant part: 65 bytes
{32-bytes signature verifier}{32-bytes dynamic data position}{1-byte signature type}
Dynamic part (solidity bytes): 32 bytes + signature data length
{32-bytes signature length}{bytes signature data}
*/
const dynamicPartPosition = (
signatures.length * SIGNATURE_LENGTH_BYTES +
dynamicBytes.length / 2
)
.toString(16)
.padStart(64, "0")
const dynamicPartLength = (sig.data.slice(2).length / 2)
.toString(16)
.padStart(64, "0")
const staticSignature = `${sig.signer.slice(2).padStart(64, "0")}${dynamicPartPosition}00`
const dynamicPartWithLength = `${dynamicPartLength}${sig.data.slice(2)}`
signatureBytes += staticSignature
dynamicBytes += dynamicPartWithLength
} else {
signatureBytes += sig.data.slice(2)
}
}
signatureBytes += dynamicBytes
return signatureBytes as Hex
}
export const getWebAuthnSignature = async ({
owner,
hash
}: {
owner: WebAuthnAccount
hash: Hex
}) => {
const { signature: signatureData, webauthn } = await owner.sign({
hash
})
const { Signature } = await getOxExports()
const signature = Signature.fromHex(signatureData)
const match = webauthn.clientDataJSON.match(
/^\{"type":"webauthn.get","challenge":"[A-Za-z0-9\-_]{43}",(.*)\}$/
)
if (!match) {
throw new Error("challenge not found in client data JSON")
}
const [, fields] = match
if (fields === undefined) {
throw new Error("challenge not found in client data JSON")
}
return encodeAbiParameters(
[
{ name: "authenticatorData", type: "bytes" },
{ name: "clientDataJSON", type: "string" },
{ name: "signature", type: "uint256[2]" }
],
[
webauthn.authenticatorData,
fields,
[BigInt(signature.r), BigInt(signature.s)]
]
)
}
export async function signUserOperation(
parameters: UnionPartialBy<UserOperation, "sender"> & {
version: SafeVersion
entryPoint: {
address: Address
version: "0.6" | "0.7"
}
owners: (
| Account
| WebAuthnAccount
| { owner: Account; dynamic?: boolean }
)[]
account:
| OneOf<
| EthereumProvider
| WalletClient<Transport, Chain | undefined, Account>
| LocalAccount
| WebAuthnAccount
>
| {
owner: OneOf<
| EthereumProvider
| WalletClient<Transport, Chain | undefined, Account>
| LocalAccount
| WebAuthnAccount
>
/**
* When true, the signature is encoded as a dynamic part of
* the Safe signature bytes (contract signature format,
* signature type 0x00), verified through EIP-1271 on the
* owner address.
* @default false
*/
dynamic?: boolean
}
chainId: number
signatures?: Hex
validAfter?: number
validUntil?: number
safe4337ModuleAddress?: Address
safeWebAuthnSharedSignerAddress?: Address
}
) {
const {
chainId,
entryPoint,
validAfter = 0,
validUntil = 0,
safe4337ModuleAddress: _safe4337ModuleAddress,
version,
owners,
signatures: existingSignatures,
account: _account,
...userOperation
} = parameters
const account = "owner" in _account ? _account.owner : _account
const isDynamicOwner =
"owner" in _account ? (_account.dynamic ?? false) : false
const { safe4337ModuleAddress } = getDefaultAddresses(
version,
entryPoint.version,
{
safe4337ModuleAddress: _safe4337ModuleAddress
}
)
const message = {
safe: userOperation.sender,
callData: userOperation.callData,
nonce: userOperation.nonce,
initCode: userOperation.initCode ?? "0x",
maxFeePerGas: userOperation.maxFeePerGas,
maxPriorityFeePerGas: userOperation.maxPriorityFeePerGas,
preVerificationGas: userOperation.preVerificationGas,
verificationGasLimit: userOperation.verificationGasLimit,
callGasLimit: userOperation.callGasLimit,
paymasterAndData: userOperation.paymasterAndData ?? "0x",
validAfter: validAfter,
validUntil: validUntil,
entryPoint: entryPoint.address
}
if ("initCode" in userOperation) {
message.paymasterAndData = userOperation.paymasterAndData ?? "0x"
}
if ("factory" in userOperation) {
if (userOperation.factory && userOperation.factoryData) {
message.initCode = concatHex([
userOperation.factory,
userOperation.factoryData
])
}
if (!userOperation.sender) {
throw new Error("Sender is required")
}
message.paymasterAndData = getPaymasterAndData({
...userOperation,
sender: userOperation.sender
})
}
const localOwner = isWebAuthnAccount(account)
? account
: await toOwner({
owner: account
})
const signer = isWebAuthnAccount(localOwner)
? parameters.safeWebAuthnSharedSignerAddress
: localOwner.address
if (!signer) {
throw new Error("no signer found")
}
let unPackedSignatures: readonly {
signer: Address
data: Hex
dynamic: boolean
}[] = []
if (existingSignatures) {
try {
const decoded = decodeAbiParameters(
[
{
components: [
{ type: "address", name: "signer" },
{ type: "bytes", name: "data" },
{ type: "bool", name: "dynamic" }
],
name: "signatures",
type: "tuple[]"
}
],
existingSignatures
)
unPackedSignatures = decoded[0]
} catch {
const decoded = decodeAbiParameters(
[
{
components: [
{ type: "address", name: "signer" },
{ type: "bytes", name: "data" }
],
name: "signatures",
type: "tuple[]"
}
],
existingSignatures
)
unPackedSignatures = decoded[0].map((sig) => ({
...sig,
dynamic: false
}))
}
}
const signatures: { signer: Address; data: Hex; dynamic: boolean }[] = [
...unPackedSignatures,
{
signer,
dynamic: isWebAuthnAccount(localOwner) || isDynamicOwner,
data: await (async () => {
if (isWebAuthnAccount(localOwner)) {
const safeHash = hashTypedData({
domain: {
chainId,
verifyingContract: safe4337ModuleAddress
},
types:
entryPoint.version === "0.6"
? EIP712_SAFE_OPERATION_TYPE_V06
: EIP712_SAFE_OPERATION_TYPE_V07,
primaryType: "SafeOp",
message: message
})
return getWebAuthnSignature({
owner: localOwner,
hash: safeHash
})
}
return localOwner.signTypedData({
domain: {
chainId,
verifyingContract: safe4337ModuleAddress
},
types:
entryPoint.version === "0.6"
? EIP712_SAFE_OPERATION_TYPE_V06
: EIP712_SAFE_OPERATION_TYPE_V07,
primaryType: "SafeOp",
message: message
})
})()
}
]
if (signatures.length !== owners.length) {
return encodeAbiParameters(
[
{
components: [
{ type: "address", name: "signer" },
{ type: "bytes", name: "data" },
{ type: "bool", name: "dynamic" }
],
name: "signatures",
type: "tuple[]"
}
],
[signatures]
)
}
return encodePacked(
["uint48", "uint48", "bytes"],
[validAfter, validUntil, concatSignatures(signatures)]
)
}