-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathlib.rs
More file actions
1243 lines (1140 loc) · 48.5 KB
/
Copy pathlib.rs
File metadata and controls
1243 lines (1140 loc) · 48.5 KB
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of the Polymesh distribution (https://github.com/PolymeshAssociation/Polymesh).
// Copyright (c) 2020 Polymesh Association
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! # Corporate Actions module.
//!
//! The corporate actions module provides functionality for handling corporate actions (CAs) on-chain.
//!
//! Any CA is associated with an asset,
//! so most module dispatchables must be called by an external agent with appropriate corporate actions permissions.
//!
//! The starting point of any CA begins with executing `initiate_corporate_action`,
//! provided with the associated asset id, what sort of CA it is, e.g., a notice or a benefit,
//! and when, if any, a checkpoint should be recorded, or was recorded, if an existing one is to be used.
//! Additonally, free-form details, serving as on-chain documentation, may be provided.
//!
//! A CA targets a set of identities (`TargetIdentities`), but this need not be every asset holder.
//! Instead, when initiating a CA,
//! the targets may be specified either by exhaustively specifying every identity to include.
//! This is achieved through `TargetTreatment::Include`.
//! Instead of specifying an exhaustive set,
//! a set of identities can be excluded from the universe of asset holders.
//! This can be achieved through `TargetTreatment::Exclude`.
//! If the target set for an asset is usually the same,
//! a default may be specified through `set_default_targets(targets)`.
//!
//! Finally, CAs which imply some sort of benefit may have a taxable element, e.g., due to capital gains tax.
//! Sometimes, the responsibiliy paying such tax falls to the asset issuer (or external agents),
//! To handle such circumstances, a portion of the benefits may be withheld.
//! This governed by specifying a withholding tax % on-chain.
//! The tax is first and foremost specified for every identity,
//! but may also be overriden for specific identities (e.g., for DIDs in different jurisdictions).
//! As with targets, if the taxes are usually the same for every CA,
//! asset-level defaults may also be specified with `set_default_withholding_tax`
//! and `set_did_withholding_tax`.
//!
//! After having created a CA and some asset documents,
//! such documents may also be linked to the CA.
//! To do so, `link_ca_doc(ca_id, docs)` can be called,
//! with the ID of the CA specified in `ca_id` as well the IDs of each document in `docs`.
//!
//! Beyond this module, two other modules exist dedicated to CAs. These are:
//!
//! - The corporate ballots module, with which e.g., annual general meetings can be conducted on-chain.
//! - The capital distributions module, with which e.g., dividends and other benefits may be distributed.
//!
//! For more details, consult the documentation in those modules.
//!
//! ## Overview
//!
//! The module provides functions for:
//!
//! - Configuring the max length of details (chain global configuration, through PIPs)
//! - Specifying asset level CA configuration for the target set and withholding tax.
//! - Initiating CAs.
//! - Linking existing asset documentation to an existing CA.
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! - `set_max_details_length(origin, length)` sets the maximum `length` in bytes for the `details` of any CA.
//! Must be called via the PIP process.
//! - `set_default_targets(origin, asset_id, targets)` sets the default `targets`
//! for all CAs associated with `asset_id`.
//! - `set_default_withholding_tax(origin, asset_id, tax)` sets the default withholding tax
//! for every identity for all CAs associated with `asset_id`.
//! - `set_did_withholding_tax(origin, asset_id, taxed_did, tax)` sets a withholding tax
//! for CAs associated with `asset_id` and specific to `taxed_did` to `tax`,
//! or resets the tax of `taxed_did` to the default if `tax` is `None`.
//! - `initiate_corporate_action(...)` initates a corporate action.
//! - `link_ca_doc(origin, id, docs)` is called by external agents to associate `docs` to the CA with `id`.
//! - `remove_ca(origin, id)` removes the CA identified by `id`.
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
pub mod ballot;
pub mod distribution;
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::dispatch::{DispatchError, DispatchResult};
use frame_support::ensure;
use frame_support::traits::Get;
use frame_support::weights::Weight;
use frame_system::ensure_root;
use scale_info::TypeInfo;
use sp_arithmetic::Permill;
use sp_std::prelude::*;
use pallet_asset::checkpoint::{SchedulePoints, Timestamps};
use pallet_asset::{checkpoint, BalanceOf};
use pallet_base::try_next_post;
use pallet_identity::{Config as IdentityConfig, PermissionedCallOriginData};
use polymesh_common_utilities::checkpoint::ScheduleId;
use polymesh_primitives::asset::{AssetId, CheckpointId};
use polymesh_primitives::{impl_checked_inc, storage_migration_ver, Balance, DocumentId};
use polymesh_primitives::{EventDid, IdentityId, Moment, PortfolioNumber, GC_DID};
use polymesh_primitives_derive::VecU8StrongTyped;
use ballot::{BallotMeta, BallotTimeRange, TimeRanges, WeightInfo as BallotWeightInfo};
use distribution::{Distributions, WeightInfo as DistWeightInfoTrait};
storage_migration_ver!(1);
/// Combinded config traits of the corporate actions and distribution pallets.
pub trait CAConfig: Config + distribution::Config + ballot::Config {}
impl<T: Config + distribution::Config + ballot::Config> CAConfig for T {}
/// Representation of a % to tax, with 10^6 precision.
pub type Tax = Permill;
/// How should `identities` in `TargetIdentities` be used?
#[derive(
Clone,
Copy,
PartialEq,
Eq,
Encode,
Decode,
TypeInfo,
MaxEncodedLen,
Debug
)]
pub enum TargetTreatment {
/// Only those identities should be included.
Include,
/// All identities *but* those should be included.
Exclude,
}
impl Default for TargetTreatment {
fn default() -> Self {
// By default, an empty list of identities to exclude means all identities are included.
Self::Exclude
}
}
impl TargetTreatment {
/// Is this the `Include` treatment?
pub fn is_include(self) -> bool {
match self {
Self::Include => true,
Self::Exclude => false,
}
}
}
/// A description of which identities that a CA will apply to.
#[derive(Clone, PartialEq, Eq, Encode, Decode, TypeInfo, Default, Debug)]
pub struct TargetIdentities {
/// The specified identities either relevant or irrelevant, depending on `treatment`, for CAs.
pub identities: Vec<IdentityId>,
/// How should `identities` be treated?
pub treatment: TargetTreatment,
}
impl TargetIdentities {
/// Sort and deduplicate all identities.
fn dedup(mut self) -> Self {
self.identities.sort_unstable();
self.identities.dedup();
self
}
/// Does this target `did`?
/// Complexity: O(log n) with `n` being the number of identities listed.
pub fn targets(&self, did: &IdentityId) -> bool {
// N.B. The binary search here is OK since the list of identities is sorted.
self.treatment.is_include() == self.identities.binary_search(&did).is_ok()
}
}
/// The kind of a `CorporateAction`.
#[derive(
Copy,
Clone,
PartialEq,
Eq,
Encode,
Decode,
TypeInfo,
MaxEncodedLen,
Debug
)]
pub enum CAKind {
/// A predictable benefit.
/// These are known at the time the asset is created.
/// Examples include bonds and warrants.
PredictableBenefit,
/// An unpredictable benefit.
/// These are announced during the *"life"* of the asset.
/// Examples include dividends, bonus issues.
UnpredictableBenefit,
/// A notice to the position holders, where the goal is to dessiminate information to them,
/// resulting in no change to the securities or cash position of the position holder.
/// Examples include Annual General Meetings.
IssuerNotice,
/// A reorganization of the tokens.
/// For example, for every 1 ACME token a holder owns, turn them into 2 tokens.
/// These do not really change the position of holders, and is more of an accounting exercise.
/// However, a reorganization does increase the supply of tokens, which could matter for indivisible ones.
Reorganization,
/// Some generic uncategorized CA.
/// In other words, none of the above.
Other,
}
impl CAKind {
/// Is this some sort of benefit CA?
pub fn is_benefit(&self) -> bool {
matches!(self, Self::PredictableBenefit | Self::UnpredictableBenefit)
}
}
#[derive(Encode, Decode, TypeInfo, VecU8StrongTyped)]
#[derive(Clone, PartialEq, Eq, Default, Debug)]
pub struct CADetails(pub Vec<u8>);
/// Defines how to identify a CA's associated checkpoint, if any.
#[derive(
Copy,
Clone,
PartialEq,
Eq,
Encode,
Decode,
TypeInfo,
MaxEncodedLen,
Debug
)]
pub enum CACheckpoint {
/// CA uses a record date scheduled to occur in the future.
/// Checkpoint ID will be taken after the record date.
///
/// Since a schedule can be recurring,
/// the `u64` stores the number of checkpoints before the CA was made.
/// This allows indexing into the list of CPs, getting exactly the right one.
Scheduled(ScheduleId, u64),
/// CA uses an existing checkpoint ID which was recorded in the past.
Existing(CheckpointId),
}
/// Defines the record date, at which impact should be calculated,
/// along with checkpoint info to assess the impact at the date.
#[derive(
Copy,
Clone,
PartialEq,
Eq,
Encode,
Decode,
TypeInfo,
MaxEncodedLen,
Debug
)]
pub struct RecordDate {
/// When the impact should be calculated, or already has.
pub date: Moment,
/// Info used to determine the `CheckpointId` once `date` has passed.
pub checkpoint: CACheckpoint,
}
/// Input specification of the record date used to derive impact for a CA.
#[derive(
Copy,
Clone,
PartialEq,
Eq,
Encode,
Decode,
TypeInfo,
MaxEncodedLen,
Debug
)]
pub enum RecordDateSpec {
/// Record date is in the future.
/// A checkpoint should be created.
Scheduled(Moment),
/// A schedule already exists, infer record date from it.
ExistingSchedule(ScheduleId),
/// Checkpoint already exists, infer record date instead.
Existing(CheckpointId),
}
/// Details of a generic CA.
/// The `(AssetId, ID)` denoting a unique identifier for the CA is stored as a key outside.
#[derive(Clone, PartialEq, Eq, Encode, Decode, TypeInfo, Debug)]
pub struct CorporateAction {
/// The kind of CA that this is.
pub kind: CAKind,
/// When the CA was declared off-chain.
pub decl_date: Moment,
/// Date at which any impact, if any, should be calculated.
pub record_date: Option<RecordDate>,
/// The identities this CA is relevant to.
pub targets: TargetIdentities,
/// The default withholding tax at the time of CA creation.
/// For more on withholding tax, see the `DefaultWithholdingTax` storage item.
pub default_withholding_tax: Tax,
/// Any per-DID withholding tax overrides in relation to the default.
pub withholding_tax: Vec<(IdentityId, Tax)>,
}
impl CorporateAction {
/// Returns the tax of `did` in this CA.
fn tax_of(&self, did: &IdentityId) -> Tax {
// N.B. we maintain a sorted list to enable O(log n) access here.
self.withholding_tax
.binary_search_by_key(&did, |(did, _)| did)
.map(|idx| self.withholding_tax[idx].1)
.unwrap_or_else(|_| self.default_withholding_tax)
}
}
/// A `AssetId`-local CA ID.
/// By *local*, we mean that the same number might be used for a different `AssetId`
/// to uniquely identify a different CA.
#[derive(
Copy,
Clone,
PartialEq,
Eq,
Encode,
Decode,
TypeInfo,
MaxEncodedLen,
Default,
Debug
)]
pub struct LocalCAId(pub u32);
impl_checked_inc!(LocalCAId);
/// A unique global identifier for a CA.
#[derive(
Copy,
Clone,
PartialEq,
Eq,
Encode,
Decode,
TypeInfo,
MaxEncodedLen,
Debug
)]
pub struct CAId {
/// The `[`AssetId`]` component used to disambiguate the `local` one.
pub asset_id: AssetId,
/// The per-`AssetId` local identifier.
pub local_id: LocalCAId,
}
#[derive(Clone, PartialEq, Eq, Encode, Decode, TypeInfo, Debug)]
pub struct InitiateCorporateActionArgs {
asset_id: AssetId,
kind: CAKind,
decl_date: Moment,
record_date: Option<RecordDateSpec>,
details: CADetails,
targets: Option<TargetIdentities>,
default_withholding_tax: Option<Tax>,
withholding_tax: Option<Vec<(IdentityId, Tax)>>,
}
/// Weight abstraction for the corporate actions module.
pub trait WeightInfo {
fn set_max_details_length() -> Weight;
fn set_default_targets(i: u32) -> Weight;
fn set_default_withholding_tax() -> Weight;
fn set_did_withholding_tax(existing_overrides: u32) -> Weight;
fn initiate_corporate_action_use_defaults(whts: u32, target_ids: u32) -> Weight;
fn initiate_corporate_action_provided(whts: u32, target_ids: u32) -> Weight;
fn link_ca_doc(docs: u32) -> Weight;
fn remove_ca_with_ballot() -> Weight;
fn remove_ca_with_dist() -> Weight;
fn change_record_date_with_ballot() -> Weight;
fn change_record_date_with_dist() -> Weight;
}
type Asset<T> = pallet_asset::Pallet<T>;
type Ballot<T> = ballot::Pallet<T>;
type Checkpoint<T> = checkpoint::Pallet<T>;
type Distribution<T> = distribution::Pallet<T>;
type ExternalAgents<T> = pallet_external_agents::Pallet<T>;
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::{ValueQuery, *};
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config:
frame_system::Config
+ IdentityConfig
+ pallet_asset::Config
+ pallet_asset::checkpoint::Config
{
/// The overarching event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Max number of DID specified in `TargetIdentities`.
#[pallet::constant]
type MaxTargetIds: Get<u32>;
/// Max number of per-DID withholding tax overrides.
#[pallet::constant]
type MaxDidWhts: Get<u32>;
/// Weight information for extrinsics in the corporate actions pallet.
type WeightInfo: WeightInfo;
/// Weight information for extrinsics in the corporate ballot pallet.
type BallotWeightInfo: ballot::WeightInfo;
/// Weight information for extrinsics in the capital distribution pallet.
type DistWeightInfo: distribution::WeightInfo;
}
#[pallet::pallet]
pub struct Pallet<T>(_);
/// Determines the maximum number of bytes that the free-form `details` of a CA can store.
///
/// Note that this is not the number of `char`s or the number of [graphemes].
/// While this may be unnatural in terms of human understanding of a text's length,
/// it more closely reflects actual storage costs (`'a'` is cheaper to store than an emoji).
///
/// [graphemes]: https://en.wikipedia.org/wiki/Grapheme
#[pallet::storage]
pub type MaxDetailsLength<T> = StorageValue<_, u32, ValueQuery>;
/// The identities targeted by default for CAs for this asset,
/// either to be excluded or included.
///
/// (AssetId => target identities)
#[pallet::storage]
#[pallet::unbounded]
pub type DefaultTargetIdentities<T> =
StorageMap<_, Blake2_128Concat, AssetId, TargetIdentities, ValueQuery>;
/// The default amount of tax to withhold ("withholding tax", WT) for this asset when distributing dividends.
///
/// To understand withholding tax, e.g., let's assume that you hold ACME shares.
/// ACME now decides to distribute 100 SEK to Alice.
/// Alice lives in Sweden, so Skatteverket (the Swedish tax authority) wants 30% of that.
/// Then those 100 * 30% are withheld from Alice, and ACME will send them to Skatteverket.
///
/// (AssetId => % to withhold)
#[pallet::storage]
pub type DefaultWithholdingTax<T> = StorageMap<_, Blake2_128Concat, AssetId, Tax, ValueQuery>;
/// The amount of tax to withhold ("withholding tax", WT) for a certain AssetId x DID.
/// If an entry exists for a certain DID, it overrides the default in `DefaultWithholdingTax`.
///
/// (AssetId => [(did, % to withhold)]
#[pallet::storage]
#[pallet::unbounded]
pub type DidWithholdingTax<T> =
StorageMap<_, Blake2_128Concat, AssetId, Vec<(IdentityId, Tax)>, ValueQuery>;
/// The next per-`AssetId` CA ID in the sequence.
/// The full ID is defined as a combination of `AssetId` and a number in this sequence.
#[pallet::storage]
pub type CAIdSequence<T> = StorageMap<_, Blake2_128Concat, AssetId, LocalCAId, ValueQuery>;
/// All recorded CAs thus far.
/// Only generic information is stored here.
/// Specific `CAKind`s, e.g., benefits and corporate ballots, may use additional on-chain storage.
///
/// (AssetId => local ID => the corporate action)
#[pallet::storage]
#[pallet::unbounded]
pub type CorporateActions<T> = StorageDoubleMap<
_,
Blake2_128Concat,
AssetId,
Twox64Concat,
LocalCAId,
CorporateAction,
OptionQuery,
>;
/// Associations from CAs to `Document`s via their IDs.
/// (CAId => [DocumentId])
///
/// The `CorporateActions` map stores `AssetId => LocalId => The CA`,
/// so we can infer `AssetId => CAId`. Therefore, we don't need a double map.
#[pallet::storage]
#[pallet::unbounded]
pub type CADocLink<T> = StorageMap<_, Blake2_128Concat, CAId, Vec<DocumentId>, ValueQuery>;
/// Associates details in free-form text with a CA by its ID.
/// (CAId => CADetails)
#[pallet::storage]
#[pallet::unbounded]
pub type Details<T> = StorageMap<_, Blake2_128Concat, CAId, CADetails, ValueQuery>;
/// Storage version.
#[pallet::storage]
pub(super) type StorageVersion<T: Config> = StorageValue<_, Version, ValueQuery>;
#[pallet::genesis_config]
#[derive(Default)]
pub struct GenesisConfig {
pub max_details_length: u32,
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
StorageVersion::<T>::put(Version::new(1));
MaxDetailsLength::<T>::put(self.max_details_length);
}
}
#[pallet::call]
impl<T: Config> Pallet<T>
where
T: CAConfig,
{
/// Set the max `length` of `details` in terms of bytes.
/// May only be called via a PIP.
#[pallet::weight(<T as Config>::WeightInfo::set_max_details_length())]
#[pallet::call_index(0)]
pub fn set_max_details_length(origin: OriginFor<T>, length: u32) -> DispatchResult {
ensure_root(origin)?;
MaxDetailsLength::<T>::put(length);
Self::deposit_event(Event::MaxDetailsLengthChanged(GC_DID, length));
Ok(())
}
/// Set the default CA `TargetIdentities` to `targets`.
///
/// ## Arguments
/// - `origin` which must be an external agent of `asset_id` with relevant permissions.
/// - `asset_id` for which the default identities are changing.
/// - `targets` the default target identities for a CA.
///
/// ## Errors
/// - `UnauthorizedAgent` if `origin` is not agent-permissioned for `asset_id`.
/// - `TooManyTargetIds` if `targets.identities.len() > T::MaxTargetIds::get()`.
///
/// # Permissions
/// * Asset
#[pallet::weight(<T as Config>::WeightInfo::set_default_targets(targets.identities.len() as u32))]
#[pallet::call_index(1)]
pub fn set_default_targets(
origin: OriginFor<T>,
asset_id: AssetId,
targets: TargetIdentities,
) -> DispatchResult {
let agent = <ExternalAgents<T>>::ensure_perms(origin, asset_id)?;
Self::ensure_target_ids_limited(&targets)?;
// Dedup + sort any DIDs in `targets` for `O(log n)` containment check later.
let new = targets.dedup();
// Commit + emit event.
DefaultTargetIdentities::<T>::mutate(asset_id, |slot| *slot = new.clone());
Self::deposit_event(Event::DefaultTargetIdentitiesChanged(agent, asset_id, new));
Ok(())
}
/// Set the default withholding tax for all DIDs and CAs relevant to this `asset_id`.
///
/// ## Arguments
/// - `origin` which must be an external agent of `asset_id` with relevant permissions.
/// - `asset_id` that the withholding tax will apply to.
/// - `tax` that should be withheld when distributing dividends, etc.
///
/// ## Errors
/// - `UnauthorizedAgent` if `origin` is not agent-permissioned for `asset_id`.
///
/// # Permissions
/// * Asset
#[pallet::weight(<T as Config>::WeightInfo::set_default_withholding_tax())]
#[pallet::call_index(2)]
pub fn set_default_withholding_tax(
origin: OriginFor<T>,
asset_id: AssetId,
tax: Tax,
) -> DispatchResult {
let agent = <ExternalAgents<T>>::ensure_perms(origin, asset_id)?;
DefaultWithholdingTax::<T>::mutate(asset_id, |slot| *slot = tax);
Self::deposit_event(Event::DefaultWithholdingTaxChanged(agent, asset_id, tax));
Ok(())
}
/// Set the withholding tax of `asset_id` for `taxed_did` to `tax`.
/// If `Some(tax)`, this overrides the default withholding tax of `asset_id` to `tax` for `taxed_did`.
/// Otherwise, if `None`, the default withholding tax will be used.
///
/// ## Arguments
/// - `origin` which must be an external agent of `asset_id` with relevant permissions.
/// - `asset_id` that the withholding tax will apply to.
/// - `taxed_did` that will have its withholding tax updated.
/// - `tax` that should be withheld when distributing dividends, etc.
///
/// ## Errors
/// - `UnauthorizedAgent` if `origin` is not agent-permissioned for `asset_id`.
/// - `TooManyDidTaxes` if `Some(tax)` and adding the override would go over the limit `MaxDidWhts`.
///
/// # Permissions
/// * Asset
#[pallet::weight(<T as Config>::WeightInfo::set_did_withholding_tax(T::MaxDidWhts::get()))]
#[pallet::call_index(3)]
pub fn set_did_withholding_tax(
origin: OriginFor<T>,
asset_id: AssetId,
taxed_did: IdentityId,
tax: Option<Tax>,
) -> DispatchResult {
let agent = <ExternalAgents<T>>::ensure_perms(origin, asset_id)?;
DidWithholdingTax::<T>::try_mutate(asset_id, |whts| -> DispatchResult {
// We maintain sorted order, so we get O(log n) search but O(n) insertion/deletion.
// This is maintained to get O(log n) in capital distribution.
match (tax, whts.binary_search_by_key(&taxed_did, |(did, _)| *did)) {
(Some(tax), Ok(idx)) => whts[idx] = (taxed_did, tax),
(Some(tax), Err(idx)) => {
Self::ensure_did_whts_limited(whts.len() + 1)?;
whts.insert(idx, (taxed_did, tax))
}
(None, Ok(idx)) => drop(whts.remove(idx)),
(None, Err(_)) => {}
}
Ok(())
})?;
Self::deposit_event(Event::DidWithholdingTaxChanged(
agent, asset_id, taxed_did, tax,
));
Ok(())
}
/// Initiates a CA for `asset_id` of `kind` with `details` and other provided arguments.
///
/// ## Arguments
/// - `origin` which must be an external agent of `asset_id` with relevant permissions.
/// - `asset_id` that the CA is made for.
/// - `kind` of CA being initiated.
/// - `decl_date` of CA bring initialized.
/// - `record_date`, if any, to calculate the impact of this CA.
/// If provided, this results in a scheduled balance snapshot ("checkpoint") at the date.
/// - `details` of the CA in free-text form, up to a certain number of bytes in length.
/// - `targets`, if any, which this CA is relevant/irrelevant to.
/// Overrides, if provided, the default at the asset level (`set_default_targets`).
/// - `default_withholding_tax`, if any, is the default withholding tax to use for this CA.
/// Overrides, if provided, the default at the asset level (`set_default_withholding_tax`).
/// - `withholding_tax`, if any, provides per-DID withholding tax overrides.
/// Overrides, if provided, the default at the asset level (`set_did_withholding_tax`).
///
/// # Errors
/// - `DetailsTooLong` if `details.len()` goes beyond `max_details_length`.
/// - `UnauthorizedAgent` if `origin` is not agent-permissioned for `asset_id`.
/// - `CounterOverflow` in the unlikely event that so many CAs were created for this `asset_id`,
/// that integer overflow would have occured if instead allowed.
/// - `TooManyDidTaxes` if `withholding_tax.unwrap().len()` would go over the limit `MaxDidWhts`.
/// - `DuplicateDidTax` if a DID is included more than once in `wt`.
/// - `TooManyTargetIds` if `targets.unwrap().identities.len() > T::MaxTargetIds::get()`.
/// - `DeclDateInFuture` if the declaration date is not in the past.
/// - When `record_date.is_some()`, other errors due to checkpoint scheduling may occur.
///
/// # Permissions
/// * Asset
#[pallet::weight(initiate_corporate_action_weight::<T>(targets, withholding_tax))]
#[pallet::call_index(4)]
pub fn initiate_corporate_action(
origin: OriginFor<T>,
asset_id: AssetId,
kind: CAKind,
decl_date: Moment,
record_date: Option<RecordDateSpec>,
details: CADetails,
targets: Option<TargetIdentities>,
default_withholding_tax: Option<Tax>,
withholding_tax: Option<Vec<(IdentityId, Tax)>>,
) -> DispatchResult {
// Ensure that a permissioned agent is calling.
let caller_did = <ExternalAgents<T>>::ensure_perms(origin, asset_id)?;
Self::unsafe_initiate_corporate_action(
caller_did,
asset_id,
kind,
decl_date,
record_date,
details,
targets,
default_withholding_tax,
withholding_tax,
)
.map(drop)
}
/// Link the given CA `id` to the given `docs`.
/// Any previous links for the CA are removed in favor of `docs`.
///
/// The workflow here is to add the documents and initiating the CA in any order desired.
/// Once both exist, they can now be linked together.
///
/// ## Arguments
/// - `origin` which must be an external agent of `id.asset_id` with relevant permissions.
/// - `id` of the CA to associate with `docs`.
/// - `docs` to associate with the CA with `id`.
///
/// # Errors
/// - `UnauthorizedAgent` if `origin` is not agent-permissioned for `asset_id`.
/// - `NoSuchCA` if `id` does not identify an existing CA.
/// - `NoSuchDoc` if any of `docs` does not identify an existing document.
///
/// # Permissions
/// * Asset
#[pallet::weight(<T as Config>::WeightInfo::link_ca_doc(docs.len() as u32))]
#[pallet::call_index(5)]
pub fn link_ca_doc(
origin: OriginFor<T>,
id: CAId,
docs: Vec<DocumentId>,
) -> DispatchResult {
// Ensure that a permissioned agent is calling and that CA and the docs exists.
let agent = <ExternalAgents<T>>::ensure_perms(origin, id.asset_id)?;
Self::ensure_ca_exists(id)?;
for doc in &docs {
<Asset<T>>::ensure_doc_exists(&id.asset_id, doc)?;
}
// Add the link and emit event.
CADocLink::<T>::mutate(id, |slot| *slot = docs.clone());
Self::deposit_event(Event::CALinkedToDoc(agent, id, docs));
Ok(())
}
/// Removes the CA identified by `ca_id`.
///
/// Associated data, such as document links, ballots,
/// and capital distributions are also removed.
///
/// Any schedule associated with the record date will see
/// `strong_ref_count(schedule_id)` decremented.
///
/// ## Arguments
/// - `origin` which must be an external agent of `ca_id.asset_id` with relevant permissions.
/// - `ca_id` of the CA to remove.
///
/// # Errors
/// - `UnauthorizedAgent` if `origin` is not agent-permissioned for `asset_id`.
/// - `NoSuchCA` if `id` does not identify an existing CA.
///
/// # Permissions
/// * Asset
#[pallet::weight(<T as Config>::WeightInfo::remove_ca_with_ballot()
.max(<T as Config>::WeightInfo::remove_ca_with_dist()))]
#[pallet::call_index(6)]
pub fn remove_ca(origin: OriginFor<T>, ca_id: CAId) -> DispatchResult {
// Ensure origin is a permissioned agent + CA exists.
let agent = <ExternalAgents<T>>::ensure_perms(origin, ca_id.asset_id)?.for_event();
let ca = Self::ensure_ca_exists(ca_id)?;
// Remove associated services.
match ca.kind {
CAKind::Other | CAKind::Reorganization => {}
CAKind::IssuerNotice => {
if let Some(range) = TimeRanges::<T>::get(ca_id) {
<Ballot<T>>::remove_ballot_base(agent, ca_id, range)?;
}
}
CAKind::PredictableBenefit | CAKind::UnpredictableBenefit => {
if let Some(dist) = Distributions::<T>::get(ca_id) {
<Distribution<T>>::unverified_remove_distribution(agent, ca_id, &dist)?;
}
}
}
// Decrement, Remove, and Emit event.
Self::dec_strong_ref_count(ca_id, ca.record_date);
CorporateActions::<T>::remove(ca_id.asset_id, ca_id.local_id);
CADocLink::<T>::remove(ca_id);
Details::<T>::remove(ca_id);
Self::deposit_event(Event::CARemoved(agent, ca_id));
Ok(())
}
/// Changes the record date of the CA identified by `ca_id`.
///
/// ## Arguments
/// - `origin` which must be an external agent of `ca_id.asset_id` with relevant permissions.
/// - `ca_id` of the CA to alter.
/// - `record_date`, if any, to calculate the impact of the CA.
/// If provided, this results in a scheduled balance snapshot ("checkpoint") at the date.
///
/// # Errors
/// - `UnauthorizedAgent` if `origin` is not agent-permissioned for `asset_id`.
/// - `NoSuchCA` if `id` does not identify an existing CA.
/// - When `record_date.is_some()`, other errors due to checkpoint scheduling may occur.
///
/// # Permissions
/// * Asset
#[pallet::weight(<T as Config>::WeightInfo::change_record_date_with_ballot()
.max(<T as Config>::WeightInfo::change_record_date_with_dist()))]
#[pallet::call_index(7)]
pub fn change_record_date(
origin: OriginFor<T>,
ca_id: CAId,
record_date: Option<RecordDateSpec>,
) -> DispatchResult {
// Ensure origin is a permissioned agent + CA exists.
let caller_did = <ExternalAgents<T>>::ensure_perms(origin, ca_id.asset_id)?;
let agent = caller_did.for_event();
let mut ca = Self::ensure_ca_exists(ca_id)?;
// If provided, either use the existing CP ID or schedule one to be made.
Self::dec_strong_ref_count(ca_id, ca.record_date);
ca.record_date = record_date
.map(|date| Self::handle_record_date(caller_did, ca_id.asset_id, date))
.transpose()?;
// Ensure associated services allow changing the date.
match ca.kind {
CAKind::Other | CAKind::Reorganization => {}
CAKind::IssuerNotice => {
if let Some(range) = TimeRanges::<T>::get(ca_id) {
Self::ensure_record_date_before_start(&ca, range.start)?;
<Ballot<T>>::ensure_ballot_not_started(range)?;
}
}
CAKind::PredictableBenefit | CAKind::UnpredictableBenefit => {
if let Some(dist) = Distributions::<T>::get(ca_id) {
Self::ensure_record_date_before_start(&ca, dist.payment_at)?;
<Distribution<T>>::ensure_distribution_not_started(&dist)?;
}
}
}
// Commit changes + emit event.
CorporateActions::<T>::insert(ca_id.asset_id, ca_id.local_id, ca.clone());
Self::deposit_event(Event::RecordDateChanged(agent, ca_id, ca));
Ok(())
}
/// Utility extrinsic to batch `initiate_corporate_action` and `distribute`
#[pallet::weight(initiate_corporate_action_weight::<T>(&ca_args.targets, &ca_args.withholding_tax)
.saturating_add(<T as Config>::DistWeightInfo::distribute()))]
#[pallet::call_index(8)]
pub fn initiate_corporate_action_and_distribute(
origin: OriginFor<T>,
ca_args: InitiateCorporateActionArgs,
portfolio: Option<PortfolioNumber>,
currency: AssetId,
per_share: Balance,
amount: Balance,
payment_at: Moment,
expires_at: Option<Moment>,
) -> DispatchResult {
let InitiateCorporateActionArgs {
asset_id,
kind,
decl_date,
record_date,
details,
targets,
default_withholding_tax,
withholding_tax,
} = ca_args;
let PermissionedCallOriginData {
primary_did: caller_did,
secondary_key,
..
} = <ExternalAgents<T>>::ensure_agent_asset_perms(origin, asset_id)?;
let ca_id = Self::unsafe_initiate_corporate_action(
caller_did,
asset_id,
kind,
decl_date,
record_date,
details,
targets,
default_withholding_tax,
withholding_tax,
)?;
<distribution::Pallet<T>>::unverified_distribute(
caller_did,
secondary_key,
ca_id,
portfolio,
currency,
per_share,
amount,
payment_at,
expires_at,
)?;
Ok(())
}
#[pallet::weight(initiate_corporate_action_weight::<T>(&ca_args.targets, &ca_args.withholding_tax)
.saturating_add(<T as Config>::BallotWeightInfo::attach_ballot(ballot_meta.saturating_num_choices())))]
#[pallet::call_index(9)]
pub fn initiate_corporate_action_and_ballot(
origin: OriginFor<T>,
ca_args: InitiateCorporateActionArgs,
ballot_time_range: BallotTimeRange,
ballot_meta: BallotMeta,
rcv: bool,
) -> DispatchResult {
// Ensure that the caller is a permissioned agent
let caller_did = ExternalAgents::<T>::ensure_perms(origin, ca_args.asset_id)?;
let ca_id = Self::unsafe_initiate_corporate_action(
caller_did,
ca_args.asset_id,
ca_args.kind,
ca_args.decl_date,
ca_args.record_date,
ca_args.details,
ca_args.targets,
ca_args.default_withholding_tax,
ca_args.withholding_tax,
)?;
let motion_choices = ballot::Pallet::<T>::validate_ballot_creation_rules(
ca_id,
ballot_time_range,
&ballot_meta,
)?;
ballot::Pallet::<T>::unverified_create_ballot(
caller_did,
ca_id,
motion_choices,
ballot_time_range,
ballot_meta,
rcv,
)?;
Ok(())
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// The maximum length of `details` in bytes was changed.
/// (GC DID, new length)
MaxDetailsLengthChanged(IdentityId, u32),
/// The set of default `TargetIdentities` for the asset changed.
/// (Agent DID, AssetId, New TargetIdentities)
DefaultTargetIdentitiesChanged(IdentityId, AssetId, TargetIdentities),
/// The default withholding tax for the asset changed.
/// (Agent DID, AssetId, New Tax).
DefaultWithholdingTaxChanged(IdentityId, AssetId, Tax),
/// The withholding tax specific to a DID for the asset changed.
/// (Agent DID, AssetId, Taxed DID, New Tax).
DidWithholdingTaxChanged(IdentityId, AssetId, IdentityId, Option<Tax>),
/// A CA was initiated.
/// (Agent DID, CA id, the CA, the CA details)
CAInitiated(EventDid, CAId, CorporateAction, CADetails),
/// A CA was linked to a set of docs.
/// (Agent DID, CA Id, List of doc identifiers)
CALinkedToDoc(IdentityId, CAId, Vec<DocumentId>),
/// A CA was removed.
/// (Agent DID, CA Id)
CARemoved(EventDid, CAId),
/// A CA's record date changed.
RecordDateChanged(EventDid, CAId, CorporateAction),
}
#[pallet::error]
pub enum Error<T> {
/// The `details` of a CA exceeded the max allowed length.
DetailsTooLong,
/// A withholding tax override for a given DID was specified more than once.
/// The chain refused to make a choice, and hence there was an error.
DuplicateDidTax,
/// Too many withholding tax overrides were specified.
TooManyDidTaxes,
/// Too many identities in `TargetIdentities` were specified.
TooManyTargetIds,
/// On CA creation, a checkpoint ID was provided which doesn't exist.
NoSuchCheckpointId,
/// A CA with the given `CAId` did not exist.