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
use borsh::BorshSchema;
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::{Error, Write};
use std::rc::Rc;
use crate::{AccountId, Balance, Gas, PromiseIndex, PublicKey};
enum PromiseAction {
CreateAccount,
DeployContract {
code: Vec<u8>,
},
FunctionCall {
function_name: String,
arguments: Vec<u8>,
amount: Balance,
gas: Gas,
},
Transfer {
amount: Balance,
},
Stake {
amount: Balance,
public_key: PublicKey,
},
AddFullAccessKey {
public_key: PublicKey,
nonce: u64,
},
AddAccessKey {
public_key: PublicKey,
allowance: Balance,
receiver_id: AccountId,
function_names: String,
nonce: u64,
},
DeleteKey {
public_key: PublicKey,
},
DeleteAccount {
beneficiary_id: AccountId,
},
}
impl PromiseAction {
pub fn add(&self, promise_index: PromiseIndex) {
use PromiseAction::*;
match self {
CreateAccount => crate::env::promise_batch_action_create_account(promise_index),
DeployContract { code } => {
crate::env::promise_batch_action_deploy_contract(promise_index, code)
}
FunctionCall { function_name, arguments, amount, gas } => {
crate::env::promise_batch_action_function_call(
promise_index,
function_name,
arguments,
*amount,
*gas,
)
}
Transfer { amount } => {
crate::env::promise_batch_action_transfer(promise_index, *amount)
}
Stake { amount, public_key } => {
crate::env::promise_batch_action_stake(promise_index, *amount, public_key)
}
AddFullAccessKey { public_key, nonce } => {
crate::env::promise_batch_action_add_key_with_full_access(
promise_index,
public_key,
*nonce,
)
}
AddAccessKey { public_key, allowance, receiver_id, function_names, nonce } => {
crate::env::promise_batch_action_add_key_with_function_call(
promise_index,
public_key,
*nonce,
*allowance,
receiver_id,
function_names,
)
}
DeleteKey { public_key } => {
crate::env::promise_batch_action_delete_key(promise_index, public_key)
}
DeleteAccount { beneficiary_id } => {
crate::env::promise_batch_action_delete_account(promise_index, beneficiary_id)
}
}
}
}
struct PromiseSingle {
pub account_id: AccountId,
pub actions: RefCell<Vec<PromiseAction>>,
pub after: RefCell<Option<Promise>>,
pub promise_index: RefCell<Option<PromiseIndex>>,
}
impl PromiseSingle {
pub fn construct_recursively(&self) -> PromiseIndex {
let mut promise_lock = self.promise_index.borrow_mut();
if let Some(res) = promise_lock.as_ref() {
return *res;
}
let promise_index = if let Some(after) = self.after.borrow().as_ref() {
crate::env::promise_batch_then(after.construct_recursively(), &self.account_id)
} else {
crate::env::promise_batch_create(&self.account_id)
};
let actions_lock = self.actions.borrow();
for action in actions_lock.iter() {
action.add(promise_index);
}
*promise_lock = Some(promise_index);
promise_index
}
}
pub struct PromiseJoint {
pub promise_a: Promise,
pub promise_b: Promise,
pub promise_index: RefCell<Option<PromiseIndex>>,
}
impl PromiseJoint {
pub fn construct_recursively(&self) -> PromiseIndex {
let mut promise_lock = self.promise_index.borrow_mut();
if let Some(res) = promise_lock.as_ref() {
return *res;
}
let res = crate::env::promise_and(&[
self.promise_a.construct_recursively(),
self.promise_b.construct_recursively(),
]);
*promise_lock = Some(res);
res
}
}
pub struct Promise {
subtype: PromiseSubtype,
should_return: RefCell<bool>,
}
impl BorshSchema for Promise {
fn add_definitions_recursively(
definitions: &mut HashMap<borsh::schema::Declaration, borsh::schema::Definition>,
) {
<()>::add_definitions_recursively(definitions);
}
fn declaration() -> borsh::schema::Declaration {
<()>::declaration()
}
}
#[derive(Clone)]
enum PromiseSubtype {
Single(Rc<PromiseSingle>),
Joint(Rc<PromiseJoint>),
}
impl Promise {
pub fn new(account_id: AccountId) -> Self {
Self {
subtype: PromiseSubtype::Single(Rc::new(PromiseSingle {
account_id,
actions: RefCell::new(vec![]),
after: RefCell::new(None),
promise_index: RefCell::new(None),
})),
should_return: RefCell::new(false),
}
}
fn add_action(self, action: PromiseAction) -> Self {
match &self.subtype {
PromiseSubtype::Single(x) => x.actions.borrow_mut().push(action),
PromiseSubtype::Joint(_) => {
crate::env::panic_str("Cannot add action to a joint promise.")
}
}
self
}
pub fn create_account(self) -> Self {
self.add_action(PromiseAction::CreateAccount)
}
pub fn deploy_contract(self, code: Vec<u8>) -> Self {
self.add_action(PromiseAction::DeployContract { code })
}
pub fn function_call(
self,
function_name: String,
arguments: Vec<u8>,
amount: Balance,
gas: Gas,
) -> Self {
self.add_action(PromiseAction::FunctionCall { function_name, arguments, amount, gas })
}
pub fn transfer(self, amount: Balance) -> Self {
self.add_action(PromiseAction::Transfer { amount })
}
pub fn stake(self, amount: Balance, public_key: PublicKey) -> Self {
self.add_action(PromiseAction::Stake { amount, public_key })
}
pub fn add_full_access_key(self, public_key: PublicKey) -> Self {
self.add_full_access_key_with_nonce(public_key, 0)
}
pub fn add_full_access_key_with_nonce(self, public_key: PublicKey, nonce: u64) -> Self {
self.add_action(PromiseAction::AddFullAccessKey { public_key, nonce })
}
pub fn add_access_key(
self,
public_key: PublicKey,
allowance: Balance,
receiver_id: AccountId,
function_names: String,
) -> Self {
self.add_access_key_with_nonce(public_key, allowance, receiver_id, function_names, 0)
}
pub fn add_access_key_with_nonce(
self,
public_key: PublicKey,
allowance: Balance,
receiver_id: AccountId,
function_names: String,
nonce: u64,
) -> Self {
self.add_action(PromiseAction::AddAccessKey {
public_key,
allowance,
receiver_id,
function_names,
nonce,
})
}
pub fn delete_key(self, public_key: PublicKey) -> Self {
self.add_action(PromiseAction::DeleteKey { public_key })
}
pub fn delete_account(self, beneficiary_id: AccountId) -> Self {
self.add_action(PromiseAction::DeleteAccount { beneficiary_id })
}
pub fn and(self, other: Promise) -> Promise {
Promise {
subtype: PromiseSubtype::Joint(Rc::new(PromiseJoint {
promise_a: self,
promise_b: other,
promise_index: RefCell::new(None),
})),
should_return: RefCell::new(false),
}
}
pub fn then(self, mut other: Promise) -> Promise {
match &mut other.subtype {
PromiseSubtype::Single(x) => {
let mut after = x.after.borrow_mut();
if after.is_some() {
crate::env::panic_str(
"Cannot callback promise which is already scheduled after another",
);
}
*after = Some(self)
}
PromiseSubtype::Joint(_) => crate::env::panic_str("Cannot callback joint promise."),
}
other
}
#[allow(clippy::wrong_self_convention)]
pub fn as_return(self) -> Self {
*self.should_return.borrow_mut() = true;
self
}
fn construct_recursively(&self) -> PromiseIndex {
let res = match &self.subtype {
PromiseSubtype::Single(x) => x.construct_recursively(),
PromiseSubtype::Joint(x) => x.construct_recursively(),
};
if *self.should_return.borrow() {
crate::env::promise_return(res);
}
res
}
}
impl Drop for Promise {
fn drop(&mut self) {
self.construct_recursively();
}
}
impl serde::Serialize for Promise {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
*self.should_return.borrow_mut() = true;
serializer.serialize_unit()
}
}
impl borsh::BorshSerialize for Promise {
fn serialize<W: Write>(&self, _writer: &mut W) -> Result<(), Error> {
*self.should_return.borrow_mut() = true;
Ok(())
}
}
#[derive(serde::Serialize)]
#[serde(untagged)]
pub enum PromiseOrValue<T> {
Promise(Promise),
Value(T),
}
impl<T> BorshSchema for PromiseOrValue<T>
where
T: BorshSchema,
{
fn add_definitions_recursively(
definitions: &mut HashMap<borsh::schema::Declaration, borsh::schema::Definition>,
) {
T::add_definitions_recursively(definitions);
}
fn declaration() -> borsh::schema::Declaration {
T::declaration()
}
}
impl<T> From<Promise> for PromiseOrValue<T> {
fn from(promise: Promise) -> Self {
PromiseOrValue::Promise(promise)
}
}
impl<T: borsh::BorshSerialize> borsh::BorshSerialize for PromiseOrValue<T> {
fn serialize<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
match self {
PromiseOrValue::Value(x) => x.serialize(writer),
PromiseOrValue::Promise(p) => p.serialize(writer),
}
}
}