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
use crate::{OnChainProgramState, ProgramManager};
use snarkvm_console::{
account::PrivateKey,
prelude::ToBytes,
program::{Network, Plaintext, ProgramID, Record},
};
use snarkvm_synthesizer::{ConsensusMemory, ConsensusStore, Program, Query, Transaction, VM};
use anyhow::{anyhow, bail, ensure, Error, Result};
impl<N: Network> ProgramManager<N> {
pub fn deploy_program(
&mut self,
program_id: impl TryInto<ProgramID<N>>,
fee: u64,
fee_record: Record<N, Plaintext<N>>,
password: Option<&str>,
) -> Result<String> {
ensure!(
self.api_client.is_some(),
"❌ Network client not set, network config must be set before deployment in order to send transactions to the Aleo network"
);
ensure!(fee > 0, "❌ Fee must be greater than zero in order to deploy a program");
let record_amount = ***fee_record.gates();
ensure!(
record_amount >= fee,
"❌ The record supplied has balance of {record_amount:?} gates which is insufficient to pay the specified fee of {fee:?} gates"
);
let program_id = program_id.try_into().map_err(|_| anyhow!("Invalid program ID"))?;
ensure!(
self.api_client()?.get_program(program_id).is_err(),
"❌ Program {:?} already deployed on chain, cancelling deployment",
program_id
);
println!("Loading program {program_id:?}..");
let program = if let Ok(program) = self.get_program(program_id) {
println!("Program {:?} already exists in program manager, using existing program", program_id);
program
} else if let Some(dir) = self.local_program_directory.as_ref() {
let program = self.find_program_on_disk(&program_id);
if program.is_err() {
bail!(
"❌ Program {program_id:?} could not be found at {dir:?} or in the program manager, please ensure the program is in the correct directory before continuing with deployment"
);
}
program?
} else {
bail!(
"❌ Program {:?} not found in program manager and no local program directory was configured",
program_id
);
};
let mut imports = vec![];
program.imports().keys().try_for_each(|program_id| {
let imported_program = if self.contains_program(program_id)? {
self.get_program(program_id)
} else {
self.find_program(program_id)
}.map_err(|_| anyhow!("❌ Imported program {program_id:?} could not be found locally or on the Aleo Network"))?;
let imported_program_id = imported_program.id();
match self.on_chain_program_state(&imported_program)? {
OnChainProgramState::NotDeployed => {
bail!("❌ Imported program {imported_program_id:?} could not be found on the Aleo Network, please deploy this imported program first before continuing with deployment of {program_id:?}");
}
OnChainProgramState::Different => {
bail!("❌ Imported program {imported_program_id:?} is already deployed on chain and did not match local import");
}
OnChainProgramState::Same => (),
};
if imports.contains(&imported_program) {
bail!("❌ Imported program {imported_program_id:?} was specified twice by {program_id:?}, remove the duplicated import before trying again");
}
if imported_program_id.to_string() != "credits.aleo" {
imports.push(imported_program);
}
Ok::<_, Error>(())
})?;
let private_key = self.get_private_key(password)?;
println!("Building transaction..");
let query = self.api_client.as_ref().unwrap().base_url();
let transaction =
Self::create_deploy_transaction(&program, &imports, &private_key, fee, fee_record, query.to_string())?;
println!(
"Attempting to broadcast a deploy transaction for program {:?} to node {:?}",
program_id,
self.api_client().unwrap().base_url()
);
let required_fee = transaction.to_bytes_le()?.len();
let result = if usize::try_from(fee)? >= required_fee {
self.broadcast_transaction(transaction)
} else {
bail!(
"❌ Insufficient funds to pay for transaction fee, required fee: {}, fee specified in the record: {}",
required_fee,
fee
)
};
if result.is_ok() {
println!("✅ Deployment transaction for {program_id:?} broadcast successfully");
} else {
println!("❌ Deployment transaction for {program_id:?} failed to broadcast");
};
result
}
pub fn create_deploy_transaction(
program: &Program<N>,
imports: &[Program<N>],
private_key: &PrivateKey<N>,
fee: u64,
fee_record: Record<N, Plaintext<N>>,
query: String,
) -> Result<Transaction<N>> {
let rng = &mut rand::thread_rng();
let query = Query::from(query);
let store = ConsensusStore::<N, ConsensusMemory<N>>::open(None)?;
let vm = VM::<N, ConsensusMemory<N>>::from(store)?;
imports.iter().try_for_each(|imported_program| {
if imported_program.id().to_string() != "credits.aleo" {
vm.process().write().add_program(imported_program)?;
};
Ok::<_, Error>(())
})?;
Transaction::<N>::deploy(&vm, private_key, program, (fee_record, fee), Some(query), rng)
}
}
#[cfg(test)]
#[cfg(not(feature = "wasm"))]
mod tests {
use super::*;
use crate::{
test_utils::{
random_program,
random_program_id,
setup_directory,
transfer_to_test_account,
CREDITS_IMPORT_TEST_PROGRAM,
HELLO_PROGRAM,
RECORD_2000000001_GATES,
RECORD_5_GATES,
},
AleoAPIClient,
RecordFinder,
};
use snarkvm_console::network::Testnet3;
use std::{ops::Add, str::FromStr, thread};
#[test]
#[ignore]
fn test_deploy() {
let rng = &mut rand::thread_rng();
let recipient_private_key = PrivateKey::<Testnet3>::new(rng).unwrap();
thread::sleep(std::time::Duration::from_secs(5));
transfer_to_test_account(2000000001, 4, recipient_private_key, "3030").unwrap();
let api_client = AleoAPIClient::<Testnet3>::local_testnet3("3030");
let record_finder = RecordFinder::<Testnet3>::new(api_client.clone());
let temp_dir = setup_directory("aleo_test_deploy", CREDITS_IMPORT_TEST_PROGRAM, vec![]).unwrap();
let mut program_manager =
ProgramManager::<Testnet3>::new(Some(recipient_private_key), None, Some(api_client), Some(temp_dir))
.unwrap();
thread::sleep(std::time::Duration::from_secs(30));
let deployment_fee = 200000001;
let fee_record = record_finder.find_one_record(&recipient_private_key, deployment_fee).unwrap();
program_manager.deploy_program("credits_import_test.aleo", deployment_fee, fee_record, None).unwrap();
thread::sleep(std::time::Duration::from_secs(45));
for _ in 0..4 {
let deployed_program = program_manager.api_client().unwrap().get_program("credits_import_test.aleo");
if deployed_program.is_ok() {
assert_eq!(deployed_program.unwrap(), Program::from_str(CREDITS_IMPORT_TEST_PROGRAM).unwrap());
break;
}
println!("Program has not yet appeared on chain, waiting another 15 seconds");
thread::sleep(std::time::Duration::from_secs(15));
}
}
#[test]
fn test_deploy_failure_conditions() {
let rng = &mut rand::thread_rng();
let recipient_private_key = PrivateKey::<Testnet3>::new(rng).unwrap();
let record_5_gates = Record::<Testnet3, Plaintext<Testnet3>>::from_str(RECORD_5_GATES).unwrap();
let record_2000000001_gates =
Record::<Testnet3, Plaintext<Testnet3>>::from_str(RECORD_2000000001_GATES).unwrap();
let api_client = AleoAPIClient::<Testnet3>::local_testnet3("3030");
let randomized_program = random_program();
let randomized_program_id = randomized_program.id().to_string();
let randomized_program_string = randomized_program.to_string();
let temp_dir = setup_directory("aleo_unit_test_fees", &randomized_program.to_string(), vec![]).unwrap();
let mut program_manager = ProgramManager::<Testnet3>::new(
Some(recipient_private_key),
None,
Some(api_client.clone()),
Some(temp_dir),
)
.unwrap();
let deployment_fee = 200000001;
let deployment = program_manager.deploy_program(&randomized_program_id, 0, record_5_gates.clone(), None);
assert!(deployment.is_err());
let deployment = program_manager.deploy_program(&randomized_program_id, 2, record_5_gates.clone(), None);
assert!(deployment.is_err());
let deployment = program_manager.deploy_program(&randomized_program_id, deployment_fee, record_5_gates, None);
assert!(deployment.is_err());
let deployment =
program_manager.deploy_program("hello.aleo", deployment_fee, record_2000000001_gates.clone(), None);
assert!(deployment.is_err());
let missing_import_program_string =
format!("import {};\n", random_program_id(16)).add(&randomized_program_string);
let temp_dir_2 = setup_directory("aleo_unit_test_imports", &missing_import_program_string, vec![
("hello.aleo", HELLO_PROGRAM),
(&randomized_program_id, &missing_import_program_string),
])
.unwrap();
let mut program_manager =
ProgramManager::<Testnet3>::new(Some(recipient_private_key), None, Some(api_client), Some(temp_dir_2))
.unwrap();
let deployment =
program_manager.deploy_program(&randomized_program_id, deployment_fee, record_2000000001_gates, None);
assert!(deployment.is_err());
}
}