aleph_client 3.0.0

This crate provides a Rust application interface for submitting transactions to `aleph-node` chain.
Documentation
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
use std::{collections::HashSet, marker::PhantomData};

use anyhow::{anyhow, ensure};
use codec::{Decode, Encode};

use crate::{
    account_from_keypair, aleph_runtime::RuntimeCall, api, api::runtime_types, connections::TxInfo,
    sp_core::blake2_256, sp_runtime::traits::TrailingZeroInput, sp_weights::weight_v2::Weight,
    AccountId, Balance, BlockHash, BlockNumber, ConnectionApi, SignedConnectionApi, TxStatus,
};

/// An alias for a call hash.
pub type CallHash = [u8; 32];
/// An alias for a call.
pub type Call = RuntimeCall;
/// An alias for a threshold.
pub type MultisigThreshold = u16;
/// An alias for a timepoint.
pub type Timepoint = runtime_types::pallet_multisig::Timepoint<BlockNumber>;
/// An alias for a multisig structure in the pallet storage.
pub type Multisig = runtime_types::pallet_multisig::Multisig<BlockNumber, Balance, AccountId>;

/// `MAX_WEIGHT` is the extrinsic parameter specifying upperbound for executing approved call.
/// Unless the approval is final, it has no effect. However, if due to your approval the
/// threshold is reached, you will be charged for execution process. By setting `max_weight`
/// low enough, you can avoid paying and left it for another member.
///
/// However, passing such parameter everytime is cumbersome and introduces the need of either
/// estimating call weight or setting very high universal bound at every caller side.
/// Thus, we keep a fairly high limit, which should cover almost any call (0.05 token).
pub const DEFAULT_MAX_WEIGHT: Weight = Weight::new(500_000_000, 0);

/// Pallet multisig api.
#[async_trait::async_trait]
pub trait MultisigUserApi {
    /// API for [`as_multi_threshold_1`](https://paritytech.github.io/substrate/master/pallet_multisig/pallet/struct.Pallet.html#method.as_multi_threshold_1) call.
    async fn as_multi_threshold_1(
        &self,
        other_signatories: Vec<AccountId>,
        call: Call,
        status: TxStatus,
    ) -> anyhow::Result<TxInfo>;
    /// API for [`as_multi`](https://paritytech.github.io/substrate/master/pallet_multisig/pallet/struct.Pallet.html#method.as_multi) call.
    async fn as_multi(
        &self,
        threshold: MultisigThreshold,
        other_signatories: Vec<AccountId>,
        timepoint: Option<Timepoint>,
        max_weight: Weight,
        call: Call,
        status: TxStatus,
    ) -> anyhow::Result<TxInfo>;
    /// API for [`approve_as_multi`](https://paritytech.github.io/substrate/master/pallet_multisig/pallet/struct.Pallet.html#method.approve_as_multi) call.
    async fn approve_as_multi(
        &self,
        threshold: MultisigThreshold,
        other_signatories: Vec<AccountId>,
        timepoint: Option<Timepoint>,
        max_weight: Weight,
        call_hash: CallHash,
        status: TxStatus,
    ) -> anyhow::Result<TxInfo>;
    /// API for [`cancel_as_multi`](https://paritytech.github.io/substrate/master/pallet_multisig/pallet/struct.Pallet.html#method.cancel_as_multi) call.
    async fn cancel_as_multi(
        &self,
        threshold: MultisigThreshold,
        other_signatories: Vec<AccountId>,
        timepoint: Timepoint,
        call_hash: CallHash,
        status: TxStatus,
    ) -> anyhow::Result<TxInfo>;
}

#[async_trait::async_trait]
impl<S: SignedConnectionApi> MultisigUserApi for S {
    async fn as_multi_threshold_1(
        &self,
        other_signatories: Vec<AccountId>,
        call: Call,
        status: TxStatus,
    ) -> anyhow::Result<TxInfo> {
        let tx = api::tx()
            .multisig()
            .as_multi_threshold_1(other_signatories, call);

        self.send_tx(tx, status).await
    }

    async fn as_multi(
        &self,
        threshold: MultisigThreshold,
        other_signatories: Vec<AccountId>,
        timepoint: Option<Timepoint>,
        max_weight: Weight,
        call: Call,
        status: TxStatus,
    ) -> anyhow::Result<TxInfo> {
        let tx = api::tx().multisig().as_multi(
            threshold,
            other_signatories,
            timepoint,
            call,
            max_weight,
        );

        self.send_tx(tx, status).await
    }

    async fn approve_as_multi(
        &self,
        threshold: MultisigThreshold,
        other_signatories: Vec<AccountId>,
        timepoint: Option<Timepoint>,
        max_weight: Weight,
        call_hash: CallHash,
        status: TxStatus,
    ) -> anyhow::Result<TxInfo> {
        let tx = api::tx().multisig().approve_as_multi(
            threshold,
            other_signatories,
            timepoint,
            call_hash,
            max_weight,
        );

        self.send_tx(tx, status).await
    }

    async fn cancel_as_multi(
        &self,
        threshold: MultisigThreshold,
        other_signatories: Vec<AccountId>,
        timepoint: Timepoint,
        call_hash: CallHash,
        status: TxStatus,
    ) -> anyhow::Result<TxInfo> {
        let tx = api::tx().multisig().cancel_as_multi(
            threshold,
            other_signatories,
            timepoint,
            call_hash,
        );

        self.send_tx(tx, status).await
    }
}

/// A group of accounts together with a threshold.
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct MultisigParty {
    signatories: Vec<AccountId>,
    threshold: MultisigThreshold,
}

impl MultisigParty {
    /// Create new party from `signatories` and `threshold`.
    ///
    /// `signatories` can contain duplicates and doesn't have to be sorted. However, there must be
    /// at least 2 unique accounts. There is also a virtual upper bound - `MaxSignatories` constant.
    /// It isn't checked here (since it requires client), however, using too big party will fail
    /// when performing any chain interaction.
    ///
    /// `threshold` must be between 2 and number of unique accounts in `signatories`. For threshold
    /// 1, use special method `MultisigUserApi::as_multi_threshold_1`.
    pub fn new(signatories: &[AccountId], threshold: MultisigThreshold) -> anyhow::Result<Self> {
        let mut sorted_signatories = signatories.to_vec();
        sorted_signatories.sort();
        sorted_signatories.dedup();

        ensure!(
            sorted_signatories.len() > 1,
            "There must be at least 2 different signatories"
        );
        ensure!(
            sorted_signatories.len() >= threshold as usize,
            "Threshold must not be greater than the number of unique signatories"
        );
        ensure!(
            threshold >= 2,
            "Threshold must be at least 2 - for threshold 1, use `as_multi_threshold_1`"
        );

        Ok(Self {
            signatories: sorted_signatories,
            threshold,
        })
    }

    /// The multisig account derived from signatories and threshold.
    ///
    /// This method is copied from the pallet, because:
    ///  -  we don't want to add a new dependency
    ///  -  we cannot instantiate pallet object here anyway (the corresponding functionality exists
    ///     as pallet's method rather than standalone function)
    pub fn account(&self) -> AccountId {
        let entropy =
            (b"modlpy/utilisuba", &self.signatories, &self.threshold).using_encoded(blake2_256);
        Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref()))
            .expect("infinite length input; no invalid inputs for type; qed")
    }
}

/// Pallet multisig functionality that is not directly related to any pallet call.
#[async_trait::async_trait]
pub trait MultisigApiExt {
    /// Get the coordinate that corresponds to the ongoing signature aggregation for `party_account`
    /// and `call_hash`.
    async fn get_timepoint(
        &self,
        party_account: &AccountId,
        call_hash: &CallHash,
        block_hash: Option<BlockHash>,
    ) -> Timepoint;
}

#[async_trait::async_trait]
impl<C: ConnectionApi> MultisigApiExt for C {
    async fn get_timepoint(
        &self,
        party_account: &AccountId,
        call_hash: &CallHash,
        block_hash: Option<BlockHash>,
    ) -> Timepoint {
        let multisigs = api::storage()
            .multisig()
            .multisigs(party_account, call_hash);
        let Multisig { when, .. } = self.get_storage_entry(&multisigs, block_hash).await;
        when
    }
}

/// We will mark context object as either ongoing procedure or a closed one. However, we put this
/// distinction to the type level, so instead of enum, we use a trait.
pub trait ContextState {}

/// Context of the signature aggregation that is still in progress.
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum Ongoing {}
impl ContextState for Ongoing {}

/// Context of the signature aggregation that was either successfully performed or canceled.
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum Closed {}
impl ContextState for Closed {}

/// A context in which ongoing signature aggregation is performed.
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Context<S: ContextState> {
    /// The entity for which aggregation is being made.
    party: MultisigParty,
    /// Derived multisig account (the source of the target call).
    author: AccountId,

    /// Pallet's coordinate for this aggregation.
    timepoint: Timepoint,
    /// Weight limit when dispatching the call.
    max_weight: Weight,

    /// The target dispatchable, if already provided.
    call: Option<Call>,
    /// The hash of the target dispatchable.
    call_hash: CallHash,

    /// The set of accounts, that already approved the call (via this context object), including the
    /// author.
    ///
    /// `approvers.len() < party.threshold` always holds.
    approvers: HashSet<AccountId>,

    _phantom: PhantomData<S>,
}

/// After approval action, our context can be in two modes - either for further use (`Ongoing`), or
/// read only (`Closed`).
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum ContextAfterUse {
    /// Signature aggregation is in progress.
    Ongoing(Context<Ongoing>),
    /// Signature aggregation was either successfully performed or was canceled.
    Closed(Context<Closed>),
}

impl Context<Ongoing> {
    fn new(
        party: MultisigParty,
        author: AccountId,
        timepoint: Timepoint,
        max_weight: Weight,
        call: Option<Call>,
        call_hash: CallHash,
    ) -> Self {
        Self {
            party,
            author: author.clone(),
            timepoint,
            max_weight,
            call,
            call_hash,
            approvers: HashSet::from([author]),
            _phantom: PhantomData,
        }
    }

    /// In case `Context` object has been passed somewhere, where this limit should be adjusted, we
    /// allow for that.
    ///
    /// Actually, this isn't used until threshold is met, so such changing is perfectly safe.
    pub fn change_max_weight(&mut self, max_weight: Weight) {
        self.max_weight = max_weight;
    }

    /// Set `call` only if `self.call_hash` is matching.
    fn set_call(&mut self, call: Call) -> anyhow::Result<()> {
        ensure!(
            self.call_hash == compute_call_hash(&call),
            "Call doesn't match to the registered hash"
        );
        self.call = Some(call);
        Ok(())
    }

    /// Register another approval. Depending on the threshold meeting and `call` content, we treat
    /// signature aggregation process as either still ongoing or closed.
    fn add_approval(mut self, approver: AccountId) -> ContextAfterUse {
        self.approvers.insert(approver);
        if self.call.is_some() && self.approvers.len() >= (self.party.threshold as usize) {
            ContextAfterUse::Closed(self.close())
        } else {
            ContextAfterUse::Ongoing(self)
        }
    }

    /// Casting to the closed variant. Private, so that the user don't accidentally call `into()`
    /// and close ongoing context.
    fn close(self) -> Context<Closed> {
        Context::<Closed> {
            party: self.party,
            author: self.author,
            timepoint: self.timepoint,
            max_weight: self.max_weight,
            call: self.call,
            call_hash: self.call_hash,
            approvers: self.approvers,
            _phantom: Default::default(),
        }
    }
}

impl Context<Closed> {
    /// Read party.
    pub fn party(&self) -> &MultisigParty {
        &self.party
    }
    /// Read author.
    pub fn author(&self) -> &AccountId {
        &self.author
    }
    /// Read timepoint.
    pub fn timepoint(&self) -> &Timepoint {
        &self.timepoint
    }
    /// Read max weight.
    pub fn max_weight(&self) -> &Weight {
        &self.max_weight
    }
    /// Read call.
    pub fn call(&self) -> &Option<Call> {
        &self.call
    }
    /// Read call hash.
    pub fn call_hash(&self) -> CallHash {
        self.call_hash
    }
    /// Read approvers set.
    pub fn approvers(&self) -> &HashSet<AccountId> {
        &self.approvers
    }
}

/// Pallet multisig API, but suited for cases when the whole scenario is performed in a single place
/// - we keep data in a context object which helps in concise programming.
#[async_trait::async_trait]
pub trait MultisigContextualApi {
    /// Start signature aggregation for `party` and `call_hash`. Get `Context` object as a result
    /// (together with standard tx coordinates).
    ///
    /// This is the recommended way of initialization.
    async fn initiate(
        &self,
        party: &MultisigParty,
        max_weight: &Weight,
        call_hash: CallHash,
        status: TxStatus,
    ) -> anyhow::Result<(TxInfo, Context<Ongoing>)>;
    /// Start signature aggregation for `party` and `call`. Get `Context` object as a result
    /// (together with standard tx coordinates).
    ///
    /// Note: it is usually a better idea to pass `call` only with the final approval (so that it
    /// isn't stored on-chain).
    async fn initiate_with_call(
        &self,
        party: &MultisigParty,
        max_weight: &Weight,
        call: Call,
        status: TxStatus,
    ) -> anyhow::Result<(TxInfo, Context<Ongoing>)>;
    /// Express contextual approval for the call hash.
    ///
    /// This is the recommended way for every intermediate approval.
    async fn approve(
        &self,
        context: Context<Ongoing>,
        status: TxStatus,
    ) -> anyhow::Result<(TxInfo, ContextAfterUse)>;
    /// Express contextual approval for the `call`.
    ///
    /// This is the recommended way only for the final approval.
    async fn approve_with_call(
        &self,
        context: Context<Ongoing>,
        call: Option<Call>,
        status: TxStatus,
    ) -> anyhow::Result<(TxInfo, ContextAfterUse)>;
    /// Cancel signature aggregation.
    async fn cancel(
        &self,
        context: Context<Ongoing>,
        status: TxStatus,
    ) -> anyhow::Result<(TxInfo, Context<Closed>)>;
}

#[async_trait::async_trait]
impl<S: SignedConnectionApi> MultisigContextualApi for S {
    async fn initiate(
        &self,
        party: &MultisigParty,
        max_weight: &Weight,
        call_hash: CallHash,
        status: TxStatus,
    ) -> anyhow::Result<(TxInfo, Context<Ongoing>)> {
        let other_signatories = ensure_signer_in_party(self, party)?;

        let tx_info = self
            .approve_as_multi(
                party.threshold,
                other_signatories,
                None,
                max_weight.clone(),
                call_hash,
                status,
            )
            .await?;

        // Even though `subxt` allows us to get timepoint when waiting for the submission
        // confirmation (see e.g. `ExtrinsicEvents` object that is returned from
        // `wait_for_finalized_success`), we chose to perform one additional storage read.
        // Firstly, because of brevity here (we would have to duplicate some lines from
        // `connections` module. Secondly, if `Timepoint` struct change, this method (reading raw
        // extrinsic position) might become incorrect.
        let timepoint = self
            .get_timepoint(&party.account(), &call_hash, Some(tx_info.block_hash))
            .await;

        Ok((
            tx_info,
            Context::new(
                party.clone(),
                self.account_id().clone(),
                timepoint,
                max_weight.clone(),
                None,
                call_hash,
            ),
        ))
    }

    async fn initiate_with_call(
        &self,
        party: &MultisigParty,
        max_weight: &Weight,
        call: Call,
        status: TxStatus,
    ) -> anyhow::Result<(TxInfo, Context<Ongoing>)> {
        let other_signatories = ensure_signer_in_party(self, party)?;

        let tx_info = self
            .as_multi(
                party.threshold,
                other_signatories,
                None,
                max_weight.clone(),
                call.clone(),
                status,
            )
            .await?;

        let call_hash = compute_call_hash(&call);
        let timepoint = self
            .get_timepoint(&party.account(), &call_hash, Some(tx_info.block_hash))
            .await;

        Ok((
            tx_info,
            Context::new(
                party.clone(),
                self.account_id().clone(),
                timepoint,
                max_weight.clone(),
                Some(call.clone()),
                call_hash,
            ),
        ))
    }

    async fn approve(
        &self,
        context: Context<Ongoing>,
        status: TxStatus,
    ) -> anyhow::Result<(TxInfo, ContextAfterUse)> {
        let other_signatories = ensure_signer_in_party(self, &context.party)?;

        self.approve_as_multi(
            context.party.threshold,
            other_signatories,
            Some(context.timepoint.clone()),
            context.max_weight.clone(),
            context.call_hash,
            status,
        )
        .await
        .map(|tx_info| (tx_info, context.add_approval(self.account_id().clone())))
    }

    async fn approve_with_call(
        &self,
        mut context: Context<Ongoing>,
        call: Option<Call>,
        status: TxStatus,
    ) -> anyhow::Result<(TxInfo, ContextAfterUse)> {
        let other_signatories = ensure_signer_in_party(self, &context.party)?;

        let call = match (call.as_ref(), context.call.as_ref()) {
            (None, None) => Err(anyhow!(
                "Call wasn't provided earlier - you must pass it now"
            )),
            (None, Some(call)) => Ok(call),
            (Some(call), None) => {
                context.set_call(call.clone())?;
                Ok(call)
            }
            (Some(saved_call), Some(new_call)) => {
                ensure!(
                    saved_call == new_call,
                    "The call is different that the one used previously"
                );
                Ok(new_call)
            }
        }?;

        self.as_multi(
            context.party.threshold,
            other_signatories,
            Some(context.timepoint.clone()),
            context.max_weight.clone(),
            call.clone(),
            status,
        )
        .await
        .map(|tx_info| (tx_info, context.add_approval(self.account_id().clone())))
    }

    async fn cancel(
        &self,
        context: Context<Ongoing>,
        status: TxStatus,
    ) -> anyhow::Result<(TxInfo, Context<Closed>)> {
        let other_signatories = ensure_signer_in_party(self, &context.party)?;

        ensure!(
            *self.account_id() == context.author,
            "Only the author can cancel multisig aggregation"
        );

        let tx_info = self
            .cancel_as_multi(
                context.party.threshold,
                other_signatories,
                context.timepoint.clone(),
                context.call_hash,
                status,
            )
            .await?;

        Ok((tx_info, context.close()))
    }
}

/// Compute hash of `call`.
pub fn compute_call_hash(call: &Call) -> CallHash {
    call.using_encoded(blake2_256)
}

/// Ensure that the signer of `conn` is present in `party.signatories`. If so, return all other
/// signatories.
fn ensure_signer_in_party<S: SignedConnectionApi>(
    conn: &S,
    party: &MultisigParty,
) -> anyhow::Result<Vec<AccountId>> {
    let signer_account = account_from_keypair(conn.signer().signer());
    if let Ok(index) = party.signatories.binary_search(&signer_account) {
        let mut other_signatories = party.signatories.clone();
        other_signatories.remove(index);
        Ok(other_signatories)
    } else {
        Err(anyhow!("Connection should be signed by a party member"))
    }
}