-
-
Notifications
You must be signed in to change notification settings - Fork 944
/
Copy pathprepareTransactionRequest.ts
423 lines (399 loc) · 12.9 KB
/
prepareTransactionRequest.ts
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
import type { Address } from 'abitype'
import type { Account } from '../../accounts/types.js'
import {
type ParseAccountErrorType,
parseAccount,
} from '../../accounts/utils/parseAccount.js'
import {
type EstimateFeesPerGasErrorType,
internal_estimateFeesPerGas,
} from '../../actions/public/estimateFeesPerGas.js'
import {
type EstimateGasErrorType,
type EstimateGasParameters,
estimateGas,
} from '../../actions/public/estimateGas.js'
import {
type GetBlockErrorType,
getBlock as getBlock_,
} from '../../actions/public/getBlock.js'
import {
type GetTransactionCountErrorType,
getTransactionCount,
} from '../../actions/public/getTransactionCount.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import type { AccountNotFoundErrorType } from '../../errors/account.js'
import {
Eip1559FeesNotSupportedError,
MaxFeePerGasTooLowError,
} from '../../errors/fee.js'
import type { DeriveAccount, GetAccountParameter } from '../../types/account.js'
import type { Block } from '../../types/block.js'
import type { Chain, DeriveChain } from '../../types/chain.js'
import type { GetChainParameter } from '../../types/chain.js'
import type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'
import type {
TransactionRequest,
TransactionRequestEIP1559,
TransactionRequestEIP2930,
TransactionRequestEIP4844,
TransactionRequestEIP7702,
TransactionRequestLegacy,
TransactionSerializable,
} from '../../types/transaction.js'
import type {
ExactPartial,
IsNever,
Prettify,
UnionOmit,
UnionRequiredBy,
} from '../../types/utils.js'
import { blobsToCommitments } from '../../utils/blob/blobsToCommitments.js'
import { blobsToProofs } from '../../utils/blob/blobsToProofs.js'
import { commitmentsToVersionedHashes } from '../../utils/blob/commitmentsToVersionedHashes.js'
import { toBlobSidecars } from '../../utils/blob/toBlobSidecars.js'
import type { FormattedTransactionRequest } from '../../utils/formatters/transactionRequest.js'
import { getAction } from '../../utils/getAction.js'
import type { NonceManager } from '../../utils/nonceManager.js'
import {
type AssertRequestErrorType,
type AssertRequestParameters,
assertRequest,
} from '../../utils/transaction/assertRequest.js'
import {
type GetTransactionType,
getTransactionType,
} from '../../utils/transaction/getTransactionType.js'
import { getChainId as getChainId_ } from '../public/getChainId.js'
export const defaultParameters = [
'blobVersionedHashes',
'chainId',
'fees',
'gas',
'nonce',
'type',
] as const
export type PrepareTransactionRequestParameterType =
| 'blobVersionedHashes'
| 'chainId'
| 'fees'
| 'gas'
| 'nonce'
| 'sidecars'
| 'type'
type ParameterTypeToParameters<
parameterType extends PrepareTransactionRequestParameterType,
> = parameterType extends 'fees'
? 'maxFeePerGas' | 'maxPriorityFeePerGas' | 'gasPrice'
: parameterType
export type PrepareTransactionRequestRequest<
chain extends Chain | undefined = Chain | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
///
_derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,
> = UnionOmit<FormattedTransactionRequest<_derivedChain>, 'from'> &
GetTransactionRequestKzgParameter & {
/**
* Nonce manager to use for the transaction request.
*/
nonceManager?: NonceManager | undefined
/**
* Parameters to prepare for the transaction request.
*
* @default ['blobVersionedHashes', 'chainId', 'fees', 'gas', 'nonce', 'type']
*/
parameters?: readonly PrepareTransactionRequestParameterType[] | undefined
}
export type PrepareTransactionRequestParameters<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
accountOverride extends Account | Address | undefined =
| Account
| Address
| undefined,
request extends PrepareTransactionRequestRequest<
chain,
chainOverride
> = PrepareTransactionRequestRequest<chain, chainOverride>,
> = request &
GetAccountParameter<account, accountOverride, false, true> &
GetChainParameter<chain, chainOverride> &
GetTransactionRequestKzgParameter<request> & { chainId?: number | undefined }
export type PrepareTransactionRequestReturnType<
chain extends Chain | undefined = Chain | undefined,
account extends Account | undefined = Account | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
accountOverride extends Account | Address | undefined =
| Account
| Address
| undefined,
request extends PrepareTransactionRequestRequest<
chain,
chainOverride
> = PrepareTransactionRequestRequest<chain, chainOverride>,
///
_derivedAccount extends Account | Address | undefined = DeriveAccount<
account,
accountOverride
>,
_derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,
_transactionType = request['type'] extends string | undefined
? request['type']
: GetTransactionType<request> extends 'legacy'
? unknown
: GetTransactionType<request>,
_transactionRequest extends TransactionRequest =
| (_transactionType extends 'legacy' ? TransactionRequestLegacy : never)
| (_transactionType extends 'eip1559' ? TransactionRequestEIP1559 : never)
| (_transactionType extends 'eip2930' ? TransactionRequestEIP2930 : never)
| (_transactionType extends 'eip4844' ? TransactionRequestEIP4844 : never)
| (_transactionType extends 'eip7702' ? TransactionRequestEIP7702 : never),
> = Prettify<
UnionRequiredBy<
Extract<
UnionOmit<FormattedTransactionRequest<_derivedChain>, 'from'> &
(_derivedChain extends Chain
? { chain: _derivedChain }
: { chain?: undefined }) &
(_derivedAccount extends Account
? { account: _derivedAccount; from: Address }
: { account?: undefined; from?: undefined }),
IsNever<_transactionRequest> extends true
? unknown
: ExactPartial<_transactionRequest>
> & { chainId?: number | undefined },
ParameterTypeToParameters<
request['parameters'] extends readonly PrepareTransactionRequestParameterType[]
? request['parameters'][number]
: (typeof defaultParameters)[number]
>
> &
(unknown extends request['kzg'] ? {} : Pick<request, 'kzg'>)
>
export type PrepareTransactionRequestErrorType =
| AccountNotFoundErrorType
| AssertRequestErrorType
| ParseAccountErrorType
| GetBlockErrorType
| GetTransactionCountErrorType
| EstimateGasErrorType
| EstimateFeesPerGasErrorType
/**
* Prepares a transaction request for signing.
*
* - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest
*
* @param args - {@link PrepareTransactionRequestParameters}
* @returns The transaction request. {@link PrepareTransactionRequestReturnType}
*
* @example
* import { createWalletClient, custom } from 'viem'
* import { mainnet } from 'viem/chains'
* import { prepareTransactionRequest } from 'viem/actions'
*
* const client = createWalletClient({
* chain: mainnet,
* transport: custom(window.ethereum),
* })
* const request = await prepareTransactionRequest(client, {
* account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
* to: '0x0000000000000000000000000000000000000000',
* value: 1n,
* })
*
* @example
* // Account Hoisting
* import { createWalletClient, http } from 'viem'
* import { privateKeyToAccount } from 'viem/accounts'
* import { mainnet } from 'viem/chains'
* import { prepareTransactionRequest } from 'viem/actions'
*
* const client = createWalletClient({
* account: privateKeyToAccount('0x…'),
* chain: mainnet,
* transport: custom(window.ethereum),
* })
* const request = await prepareTransactionRequest(client, {
* to: '0x0000000000000000000000000000000000000000',
* value: 1n,
* })
*/
export async function prepareTransactionRequest<
chain extends Chain | undefined,
account extends Account | undefined,
const request extends PrepareTransactionRequestRequest<chain, chainOverride>,
accountOverride extends Account | Address | undefined = undefined,
chainOverride extends Chain | undefined = undefined,
>(
client: Client<Transport, chain, account>,
args: PrepareTransactionRequestParameters<
chain,
account,
chainOverride,
accountOverride,
request
>,
): Promise<
PrepareTransactionRequestReturnType<
chain,
account,
chainOverride,
accountOverride,
request
>
> {
const {
account: account_ = client.account,
blobs,
chain,
gas,
kzg,
nonce,
nonceManager,
parameters = defaultParameters,
type,
} = args
const account = account_ ? parseAccount(account_) : account_
const request = { ...args, ...(account ? { from: account?.address } : {}) }
let block: Block | undefined
async function getBlock(): Promise<Block> {
if (block) return block
block = await getAction(
client,
getBlock_,
'getBlock',
)({ blockTag: 'latest' })
return block
}
let chainId: number | undefined
async function getChainId(): Promise<number> {
if (chainId) return chainId
if (chain) return chain.id
if (typeof args.chainId !== 'undefined') return args.chainId
const chainId_ = await getAction(client, getChainId_, 'getChainId')({})
chainId = chainId_
return chainId
}
if (
(parameters.includes('blobVersionedHashes') ||
parameters.includes('sidecars')) &&
blobs &&
kzg
) {
const commitments = blobsToCommitments({ blobs, kzg })
if (parameters.includes('blobVersionedHashes')) {
const versionedHashes = commitmentsToVersionedHashes({
commitments,
to: 'hex',
})
request.blobVersionedHashes = versionedHashes
}
if (parameters.includes('sidecars')) {
const proofs = blobsToProofs({ blobs, commitments, kzg })
const sidecars = toBlobSidecars({
blobs,
commitments,
proofs,
to: 'hex',
})
request.sidecars = sidecars
}
}
if (parameters.includes('chainId')) request.chainId = await getChainId()
if (
(parameters.includes('fees') || parameters.includes('type')) &&
typeof type === 'undefined'
) {
try {
request.type = getTransactionType(
request as TransactionSerializable,
) as any
} catch {
// infer type from block
const block = await getBlock()
request.type =
typeof block?.baseFeePerGas === 'bigint' ? 'eip1559' : 'legacy'
}
}
if (parameters.includes('fees')) {
// TODO(4844): derive blob base fees once https://github.com/ethereum/execution-apis/pull/486 is merged.
if (request.type !== 'legacy' && request.type !== 'eip2930') {
// EIP-1559 fees
if (
typeof request.maxFeePerGas === 'undefined' ||
typeof request.maxPriorityFeePerGas === 'undefined'
) {
const block = await getBlock()
const { maxFeePerGas, maxPriorityFeePerGas } =
await internal_estimateFeesPerGas(client, {
block: block as Block,
chain,
request: request as PrepareTransactionRequestParameters,
})
if (
typeof args.maxPriorityFeePerGas === 'undefined' &&
args.maxFeePerGas &&
args.maxFeePerGas < maxPriorityFeePerGas
)
throw new MaxFeePerGasTooLowError({
maxPriorityFeePerGas,
})
request.maxPriorityFeePerGas = maxPriorityFeePerGas
request.maxFeePerGas = maxFeePerGas
}
} else {
// Legacy fees
if (
typeof args.maxFeePerGas !== 'undefined' ||
typeof args.maxPriorityFeePerGas !== 'undefined'
)
throw new Eip1559FeesNotSupportedError()
const block = await getBlock()
const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(
client,
{
block: block as Block,
chain,
request: request as PrepareTransactionRequestParameters,
type: 'legacy',
},
)
request.gasPrice = gasPrice_
}
}
if (parameters.includes('gas') && typeof gas === 'undefined')
request.gas = await getAction(
client,
estimateGas,
'estimateGas',
)({
...request,
account: account
? { address: account.address, type: 'json-rpc' }
: account,
} as EstimateGasParameters)
if (parameters.includes('nonce') && typeof nonce === 'undefined' && account) {
if (nonceManager) {
const chainId = await getChainId()
request.nonce = await nonceManager.consume({
address: account.address,
chainId,
client,
})
} else {
request.nonce = await getAction(
client,
getTransactionCount,
'getTransactionCount',
)({
address: account.address,
blockTag: 'pending',
})
}
}
assertRequest(request as AssertRequestParameters)
delete request.parameters
return request as any
}