-
Notifications
You must be signed in to change notification settings - Fork 991
/
runtime_adapter.rs
213 lines (192 loc) · 7.85 KB
/
runtime_adapter.rs
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
use std::{sync::Arc, time::Instant};
use crate::data_source::MappingABI;
use crate::{
capabilities::NodeCapabilities, network::EthereumNetworkAdapters, Chain, DataSource,
EthereumAdapter, EthereumAdapterTrait, EthereumContractCall, EthereumContractCallError,
};
use anyhow::{Context, Error};
use blockchain::HostFn;
use graph::runtime::{AscIndexId, IndexForAscTypeId};
use graph::{
blockchain::{self, BlockPtr, HostFnCtx},
cheap_clone::CheapClone,
prelude::{
ethabi::{self, Address, Token},
EthereumCallCache, Future01CompatExt,
},
runtime::{asc_get, asc_new, AscPtr, HostExportError},
semver::Version,
slog::{info, trace, Logger},
};
use graph_runtime_wasm::asc_abi::class::{AscEnumArray, EthereumValueKind};
use super::abi::{AscUnresolvedContractCall, AscUnresolvedContractCall_0_0_4};
pub struct RuntimeAdapter {
pub(crate) eth_adapters: Arc<EthereumNetworkAdapters>,
pub(crate) call_cache: Arc<dyn EthereumCallCache>,
}
impl blockchain::RuntimeAdapter<Chain> for RuntimeAdapter {
fn host_fns(&self, ds: &DataSource) -> Result<Vec<HostFn>, Error> {
let abis = ds.mapping.abis.clone();
let call_cache = self.call_cache.cheap_clone();
let eth_adapter = self
.eth_adapters
.cheapest_with(&NodeCapabilities {
archive: ds.mapping.requires_archive()?,
traces: false,
})?
.cheap_clone();
let ethereum_call = HostFn {
name: "ethereum.call",
func: Arc::new(move |ctx, wasm_ptr| {
ethereum_call(ð_adapter, call_cache.cheap_clone(), ctx, wasm_ptr, &abis)
.map(|ptr| ptr.wasm_ptr())
}),
};
Ok(vec![ethereum_call])
}
}
/// function ethereum.call(call: SmartContractCall): Array<Token> | null
fn ethereum_call(
eth_adapter: &EthereumAdapter,
call_cache: Arc<dyn EthereumCallCache>,
ctx: HostFnCtx<'_>,
wasm_ptr: u32,
abis: &[Arc<MappingABI>],
) -> Result<AscEnumArray<EthereumValueKind>, HostExportError> {
// For apiVersion >= 0.0.4 the call passed from the mapping includes the
// function signature; subgraphs using an apiVersion < 0.0.4 don't pass
// the signature along with the call.
let call: UnresolvedContractCall = if ctx.heap.api_version() >= Version::new(0, 0, 4) {
asc_get::<_, AscUnresolvedContractCall_0_0_4, _>(ctx.heap, wasm_ptr.into())?
} else {
asc_get::<_, AscUnresolvedContractCall, _>(ctx.heap, wasm_ptr.into())?
};
let result = eth_call(
eth_adapter,
call_cache,
&ctx.logger,
&ctx.block_ptr,
call,
abis,
)?;
match result {
Some(tokens) => Ok(asc_new(ctx.heap, tokens.as_slice())?),
None => Ok(AscPtr::null()),
}
}
/// Returns `Ok(None)` if the call was reverted.
fn eth_call(
eth_adapter: &EthereumAdapter,
call_cache: Arc<dyn EthereumCallCache>,
logger: &Logger,
block_ptr: &BlockPtr,
unresolved_call: UnresolvedContractCall,
abis: &[Arc<MappingABI>],
) -> Result<Option<Vec<Token>>, HostExportError> {
let start_time = Instant::now();
// Obtain the path to the contract ABI
let contract = abis
.iter()
.find(|abi| abi.name == unresolved_call.contract_name)
.with_context(|| {
format!(
"Could not find ABI for contract \"{}\", try adding it to the 'abis' section \
of the subgraph manifest",
unresolved_call.contract_name
)
})?
.contract
.clone();
let function = match unresolved_call.function_signature {
// Behavior for apiVersion < 0.0.4: look up function by name; for overloaded
// functions this always picks the same overloaded variant, which is incorrect
// and may lead to encoding/decoding errors
None => contract
.function(unresolved_call.function_name.as_str())
.with_context(|| {
format!(
"Unknown function \"{}::{}\" called from WASM runtime",
unresolved_call.contract_name, unresolved_call.function_name
)
})?,
// Behavior for apiVersion >= 0.0.04: look up function by signature of
// the form `functionName(uint256,string) returns (bytes32,string)`; this
// correctly picks the correct variant of an overloaded function
Some(ref function_signature) => contract
.functions_by_name(unresolved_call.function_name.as_str())
.with_context(|| {
format!(
"Unknown function \"{}::{}\" called from WASM runtime",
unresolved_call.contract_name, unresolved_call.function_name
)
})?
.iter()
.find(|f| function_signature == &f.signature())
.with_context(|| {
format!(
"Unknown function \"{}::{}\" with signature `{}` \
called from WASM runtime",
unresolved_call.contract_name,
unresolved_call.function_name,
function_signature,
)
})?,
};
let call = EthereumContractCall {
address: unresolved_call.contract_address,
block_ptr: block_ptr.cheap_clone(),
function: function.clone(),
args: unresolved_call.function_args.clone(),
};
// Run Ethereum call in tokio runtime
let logger1 = logger.clone();
let call_cache = call_cache.clone();
let result = match graph::block_on(
eth_adapter.contract_call(&logger1, call, call_cache).compat()
) {
Ok(tokens) => Ok(Some(tokens)),
Err(EthereumContractCallError::Revert(reason)) => {
info!(logger, "Contract call reverted"; "reason" => reason);
Ok(None)
}
// Any error reported by the Ethereum node could be due to the block no longer being on
// the main chain. This is very unespecific but we don't want to risk failing a
// subgraph due to a transient error such as a reorg.
Err(EthereumContractCallError::Web3Error(e)) => Err(HostExportError::PossibleReorg(anyhow::anyhow!(
"Ethereum node returned an error when calling function \"{}\" of contract \"{}\": {}",
unresolved_call.function_name,
unresolved_call.contract_name,
e
))),
// Also retry on timeouts.
Err(EthereumContractCallError::Timeout) => Err(HostExportError::PossibleReorg(anyhow::anyhow!(
"Ethereum node did not respond when calling function \"{}\" of contract \"{}\"",
unresolved_call.function_name,
unresolved_call.contract_name,
))),
Err(e) => Err(HostExportError::Unknown(anyhow::anyhow!(
"Failed to call function \"{}\" of contract \"{}\": {}",
unresolved_call.function_name,
unresolved_call.contract_name,
e
))),
};
trace!(logger, "Contract call finished";
"address" => &unresolved_call.contract_address.to_string(),
"contract" => &unresolved_call.contract_name,
"function" => &unresolved_call.function_name,
"function_signature" => &unresolved_call.function_signature,
"time" => format!("{}ms", start_time.elapsed().as_millis()));
result
}
#[derive(Clone, Debug)]
pub struct UnresolvedContractCall {
pub contract_name: String,
pub contract_address: Address,
pub function_name: String,
pub function_signature: Option<String>,
pub function_args: Vec<ethabi::Token>,
}
impl AscIndexId for AscUnresolvedContractCall {
const INDEX_ASC_TYPE_ID: IndexForAscTypeId = IndexForAscTypeId::SmartContractCall;
}