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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
use super::{
super::NotPreparedError, Account, AccountError, ConnectedAccount, ExecutionV3,
PreparedExecutionV3, RawExecutionV3,
};
use crate::ExecutionEncoder;
use starknet_core::types::{
BroadcastedInvokeTransactionV3, BroadcastedTransaction, Call, DataAvailabilityMode,
FeeEstimate, Felt, InvokeTransactionResult, ResourceBounds, ResourceBoundsMapping,
SimulatedTransaction, SimulationFlag, SimulationFlagForEstimateFee,
};
use starknet_crypto::PoseidonHasher;
use starknet_providers::Provider;
use starknet_signers::SignerInteractivityContext;
/// Cairo string for "invoke"
const PREFIX_INVOKE: Felt = Felt::from_raw([
513398556346534256,
18446744073709551615,
18446744073709551615,
18443034532770911073,
]);
/// 2 ^ 128 + 3
const QUERY_VERSION_THREE: Felt = Felt::from_raw([
576460752142432688,
18446744073709551584,
17407,
18446744073700081569,
]);
impl<'a, A> ExecutionV3<'a, A> {
/// Constructs a new [`ExecutionV3`].
///
/// Users would typically use [`execute_v3`](fn.execute_v3) on an [`Account`] instead of
/// directly calling this method.
pub const fn new(calls: Vec<Call>, account: &'a A) -> Self {
Self {
account,
calls,
nonce: None,
l1_gas: None,
l1_gas_price: None,
l2_gas: None,
l2_gas_price: None,
l1_data_gas: None,
l1_data_gas_price: None,
gas_estimate_multiplier: 1.5,
gas_price_estimate_multiplier: 1.5,
tip: None,
}
}
/// Returns a new [`ExecutionV3`] with the `nonce`.
pub fn nonce(self, nonce: Felt) -> Self {
Self {
nonce: Some(nonce),
..self
}
}
/// Returns a new [`ExecutionV3`] with the `l1_gas`.
pub fn l1_gas(self, l1_gas: u64) -> Self {
Self {
l1_gas: Some(l1_gas),
..self
}
}
/// Returns a new [`ExecutionV3`] with the `l1_gas_price`.
pub fn l1_gas_price(self, l1_gas_price: u128) -> Self {
Self {
l1_gas_price: Some(l1_gas_price),
..self
}
}
/// Returns a new [`ExecutionV3`] with the `l2_gas`.
pub fn l2_gas(self, l2_gas: u64) -> Self {
Self {
l2_gas: Some(l2_gas),
..self
}
}
/// Returns a new [`ExecutionV3`] with the `l2_gas_price`.
pub fn l2_gas_price(self, l2_gas_price: u128) -> Self {
Self {
l2_gas_price: Some(l2_gas_price),
..self
}
}
/// Returns a new [`ExecutionV3`] with the `l1_data_gas`.
pub fn l1_data_gas(self, l1_data_gas: u64) -> Self {
Self {
l1_data_gas: Some(l1_data_gas),
..self
}
}
/// Returns a new [`ExecutionV3`] with the `l1_data_gas_price`.
pub fn l1_data_gas_price(self, l1_data_gas_price: u128) -> Self {
Self {
l1_data_gas_price: Some(l1_data_gas_price),
..self
}
}
/// Returns a new [`ExecutionV3`] with the gas amount estimate multiplier. The multiplier is
/// used when the gas amount is not manually specified and must be fetched from a [`Provider`]
/// instead.
pub fn gas_estimate_multiplier(self, gas_estimate_multiplier: f64) -> Self {
Self {
gas_estimate_multiplier,
..self
}
}
/// Returns a new [`ExecutionV3`] with the gas price estimate multiplier. The multiplier is
/// used when the gas price is not manually specified and must be fetched from a [`Provider`]
/// instead.
pub fn gas_price_estimate_multiplier(self, gas_price_estimate_multiplier: f64) -> Self {
Self {
gas_price_estimate_multiplier,
..self
}
}
/// Returns a new [`ExecutionV3`] with the `tip`.
pub fn tip(self, tip: u64) -> Self {
Self {
tip: Some(tip),
..self
}
}
/// Calling this function after manually specifying `nonce`, `gas` and `gas_price` turns
/// [`ExecutionV3`] into [`PreparedExecutionV3`]. Returns `Err` if any field is `None`.
pub fn prepared(self) -> Result<PreparedExecutionV3<'a, A>, NotPreparedError> {
let nonce = self.nonce.ok_or(NotPreparedError)?;
let l1_gas = self.l1_gas.ok_or(NotPreparedError)?;
let l1_gas_price = self.l1_gas_price.ok_or(NotPreparedError)?;
let l2_gas = self.l2_gas.ok_or(NotPreparedError)?;
let l2_gas_price = self.l2_gas_price.ok_or(NotPreparedError)?;
let l1_data_gas = self.l1_data_gas.ok_or(NotPreparedError)?;
let l1_data_gas_price = self.l1_data_gas_price.ok_or(NotPreparedError)?;
let tip = self.tip.ok_or(NotPreparedError)?;
Ok(PreparedExecutionV3 {
account: self.account,
inner: RawExecutionV3 {
calls: self.calls,
nonce,
l1_gas,
l1_gas_price,
l2_gas,
l2_gas_price,
l1_data_gas,
l1_data_gas_price,
tip,
},
})
}
}
impl<'a, A> ExecutionV3<'a, A>
where
A: ConnectedAccount + Sync,
{
/// Estimates transaction fees from a [`Provider`].
pub async fn estimate_fee(&self) -> Result<FeeEstimate, AccountError<A::SignError>> {
// Resolves nonce
let nonce = match self.nonce {
Some(value) => value,
None => self
.account
.get_nonce()
.await
.map_err(AccountError::Provider)?,
};
self.estimate_fee_with_nonce(nonce).await
}
/// Simulates the transaction from a [`Provider`]. Transaction validation and fee transfer can
/// be skipped.
pub async fn simulate(
&self,
skip_validate: bool,
skip_fee_charge: bool,
) -> Result<SimulatedTransaction, AccountError<A::SignError>> {
// Resolves nonce
let nonce = match self.nonce {
Some(value) => value,
None => self
.account
.get_nonce()
.await
.map_err(AccountError::Provider)?,
};
self.simulate_with_nonce(nonce, skip_validate, skip_fee_charge)
.await
}
/// Signs and broadcasts the transaction to the network.
pub async fn send(&self) -> Result<InvokeTransactionResult, AccountError<A::SignError>> {
self.prepare().await?.send().await
}
async fn prepare(&self) -> Result<PreparedExecutionV3<'a, A>, AccountError<A::SignError>> {
// Resolves nonce
let nonce = match self.nonce {
Some(value) => value,
None => self
.account
.get_nonce()
.await
.map_err(AccountError::Provider)?,
};
// Resolves fee settings
let (
l1_gas,
l1_gas_price,
l2_gas,
l2_gas_price,
l1_data_gas,
l1_data_gas_price,
full_block,
) = match (
self.l1_gas,
self.l1_gas_price,
self.l2_gas,
self.l2_gas_price,
self.l1_data_gas,
self.l1_data_gas_price,
) {
(
Some(l1_gas),
Some(l1_gas_price),
Some(l2_gas),
Some(l2_gas_price),
Some(l1_data_gas),
Some(l1_data_gas_price),
) => (
l1_gas,
l1_gas_price,
l2_gas,
l2_gas_price,
l1_data_gas,
l1_data_gas_price,
None,
),
(Some(l1_gas), _, Some(l2_gas), _, Some(l1_data_gas), _) => {
// When all `gas` fields are specified, we only need the gas prices in FRI. By
// specifying all gas values, the user might be trying to avoid a full fee
// estimation (e.g. flaky dependencies), so it's inappropriate to call
// `estimate_fee` here.
let (block_l1_gas_price, block_l2_gas_price, block_l1_data_gas_price, full_block) =
if self.tip.is_some() {
// No need to estimate tip. Just fetch the lightest-weight block we can get.
let block = self
.account
.provider()
.get_block_with_tx_hashes(self.account.block_id())
.await
.map_err(AccountError::Provider)?;
(
block.l1_gas_price().price_in_fri,
block.l2_gas_price().price_in_fri,
block.l1_data_gas_price().price_in_fri,
None,
)
} else {
// We only need th block header here but still fetching the full block to be used
// for tip estimation below.
let block = self
.account
.provider()
.get_block_with_txs(self.account.block_id())
.await
.map_err(AccountError::Provider)?;
(
block.l1_gas_price().price_in_fri,
block.l2_gas_price().price_in_fri,
block.l1_data_gas_price().price_in_fri,
Some(block),
)
};
let adjusted_l1_gas_price =
((TryInto::<u64>::try_into(block_l1_gas_price)
.map_err(|_| AccountError::FeeOutOfRange)? as f64)
* self.gas_price_estimate_multiplier) as u128;
let adjusted_l2_gas_price =
((TryInto::<u64>::try_into(block_l2_gas_price)
.map_err(|_| AccountError::FeeOutOfRange)? as f64)
* self.gas_price_estimate_multiplier) as u128;
let adjusted_l1_data_gas_price =
((TryInto::<u64>::try_into(block_l1_data_gas_price)
.map_err(|_| AccountError::FeeOutOfRange)? as f64)
* self.gas_price_estimate_multiplier) as u128;
(
l1_gas,
adjusted_l1_gas_price,
l2_gas,
adjusted_l2_gas_price,
l1_data_gas,
adjusted_l1_data_gas_price,
full_block,
)
}
// We have to perform fee estimation as long as gas is not specified
_ => {
let fee_estimate = self.estimate_fee_with_nonce(nonce).await?;
(
((fee_estimate.l1_gas_consumed as f64) * self.gas_estimate_multiplier) as u64,
((TryInto::<u64>::try_into(fee_estimate.l1_gas_price)
.map_err(|_| AccountError::FeeOutOfRange)? as f64)
* self.gas_price_estimate_multiplier) as u128,
((fee_estimate.l2_gas_consumed as f64) * self.gas_estimate_multiplier) as u64,
((TryInto::<u64>::try_into(fee_estimate.l2_gas_price)
.map_err(|_| AccountError::FeeOutOfRange)? as f64)
* self.gas_price_estimate_multiplier) as u128,
((fee_estimate.l1_data_gas_consumed as f64) * self.gas_estimate_multiplier)
as u64,
((TryInto::<u64>::try_into(fee_estimate.l1_data_gas_price)
.map_err(|_| AccountError::FeeOutOfRange)? as f64)
* self.gas_price_estimate_multiplier) as u128,
None,
)
}
};
let tip = match self.tip {
Some(tip) => tip,
None => {
// Need to estimate tip from median. Maybe a full block has already been fetched?
let block = match full_block {
Some(block) => block,
None => self
.account
.provider()
.get_block_with_txs(self.account.block_id())
.await
.map_err(AccountError::Provider)?,
};
block.median_tip()
}
};
Ok(PreparedExecutionV3 {
account: self.account,
inner: RawExecutionV3 {
calls: self.calls.clone(),
nonce,
l1_gas,
l1_gas_price,
l2_gas,
l2_gas_price,
l1_data_gas,
l1_data_gas_price,
tip,
},
})
}
async fn estimate_fee_with_nonce(
&self,
nonce: Felt,
) -> Result<FeeEstimate, AccountError<A::SignError>> {
let skip_signature = self
.account
.is_signer_interactive(SignerInteractivityContext::Execution { calls: &self.calls });
let prepared = PreparedExecutionV3 {
account: self.account,
inner: RawExecutionV3 {
calls: self.calls.clone(),
nonce,
l1_gas: 0,
l1_gas_price: 0,
l2_gas: 0,
l2_gas_price: 0,
l1_data_gas: 0,
l1_data_gas_price: 0,
tip: 0,
},
};
let invoke = prepared
.get_invoke_request(true, skip_signature)
.await
.map_err(AccountError::Signing)?;
self.account
.provider()
.estimate_fee_single(
BroadcastedTransaction::Invoke(invoke),
if skip_signature {
// Validation would fail since real signature was not requested
vec![SimulationFlagForEstimateFee::SkipValidate]
} else {
// With the correct signature in place, run validation for accurate results
vec![]
},
self.account.block_id(),
)
.await
.map_err(AccountError::Provider)
}
async fn simulate_with_nonce(
&self,
nonce: Felt,
skip_validate: bool,
skip_fee_charge: bool,
) -> Result<SimulatedTransaction, AccountError<A::SignError>> {
let skip_signature = if self
.account
.is_signer_interactive(SignerInteractivityContext::Execution { calls: &self.calls })
{
// If signer is interactive, we would try to minimize signing requests. However, if the
// caller has decided to not skip validation, it's best we still request a real
// signature, as otherwise the simulation would most likely fail.
skip_validate
} else {
// Signing with non-interactive signers is cheap so always request signatures.
false
};
let prepared = PreparedExecutionV3 {
account: self.account,
inner: RawExecutionV3 {
calls: self.calls.clone(),
nonce,
l1_gas: self.l1_gas.unwrap_or_default(),
l1_gas_price: self.l1_gas_price.unwrap_or_default(),
l2_gas: self.l2_gas.unwrap_or_default(),
l2_gas_price: self.l2_gas_price.unwrap_or_default(),
l1_data_gas: self.l1_data_gas.unwrap_or_default(),
l1_data_gas_price: self.l1_data_gas_price.unwrap_or_default(),
tip: self.tip.unwrap_or_default(),
},
};
let invoke = prepared
.get_invoke_request(true, skip_signature)
.await
.map_err(AccountError::Signing)?;
let mut flags = vec![];
if skip_validate {
flags.push(SimulationFlag::SkipValidate);
}
if skip_fee_charge {
flags.push(SimulationFlag::SkipFeeCharge);
}
self.account
.provider()
.simulate_transaction(
self.account.block_id(),
BroadcastedTransaction::Invoke(invoke),
&flags,
)
.await
.map_err(AccountError::Provider)
}
}
impl RawExecutionV3 {
/// Calculates transaction hash given `chain_id`, `address`, `query_only`, and `encoder`.
pub fn transaction_hash<E>(
&self,
chain_id: Felt,
address: Felt,
query_only: bool,
encoder: E,
) -> Felt
where
E: ExecutionEncoder,
{
let mut hasher = PoseidonHasher::new();
hasher.update(PREFIX_INVOKE);
hasher.update(if query_only {
QUERY_VERSION_THREE
} else {
Felt::THREE
});
hasher.update(address);
hasher.update({
let mut fee_hasher = PoseidonHasher::new();
fee_hasher.update(self.tip.into());
let mut resource_buffer = [
0, 0, b'L', b'1', b'_', b'G', b'A', b'S', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
resource_buffer[8..(8 + 8)].copy_from_slice(&self.l1_gas.to_be_bytes());
resource_buffer[(8 + 8)..].copy_from_slice(&self.l1_gas_price.to_be_bytes());
fee_hasher.update(Felt::from_bytes_be(&resource_buffer));
let mut resource_buffer = [
0, 0, b'L', b'2', b'_', b'G', b'A', b'S', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
resource_buffer[8..(8 + 8)].copy_from_slice(&self.l2_gas.to_be_bytes());
resource_buffer[(8 + 8)..].copy_from_slice(&self.l2_gas_price.to_be_bytes());
fee_hasher.update(Felt::from_bytes_be(&resource_buffer));
let mut resource_buffer = [
0, b'L', b'1', b'_', b'D', b'A', b'T', b'A', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
resource_buffer[8..(8 + 8)].copy_from_slice(&self.l1_data_gas.to_be_bytes());
resource_buffer[(8 + 8)..].copy_from_slice(&self.l1_data_gas_price.to_be_bytes());
fee_hasher.update(Felt::from_bytes_be(&resource_buffer));
fee_hasher.finalize()
});
// Hard-coded empty `paymaster_data`
hasher.update(PoseidonHasher::new().finalize());
hasher.update(chain_id);
hasher.update(self.nonce);
// Hard-coded L1 DA mode for nonce and fee
hasher.update(Felt::ZERO);
// Hard-coded empty `account_deployment_data`
hasher.update(PoseidonHasher::new().finalize());
hasher.update({
let mut calldata_hasher = PoseidonHasher::new();
encoder
.encode_calls(&self.calls)
.into_iter()
.for_each(|element| calldata_hasher.update(element));
calldata_hasher.finalize()
});
hasher.finalize()
}
/// Gets a reference to the list of contract calls included in the execution.
pub fn calls(&self) -> &[Call] {
&self.calls
}
/// Gets the `nonce` of the execution request.
pub const fn nonce(&self) -> Felt {
self.nonce
}
/// Gets the `l1_gas` of the execution request.
pub const fn l1_gas(&self) -> u64 {
self.l1_gas
}
/// Gets the `l1_gas_price` of the execution request.
pub const fn l1_gas_price(&self) -> u128 {
self.l1_gas_price
}
/// Gets the `l2_gas` of the execution request.
pub const fn l2_gas(&self) -> u64 {
self.l2_gas
}
/// Gets the `l2_gas_price` of the execution request.
pub const fn l2_gas_price(&self) -> u128 {
self.l2_gas_price
}
/// Gets the `l1_data_gas` of the execution request.
pub const fn l1_data_gas(&self) -> u64 {
self.l1_data_gas
}
/// Gets the `l1_data_gas_price` of the execution request.
pub const fn l1_data_gas_price(&self) -> u128 {
self.l1_data_gas_price
}
/// Gets the `tip` of the execution request.
pub const fn tip(&self) -> u64 {
self.tip
}
}
impl<A> PreparedExecutionV3<'_, A>
where
A: Account,
{
/// Locally calculates the hash of the transaction to be sent from this execution given the
/// parameters.
pub fn transaction_hash(&self, query_only: bool) -> Felt {
self.inner.transaction_hash(
self.account.chain_id(),
self.account.address(),
query_only,
self.account,
)
}
}
impl<A> PreparedExecutionV3<'_, A>
where
A: ConnectedAccount,
{
/// Signs and broadcasts the transaction to the network.
pub async fn send(&self) -> Result<InvokeTransactionResult, AccountError<A::SignError>> {
let tx_request = self
.get_invoke_request(false, false)
.await
.map_err(AccountError::Signing)?;
self.account
.provider()
.add_invoke_transaction(tx_request)
.await
.map_err(AccountError::Provider)
}
// The `simulate` function is temporarily removed until it's supported in [Provider]
// TODO: add `simulate` back once transaction simulation in supported
/// Get the broadcasted invoke transaction request.
pub async fn get_invoke_request(
&self,
query_only: bool,
skip_signature: bool,
) -> Result<BroadcastedInvokeTransactionV3, A::SignError> {
Ok(BroadcastedInvokeTransactionV3 {
sender_address: self.account.address(),
calldata: self.account.encode_calls(&self.inner.calls),
signature: if skip_signature {
vec![]
} else {
self.account
.sign_execution_v3(&self.inner, query_only)
.await?
},
nonce: self.inner.nonce,
resource_bounds: ResourceBoundsMapping {
l1_gas: ResourceBounds {
max_amount: self.inner.l1_gas,
max_price_per_unit: self.inner.l1_gas_price,
},
l1_data_gas: ResourceBounds {
max_amount: self.inner.l1_data_gas,
max_price_per_unit: self.inner.l1_data_gas_price,
},
l2_gas: ResourceBounds {
max_amount: self.inner.l2_gas,
max_price_per_unit: self.inner.l2_gas_price,
},
},
tip: self.inner.tip,
// Hard-coded empty `paymaster_data`
paymaster_data: vec![],
// Hard-coded empty `account_deployment_data`
account_deployment_data: vec![],
// Hard-coded L1 DA mode for nonce and fee
nonce_data_availability_mode: DataAvailabilityMode::L1,
fee_data_availability_mode: DataAvailabilityMode::L1,
is_query: query_only,
})
}
}