@dfinity/cmc 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2021 DFINITY LLC.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,97 @@
1
+ # cmc-js
2
+
3
+ A library for interfacing with the cycle minting canister.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@dfinity/cmc.svg?logo=npm)](https://www.npmjs.com/package/@dfinity/cmc) [![GitHub license](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
6
+
7
+ ## Table of contents
8
+
9
+ - [Installation](#installation)
10
+ - [Usage](#usage)
11
+ - [Features](#features)
12
+
13
+ ## Installation
14
+
15
+ You can use `cmc-js` by installing it in your project.
16
+
17
+ ```bash
18
+ npm i @dfinity/cmc
19
+ ```
20
+
21
+ The bundle needs peer dependencies, be sure that following resources are available in your project as well.
22
+
23
+ ```bash
24
+ npm i @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ The features are available through the class `CMCCanister`. It has to be instantiated with the canister ID of the cycles minting canister. On `mainnet`, its ID is `rkp4c-7iaaa-aaaaa-aaaca-cai`.
30
+
31
+ e.g. querying the current Icp to cycles conversion rate.
32
+
33
+ ```ts
34
+ import { CMCCanister } from "@dfinity/cmc";
35
+ import { createAgent } from "@dfinity/utils";
36
+
37
+ const agent = await createAgent({
38
+ identity,
39
+ host: HOST,
40
+ });
41
+
42
+ const { getIcpToCyclesConversionRate } = CMCCanister.create({
43
+ agent,
44
+ canisterId: CYCLES_MINTING_CANISTER_ID,
45
+ });
46
+
47
+ const rate = await getIcpToCyclesConversionRate();
48
+ ```
49
+
50
+ ## Features
51
+
52
+ `cmc-js` implements following features:
53
+
54
+ <!-- TSDOC_START -->
55
+
56
+ ### :factory: CMCCanister
57
+
58
+ #### Methods
59
+
60
+ - [create](#gear-create)
61
+ - [getIcpToCyclesConversionRate](#gear-geticptocyclesconversionrate)
62
+ - [notifyCreateCanister](#gear-notifycreatecanister)
63
+ - [notifyTopUp](#gear-notifytopup)
64
+
65
+ ##### :gear: create
66
+
67
+ | Method | Type |
68
+ | -------- | ---------------------------------------------- |
69
+ | `create` | `(options: CMCCanisterOptions) => CMCCanister` |
70
+
71
+ ##### :gear: getIcpToCyclesConversionRate
72
+
73
+ Returns conversion rate of ICP to Cycles
74
+
75
+ | Method | Type |
76
+ | ------------------------------ | ----------------------- |
77
+ | `getIcpToCyclesConversionRate` | `() => Promise<bigint>` |
78
+
79
+ ##### :gear: notifyCreateCanister
80
+
81
+ Notifies Cycles Minting Canister of the creation of a new canister.
82
+ It returns the new canister principal.
83
+
84
+ | Method | Type |
85
+ | ---------------------- | ---------------------------------------------------------- |
86
+ | `notifyCreateCanister` | `(request: NotifyCreateCanisterArg) => Promise<Principal>` |
87
+
88
+ ##### :gear: notifyTopUp
89
+
90
+ Notifies Cycles Minting Canister of new cycles being added to canister.
91
+ It returns the new Cycles of the canister.
92
+
93
+ | Method | Type |
94
+ | ------------- | ---------------------------------------------- |
95
+ | `notifyTopUp` | `(request: NotifyTopUpArg) => Promise<bigint>` |
96
+
97
+ <!-- TSDOC_END -->
@@ -0,0 +1,2 @@
1
+ import type { IDL } from "@dfinity/candid";
2
+ export const idlFactory: IDL.InterfaceFactory;
@@ -0,0 +1,63 @@
1
+ /* Do not edit. Compiled with ./scripts/compile-idl-js from packages/cmc/candid/cmc.did */
2
+ export const idlFactory = ({ IDL }) => {
3
+ const IcpXdrConversionRate = IDL.Record({
4
+ 'xdr_permyriad_per_icp' : IDL.Nat64,
5
+ 'timestamp_seconds' : IDL.Nat64,
6
+ });
7
+ const IcpXdrConversionRateResponse = IDL.Record({
8
+ 'certificate' : IDL.Vec(IDL.Nat8),
9
+ 'data' : IcpXdrConversionRate,
10
+ 'hash_tree' : IDL.Vec(IDL.Nat8),
11
+ });
12
+ const SubnetTypesToSubnetsResponse = IDL.Record({
13
+ 'data' : IDL.Vec(IDL.Tuple(IDL.Text, IDL.Vec(IDL.Principal))),
14
+ });
15
+ const BlockIndex = IDL.Nat64;
16
+ const NotifyCreateCanisterArg = IDL.Record({
17
+ 'controller' : IDL.Principal,
18
+ 'block_index' : BlockIndex,
19
+ 'subnet_type' : IDL.Opt(IDL.Text),
20
+ });
21
+ const NotifyError = IDL.Variant({
22
+ 'Refunded' : IDL.Record({
23
+ 'block_index' : IDL.Opt(BlockIndex),
24
+ 'reason' : IDL.Text,
25
+ }),
26
+ 'InvalidTransaction' : IDL.Text,
27
+ 'Other' : IDL.Record({
28
+ 'error_message' : IDL.Text,
29
+ 'error_code' : IDL.Nat64,
30
+ }),
31
+ 'Processing' : IDL.Null,
32
+ 'TransactionTooOld' : BlockIndex,
33
+ });
34
+ const NotifyCreateCanisterResult = IDL.Variant({
35
+ 'Ok' : IDL.Principal,
36
+ 'Err' : NotifyError,
37
+ });
38
+ const NotifyTopUpArg = IDL.Record({
39
+ 'block_index' : BlockIndex,
40
+ 'canister_id' : IDL.Principal,
41
+ });
42
+ const Cycles = IDL.Nat;
43
+ const NotifyTopUpResult = IDL.Variant({ 'Ok' : Cycles, 'Err' : NotifyError });
44
+ return IDL.Service({
45
+ 'get_icp_xdr_conversion_rate' : IDL.Func(
46
+ [],
47
+ [IcpXdrConversionRateResponse],
48
+ [],
49
+ ),
50
+ 'get_subnet_types_to_subnets' : IDL.Func(
51
+ [],
52
+ [SubnetTypesToSubnetsResponse],
53
+ [],
54
+ ),
55
+ 'notify_create_canister' : IDL.Func(
56
+ [NotifyCreateCanisterArg],
57
+ [NotifyCreateCanisterResult],
58
+ [],
59
+ ),
60
+ 'notify_top_up' : IDL.Func([NotifyTopUpArg], [NotifyTopUpResult], []),
61
+ });
62
+ };
63
+ export const init = ({ IDL }) => { return []; };
@@ -0,0 +1,47 @@
1
+ import type { ActorMethod } from "@dfinity/agent";
2
+ import type { Principal } from "@dfinity/principal";
3
+
4
+ export type BlockIndex = bigint;
5
+ export type Cycles = bigint;
6
+ export interface IcpXdrConversionRate {
7
+ xdr_permyriad_per_icp: bigint;
8
+ timestamp_seconds: bigint;
9
+ }
10
+ export interface IcpXdrConversionRateResponse {
11
+ certificate: Uint8Array;
12
+ data: IcpXdrConversionRate;
13
+ hash_tree: Uint8Array;
14
+ }
15
+ export interface NotifyCreateCanisterArg {
16
+ controller: Principal;
17
+ block_index: BlockIndex;
18
+ subnet_type: [] | [string];
19
+ }
20
+ export type NotifyCreateCanisterResult =
21
+ | { Ok: Principal }
22
+ | { Err: NotifyError };
23
+ export type NotifyError =
24
+ | {
25
+ Refunded: { block_index: [] | [BlockIndex]; reason: string };
26
+ }
27
+ | { InvalidTransaction: string }
28
+ | { Other: { error_message: string; error_code: bigint } }
29
+ | { Processing: null }
30
+ | { TransactionTooOld: BlockIndex };
31
+ export interface NotifyTopUpArg {
32
+ block_index: BlockIndex;
33
+ canister_id: Principal;
34
+ }
35
+ export type NotifyTopUpResult = { Ok: Cycles } | { Err: NotifyError };
36
+ export interface SubnetTypesToSubnetsResponse {
37
+ data: Array<[string, Array<Principal>]>;
38
+ }
39
+ export interface _SERVICE {
40
+ get_icp_xdr_conversion_rate: ActorMethod<[], IcpXdrConversionRateResponse>;
41
+ get_subnet_types_to_subnets: ActorMethod<[], SubnetTypesToSubnetsResponse>;
42
+ notify_create_canister: ActorMethod<
43
+ [NotifyCreateCanisterArg],
44
+ NotifyCreateCanisterResult
45
+ >;
46
+ notify_top_up: ActorMethod<[NotifyTopUpArg], NotifyTopUpResult>;
47
+ }
@@ -0,0 +1,116 @@
1
+ // Generated from IC repo commit 6e2d9e9a3ff2a3ae4854d9eea8c9337fd1f77415 'rs/nns/cmc/cmc.did' by import-candid
2
+ type Cycles = nat;
3
+ type BlockIndex = nat64;
4
+
5
+ // The argument of the [notify_top_up] method.
6
+ type NotifyTopUpArg = record {
7
+ // Index of the block on the ICP ledger that contains the payment.
8
+ block_index : BlockIndex;
9
+
10
+ // The canister to top up.
11
+ canister_id : principal;
12
+ };
13
+
14
+ // The argument of the [notify_create_canister] method.
15
+ type NotifyCreateCanisterArg = record {
16
+ // Index of the block on the ICP ledger that contains the payment.
17
+ block_index : BlockIndex;
18
+
19
+ // The controller of canister to create.
20
+ controller : principal;
21
+
22
+ // An optional subnet type that, if set, determines what type of subnet
23
+ // the new canister will be created on.
24
+ subnet_type: opt text;
25
+ };
26
+
27
+ type NotifyError = variant {
28
+ // The payment processing failed and the payment was returned the caller.
29
+ // This is a non-retriable error.
30
+ Refunded : record {
31
+ // The reason for the refund.
32
+ reason : text;
33
+ // The index of the block containing the refund.
34
+ block_index : opt BlockIndex;
35
+ };
36
+
37
+ // The same payment is already being processed by a concurrent request.
38
+ // This is a retriable error.
39
+ Processing;
40
+
41
+ // The payment was too old to be processed.
42
+ // The value of the variant is the oldest block index that can still be processed.
43
+ // This a non-retriable error.
44
+ TransactionTooOld : BlockIndex;
45
+
46
+ // The transaction does not satisfy the cycle minting canister payment protocol.
47
+ // The text contains the description of the problem.
48
+ // This is a non-retriable error.
49
+ InvalidTransaction : text;
50
+
51
+ // Other error.
52
+ Other : record { error_code : nat64; error_message : text };
53
+ };
54
+
55
+ type NotifyTopUpResult = variant {
56
+ // The amount of cycles sent to the specified canister.
57
+ Ok : Cycles;
58
+ Err : NotifyError;
59
+ };
60
+
61
+ type NotifyCreateCanisterResult = variant {
62
+ // The principal of the newly created canister.
63
+ Ok : principal;
64
+ Err : NotifyError;
65
+ };
66
+
67
+ type IcpXdrConversionRate = record {
68
+ // The time for which the market data was queried, expressed in UNIX epoch
69
+ // time in seconds.
70
+ timestamp_seconds : nat64;
71
+
72
+ // The number of 10,000ths of IMF SDR (currency code XDR) that corresponds
73
+ // to 1 ICP. This value reflects the current market price of one ICP token.
74
+ xdr_permyriad_per_icp : nat64;
75
+ };
76
+
77
+
78
+ type IcpXdrConversionRateResponse = record {
79
+ // The latest ICP/XDR conversion rate.
80
+ data : IcpXdrConversionRate;
81
+
82
+ // CBOR-serialized hash tree as specified in
83
+ // https://smartcontracts.org/docs/interface-spec/index.html#certification-encoding.
84
+ // The hash tree is used for certification and hash the following structure:
85
+ // ```
86
+ // *
87
+ // |
88
+ // +-- ICP_XDR_CONVERSION_RATE -- [ Candid encoded IcpXdrConversionRate ]
89
+ // |
90
+ // `-- AVERAGE_ICP_XDR_CONVERSION_RATE -- [ Candid encoded IcpXdrConversionRate ]
91
+ // ```
92
+ hash_tree : blob;
93
+
94
+ // System certificate as specified in
95
+ // https://smartcontracts.org/docs/interface-spec/index.html#certification-encoding
96
+ certificate : blob;
97
+ };
98
+
99
+ type SubnetTypesToSubnetsResponse = record {
100
+ data: vec record { text; vec principal };
101
+ }
102
+
103
+ service : {
104
+ // Propmts the cycles minting canister to process a payment by converting ICP
105
+ // into cycles and sending the cycles the specified canister.
106
+ notify_top_up : (NotifyTopUpArg) -> (NotifyTopUpResult);
107
+
108
+ // Prompts the cycles minting canister to process a payment for canister creation.
109
+ notify_create_canister : (NotifyCreateCanisterArg) -> (NotifyCreateCanisterResult);
110
+
111
+ // Returns the ICP/XDR conversion rate.
112
+ get_icp_xdr_conversion_rate : () -> (IcpXdrConversionRateResponse) query;
113
+
114
+ // Returns the current mapping of subnet types to subnets.
115
+ get_subnet_types_to_subnets : () -> (SubnetTypesToSubnetsResponse) query;
116
+ }
@@ -0,0 +1,2 @@
1
+ import type { IDL } from "@dfinity/candid";
2
+ export const idlFactory: IDL.InterfaceFactory;
@@ -0,0 +1,63 @@
1
+ /* Do not edit. Compiled with ./scripts/compile-idl-js from packages/cmc/candid/cmc.did */
2
+ export const idlFactory = ({ IDL }) => {
3
+ const IcpXdrConversionRate = IDL.Record({
4
+ 'xdr_permyriad_per_icp' : IDL.Nat64,
5
+ 'timestamp_seconds' : IDL.Nat64,
6
+ });
7
+ const IcpXdrConversionRateResponse = IDL.Record({
8
+ 'certificate' : IDL.Vec(IDL.Nat8),
9
+ 'data' : IcpXdrConversionRate,
10
+ 'hash_tree' : IDL.Vec(IDL.Nat8),
11
+ });
12
+ const SubnetTypesToSubnetsResponse = IDL.Record({
13
+ 'data' : IDL.Vec(IDL.Tuple(IDL.Text, IDL.Vec(IDL.Principal))),
14
+ });
15
+ const BlockIndex = IDL.Nat64;
16
+ const NotifyCreateCanisterArg = IDL.Record({
17
+ 'controller' : IDL.Principal,
18
+ 'block_index' : BlockIndex,
19
+ 'subnet_type' : IDL.Opt(IDL.Text),
20
+ });
21
+ const NotifyError = IDL.Variant({
22
+ 'Refunded' : IDL.Record({
23
+ 'block_index' : IDL.Opt(BlockIndex),
24
+ 'reason' : IDL.Text,
25
+ }),
26
+ 'InvalidTransaction' : IDL.Text,
27
+ 'Other' : IDL.Record({
28
+ 'error_message' : IDL.Text,
29
+ 'error_code' : IDL.Nat64,
30
+ }),
31
+ 'Processing' : IDL.Null,
32
+ 'TransactionTooOld' : BlockIndex,
33
+ });
34
+ const NotifyCreateCanisterResult = IDL.Variant({
35
+ 'Ok' : IDL.Principal,
36
+ 'Err' : NotifyError,
37
+ });
38
+ const NotifyTopUpArg = IDL.Record({
39
+ 'block_index' : BlockIndex,
40
+ 'canister_id' : IDL.Principal,
41
+ });
42
+ const Cycles = IDL.Nat;
43
+ const NotifyTopUpResult = IDL.Variant({ 'Ok' : Cycles, 'Err' : NotifyError });
44
+ return IDL.Service({
45
+ 'get_icp_xdr_conversion_rate' : IDL.Func(
46
+ [],
47
+ [IcpXdrConversionRateResponse],
48
+ ['query'],
49
+ ),
50
+ 'get_subnet_types_to_subnets' : IDL.Func(
51
+ [],
52
+ [SubnetTypesToSubnetsResponse],
53
+ ['query'],
54
+ ),
55
+ 'notify_create_canister' : IDL.Func(
56
+ [NotifyCreateCanisterArg],
57
+ [NotifyCreateCanisterResult],
58
+ [],
59
+ ),
60
+ 'notify_top_up' : IDL.Func([NotifyTopUpArg], [NotifyTopUpResult], []),
61
+ });
62
+ };
63
+ export const init = ({ IDL }) => { return []; };
@@ -0,0 +1,2 @@
1
+ "use strict";var f=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var T=(t,e)=>{for(var r in e)f(t,r,{get:e[r],enumerable:!0})},O=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of h(e))!E.call(t,o)&&o!==r&&f(t,o,{get:()=>e[o],enumerable:!(i=g(e,o))||i.enumerable});return t};var R=t=>O(f({},"__esModule",{value:!0}),t);var v={};T(v,{CMCCanister:()=>n,CMCError:()=>a,InvalidaTransactionError:()=>c,ProcessingError:()=>p,RefundedError:()=>s,TransactionTooOldError:()=>d,throwNotifyError:()=>y});module.exports=R(v);var u=require("@dfinity/agent");var _=({IDL:t})=>{let e=t.Record({xdr_permyriad_per_icp:t.Nat64,timestamp_seconds:t.Nat64}),r=t.Record({certificate:t.Vec(t.Nat8),data:e,hash_tree:t.Vec(t.Nat8)}),i=t.Record({data:t.Vec(t.Tuple(t.Text,t.Vec(t.Principal)))}),o=t.Nat64,m=t.Record({controller:t.Principal,block_index:o,subnet_type:t.Opt(t.Text)}),l=t.Variant({Refunded:t.Record({block_index:t.Opt(o),reason:t.Text}),InvalidTransaction:t.Text,Other:t.Record({error_message:t.Text,error_code:t.Nat64}),Processing:t.Null,TransactionTooOld:o}),x=t.Variant({Ok:t.Principal,Err:l}),C=t.Record({block_index:o,canister_id:t.Principal}),N=t.Nat,w=t.Variant({Ok:N,Err:l});return t.Service({get_icp_xdr_conversion_rate:t.Func([],[r],["query"]),get_subnet_types_to_subnets:t.Func([],[i],["query"]),notify_create_canister:t.Func([m],[x],[]),notify_top_up:t.Func([C],[w],[])})};var s=class extends Error{},c=class extends Error{},a=class extends Error{},p=class extends Error{},d=class extends Error{},y=({Err:t})=>{throw"Refunded"in t?new s(t.Refunded.reason):"InvalidTransaction"in t?new c(t.InvalidTransaction):"Processing"in t?new p:"TransactionTooOld"in t?new d:"Other"in t?new a(`Error in CMC with code ${t.Other.error_code}: ${t.Other.error_message}`):new Error(`Unsupported error type ${JSON.stringify(t)}`)};var n=class{constructor(e){this.service=e;this.getIcpToCyclesConversionRate=async()=>{let{data:e}=await this.service.get_icp_xdr_conversion_rate();return e.xdr_permyriad_per_icp};this.notifyCreateCanister=async e=>{let r=await this.service.notify_create_canister(e);if("Err"in r&&y(r),"Ok"in r)return r.Ok;throw new Error(`Unsupported response type in notifyCreateCanister ${JSON.stringify(r)}`)};this.notifyTopUp=async e=>{let r=await this.service.notify_top_up(e);if("Err"in r&&y(r),"Ok"in r)return r.Ok;throw new Error(`Unsupported response type in notifyTopUp ${JSON.stringify(r)}`)};this.service=e}static create(e){let r=e.agent,i=e.canisterId,o=e.serviceOverride??u.Actor.createActor(_,{agent:r,canisterId:i});return new n(o)}};0&&(module.exports={CMCCanister,CMCError,InvalidaTransactionError,ProcessingError,RefundedError,TransactionTooOldError,throwNotifyError});
2
+ //# sourceMappingURL=index.cjs.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/index.ts", "../../src/cmc.canister.ts", "../../candid/cmc.idl.js", "../../src/cmc.errors.ts"],
4
+ "sourcesContent": ["export type {\n Cycles,\n NotifyCreateCanisterArg,\n NotifyTopUpArg,\n} from \"../candid/cmc\";\nexport { CMCCanister } from \"./cmc.canister\";\nexport * from \"./cmc.errors\";\n", "import { Actor } from \"@dfinity/agent\";\nimport type { Principal } from \"@dfinity/principal\";\nimport type {\n Cycles,\n NotifyCreateCanisterArg,\n NotifyTopUpArg,\n _SERVICE,\n} from \"../candid/cmc\";\nimport { idlFactory } from \"../candid/cmc.idl\";\nimport { throwNotifyError } from \"./cmc.errors\";\nimport type { CMCCanisterOptions } from \"./cmc.options\";\n\nexport class CMCCanister {\n private constructor(private readonly service: _SERVICE) {\n this.service = service;\n }\n\n public static create(options: CMCCanisterOptions) {\n const agent = options.agent;\n const canisterId = options.canisterId;\n\n const service =\n options.serviceOverride ??\n Actor.createActor<_SERVICE>(idlFactory, {\n agent,\n canisterId,\n });\n\n return new CMCCanister(service);\n }\n\n /**\n * Returns conversion rate of ICP to Cycles\n *\n * @returns Promise<BigInt>\n */\n public getIcpToCyclesConversionRate = async (): Promise<bigint> => {\n const { data } = await this.service.get_icp_xdr_conversion_rate();\n\n // TODO: validate the certificate in the response - https://dfinity.atlassian.net/browse/FOLLOW-223\n return data.xdr_permyriad_per_icp;\n };\n\n /**\n * Notifies Cycles Minting Canister of the creation of a new canister.\n * It returns the new canister principal.\n *\n * @param {Object} request\n * @param {Principal} request.controller\n * @param {BlockIndex} request.block_index\n * @returns Promise<Principal>\n * @throws RefundedError, InvalidaTransactionError, ProcessingError, TransactionTooOldError, CMCError\n */\n public notifyCreateCanister = async (\n request: NotifyCreateCanisterArg\n ): Promise<Principal> => {\n const response = await this.service.notify_create_canister(request);\n if (\"Err\" in response) {\n throwNotifyError(response);\n }\n if (\"Ok\" in response) {\n return response.Ok;\n }\n // Edge case\n throw new Error(\n `Unsupported response type in notifyCreateCanister ${JSON.stringify(\n response\n )}`\n );\n };\n\n /**\n * Notifies Cycles Minting Canister of new cycles being added to canister.\n * It returns the new Cycles of the canister.\n *\n * @param {Object} request\n * @param {Principal} request.canister_id\n * @param {BlockIndex} request.block_index\n * @returns Promise<Cycles>\n * @throws RefundedError, InvalidaTransactionError, ProcessingError, TransactionTooOldError, CMCError\n */\n public notifyTopUp = async (request: NotifyTopUpArg): Promise<Cycles> => {\n const response = await this.service.notify_top_up(request);\n if (\"Err\" in response) {\n throwNotifyError(response);\n }\n if (\"Ok\" in response) {\n return response.Ok;\n }\n // Edge case\n throw new Error(\n `Unsupported response type in notifyTopUp ${JSON.stringify(response)}`\n );\n };\n}\n", "/* Do not edit. Compiled with ./scripts/compile-idl-js from packages/cmc/candid/cmc.did */\nexport const idlFactory = ({ IDL }) => {\n const IcpXdrConversionRate = IDL.Record({\n 'xdr_permyriad_per_icp' : IDL.Nat64,\n 'timestamp_seconds' : IDL.Nat64,\n });\n const IcpXdrConversionRateResponse = IDL.Record({\n 'certificate' : IDL.Vec(IDL.Nat8),\n 'data' : IcpXdrConversionRate,\n 'hash_tree' : IDL.Vec(IDL.Nat8),\n });\n const SubnetTypesToSubnetsResponse = IDL.Record({\n 'data' : IDL.Vec(IDL.Tuple(IDL.Text, IDL.Vec(IDL.Principal))),\n });\n const BlockIndex = IDL.Nat64;\n const NotifyCreateCanisterArg = IDL.Record({\n 'controller' : IDL.Principal,\n 'block_index' : BlockIndex,\n 'subnet_type' : IDL.Opt(IDL.Text),\n });\n const NotifyError = IDL.Variant({\n 'Refunded' : IDL.Record({\n 'block_index' : IDL.Opt(BlockIndex),\n 'reason' : IDL.Text,\n }),\n 'InvalidTransaction' : IDL.Text,\n 'Other' : IDL.Record({\n 'error_message' : IDL.Text,\n 'error_code' : IDL.Nat64,\n }),\n 'Processing' : IDL.Null,\n 'TransactionTooOld' : BlockIndex,\n });\n const NotifyCreateCanisterResult = IDL.Variant({\n 'Ok' : IDL.Principal,\n 'Err' : NotifyError,\n });\n const NotifyTopUpArg = IDL.Record({\n 'block_index' : BlockIndex,\n 'canister_id' : IDL.Principal,\n });\n const Cycles = IDL.Nat;\n const NotifyTopUpResult = IDL.Variant({ 'Ok' : Cycles, 'Err' : NotifyError });\n return IDL.Service({\n 'get_icp_xdr_conversion_rate' : IDL.Func(\n [],\n [IcpXdrConversionRateResponse],\n ['query'],\n ),\n 'get_subnet_types_to_subnets' : IDL.Func(\n [],\n [SubnetTypesToSubnetsResponse],\n ['query'],\n ),\n 'notify_create_canister' : IDL.Func(\n [NotifyCreateCanisterArg],\n [NotifyCreateCanisterResult],\n [],\n ),\n 'notify_top_up' : IDL.Func([NotifyTopUpArg], [NotifyTopUpResult], []),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n", "import type { NotifyError } from \"../candid/cmc\";\n\nexport class RefundedError extends Error {}\nexport class InvalidaTransactionError extends Error {}\nexport class CMCError extends Error {}\nexport class ProcessingError extends Error {}\nexport class TransactionTooOldError extends Error {}\n\n// Throws one of the errors above\nexport const throwNotifyError = ({\n Err: error,\n}: {\n Err: NotifyError;\n}): void => {\n if (\"Refunded\" in error) {\n throw new RefundedError(error.Refunded.reason);\n }\n if (\"InvalidTransaction\" in error) {\n throw new InvalidaTransactionError(error.InvalidTransaction);\n }\n if (\"Processing\" in error) {\n throw new ProcessingError();\n }\n if (\"TransactionTooOld\" in error) {\n throw new TransactionTooOldError();\n }\n if (\"Other\" in error) {\n throw new CMCError(\n `Error in CMC with code ${error.Other.error_code}: ${error.Other.error_message}`\n );\n }\n // Edge case\n throw new Error(`Unsupported error type ${JSON.stringify(error)}`);\n};\n"],
5
+ "mappings": "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",
6
+ "names": []
7
+ }
@@ -0,0 +1,2 @@
1
+ import{f as c}from"./chunk-YHCCTGII.js";import{Actor as l}from"@dfinity/agent";var a=({IDL:r})=>{let t=r.Record({xdr_permyriad_per_icp:r.Nat64,timestamp_seconds:r.Nat64}),e=r.Record({certificate:r.Vec(r.Nat8),data:t,hash_tree:r.Vec(r.Nat8)}),n=r.Record({data:r.Vec(r.Tuple(r.Text,r.Vec(r.Principal)))}),i=r.Nat64,p=r.Record({controller:r.Principal,block_index:i,subnet_type:r.Opt(r.Text)}),s=r.Variant({Refunded:r.Record({block_index:r.Opt(i),reason:r.Text}),InvalidTransaction:r.Text,Other:r.Record({error_message:r.Text,error_code:r.Nat64}),Processing:r.Null,TransactionTooOld:i}),y=r.Variant({Ok:r.Principal,Err:s}),d=r.Record({block_index:i,canister_id:r.Principal}),_=r.Nat,f=r.Variant({Ok:_,Err:s});return r.Service({get_icp_xdr_conversion_rate:r.Func([],[e],["query"]),get_subnet_types_to_subnets:r.Func([],[n],["query"]),notify_create_canister:r.Func([p],[y],[]),notify_top_up:r.Func([d],[f],[])})};var o=class{constructor(t){this.service=t;this.service=t}static create(t){let e=t.agent,n=t.canisterId,i=t.serviceOverride??l.createActor(a,{agent:e,canisterId:n});return new o(i)}getIcpToCyclesConversionRate=async()=>{let{data:t}=await this.service.get_icp_xdr_conversion_rate();return t.xdr_permyriad_per_icp};notifyCreateCanister=async t=>{let e=await this.service.notify_create_canister(t);if("Err"in e&&c(e),"Ok"in e)return e.Ok;throw new Error(`Unsupported response type in notifyCreateCanister ${JSON.stringify(e)}`)};notifyTopUp=async t=>{let e=await this.service.notify_top_up(t);if("Err"in e&&c(e),"Ok"in e)return e.Ok;throw new Error(`Unsupported response type in notifyTopUp ${JSON.stringify(e)}`)}};export{o as a};
2
+ //# sourceMappingURL=chunk-BGX6BTZV.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/cmc.canister.ts", "../../candid/cmc.idl.js"],
4
+ "sourcesContent": ["import { Actor } from \"@dfinity/agent\";\nimport type { Principal } from \"@dfinity/principal\";\nimport type {\n Cycles,\n NotifyCreateCanisterArg,\n NotifyTopUpArg,\n _SERVICE,\n} from \"../candid/cmc\";\nimport { idlFactory } from \"../candid/cmc.idl\";\nimport { throwNotifyError } from \"./cmc.errors\";\nimport type { CMCCanisterOptions } from \"./cmc.options\";\n\nexport class CMCCanister {\n private constructor(private readonly service: _SERVICE) {\n this.service = service;\n }\n\n public static create(options: CMCCanisterOptions) {\n const agent = options.agent;\n const canisterId = options.canisterId;\n\n const service =\n options.serviceOverride ??\n Actor.createActor<_SERVICE>(idlFactory, {\n agent,\n canisterId,\n });\n\n return new CMCCanister(service);\n }\n\n /**\n * Returns conversion rate of ICP to Cycles\n *\n * @returns Promise<BigInt>\n */\n public getIcpToCyclesConversionRate = async (): Promise<bigint> => {\n const { data } = await this.service.get_icp_xdr_conversion_rate();\n\n // TODO: validate the certificate in the response - https://dfinity.atlassian.net/browse/FOLLOW-223\n return data.xdr_permyriad_per_icp;\n };\n\n /**\n * Notifies Cycles Minting Canister of the creation of a new canister.\n * It returns the new canister principal.\n *\n * @param {Object} request\n * @param {Principal} request.controller\n * @param {BlockIndex} request.block_index\n * @returns Promise<Principal>\n * @throws RefundedError, InvalidaTransactionError, ProcessingError, TransactionTooOldError, CMCError\n */\n public notifyCreateCanister = async (\n request: NotifyCreateCanisterArg\n ): Promise<Principal> => {\n const response = await this.service.notify_create_canister(request);\n if (\"Err\" in response) {\n throwNotifyError(response);\n }\n if (\"Ok\" in response) {\n return response.Ok;\n }\n // Edge case\n throw new Error(\n `Unsupported response type in notifyCreateCanister ${JSON.stringify(\n response\n )}`\n );\n };\n\n /**\n * Notifies Cycles Minting Canister of new cycles being added to canister.\n * It returns the new Cycles of the canister.\n *\n * @param {Object} request\n * @param {Principal} request.canister_id\n * @param {BlockIndex} request.block_index\n * @returns Promise<Cycles>\n * @throws RefundedError, InvalidaTransactionError, ProcessingError, TransactionTooOldError, CMCError\n */\n public notifyTopUp = async (request: NotifyTopUpArg): Promise<Cycles> => {\n const response = await this.service.notify_top_up(request);\n if (\"Err\" in response) {\n throwNotifyError(response);\n }\n if (\"Ok\" in response) {\n return response.Ok;\n }\n // Edge case\n throw new Error(\n `Unsupported response type in notifyTopUp ${JSON.stringify(response)}`\n );\n };\n}\n", "/* Do not edit. Compiled with ./scripts/compile-idl-js from packages/cmc/candid/cmc.did */\nexport const idlFactory = ({ IDL }) => {\n const IcpXdrConversionRate = IDL.Record({\n 'xdr_permyriad_per_icp' : IDL.Nat64,\n 'timestamp_seconds' : IDL.Nat64,\n });\n const IcpXdrConversionRateResponse = IDL.Record({\n 'certificate' : IDL.Vec(IDL.Nat8),\n 'data' : IcpXdrConversionRate,\n 'hash_tree' : IDL.Vec(IDL.Nat8),\n });\n const SubnetTypesToSubnetsResponse = IDL.Record({\n 'data' : IDL.Vec(IDL.Tuple(IDL.Text, IDL.Vec(IDL.Principal))),\n });\n const BlockIndex = IDL.Nat64;\n const NotifyCreateCanisterArg = IDL.Record({\n 'controller' : IDL.Principal,\n 'block_index' : BlockIndex,\n 'subnet_type' : IDL.Opt(IDL.Text),\n });\n const NotifyError = IDL.Variant({\n 'Refunded' : IDL.Record({\n 'block_index' : IDL.Opt(BlockIndex),\n 'reason' : IDL.Text,\n }),\n 'InvalidTransaction' : IDL.Text,\n 'Other' : IDL.Record({\n 'error_message' : IDL.Text,\n 'error_code' : IDL.Nat64,\n }),\n 'Processing' : IDL.Null,\n 'TransactionTooOld' : BlockIndex,\n });\n const NotifyCreateCanisterResult = IDL.Variant({\n 'Ok' : IDL.Principal,\n 'Err' : NotifyError,\n });\n const NotifyTopUpArg = IDL.Record({\n 'block_index' : BlockIndex,\n 'canister_id' : IDL.Principal,\n });\n const Cycles = IDL.Nat;\n const NotifyTopUpResult = IDL.Variant({ 'Ok' : Cycles, 'Err' : NotifyError });\n return IDL.Service({\n 'get_icp_xdr_conversion_rate' : IDL.Func(\n [],\n [IcpXdrConversionRateResponse],\n ['query'],\n ),\n 'get_subnet_types_to_subnets' : IDL.Func(\n [],\n [SubnetTypesToSubnetsResponse],\n ['query'],\n ),\n 'notify_create_canister' : IDL.Func(\n [NotifyCreateCanisterArg],\n [NotifyCreateCanisterResult],\n [],\n ),\n 'notify_top_up' : IDL.Func([NotifyTopUpArg], [NotifyTopUpResult], []),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n"],
5
+ "mappings": "wCAAA,uCCCO,GAAM,GAAa,CAAC,CAAE,SAAU,CACrC,GAAM,GAAuB,EAAI,OAAO,CACtC,sBAA0B,EAAI,MAC9B,kBAAsB,EAAI,KAC5B,CAAC,EACK,EAA+B,EAAI,OAAO,CAC9C,YAAgB,EAAI,IAAI,EAAI,IAAI,EAChC,KAAS,EACT,UAAc,EAAI,IAAI,EAAI,IAAI,CAChC,CAAC,EACK,EAA+B,EAAI,OAAO,CAC9C,KAAS,EAAI,IAAI,EAAI,MAAM,EAAI,KAAM,EAAI,IAAI,EAAI,SAAS,CAAC,CAAC,CAC9D,CAAC,EACK,EAAa,EAAI,MACjB,EAA0B,EAAI,OAAO,CACzC,WAAe,EAAI,UACnB,YAAgB,EAChB,YAAgB,EAAI,IAAI,EAAI,IAAI,CAClC,CAAC,EACK,EAAc,EAAI,QAAQ,CAC9B,SAAa,EAAI,OAAO,CACtB,YAAgB,EAAI,IAAI,CAAU,EAClC,OAAW,EAAI,IACjB,CAAC,EACD,mBAAuB,EAAI,KAC3B,MAAU,EAAI,OAAO,CACnB,cAAkB,EAAI,KACtB,WAAe,EAAI,KACrB,CAAC,EACD,WAAe,EAAI,KACnB,kBAAsB,CACxB,CAAC,EACK,EAA6B,EAAI,QAAQ,CAC7C,GAAO,EAAI,UACX,IAAQ,CACV,CAAC,EACK,EAAiB,EAAI,OAAO,CAChC,YAAgB,EAChB,YAAgB,EAAI,SACtB,CAAC,EACK,EAAS,EAAI,IACb,EAAoB,EAAI,QAAQ,CAAE,GAAO,EAAQ,IAAQ,CAAY,CAAC,EAC5E,MAAO,GAAI,QAAQ,CACjB,4BAAgC,EAAI,KAChC,CAAC,EACD,CAAC,CAA4B,EAC7B,CAAC,OAAO,CACV,EACF,4BAAgC,EAAI,KAChC,CAAC,EACD,CAAC,CAA4B,EAC7B,CAAC,OAAO,CACV,EACF,uBAA2B,EAAI,KAC3B,CAAC,CAAuB,EACxB,CAAC,CAA0B,EAC3B,CAAC,CACH,EACF,cAAkB,EAAI,KAAK,CAAC,CAAc,EAAG,CAAC,CAAiB,EAAG,CAAC,CAAC,CACtE,CAAC,CACH,EDjDO,GAAM,GAAN,KAAkB,CACvB,AAAQ,YAA6B,EAAmB,CAAnB,eACnC,KAAK,QAAU,CACjB,CAEA,MAAc,QAAO,EAA6B,CAChD,GAAM,GAAQ,EAAQ,MAChB,EAAa,EAAQ,WAErB,EACJ,EAAQ,iBACR,EAAM,YAAsB,EAAY,CACtC,QACA,YACF,CAAC,EAEH,MAAO,IAAI,GAAY,CAAO,CAChC,CAOA,AAAO,6BAA+B,SAA6B,CACjE,GAAM,CAAE,QAAS,KAAM,MAAK,QAAQ,4BAA4B,EAGhE,MAAO,GAAK,qBACd,EAYA,AAAO,qBAAuB,KAC5B,IACuB,CACvB,GAAM,GAAW,KAAM,MAAK,QAAQ,uBAAuB,CAAO,EAIlE,GAHI,OAAS,IACX,EAAiB,CAAQ,EAEvB,MAAQ,GACV,MAAO,GAAS,GAGlB,KAAM,IAAI,OACR,qDAAqD,KAAK,UACxD,CACF,GACF,CACF,EAYA,AAAO,YAAc,KAAO,IAA6C,CACvE,GAAM,GAAW,KAAM,MAAK,QAAQ,cAAc,CAAO,EAIzD,GAHI,OAAS,IACX,EAAiB,CAAQ,EAEvB,MAAQ,GACV,MAAO,GAAS,GAGlB,KAAM,IAAI,OACR,4CAA4C,KAAK,UAAU,CAAQ,GACrE,CACF,CACF",
6
+ "names": []
7
+ }
@@ -0,0 +1,2 @@
1
+ var e=class extends Error{},n=class extends Error{},o=class extends Error{},r=class extends Error{},i=class extends Error{},s=({Err:t})=>{throw"Refunded"in t?new e(t.Refunded.reason):"InvalidTransaction"in t?new n(t.InvalidTransaction):"Processing"in t?new r:"TransactionTooOld"in t?new i:"Other"in t?new o(`Error in CMC with code ${t.Other.error_code}: ${t.Other.error_message}`):new Error(`Unsupported error type ${JSON.stringify(t)}`)};export{e as a,n as b,o as c,r as d,i as e,s as f};
2
+ //# sourceMappingURL=chunk-YHCCTGII.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/cmc.errors.ts"],
4
+ "sourcesContent": ["import type { NotifyError } from \"../candid/cmc\";\n\nexport class RefundedError extends Error {}\nexport class InvalidaTransactionError extends Error {}\nexport class CMCError extends Error {}\nexport class ProcessingError extends Error {}\nexport class TransactionTooOldError extends Error {}\n\n// Throws one of the errors above\nexport const throwNotifyError = ({\n Err: error,\n}: {\n Err: NotifyError;\n}): void => {\n if (\"Refunded\" in error) {\n throw new RefundedError(error.Refunded.reason);\n }\n if (\"InvalidTransaction\" in error) {\n throw new InvalidaTransactionError(error.InvalidTransaction);\n }\n if (\"Processing\" in error) {\n throw new ProcessingError();\n }\n if (\"TransactionTooOld\" in error) {\n throw new TransactionTooOldError();\n }\n if (\"Other\" in error) {\n throw new CMCError(\n `Error in CMC with code ${error.Other.error_code}: ${error.Other.error_message}`\n );\n }\n // Edge case\n throw new Error(`Unsupported error type ${JSON.stringify(error)}`);\n};\n"],
5
+ "mappings": "AAEO,GAAM,GAAN,aAA4B,MAAM,CAAC,EAC7B,EAAN,aAAuC,MAAM,CAAC,EACxC,EAAN,aAAuB,MAAM,CAAC,EACxB,EAAN,aAA8B,MAAM,CAAC,EAC/B,EAAN,aAAqC,MAAM,CAAC,EAGtC,EAAmB,CAAC,CAC/B,IAAK,KAGK,CACV,KAAI,YAAc,GACV,GAAI,GAAc,EAAM,SAAS,MAAM,EAE3C,sBAAwB,GACpB,GAAI,GAAyB,EAAM,kBAAkB,EAEzD,cAAgB,GACZ,GAAI,GAER,qBAAuB,GACnB,GAAI,GAER,SAAW,GACP,GAAI,GACR,0BAA0B,EAAM,MAAM,eAAe,EAAM,MAAM,eACnE,EAGI,GAAI,OAAM,0BAA0B,KAAK,UAAU,CAAK,GAAG,CACnE",
6
+ "names": []
7
+ }
@@ -0,0 +1,2 @@
1
+ import{a}from"./chunk-BGX6BTZV.js";import"./chunk-YHCCTGII.js";export{a as CMCCanister};
2
+ //# sourceMappingURL=cmc.canister.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d,e,f}from"./chunk-YHCCTGII.js";export{c as CMCError,b as InvalidaTransactionError,d as ProcessingError,a as RefundedError,e as TransactionTooOldError,f as throwNotifyError};
2
+ //# sourceMappingURL=cmc.errors.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,2 @@
1
+ import{Principal as t}from"@dfinity/principal";var o="xlmdg-vkosz-ceopx-7wtgu-g3xmd-koiyc-awqaq-7modz-zf6r6-364rh-oqe",i=t.fromText(o),r={getPrincipal:()=>i};export{r as mockIdentity,i as mockPrincipal,o as mockPrincipalText};
2
+ //# sourceMappingURL=cmc.mock.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/cmc.mock.ts"],
4
+ "sourcesContent": ["import type { Identity } from \"@dfinity/agent\";\nimport { Principal } from \"@dfinity/principal\";\n\nexport const mockPrincipalText =\n \"xlmdg-vkosz-ceopx-7wtgu-g3xmd-koiyc-awqaq-7modz-zf6r6-364rh-oqe\";\n\nexport const mockPrincipal = Principal.fromText(mockPrincipalText);\n\nexport const mockIdentity = {\n getPrincipal: () => mockPrincipal,\n} as unknown as Identity;\n"],
5
+ "mappings": "AACA,+CAEO,GAAM,GACX,kEAEW,EAAgB,EAAU,SAAS,CAAiB,EAEpD,EAAe,CAC1B,aAAc,IAAM,CACtB",
6
+ "names": []
7
+ }
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=cmc.options.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,2 @@
1
+ import{a as r}from"./chunk-BGX6BTZV.js";import{a as e,b as o,c as t,d as p,e as C,f}from"./chunk-YHCCTGII.js";export{r as CMCCanister,t as CMCError,o as InvalidaTransactionError,p as ProcessingError,e as RefundedError,C as TransactionTooOldError,f as throwNotifyError};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1 @@
1
+ module.exports = require('./cjs/index.cjs.js');
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './esm/index.js';
@@ -0,0 +1,36 @@
1
+ import type { Principal } from "@dfinity/principal";
2
+ import type { Cycles, NotifyCreateCanisterArg, NotifyTopUpArg } from "../candid/cmc";
3
+ import type { CMCCanisterOptions } from "./cmc.options";
4
+ export declare class CMCCanister {
5
+ private readonly service;
6
+ private constructor();
7
+ static create(options: CMCCanisterOptions): CMCCanister;
8
+ /**
9
+ * Returns conversion rate of ICP to Cycles
10
+ *
11
+ * @returns Promise<BigInt>
12
+ */
13
+ getIcpToCyclesConversionRate: () => Promise<bigint>;
14
+ /**
15
+ * Notifies Cycles Minting Canister of the creation of a new canister.
16
+ * It returns the new canister principal.
17
+ *
18
+ * @param {Object} request
19
+ * @param {Principal} request.controller
20
+ * @param {BlockIndex} request.block_index
21
+ * @returns Promise<Principal>
22
+ * @throws RefundedError, InvalidaTransactionError, ProcessingError, TransactionTooOldError, CMCError
23
+ */
24
+ notifyCreateCanister: (request: NotifyCreateCanisterArg) => Promise<Principal>;
25
+ /**
26
+ * Notifies Cycles Minting Canister of new cycles being added to canister.
27
+ * It returns the new Cycles of the canister.
28
+ *
29
+ * @param {Object} request
30
+ * @param {Principal} request.canister_id
31
+ * @param {BlockIndex} request.block_index
32
+ * @returns Promise<Cycles>
33
+ * @throws RefundedError, InvalidaTransactionError, ProcessingError, TransactionTooOldError, CMCError
34
+ */
35
+ notifyTopUp: (request: NotifyTopUpArg) => Promise<Cycles>;
36
+ }
@@ -0,0 +1,14 @@
1
+ import type { NotifyError } from "../candid/cmc";
2
+ export declare class RefundedError extends Error {
3
+ }
4
+ export declare class InvalidaTransactionError extends Error {
5
+ }
6
+ export declare class CMCError extends Error {
7
+ }
8
+ export declare class ProcessingError extends Error {
9
+ }
10
+ export declare class TransactionTooOldError extends Error {
11
+ }
12
+ export declare const throwNotifyError: ({ Err: error, }: {
13
+ Err: NotifyError;
14
+ }) => void;
@@ -0,0 +1,6 @@
1
+ import type { Principal } from "@dfinity/principal";
2
+ import type { CanisterOptions } from "@dfinity/utils";
3
+ import type { _SERVICE as CanisterService } from "../candid/cmc";
4
+ export interface CMCCanisterOptions extends Omit<CanisterOptions<CanisterService>, "canisterId"> {
5
+ canisterId: string | Principal;
6
+ }
@@ -0,0 +1,3 @@
1
+ export type { Cycles, NotifyCreateCanisterArg, NotifyTopUpArg, } from "../candid/cmc";
2
+ export { CMCCanister } from "./cmc.canister";
3
+ export * from "./cmc.errors";
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@dfinity/cmc",
3
+ "version": "0.0.1",
4
+ "description": "A library for interfacing with the cycle minting canister.",
5
+ "license": "Apache-2.0",
6
+ "main": "dist/cjs/index.cjs.js",
7
+ "module": "dist/esm/index.js",
8
+ "types": "dist/types/index.d.ts",
9
+ "files": [
10
+ "dist",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "scripts": {
15
+ "rmdir": "node ../../scripts/rmdir.mjs",
16
+ "ts-declaration": "tsc --emitDeclarationOnly --outDir dist/types",
17
+ "build": "npm run rmdir && mkdir -p dist && cp -R candid dist && node esbuild.mjs && npm run ts-declaration",
18
+ "prepack": "npm run build",
19
+ "test": "jest"
20
+ },
21
+ "devDependencies": {},
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/dfinity/ic-js.git",
25
+ "directory": "packages/cmc"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/dfinity/ic-js"
29
+ },
30
+ "keywords": [
31
+ "internet computer",
32
+ "internet-computer",
33
+ "ic",
34
+ "dfinity",
35
+ "cmc",
36
+ "cycle minting canister"
37
+ ],
38
+ "peerDependencies": {
39
+ "@dfinity/utils": "^0.0.4"
40
+ },
41
+ "homepage": "https://github.com/dfinity/ic-js#readme",
42
+ "author": ""
43
+ }