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
use anyhow::{anyhow, bail, Context, Result};
use forc_pkg::{self as pkg, fuel_core_not_running, PackageManifestFile};
use fuel_gql_client::client::FuelClient;
use fuel_tx::{ContractId, Transaction, TransactionBuilder, UniqueIdentifier};
use futures::TryFutureExt;
use pkg::BuiltPackage;
use std::time::Duration;
use std::{path::PathBuf, str::FromStr};
use sway_core::language::parsed::TreeType;
use tokio::time::timeout;
use tracing::info;
use crate::ops::pkg_util::built_pkgs_with_manifest;
use crate::ops::tx_util::{TransactionBuilderExt, TxParameters, TX_SUBMIT_TIMEOUT_MS};
use super::cmd::RunCommand;
pub const NODE_URL: &str = "http://127.0.0.1:4000";
pub struct RanScript {
pub receipts: Vec<fuel_tx::Receipt>,
}
pub async fn run(command: RunCommand) -> Result<Vec<RanScript>> {
let mut receipts = Vec::new();
let curr_dir = if let Some(path) = &command.path {
PathBuf::from(path)
} else {
std::env::current_dir().map_err(|e| anyhow!("{:?}", e))?
};
let build_opts = build_opts_from_cmd(&command);
let built_pkgs_with_manifest = built_pkgs_with_manifest(&curr_dir, build_opts)?;
for (member_manifest, built_pkg) in built_pkgs_with_manifest {
if member_manifest
.check_program_type(vec![TreeType::Script])
.is_ok()
{
let pkg_receipts = run_pkg(&command, &member_manifest, &built_pkg).await?;
receipts.push(pkg_receipts);
}
}
Ok(receipts)
}
pub async fn run_pkg(
command: &RunCommand,
manifest: &PackageManifestFile,
compiled: &BuiltPackage,
) -> Result<RanScript> {
let input_data = command.data.as_deref().unwrap_or("");
let data = format_hex_data(input_data);
let script_data = hex::decode(data).expect("Invalid hex");
let node_url = command
.node_url
.as_deref()
.or_else(|| manifest.network.as_ref().map(|nw| &nw.url[..]))
.unwrap_or(NODE_URL);
let client = FuelClient::new(node_url)?;
let contract_ids = command
.contract
.as_ref()
.into_iter()
.flat_map(|contracts| contracts.iter())
.map(|contract| {
ContractId::from_str(contract)
.map_err(|e| anyhow!("Failed to parse contract id: {}", e))
})
.collect::<Result<Vec<ContractId>>>()?;
let tx = TransactionBuilder::script(compiled.bytecode.clone(), script_data)
.params(TxParameters::new(command.gas_limit, command.gas_price))
.add_contracts(contract_ids)
.finalize_signed(client.clone(), command.unsigned, command.signing_key)
.await?;
if command.dry_run {
info!("{:?}", tx);
Ok(RanScript { receipts: vec![] })
} else {
let receipts =
try_send_tx(node_url, &tx.into(), command.pretty_print, command.simulate).await?;
Ok(RanScript { receipts })
}
}
async fn try_send_tx(
node_url: &str,
tx: &Transaction,
pretty_print: bool,
simulate: bool,
) -> Result<Vec<fuel_tx::Receipt>> {
let client = FuelClient::new(node_url)?;
match client.health().await {
Ok(_) => timeout(
Duration::from_millis(TX_SUBMIT_TIMEOUT_MS),
send_tx(&client, tx, pretty_print, simulate),
)
.await
.with_context(|| format!("timeout waiting for {} to be included in a block", tx.id()))?,
Err(_) => Err(fuel_core_not_running(node_url)),
}
}
async fn send_tx(
client: &FuelClient,
tx: &Transaction,
pretty_print: bool,
simulate: bool,
) -> Result<Vec<fuel_tx::Receipt>> {
let id = format!("{:#x}", tx.id());
let outputs = {
if !simulate {
client
.submit_and_await_commit(tx)
.and_then(|_| client.receipts(id.as_str()))
.await
} else {
client
.dry_run(tx)
.and_then(|_| client.receipts(id.as_str()))
.await
}
};
match outputs {
Ok(logs) => {
print_receipt_output(&logs, pretty_print)?;
Ok(logs)
}
Err(e) => bail!("{e}"),
}
}
fn format_hex_data(data: &str) -> &str {
data.strip_prefix("0x").unwrap_or(data)
}
fn print_receipt_output(receipts: &Vec<fuel_tx::Receipt>, pretty_print: bool) -> Result<()> {
let mut receipt_to_json_array = serde_json::to_value(receipts)?;
for (rec_index, receipt) in receipts.iter().enumerate() {
let rec_value = receipt_to_json_array.get_mut(rec_index).ok_or_else(|| {
anyhow!(
"Serialized receipts does not contain {} th index",
rec_index
)
})?;
match receipt {
fuel_tx::Receipt::LogData { data, .. } => {
if let Some(v) = rec_value.pointer_mut("/LogData/data") {
*v = hex::encode(data).into();
}
}
fuel_tx::Receipt::ReturnData { data, .. } => {
if let Some(v) = rec_value.pointer_mut("/ReturnData/data") {
*v = hex::encode(data).into();
}
}
_ => {}
}
}
if pretty_print {
info!("{}", serde_json::to_string_pretty(&receipt_to_json_array)?);
} else {
info!("{}", serde_json::to_string(&receipt_to_json_array)?);
}
Ok(())
}
fn build_opts_from_cmd(cmd: &RunCommand) -> pkg::BuildOpts {
pkg::BuildOpts {
pkg: pkg::PkgOpts {
path: cmd.path.clone(),
offline: false,
terse: cmd.terse_mode,
locked: cmd.locked,
output_directory: cmd.output_directory.clone(),
},
print: pkg::PrintOpts {
ast: cmd.print_ast,
finalized_asm: cmd.print_finalized_asm,
intermediate_asm: cmd.print_intermediate_asm,
ir: cmd.print_ir,
},
minify: pkg::MinifyOpts {
json_abi: cmd.minify_json_abi,
json_storage_slots: cmd.minify_json_storage_slots,
},
build_profile: cmd.build_profile.clone(),
release: cmd.release,
time_phases: cmd.time_phases,
binary_outfile: cmd.binary_outfile.clone(),
debug_outfile: cmd.debug_outfile.clone(),
tests: false,
}
}