-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathtrigger.rs
More file actions
623 lines (547 loc) · 18.6 KB
/
trigger.rs
File metadata and controls
623 lines (547 loc) · 18.6 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
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
use graph::blockchain::MappingTriggerTrait;
use graph::blockchain::TriggerData;
use graph::data::subgraph::API_VERSION_0_0_2;
use graph::data::subgraph::API_VERSION_0_0_6;
use graph::data::subgraph::API_VERSION_0_0_7;
use graph::data_source::common::DeclaredCall;
use graph::prelude::ethabi::ethereum_types::H160;
use graph::prelude::ethabi::ethereum_types::H256;
use graph::prelude::ethabi::ethereum_types::U128;
use graph::prelude::ethabi::ethereum_types::U256;
use graph::prelude::ethabi::ethereum_types::U64;
use graph::prelude::ethabi::Address;
use graph::prelude::ethabi::LogParam;
use graph::prelude::web3::types::Block;
use graph::prelude::web3::types::Log;
use graph::prelude::web3::types::Transaction;
use graph::prelude::web3::types::TransactionReceipt;
use graph::prelude::BlockNumber;
use graph::prelude::BlockPtr;
use graph::prelude::{CheapClone, EthereumCall};
use graph::runtime::asc_new;
use graph::runtime::gas::GasCounter;
use graph::runtime::AscHeap;
use graph::runtime::AscPtr;
use graph::runtime::HostExportError;
use graph::semver::Version;
use graph_runtime_wasm::module::ToAscPtr;
use std::{cmp::Ordering, sync::Arc};
use crate::runtime::abi::AscEthereumBlock;
use crate::runtime::abi::AscEthereumBlock_0_0_6;
use crate::runtime::abi::AscEthereumCall;
use crate::runtime::abi::AscEthereumCall_0_0_3;
use crate::runtime::abi::AscEthereumEvent;
use crate::runtime::abi::AscEthereumEvent_0_0_7;
use crate::runtime::abi::AscEthereumTransaction_0_0_1;
use crate::runtime::abi::AscEthereumTransaction_0_0_2;
use crate::runtime::abi::AscEthereumTransaction_0_0_6;
// ETHDEP: This should be defined in only one place.
type LightEthereumBlock = Block<Transaction>;
static U256_DEFAULT: U256 = U256::zero();
pub enum MappingTrigger {
Log {
block: Arc<LightEthereumBlock>,
transaction: Arc<Transaction>,
log: Arc<Log>,
params: Vec<LogParam>,
receipt: Option<Arc<TransactionReceipt>>,
calls: Vec<DeclaredCall>,
},
Call {
block: Arc<LightEthereumBlock>,
transaction: Arc<Transaction>,
call: Arc<EthereumCall>,
inputs: Vec<LogParam>,
outputs: Vec<LogParam>,
},
Block {
block: Arc<LightEthereumBlock>,
},
}
impl MappingTriggerTrait for MappingTrigger {
fn error_context(&self) -> std::string::String {
let transaction_id = match self {
MappingTrigger::Log { log, .. } => log.transaction_hash,
MappingTrigger::Call { call, .. } => call.transaction_hash,
MappingTrigger::Block { .. } => None,
};
match transaction_id {
Some(tx_hash) => format!("transaction {:x}", tx_hash),
None => String::new(),
}
}
}
// Logging the block is too verbose, so this strips the block from the trigger for Debug.
impl std::fmt::Debug for MappingTrigger {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
#[derive(Debug)]
enum MappingTriggerWithoutBlock {
Log {
_transaction: Arc<Transaction>,
_log: Arc<Log>,
_params: Vec<LogParam>,
},
Call {
_transaction: Arc<Transaction>,
_call: Arc<EthereumCall>,
_inputs: Vec<LogParam>,
_outputs: Vec<LogParam>,
},
Block,
}
let trigger_without_block = match self {
MappingTrigger::Log {
block: _,
transaction,
log,
params,
receipt: _,
calls: _,
} => MappingTriggerWithoutBlock::Log {
_transaction: transaction.cheap_clone(),
_log: log.cheap_clone(),
_params: params.clone(),
},
MappingTrigger::Call {
block: _,
transaction,
call,
inputs,
outputs,
} => MappingTriggerWithoutBlock::Call {
_transaction: transaction.cheap_clone(),
_call: call.cheap_clone(),
_inputs: inputs.clone(),
_outputs: outputs.clone(),
},
MappingTrigger::Block { block: _ } => MappingTriggerWithoutBlock::Block,
};
write!(f, "{:?}", trigger_without_block)
}
}
impl ToAscPtr for MappingTrigger {
fn to_asc_ptr<H: AscHeap>(
self,
heap: &mut H,
gas: &GasCounter,
) -> Result<AscPtr<()>, HostExportError> {
Ok(match self {
MappingTrigger::Log {
block,
transaction,
log,
params,
receipt,
calls: _,
} => {
let api_version = heap.api_version();
let ethereum_event_data = EthereumEventData::new(
block.as_ref(),
transaction.as_ref(),
log.as_ref(),
¶ms,
);
if api_version >= &API_VERSION_0_0_7 {
asc_new::<
AscEthereumEvent_0_0_7<
AscEthereumTransaction_0_0_6,
AscEthereumBlock_0_0_6,
>,
_,
_,
>(heap, &(ethereum_event_data, receipt.as_deref()), gas)?
.erase()
} else if api_version >= &API_VERSION_0_0_6 {
asc_new::<
AscEthereumEvent<AscEthereumTransaction_0_0_6, AscEthereumBlock_0_0_6>,
_,
_,
>(heap, ðereum_event_data, gas)?
.erase()
} else if api_version >= &API_VERSION_0_0_2 {
asc_new::<
AscEthereumEvent<AscEthereumTransaction_0_0_2, AscEthereumBlock>,
_,
_,
>(heap, ðereum_event_data, gas)?
.erase()
} else {
asc_new::<
AscEthereumEvent<AscEthereumTransaction_0_0_1, AscEthereumBlock>,
_,
_,
>(heap, ðereum_event_data, gas)?
.erase()
}
}
MappingTrigger::Call {
block,
transaction,
call,
inputs,
outputs,
} => {
let call = EthereumCallData::new(&block, &transaction, &call, &inputs, &outputs);
if heap.api_version() >= &Version::new(0, 0, 6) {
asc_new::<
AscEthereumCall_0_0_3<AscEthereumTransaction_0_0_6, AscEthereumBlock_0_0_6>,
_,
_,
>(heap, &call, gas)?
.erase()
} else if heap.api_version() >= &Version::new(0, 0, 3) {
asc_new::<
AscEthereumCall_0_0_3<AscEthereumTransaction_0_0_2, AscEthereumBlock>,
_,
_,
>(heap, &call, gas)?
.erase()
} else {
asc_new::<AscEthereumCall, _, _>(heap, &call, gas)?.erase()
}
}
MappingTrigger::Block { block } => {
let block = EthereumBlockData::from(block.as_ref());
if heap.api_version() >= &Version::new(0, 0, 6) {
asc_new::<AscEthereumBlock_0_0_6, _, _>(heap, &block, gas)?.erase()
} else {
asc_new::<AscEthereumBlock, _, _>(heap, &block, gas)?.erase()
}
}
})
}
}
#[derive(Clone, Debug)]
pub enum LogRef {
FullLog(Arc<Log>, Option<Arc<TransactionReceipt>>),
LogPosition(usize, Arc<TransactionReceipt>),
}
impl LogRef {
pub fn log(&self) -> &Log {
match self {
LogRef::FullLog(log, _) => log.as_ref(),
LogRef::LogPosition(index, receipt) => receipt.logs.get(*index).unwrap(),
}
}
pub fn receipt(&self) -> Option<&Arc<TransactionReceipt>> {
match self {
LogRef::FullLog(_, receipt) => receipt.as_ref(),
LogRef::LogPosition(_, receipt) => Some(receipt),
}
}
pub fn log_index(&self) -> Option<U256> {
self.log().log_index
}
pub fn transaction_index(&self) -> Option<U64> {
self.log().transaction_index
}
fn transaction_hash(&self) -> Option<H256> {
self.log().transaction_hash
}
pub fn block_hash(&self) -> Option<H256> {
self.log().block_hash
}
pub fn block_number(&self) -> Option<U64> {
self.log().block_number
}
pub fn address(&self) -> &H160 {
&self.log().address
}
}
#[derive(Clone, Debug)]
pub enum EthereumTrigger {
Block(BlockPtr, EthereumBlockTriggerType),
Call(Arc<EthereumCall>),
Log(LogRef),
}
impl PartialEq for EthereumTrigger {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Block(a_ptr, a_kind), Self::Block(b_ptr, b_kind)) => {
a_ptr == b_ptr && a_kind == b_kind
}
(Self::Call(a), Self::Call(b)) => a == b,
(Self::Log(a), Self::Log(b)) => {
a.transaction_hash() == b.transaction_hash() && a.log_index() == b.log_index()
}
_ => false,
}
}
}
impl Eq for EthereumTrigger {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EthereumBlockTriggerType {
Start,
End,
WithCallTo(Address),
}
impl EthereumTrigger {
pub fn block_number(&self) -> BlockNumber {
match self {
EthereumTrigger::Block(block_ptr, _) => block_ptr.number,
EthereumTrigger::Call(call) => call.block_number,
EthereumTrigger::Log(log_ref) => {
i32::try_from(log_ref.block_number().unwrap().as_u64()).unwrap()
}
}
}
pub fn block_hash(&self) -> H256 {
match self {
EthereumTrigger::Block(block_ptr, _) => block_ptr.hash_as_h256(),
EthereumTrigger::Call(call) => call.block_hash,
EthereumTrigger::Log(log_ref) => log_ref.block_hash().unwrap(),
}
}
/// `None` means the trigger matches any address.
pub fn address(&self) -> Option<&Address> {
match self {
EthereumTrigger::Block(_, EthereumBlockTriggerType::WithCallTo(address)) => {
Some(address)
}
EthereumTrigger::Call(call) => Some(&call.to),
EthereumTrigger::Log(log_ref) => Some(&log_ref.address()),
// Unfiltered block triggers match any data source address.
EthereumTrigger::Block(_, EthereumBlockTriggerType::End) => None,
EthereumTrigger::Block(_, EthereumBlockTriggerType::Start) => None,
}
}
}
impl Ord for EthereumTrigger {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
// Block triggers with `EthereumBlockTriggerType::Start` always come
(Self::Block(_, EthereumBlockTriggerType::Start), _) => Ordering::Less,
(_, Self::Block(_, EthereumBlockTriggerType::Start)) => Ordering::Greater,
// Keep the order when comparing two block triggers
(Self::Block(..), Self::Block(..)) => Ordering::Equal,
// Block triggers with `EthereumBlockTriggerType::End` always come last
(Self::Block(..), _) => Ordering::Greater,
(_, Self::Block(..)) => Ordering::Less,
// Calls are ordered by their tx indexes
(Self::Call(a), Self::Call(b)) => a.transaction_index.cmp(&b.transaction_index),
// Events are ordered by their log index
(Self::Log(a), Self::Log(b)) => a.log_index().cmp(&b.log_index()),
// Calls vs. events are logged by their tx index;
// if they are from the same transaction, events come first
(Self::Call(a), Self::Log(b))
if a.transaction_index == b.transaction_index().unwrap().as_u64() =>
{
Ordering::Greater
}
(Self::Log(a), Self::Call(b))
if a.transaction_index().unwrap().as_u64() == b.transaction_index =>
{
Ordering::Less
}
(Self::Call(a), Self::Log(b)) => a
.transaction_index
.cmp(&b.transaction_index().unwrap().as_u64()),
(Self::Log(a), Self::Call(b)) => a
.transaction_index()
.unwrap()
.as_u64()
.cmp(&b.transaction_index),
}
}
}
impl PartialOrd for EthereumTrigger {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl TriggerData for EthereumTrigger {
fn error_context(&self) -> std::string::String {
let transaction_id = match self {
EthereumTrigger::Log(log) => log.transaction_hash(),
EthereumTrigger::Call(call) => call.transaction_hash,
EthereumTrigger::Block(..) => None,
};
match transaction_id {
Some(tx_hash) => format!(
"block #{} ({}), transaction {:x}",
self.block_number(),
self.block_hash(),
tx_hash
),
None => String::new(),
}
}
fn address_match(&self) -> Option<&[u8]> {
self.address().map(|address| address.as_bytes())
}
}
/// Ethereum block data.
#[derive(Clone, Debug)]
pub struct EthereumBlockData<'a> {
block: &'a Block<Transaction>,
}
impl<'a> From<&'a Block<Transaction>> for EthereumBlockData<'a> {
fn from(block: &'a Block<Transaction>) -> EthereumBlockData<'a> {
EthereumBlockData { block }
}
}
impl<'a> EthereumBlockData<'a> {
pub fn hash(&self) -> &H256 {
self.block.hash.as_ref().unwrap()
}
pub fn parent_hash(&self) -> &H256 {
&self.block.parent_hash
}
pub fn uncles_hash(&self) -> &H256 {
&self.block.uncles_hash
}
pub fn author(&self) -> &H160 {
&self.block.author
}
pub fn state_root(&self) -> &H256 {
&self.block.state_root
}
pub fn transactions_root(&self) -> &H256 {
&self.block.transactions_root
}
pub fn receipts_root(&self) -> &H256 {
&self.block.receipts_root
}
pub fn number(&self) -> U64 {
self.block.number.unwrap()
}
pub fn gas_used(&self) -> &U256 {
&self.block.gas_used
}
pub fn gas_limit(&self) -> &U256 {
&self.block.gas_limit
}
pub fn timestamp(&self) -> &U256 {
&self.block.timestamp
}
pub fn difficulty(&self) -> &U256 {
&self.block.difficulty
}
pub fn total_difficulty(&self) -> &U256 {
self.block
.total_difficulty
.as_ref()
.unwrap_or(&U256_DEFAULT)
}
pub fn size(&self) -> &Option<U256> {
&self.block.size
}
pub fn base_fee_per_gas(&self) -> &Option<U256> {
&self.block.base_fee_per_gas
}
}
/// Ethereum transaction data.
#[derive(Clone, Debug)]
pub struct EthereumTransactionData<'a> {
tx: &'a Transaction,
}
impl<'a> EthereumTransactionData<'a> {
// We don't implement `From` because it causes confusion with the `from`
// accessor method
fn new(tx: &'a Transaction) -> EthereumTransactionData<'a> {
EthereumTransactionData { tx }
}
pub fn hash(&self) -> &H256 {
&self.tx.hash
}
pub fn index(&self) -> U128 {
self.tx.transaction_index.unwrap().as_u64().into()
}
pub fn from(&self) -> &H160 {
// unwrap: this is always `Some` for txns that have been mined
// (see https://github.com/tomusdrw/rust-web3/pull/407)
self.tx.from.as_ref().unwrap()
}
pub fn to(&self) -> &Option<H160> {
&self.tx.to
}
pub fn value(&self) -> &U256 {
&self.tx.value
}
pub fn gas_limit(&self) -> &U256 {
&self.tx.gas
}
pub fn gas_price(&self) -> &U256 {
// EIP-1559 made this optional.
self.tx.gas_price.as_ref().unwrap_or(&U256_DEFAULT)
}
pub fn input(&self) -> &[u8] {
&self.tx.input.0
}
pub fn nonce(&self) -> &U256 {
&self.tx.nonce
}
}
/// An Ethereum event logged from a specific contract address and block.
#[derive(Debug, Clone)]
pub struct EthereumEventData<'a> {
pub block: EthereumBlockData<'a>,
pub transaction: EthereumTransactionData<'a>,
pub params: &'a [LogParam],
log: &'a Log,
}
impl<'a> EthereumEventData<'a> {
pub fn new(
block: &'a Block<Transaction>,
tx: &'a Transaction,
log: &'a Log,
params: &'a [LogParam],
) -> Self {
EthereumEventData {
block: EthereumBlockData::from(block),
transaction: EthereumTransactionData::new(tx),
log,
params,
}
}
pub fn address(&self) -> &Address {
&self.log.address
}
pub fn log_index(&self) -> &U256 {
self.log.log_index.as_ref().unwrap_or(&U256_DEFAULT)
}
pub fn transaction_log_index(&self) -> &U256 {
// We purposely use the `log_index` here. Geth does not support
// `transaction_log_index`, and subgraphs that use it only care that
// it identifies the log, the specific value is not important. Still
// this will change the output of subgraphs that use this field.
//
// This was initially changed in commit b95c6953
self.log.log_index.as_ref().unwrap_or(&U256_DEFAULT)
}
pub fn log_type(&self) -> &Option<String> {
&self.log.log_type
}
}
/// An Ethereum call executed within a transaction within a block to a contract address.
#[derive(Debug, Clone)]
pub struct EthereumCallData<'a> {
pub block: EthereumBlockData<'a>,
pub transaction: EthereumTransactionData<'a>,
pub inputs: &'a [LogParam],
pub outputs: &'a [LogParam],
call: &'a EthereumCall,
}
impl<'a> EthereumCallData<'a> {
fn new(
block: &'a Block<Transaction>,
transaction: &'a Transaction,
call: &'a EthereumCall,
inputs: &'a [LogParam],
outputs: &'a [LogParam],
) -> EthereumCallData<'a> {
EthereumCallData {
block: EthereumBlockData::from(block),
transaction: EthereumTransactionData::new(transaction),
inputs,
outputs,
call,
}
}
pub fn from(&self) -> &Address {
&self.call.from
}
pub fn to(&self) -> &Address {
&self.call.to
}
}