From 0b745178238870eeeb326ac86adfc50ca62dd227 Mon Sep 17 00:00:00 2001 From: David Dal Busco Date: Tue, 24 Jan 2023 14:53:42 +0100 Subject: [PATCH] feat: ledger-js (#258) # Motivation The ICRC-1 ledger is not only used in Sns projects but, in ckBTC too. It can also be integrated in various other scenario - e.g. in developers' project who want to launch their own token. That's why we can launch a dedicated `@dfinity/ledger` library. # Changes - extract the existing Sns ledger to a new dedicated `@dfinity/ledger` package - move various mock and utils - rename related `SnsSomething` to `Icrc1Something` or `LedgerSomething` --- .github/workflows/nightly.yml | 4 + .github/workflows/publish.yml | 4 + CHANGELOG.md | 17 +- README.md | 7 +- package-lock.json | 20 +- package.json | 3 +- packages/ledger/LICENSE | 201 ++++++++++++++++++ packages/ledger/README.md | 152 +++++++++++++ .../candid/icrc1_ledger.certified.idl.d.ts | 0 .../candid/icrc1_ledger.certified.idl.js | 2 +- .../{sns => ledger}/candid/icrc1_ledger.d.ts | 0 .../{sns => ledger}/candid/icrc1_ledger.did | 3 +- .../candid/icrc1_ledger.idl.d.ts | 0 .../candid/icrc1_ledger.idl.js | 2 +- packages/ledger/esbuild.mjs | 5 + packages/ledger/jest.config.js | 7 + packages/ledger/package.json | 42 ++++ .../src/converters/ledger.converters.ts | 11 +- .../src/errors/ledger.errors.ts | 2 +- packages/ledger/src/index.ts | 13 ++ .../src/ledger.canister.spec.ts | 52 ++--- .../{sns => ledger}/src/ledger.canister.ts | 27 ++- packages/ledger/src/mocks/ledger.mock.ts | 22 ++ packages/ledger/src/types/canister.options.ts | 8 + .../src/types/ledger.params.ts | 6 +- .../src/types/ledger.responses.ts | 8 +- .../src/utils/ledger.utils.spec.ts | 32 +-- .../{sns => ledger}/src/utils/ledger.utils.ts | 21 +- packages/ledger/tsconfig.json | 4 + packages/sns/README.md | 187 +++------------- packages/sns/package.json | 1 + .../src/converters/governance.converters.ts | 4 +- .../src/converters/sns-index.converters.ts | 12 +- packages/sns/src/governance.canister.ts | 16 +- packages/sns/src/index.ts | 9 - packages/sns/src/mocks/ledger.mock.ts | 16 +- packages/sns/src/root.canister.ts | 3 +- packages/sns/src/sns-index.canister.spec.ts | 4 +- packages/sns/src/sns-index.canister.ts | 3 +- packages/sns/src/sns.ts | 6 +- packages/sns/src/sns.wrapper.spec.ts | 13 +- packages/sns/src/sns.wrapper.ts | 40 ++-- packages/sns/src/swap.canister.ts | 5 +- packages/sns/src/types/governance.params.ts | 19 +- packages/sns/src/types/sns-index.params.ts | 4 +- packages/sns/src/utils/governance.utils.ts | 4 +- packages/utils/README.md | 12 ++ packages/utils/src/index.ts | 2 + .../{sns => utils}/src/services/canister.ts | 0 .../{sns => utils}/src/types/query.params.ts | 2 +- scripts/compile-idl-js | 1 + scripts/docs.js | 13 +- scripts/import-candid | 4 +- 53 files changed, 728 insertions(+), 327 deletions(-) create mode 100644 packages/ledger/LICENSE create mode 100644 packages/ledger/README.md rename packages/{sns => ledger}/candid/icrc1_ledger.certified.idl.d.ts (100%) rename packages/{sns => ledger}/candid/icrc1_ledger.certified.idl.js (98%) rename packages/{sns => ledger}/candid/icrc1_ledger.d.ts (100%) rename packages/{sns => ledger}/candid/icrc1_ledger.did (94%) rename packages/{sns => ledger}/candid/icrc1_ledger.idl.d.ts (100%) rename packages/{sns => ledger}/candid/icrc1_ledger.idl.js (98%) create mode 100644 packages/ledger/esbuild.mjs create mode 100644 packages/ledger/jest.config.js create mode 100644 packages/ledger/package.json rename packages/{sns => ledger}/src/converters/ledger.converters.ts (60%) rename packages/{sns => ledger}/src/errors/ledger.errors.ts (83%) create mode 100644 packages/ledger/src/index.ts rename packages/{sns => ledger}/src/ledger.canister.spec.ts (70%) rename packages/{sns => ledger}/src/ledger.canister.ts (67%) create mode 100644 packages/ledger/src/mocks/ledger.mock.ts create mode 100644 packages/ledger/src/types/canister.options.ts rename packages/{sns => ledger}/src/types/ledger.params.ts (87%) rename packages/{sns => ledger}/src/types/ledger.responses.ts (69%) rename packages/{sns => ledger}/src/utils/ledger.utils.spec.ts (65%) rename packages/{sns => ledger}/src/utils/ledger.utils.ts (80%) create mode 100644 packages/ledger/tsconfig.json rename packages/{sns => utils}/src/services/canister.ts (100%) rename packages/{sns => utils}/src/types/query.params.ts (74%) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index e6303bcd..776ec0af 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -20,6 +20,10 @@ jobs: run: npm publish --tag next --workspace=packages/utils env: NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} + - name: Publish Ledger + run: npm publish --tag next --workspace=packages/ledger + env: + NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} - name: Publish NNS run: npm publish --tag next --workspace=packages/nns env: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ce8830b5..e00bbe5b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -21,6 +21,10 @@ jobs: run: npm publish --workspace=packages/utils --access public env: NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} + - name: Publish Ledger + run: npm publish --workspace=packages/ledger --access public + env: + NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} - name: Publish NNS run: npm publish --workspace=packages/nns --access public env: diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d93d665..54304929 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,27 @@ -# 0.12.0 (wip) +# 0.12.0 (2023-01-24) ## Release - nns `v0.12.0` - sns `v0.0.9` - cmc `v0.0.5` +- ledger `v0.0.1` - utils `v0.0.8` +### Breaking Changes + +Introducing `@dfinity/ledger` — A library for interfacing with ICRC ledgers on the Internet Computer. + +An ICRC-1 ledger is not only used in Sns projects but, in ckBTC too. It can also be integrated in various other scenario need by developers on the IC. + +That's why we are launching this new library and why we refactored Sns ledger related features to create this new library. + +De facto, `@dfinity/ledger` becomes a peer dependency of `@dfinity/sns`. + +### Features + +- enable merge neurons for HW controlled neurons + # 0.11.0 (2023-01-23) ## Release diff --git a/README.md b/README.md index 019f9b27..b12331cf 100644 --- a/README.md +++ b/README.md @@ -6,16 +6,19 @@ The libraries are still in active development, and new features will incremental ## Libraries -- [nns](/packages/nns): interfacing with the **ledger** and **governance** canisters of the IC +- [nns](/packages/nns): interfacing with the **ledger** and **governance** canisters of the Network Nervous System (NNS) - [sns](/packages/sns): interacting with a Service Nervous System (SNS) project - [cmc](/packages/cmc): interfacing with the **cmc** canister of the IC -- [utils](/packages/utils): a collection of utilities and constants for NNS/SNS projects. +- [ledger](/packages/ledger): interacting with ICRC compatible **ledgers** +- [utils](/packages/utils): a collection of utilities and constants ## Installation Install any library of this repo in your project from [npm](https://www.npmjs.com): ```bash +npm i @dfinity/utils +npm i @dfinity/ledger npm i @dfinity/nns npm i @dfinity/sns npm i @dfinity/cmc diff --git a/package-lock.json b/package-lock.json index d6552d5a..e915192b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,8 @@ "packages/utils", "packages/nns", "packages/sns", - "packages/cmc" + "packages/cmc", + "packages/ledger" ], "devDependencies": { "@types/jest": "^29.2.4", @@ -700,6 +701,10 @@ "resolved": "packages/cmc", "link": true }, + "node_modules/@dfinity/ledger": { + "resolved": "packages/ledger", + "link": true + }, "node_modules/@dfinity/nns": { "resolved": "packages/nns", "link": true @@ -6907,6 +6912,14 @@ "@dfinity/utils": "^0.0.8" } }, + "packages/ledger": { + "name": "@dfinity/ledger", + "version": "0.0.1", + "license": "Apache-2.0", + "peerDependencies": { + "@dfinity/utils": "^0.0.8" + } + }, "packages/nns": { "name": "@dfinity/nns", "version": "0.12.0", @@ -6969,6 +6982,7 @@ "js-sha256": "^0.9.0" }, "peerDependencies": { + "@dfinity/ledger": "^0.0.1", "@dfinity/utils": "^0.0.8" } }, @@ -7486,6 +7500,10 @@ "version": "file:packages/cmc", "requires": {} }, + "@dfinity/ledger": { + "version": "file:packages/ledger", + "requires": {} + }, "@dfinity/nns": { "version": "file:packages/nns", "requires": { diff --git a/package.json b/package.json index 623f3c97..ccbb3cff 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "license": "Apache-2.0", "workspaces": [ "packages/utils", + "packages/ledger", "packages/nns", "packages/sns", "packages/cmc" @@ -15,7 +16,7 @@ "format": "prettier --write .", "protoc": "bash ./scripts/update_proto.sh", "test": "jest", - "docs": "node scripts/docs.js && prettier --write packages/nns/README.md packages/sns/README.md packages/cmc/README.md packages/utils/README.md" + "docs": "node scripts/docs.js && prettier --write packages/nns/README.md packages/sns/README.md packages/cmc/README.md packages/utils/README.md packages/ledger/README.md" }, "repository": { "type": "git", diff --git a/packages/ledger/LICENSE b/packages/ledger/LICENSE new file mode 100644 index 00000000..4874b73b --- /dev/null +++ b/packages/ledger/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021 DFINITY LLC. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/ledger/README.md b/packages/ledger/README.md new file mode 100644 index 00000000..168a7bb7 --- /dev/null +++ b/packages/ledger/README.md @@ -0,0 +1,152 @@ +# ledger-js + +A library for interfacing with [ICRC ledgers](https://github.com/dfinity/ic/tree/master/rs/rosetta-api/icrc1) on the Internet Computer. + +[![npm version](https://img.shields.io/npm/v/@dfinity/ledger.svg?logo=npm)](https://www.npmjs.com/package/@dfinity/ledger) [![GitHub license](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) + +## Table of contents + +- [Installation](#installation) +- [Usage](#usage) +- [Features](#features) +- [Resources](#resources) + +## Installation + +You can use `ledger-js` by installing it in your project. + +```bash +npm i @dfinity/ledger +``` + +The bundle needs peer dependencies, be sure that following resources are available in your project as well. + +```bash +npm i @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils +``` + +## Usage + +The features are available through the class `LedgerCanister`. It has to be instantiated with a canister ID. + +e.g. fetching a token metadata. + +```ts +import { IcrcLedgerCanister } from "@dfinity/ledger"; +import { createAgent } from "@dfinity/utils"; + +const agent = await createAgent({ + identity, + host: HOST, +}); + +const { metadata } = LedgerCanister.create({ + agent, + canisterId: MY_LEDGER_CANISTER_ID, +}); + +const data = await metadata(); +``` + +## Features + +`ledger-js` implements following features: + + + +### :toolbox: Functions + +- [encodeIcrcAccount](#gear-encodeicrcaccount) +- [decodeIcrcAccount](#gear-decodeicrcaccount) + +#### :gear: encodeIcrcAccount + +Encodes an Icrc-1 account compatible into a string. +Formatting Reference: https://github.com/dfinity/ICRC-1/pull/55/files#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R238 + +| Function | Type | +| ------------------- | ------------------------------------------------- | +| `encodeIcrcAccount` | `({ owner, subaccount, }: IcrcAccount) => string` | + +Parameters: + +- `account`: : Principal, subaccount?: Uint8Array } + +#### :gear: decodeIcrcAccount + +Decodes a string into an Icrc-1 compatible account. +Formatting Reference: https://github.com/dfinity/ICRC-1/pull/55/files#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R268 + +| Function | Type | +| ------------------- | ---------------------------------------- | +| `decodeIcrcAccount` | `(accountString: string) => IcrcAccount` | + +Parameters: + +- `accountString`: string + +### :factory: IcrcLedgerCanister + +#### Constructors + +`public` + +#### Methods + +- [create](#gear-create) +- [metadata](#gear-metadata) +- [transactionFee](#gear-transactionfee) +- [balance](#gear-balance) +- [transfer](#gear-transfer) + +##### :gear: create + +| Method | Type | +| -------- | ---------------------------------------------------------------------- | +| `create` | `(options: IcrcLedgerCanisterOptions<_SERVICE>) => IcrcLedgerCanister` | + +##### :gear: metadata + +The token metadata (name, symbol, etc.). + +| Method | Type | +| ---------- | ------------------------------------------------------------- | +| `metadata` | `(params: QueryParams) => Promise` | + +##### :gear: transactionFee + +The ledger transaction fees. + +| Method | Type | +| ---------------- | ------------------------------------------ | +| `transactionFee` | `(params: QueryParams) => Promise` | + +##### :gear: balance + +Returns the balance of the given account. + +| Method | Type | +| --------- | -------------------------------------------- | +| `balance` | `(params: BalanceParams) => Promise` | + +Parameters: + +- `params`: The parameters to get the balance of an account. + +##### :gear: transfer + +Transfers tokens from the sender to the given account. + +| Method | Type | +| ---------- | --------------------------------------------- | +| `transfer` | `(params: TransferParams) => Promise` | + +Parameters: + +- `params`: The parameters to transfer tokens. + + + +## Resources + +- [Ledger & Tokenization Working Group Standards](https://github.com/dfinity/ICRC-1/) diff --git a/packages/sns/candid/icrc1_ledger.certified.idl.d.ts b/packages/ledger/candid/icrc1_ledger.certified.idl.d.ts similarity index 100% rename from packages/sns/candid/icrc1_ledger.certified.idl.d.ts rename to packages/ledger/candid/icrc1_ledger.certified.idl.d.ts diff --git a/packages/sns/candid/icrc1_ledger.certified.idl.js b/packages/ledger/candid/icrc1_ledger.certified.idl.js similarity index 98% rename from packages/sns/candid/icrc1_ledger.certified.idl.js rename to packages/ledger/candid/icrc1_ledger.certified.idl.js index 171ce532..c7bc48e0 100644 --- a/packages/sns/candid/icrc1_ledger.certified.idl.js +++ b/packages/ledger/candid/icrc1_ledger.certified.idl.js @@ -1,4 +1,4 @@ -/* Do not edit. Compiled with ./scripts/compile-idl-js from packages/sns/candid/icrc1_ledger.did */ +/* Do not edit. Compiled with ./scripts/compile-idl-js from packages/ledger/candid/icrc1_ledger.did */ export const idlFactory = ({ IDL }) => { const Value = IDL.Variant({ 'Int' : IDL.Int, diff --git a/packages/sns/candid/icrc1_ledger.d.ts b/packages/ledger/candid/icrc1_ledger.d.ts similarity index 100% rename from packages/sns/candid/icrc1_ledger.d.ts rename to packages/ledger/candid/icrc1_ledger.d.ts diff --git a/packages/sns/candid/icrc1_ledger.did b/packages/ledger/candid/icrc1_ledger.did similarity index 94% rename from packages/sns/candid/icrc1_ledger.did rename to packages/ledger/candid/icrc1_ledger.did index 9905ee8c..f3e01e55 100644 --- a/packages/sns/candid/icrc1_ledger.did +++ b/packages/ledger/candid/icrc1_ledger.did @@ -1,4 +1,4 @@ -// Generated from IC repo commit c9b2f9653afc2da47e5bd527c192090b860acbf0 'rs/rosetta-api/icrc1/ledger/icrc1.did' by import-candid +// Generated from IC repo commit 588a108b575e3b4152c8b0c69c38ba5b0f911bfe 'rs/rosetta-api/icrc1/ledger/icrc1.did' by import-candid type BlockIndex = nat; type Subaccount = blob; // Number of nanoseconds since the UNIX epoch in UTC timezone. @@ -71,7 +71,6 @@ service : (InitArgs) -> { icrc1_total_supply : () -> (Tokens) query; icrc1_fee : () -> (Tokens) query; icrc1_minting_account : () -> (opt Account) query; - icrc1_balance_of : (Account) -> (Tokens) query; icrc1_transfer : (TransferArg) -> (TransferResult); icrc1_supported_standards : () -> (vec record { name : text; url : text }) query; diff --git a/packages/sns/candid/icrc1_ledger.idl.d.ts b/packages/ledger/candid/icrc1_ledger.idl.d.ts similarity index 100% rename from packages/sns/candid/icrc1_ledger.idl.d.ts rename to packages/ledger/candid/icrc1_ledger.idl.d.ts diff --git a/packages/sns/candid/icrc1_ledger.idl.js b/packages/ledger/candid/icrc1_ledger.idl.js similarity index 98% rename from packages/sns/candid/icrc1_ledger.idl.js rename to packages/ledger/candid/icrc1_ledger.idl.js index 05be1ff9..62306390 100644 --- a/packages/sns/candid/icrc1_ledger.idl.js +++ b/packages/ledger/candid/icrc1_ledger.idl.js @@ -1,4 +1,4 @@ -/* Do not edit. Compiled with ./scripts/compile-idl-js from packages/sns/candid/icrc1_ledger.did */ +/* Do not edit. Compiled with ./scripts/compile-idl-js from packages/ledger/candid/icrc1_ledger.did */ export const idlFactory = ({ IDL }) => { const Value = IDL.Variant({ 'Int' : IDL.Int, diff --git a/packages/ledger/esbuild.mjs b/packages/ledger/esbuild.mjs new file mode 100644 index 00000000..f3cda319 --- /dev/null +++ b/packages/ledger/esbuild.mjs @@ -0,0 +1,5 @@ +#!/usr/bin/env node + +import { build } from "../../scripts/esbuild.mjs"; + +build(); diff --git a/packages/ledger/jest.config.js b/packages/ledger/jest.config.js new file mode 100644 index 00000000..e75ede62 --- /dev/null +++ b/packages/ledger/jest.config.js @@ -0,0 +1,7 @@ +const rootJestConfig = require("../../jest.config"); + +module.exports = { + ...rootJestConfig, + setupFiles: [`../../test-setup.ts`], + modulePathIgnorePatterns: ["./dist"], +}; diff --git a/packages/ledger/package.json b/packages/ledger/package.json new file mode 100644 index 00000000..3272b9c2 --- /dev/null +++ b/packages/ledger/package.json @@ -0,0 +1,42 @@ +{ + "name": "@dfinity/ledger", + "version": "0.0.1", + "description": "A library for interfacing with ICRC ledgers on the Internet Computer.", + "license": "Apache-2.0", + "main": "dist/cjs/index.cjs.js", + "module": "dist/esm/index.js", + "types": "dist/types/index.d.ts", + "files": [ + "dist", + "README.md", + "LICENSE" + ], + "scripts": { + "rmdir": "node ../../scripts/rmdir.mjs", + "ts-declaration": "tsc --emitDeclarationOnly --outDir dist/types", + "build": "npm run rmdir && mkdir -p dist && cp -R candid dist && node esbuild.mjs && npm run ts-declaration", + "prepack": "npm run build", + "test": "jest" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/dfinity/ic-js.git", + "directory": "packages/cmc" + }, + "bugs": { + "url": "https://github.com/dfinity/ic-js" + }, + "keywords": [ + "internet computer", + "internet-computer", + "ic", + "dfinity", + "Ledger", + "ICRC-1 ledger", + "token" + ], + "homepage": "https://github.com/dfinity/ic-js#readme", + "peerDependencies": { + "@dfinity/utils": "^0.0.8" + } +} diff --git a/packages/sns/src/converters/ledger.converters.ts b/packages/ledger/src/converters/ledger.converters.ts similarity index 60% rename from packages/sns/src/converters/ledger.converters.ts rename to packages/ledger/src/converters/ledger.converters.ts index f0c18817..85f6f8a1 100644 --- a/packages/sns/src/converters/ledger.converters.ts +++ b/packages/ledger/src/converters/ledger.converters.ts @@ -1,7 +1,6 @@ import { toNullable } from "@dfinity/utils"; -import type { Account, TransferArg } from "../../candid/icrc1_ledger"; +import type { TransferArg } from "../../candid/icrc1_ledger"; import type { TransferParams } from "../types/ledger.params"; -import type { SnsAccount } from "../types/ledger.responses"; export const toTransferArg = ({ to, @@ -18,11 +17,3 @@ export const toTransferArg = ({ from_subaccount: toNullable(from_subaccount), created_at_time: toNullable(created_at_time), }); - -export const toCandidAccount = ({ - owner, - subaccount, -}: SnsAccount): Account => ({ - owner, - subaccount: toNullable(subaccount), -}); diff --git a/packages/sns/src/errors/ledger.errors.ts b/packages/ledger/src/errors/ledger.errors.ts similarity index 83% rename from packages/sns/src/errors/ledger.errors.ts rename to packages/ledger/src/errors/ledger.errors.ts index 75ee86fa..be42abfd 100644 --- a/packages/sns/src/errors/ledger.errors.ts +++ b/packages/ledger/src/errors/ledger.errors.ts @@ -1,6 +1,6 @@ import type { TransferError } from "../../candid/icrc1_ledger"; -export class SnsTransferError extends Error { +export class IcrcTransferError extends Error { public errorType: TransferError; constructor({ msg, errorType }: { msg?: string; errorType: TransferError }) { super(msg); diff --git a/packages/ledger/src/index.ts b/packages/ledger/src/index.ts new file mode 100644 index 00000000..66964d3a --- /dev/null +++ b/packages/ledger/src/index.ts @@ -0,0 +1,13 @@ +export type { + BlockIndex as IcrcBlockIndex, + Subaccount as IcrcSubaccount, + Tokens as IcrcTokens, + TransferArg as IcrcTransferArg, + TransferError as IcrcTransferVariatError, + Value as IcrcValue, +} from "../candid/icrc1_ledger"; +export * from "./errors/ledger.errors"; +export { IcrcLedgerCanister } from "./ledger.canister"; +export * from "./types/ledger.params"; +export * from "./types/ledger.responses"; +export * from "./utils/ledger.utils"; diff --git a/packages/sns/src/ledger.canister.spec.ts b/packages/ledger/src/ledger.canister.spec.ts similarity index 70% rename from packages/sns/src/ledger.canister.spec.ts rename to packages/ledger/src/ledger.canister.spec.ts index d93fab53..d0b806ce 100644 --- a/packages/sns/src/ledger.canister.spec.ts +++ b/packages/ledger/src/ledger.canister.spec.ts @@ -4,21 +4,23 @@ import { arrayOfNumberToUint8Array } from "@dfinity/utils"; import { mock } from "jest-mock-extended"; import type { TransferArg, - _SERVICE as SnsLedgerService, + _SERVICE as IcrcLedgerService, } from "../candid/icrc1_ledger"; -import { SnsTransferError } from "./errors/ledger.errors"; -import { SnsLedgerCanister } from "./ledger.canister"; -import { tokeMetadataResponseMock } from "./mocks/ledger.mock"; -import { rootCanisterIdMock } from "./mocks/sns.mock"; +import { IcrcTransferError } from "./errors/ledger.errors"; +import { IcrcLedgerCanister } from "./ledger.canister"; +import { + ledgerCanisterIdMock, + tokeMetadataResponseMock, +} from "./mocks/ledger.mock"; import { TransferParams } from "./types/ledger.params"; describe("Ledger canister", () => { it("should return the token metadata", async () => { - const service = mock>(); + const service = mock>(); service.icrc1_metadata.mockResolvedValue(tokeMetadataResponseMock); - const canister = SnsLedgerCanister.create({ - canisterId: rootCanisterIdMock, + const canister = IcrcLedgerCanister.create({ + canisterId: ledgerCanisterIdMock, certifiedServiceOverride: service, }); @@ -27,12 +29,12 @@ describe("Ledger canister", () => { }); it("should return the transaction fee", async () => { - const service = mock>(); + const service = mock>(); const fee = BigInt(10_000); service.icrc1_fee.mockResolvedValue(fee); - const canister = SnsLedgerCanister.create({ - canisterId: rootCanisterIdMock, + const canister = IcrcLedgerCanister.create({ + canisterId: ledgerCanisterIdMock, certifiedServiceOverride: service, }); @@ -42,12 +44,12 @@ describe("Ledger canister", () => { describe("balance", () => { it("should return the balance of main account", async () => { - const service = mock>(); + const service = mock>(); const balance = BigInt(100); service.icrc1_balance_of.mockResolvedValue(balance); - const canister = SnsLedgerCanister.create({ - canisterId: rootCanisterIdMock, + const canister = IcrcLedgerCanister.create({ + canisterId: ledgerCanisterIdMock, certifiedServiceOverride: service, }); @@ -60,12 +62,12 @@ describe("Ledger canister", () => { }); it("should return the balance of subaccount", async () => { - const service = mock>(); + const service = mock>(); const balance = BigInt(100); service.icrc1_balance_of.mockResolvedValue(balance); - const canister = SnsLedgerCanister.create({ - canisterId: rootCanisterIdMock, + const canister = IcrcLedgerCanister.create({ + canisterId: ledgerCanisterIdMock, certifiedServiceOverride: service, }); @@ -99,12 +101,12 @@ describe("Ledger canister", () => { amount: BigInt(100_000_000), }; it("should return the block height successfully", async () => { - const service = mock>(); + const service = mock>(); const blockHeight = BigInt(100); service.icrc1_transfer.mockResolvedValue({ Ok: blockHeight }); - const canister = SnsLedgerCanister.create({ - canisterId: rootCanisterIdMock, + const canister = IcrcLedgerCanister.create({ + canisterId: ledgerCanisterIdMock, certifiedServiceOverride: service, }); @@ -113,8 +115,8 @@ describe("Ledger canister", () => { expect(service.icrc1_transfer).toBeCalledWith(transferArg); }); - it("should raise SnsTransferError error", async () => { - const service = mock>(); + it("should raise IcrcTransferError error", async () => { + const service = mock>(); const errorResponse = { Err: { InsufficientFunds: { @@ -124,13 +126,13 @@ describe("Ledger canister", () => { }; service.icrc1_transfer.mockResolvedValue(errorResponse); - const canister = SnsLedgerCanister.create({ - canisterId: rootCanisterIdMock, + const canister = IcrcLedgerCanister.create({ + canisterId: ledgerCanisterIdMock, certifiedServiceOverride: service, }); const call = () => canister.transfer(transferParams); - expect(call).rejects.toThrow(SnsTransferError); + expect(call).rejects.toThrow(IcrcTransferError); }); }); }); diff --git a/packages/sns/src/ledger.canister.ts b/packages/ledger/src/ledger.canister.ts similarity index 67% rename from packages/sns/src/ledger.canister.ts rename to packages/ledger/src/ledger.canister.ts index b7cb9eaa..febb646c 100644 --- a/packages/sns/src/ledger.canister.ts +++ b/packages/ledger/src/ledger.canister.ts @@ -1,35 +1,34 @@ -import { createServices, toNullable } from "@dfinity/utils"; +import type { QueryParams } from "@dfinity/utils"; +import { Canister, createServices, toNullable } from "@dfinity/utils"; import type { BlockIndex, Tokens, - _SERVICE as SnsLedgerService, + _SERVICE as IcrcLedgerService, } from "../candid/icrc1_ledger"; import { idlFactory as certifiedIdlFactory } from "../candid/icrc1_ledger.certified.idl"; import { idlFactory } from "../candid/icrc1_ledger.idl"; import { toTransferArg } from "./converters/ledger.converters"; -import { SnsTransferError } from "./errors/ledger.errors"; -import { Canister } from "./services/canister"; -import type { SnsCanisterOptions } from "./types/canister.options"; +import { IcrcTransferError } from "./errors/ledger.errors"; +import type { IcrcLedgerCanisterOptions } from "./types/canister.options"; import type { BalanceParams, TransferParams } from "./types/ledger.params"; -import type { SnsTokenMetadataResponse } from "./types/ledger.responses"; -import type { QueryParams } from "./types/query.params"; +import type { IcrcTokenMetadataResponse } from "./types/ledger.responses"; -export class SnsLedgerCanister extends Canister { - static create(options: SnsCanisterOptions) { +export class IcrcLedgerCanister extends Canister { + static create(options: IcrcLedgerCanisterOptions) { const { service, certifiedService, canisterId } = - createServices({ + createServices({ options, idlFactory, certifiedIdlFactory, }); - return new SnsLedgerCanister(canisterId, service, certifiedService); + return new IcrcLedgerCanister(canisterId, service, certifiedService); } /** * The token metadata (name, symbol, etc.). */ - metadata = (params: QueryParams): Promise => + metadata = (params: QueryParams): Promise => this.caller(params).icrc1_metadata(); /** @@ -57,14 +56,14 @@ export class SnsLedgerCanister extends Canister { * * @param {TransferArg} params The parameters to transfer tokens. * - * @throws {SnsTransferError} If the transfer fails. + * @throws {IcrcTransferError} If the transfer fails. */ transfer = async (params: TransferParams): Promise => { const response = await this.caller({ certified: true }).icrc1_transfer( toTransferArg(params) ); if ("Err" in response) { - throw new SnsTransferError({ + throw new IcrcTransferError({ errorType: response.Err, msg: "Failed to transfer", }); diff --git a/packages/ledger/src/mocks/ledger.mock.ts b/packages/ledger/src/mocks/ledger.mock.ts new file mode 100644 index 00000000..e6879e94 --- /dev/null +++ b/packages/ledger/src/mocks/ledger.mock.ts @@ -0,0 +1,22 @@ +import { Principal } from "@dfinity/principal"; +import type { Value } from "../../candid/icrc1_ledger"; +import { IcrcMetadataResponseEntries } from "../types/ledger.responses"; + +export const tokeMetadataResponseMock: [ + string | IcrcMetadataResponseEntries, + Value +][] = [ + [IcrcMetadataResponseEntries.DECIMALS, { Nat: BigInt(8) }], + [IcrcMetadataResponseEntries.NAME, { Text: "Beta Test" }], + [IcrcMetadataResponseEntries.SYMBOL, { Text: "BTA" }], + [IcrcMetadataResponseEntries.FEE, { Nat: BigInt(1000) }], +]; + +export const mockPrincipalText = + "xlmdg-vkosz-ceopx-7wtgu-g3xmd-koiyc-awqaq-7modz-zf6r6-364rh-oqe"; + +export const mockPrincipal = Principal.fromText(mockPrincipalText); + +export const ledgerCanisterIdMock: Principal = Principal.fromText( + "ktxdj-qiaaa-aaaaa-aacqa-cai" +); diff --git a/packages/ledger/src/types/canister.options.ts b/packages/ledger/src/types/canister.options.ts new file mode 100644 index 00000000..58f991bd --- /dev/null +++ b/packages/ledger/src/types/canister.options.ts @@ -0,0 +1,8 @@ +import type { Principal } from "@dfinity/principal"; +import type { CanisterOptions } from "@dfinity/utils"; + +export interface IcrcLedgerCanisterOptions + extends Omit, "canisterId"> { + // The canister's ID is mandatory to instantiate an ICRC-1 ledger. + canisterId: Principal; +} diff --git a/packages/sns/src/types/ledger.params.ts b/packages/ledger/src/types/ledger.params.ts similarity index 87% rename from packages/sns/src/types/ledger.params.ts rename to packages/ledger/src/types/ledger.params.ts index 61fdec09..34a2f835 100644 --- a/packages/sns/src/types/ledger.params.ts +++ b/packages/ledger/src/types/ledger.params.ts @@ -1,14 +1,14 @@ import type { Principal } from "@dfinity/principal"; +import type { QueryParams } from "@dfinity/utils"; import type { Account, Subaccount, Timestamp, Tokens, } from "../../candid/icrc1_ledger"; -import type { QueryParams } from "./query.params"; /** - * Params to get the balance of an SNS account. + * Params to get the balance of an ICRC-1 account. */ export interface BalanceParams extends QueryParams { owner: Principal; @@ -16,7 +16,7 @@ export interface BalanceParams extends QueryParams { } /** - * Params to make a transfer in an SNS ledger + * Params to make a transfer in an ICRC-1 ledger * * @param {Account} to The account to transfer tokens to. * @param {Tokens} amount The Amount of tokens to transfer. diff --git a/packages/sns/src/types/ledger.responses.ts b/packages/ledger/src/types/ledger.responses.ts similarity index 69% rename from packages/sns/src/types/ledger.responses.ts rename to packages/ledger/src/types/ledger.responses.ts index 87b30c4b..f6de4768 100644 --- a/packages/sns/src/types/ledger.responses.ts +++ b/packages/ledger/src/types/ledger.responses.ts @@ -2,19 +2,19 @@ import type { Principal } from "@dfinity/principal"; import type { Subaccount, Value } from "../../candid/icrc1_ledger"; // Source: https://github.com/dfinity/icrc-1#standard-metadata-entries -export enum SnsMetadataResponseEntries { +export enum IcrcMetadataResponseEntries { SYMBOL = "icrc1:symbol", NAME = "icrc1:name", DECIMALS = "icrc1:decimals", FEE = "icrc1:fee", } -export type SnsTokenMetadataResponse = [ - string | SnsMetadataResponseEntries, +export type IcrcTokenMetadataResponse = [ + string | IcrcMetadataResponseEntries, Value ][]; -export interface SnsAccount { +export interface IcrcAccount { owner: Principal; subaccount?: Subaccount; } diff --git a/packages/sns/src/utils/ledger.utils.spec.ts b/packages/ledger/src/utils/ledger.utils.spec.ts similarity index 65% rename from packages/sns/src/utils/ledger.utils.spec.ts rename to packages/ledger/src/utils/ledger.utils.spec.ts index 64ea3431..8ac4584e 100644 --- a/packages/sns/src/utils/ledger.utils.spec.ts +++ b/packages/ledger/src/utils/ledger.utils.spec.ts @@ -1,12 +1,12 @@ import { Principal } from "@dfinity/principal"; import { mockPrincipal } from "../mocks/ledger.mock"; -import { decodeSnsAccount, encodeSnsAccount } from "./ledger.utils"; +import { decodeIcrcAccount, encodeIcrcAccount } from "./ledger.utils"; -describe("sns-accounts utils", () => { - describe("encodeSnsAccount", () => { +describe("ledger-utils", () => { + describe("encodeIcrcAccount", () => { it("should return the principal text for main accounts", () => { const owner = mockPrincipal; - expect(encodeSnsAccount({ owner })).toEqual(owner.toText()); + expect(encodeIcrcAccount({ owner })).toEqual(owner.toText()); }); it("should return the principal text for subaccount 0", () => { @@ -15,7 +15,7 @@ describe("sns-accounts utils", () => { owner, subaccount: new Uint8Array(32).fill(0), }; - expect(encodeSnsAccount(account)).toEqual(owner.toText()); + expect(encodeIcrcAccount(account)).toEqual(owner.toText()); }); it("should return a string representation for subaccounts", () => { @@ -25,16 +25,16 @@ describe("sns-accounts utils", () => { owner: Principal.fromText("2vxsx-fae"), subaccount: subaccount, }; - expect(encodeSnsAccount(account)).toEqual( + expect(encodeIcrcAccount(account)).toEqual( Principal.fromHex("040101ff").toText() ); }); }); - describe("decodeSnsAccount", () => { + describe("decodeIcrcAccount", () => { it("should return the owner only for main accounts", () => { const owner = mockPrincipal; - expect(decodeSnsAccount(mockPrincipal.toText())).toEqual({ owner }); + expect(decodeIcrcAccount(mockPrincipal.toText())).toEqual({ owner }); }); it("should return the account with subaccounts", () => { @@ -44,22 +44,22 @@ describe("sns-accounts utils", () => { owner: Principal.fromText("2vxsx-fae"), subaccount, }; - expect(decodeSnsAccount(encodeSnsAccount(account1))).toEqual(account1); + expect(decodeIcrcAccount(encodeIcrcAccount(account1))).toEqual(account1); }); it("should raise an error if incorrect subaccount", () => { - const call1 = () => decodeSnsAccount(Principal.fromHex("ff").toText()); + const call1 = () => decodeIcrcAccount(Principal.fromHex("ff").toText()); expect(call1).toThrow(); const call2 = () => - decodeSnsAccount(Principal.fromHex("040001ff").toText()); + decodeIcrcAccount(Principal.fromHex("040001ff").toText()); expect(call2).toThrow(); const call3 = () => - decodeSnsAccount(Principal.fromHex("040103ff").toText()); + decodeIcrcAccount(Principal.fromHex("040103ff").toText()); expect(call3).toThrow(); - const call4 = () => decodeSnsAccount(Principal.fromHex("00ff").toText()); + const call4 = () => decodeIcrcAccount(Principal.fromHex("00ff").toText()); expect(call4).toThrow(); }); }); @@ -72,7 +72,7 @@ describe("sns-accounts utils", () => { owner: Principal.fromText("2vxsx-fae"), subaccount: subaccount1, }; - expect(decodeSnsAccount(encodeSnsAccount(account1))).toEqual(account1); + expect(decodeIcrcAccount(encodeIcrcAccount(account1))).toEqual(account1); const subaccount2 = new Uint8Array(32).fill(0); subaccount2[31] = 1; @@ -81,12 +81,12 @@ describe("sns-accounts utils", () => { owner: mockPrincipal, subaccount: subaccount2, }; - expect(decodeSnsAccount(encodeSnsAccount(account2))).toEqual(account2); + expect(decodeIcrcAccount(encodeIcrcAccount(account2))).toEqual(account2); const account3 = { owner: mockPrincipal, }; - expect(decodeSnsAccount(encodeSnsAccount(account3))).toEqual(account3); + expect(decodeIcrcAccount(encodeIcrcAccount(account3))).toEqual(account3); }); }); }); diff --git a/packages/sns/src/utils/ledger.utils.ts b/packages/ledger/src/utils/ledger.utils.ts similarity index 80% rename from packages/sns/src/utils/ledger.utils.ts rename to packages/ledger/src/utils/ledger.utils.ts index e295146b..aec3dbee 100644 --- a/packages/sns/src/utils/ledger.utils.ts +++ b/packages/ledger/src/utils/ledger.utils.ts @@ -1,5 +1,5 @@ import { Principal } from "@dfinity/principal"; -import type { SnsAccount } from "../types/ledger.responses"; +import type { IcrcAccount } from "../types/ledger.responses"; // https://github.com/dfinity/ICRC-1/pull/55/files#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R236 const EXTRA_BYTES = parseInt("FF", 16); @@ -20,13 +20,16 @@ const shrink = (bytes: Uint8Array): Uint8Array => { }; /** - * Encodes an SNS account into a string. + * Encodes an Icrc-1 account compatible into a string. * Formatting Reference: https://github.com/dfinity/ICRC-1/pull/55/files#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R238 * - * @param snsAccount { owner: Principal, subaccount?: Uint8Array } + * @param account { owner: Principal, subaccount?: Uint8Array } * @returns string */ -export const encodeSnsAccount = ({ owner, subaccount }: SnsAccount): string => { +export const encodeIcrcAccount = ({ + owner, + subaccount, +}: IcrcAccount): string => { if (subaccount === undefined) { return owner.toText(); } @@ -48,14 +51,14 @@ export const encodeSnsAccount = ({ owner, subaccount }: SnsAccount): string => { }; /** - * Decodes a string into an SNS account. + * Decodes a string into an Icrc-1 compatible account. * Formatting Reference: https://github.com/dfinity/ICRC-1/pull/55/files#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R268 * - * @param snsAccountString string - * @throws Error if the string is not a valid SNS account - * @returns snsAccount { owner: Principal, subaccount?: Uint8Array } + * @param accountString string + * @throws Error if the string is not a valid Icrc-1 account + * @returns IcrcAccount { owner: Principal, subaccount?: Uint8Array } */ -export const decodeSnsAccount = (accountString: string): SnsAccount => { +export const decodeIcrcAccount = (accountString: string): IcrcAccount => { const principal = Principal.fromText(accountString); const [ff, nonZeroLength, ...restReversed] = principal diff --git a/packages/ledger/tsconfig.json b/packages/ledger/tsconfig.json new file mode 100644 index 00000000..ca17af18 --- /dev/null +++ b/packages/ledger/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src/**/*", "candid/**/*"] +} diff --git a/packages/sns/README.md b/packages/sns/README.md index fd36ca0b..0e05aab9 100644 --- a/packages/sns/README.md +++ b/packages/sns/README.md @@ -21,7 +21,7 @@ npm i @dfinity/sns The bundle needs peer dependencies, be sure that following resources are available in your project as well. ```bash -npm i @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils +npm i @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils @dfinity/ledger ``` ## Usage @@ -56,14 +56,9 @@ const { metadata: governanceMetadata } = SnsGovernanceCanister.create({ agent, canisterId: rootCanisterId, }); -const { metadata: ledgerMetadata } = SnsLedgerCanister.create({ - agent, - canisterId: rootCanisterId, -}); const metadata = await governanceMetadata({ certified: true }); -const token = await ledgerMetadata({ certified: true }); -console.log("Summary data:", metadata, token); +console.log("Summary data:", metadata); ``` ## Features @@ -75,8 +70,6 @@ console.log("Summary data:", metadata, token); ### :toolbox: Functions - [initSnsWrapper](#gear-initsnswrapper) -- [encodeSnsAccount](#gear-encodesnsaccount) -- [decodeSnsAccount](#gear-decodesnsaccount) #### :gear: initSnsWrapper @@ -86,44 +79,12 @@ Lookup for the canister ids of a Sns and initialize the wrapper to access its fe | ---------------- | ---------------- | | `initSnsWrapper` | `InitSnsWrapper` | -#### :gear: encodeSnsAccount - -Encodes an SNS account into a string. -Formatting Reference: https://github.com/dfinity/ICRC-1/pull/55/files#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R238 - -| Function | Type | -| ------------------ | ----------------------------------------------- | -| `encodeSnsAccount` | `({ owner, subaccount }: SnsAccount) => string` | - -Parameters: - -- `snsAccount`: : Principal, subaccount?: Uint8Array } - -#### :gear: decodeSnsAccount - -Decodes a string into an SNS account. -Formatting Reference: https://github.com/dfinity/ICRC-1/pull/55/files#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R268 - -| Function | Type | -| ------------------ | --------------------------------------- | -| `decodeSnsAccount` | `(accountString: string) => SnsAccount` | - -Parameters: - -- `snsAccountString`: string - ### :factory: SnsGovernanceCanister #### Constructors `public` -Parameters: - -- `id` -- `service` -- `certifiedService` - #### Methods - [create](#gear-create) @@ -215,17 +176,17 @@ Get the Sns nervous system parameters (default followees, max dissolve delay, ma Get the neuron of the Sns -| Method | Type | -| ----------- | ----------------------------------------------------------------- | -| `getNeuron` | `(params: SnsGetNeuronParams and QueryParams) => Promise` | +| Method | Type | +| ----------- | ------------------------------------------------- | +| `getNeuron` | `(params: SnsGetNeuronParams) => Promise` | ##### :gear: queryNeuron Same as `getNeuron` but returns undefined instead of raising error when not found. -| Method | Type | -| ------------- | ----------------------------------------------------------------- | -| `queryNeuron` | `(params: SnsGetNeuronParams and QueryParams) => Promise` | +| Method | Type | +| ------------- | ------------------------------------------------- | +| `queryNeuron` | `(params: SnsGetNeuronParams) => Promise` | ##### :gear: manageNeuron @@ -349,84 +310,12 @@ Claim neuron | ------------- | -------------------------------------------------------------------------------- | | `claimNeuron` | `({ memo, controller, subaccount, }: SnsClaimNeuronParams) => Promise` | -### :factory: SnsLedgerCanister - -#### Constructors - -`public` - -Parameters: - -- `id` -- `service` -- `certifiedService` - -#### Methods - -- [create](#gear-create) -- [metadata](#gear-metadata) -- [transactionFee](#gear-transactionfee) -- [balance](#gear-balance) -- [transfer](#gear-transfer) - -##### :gear: create - -| Method | Type | -| -------- | -------------------------------------------------------------- | -| `create` | `(options: SnsCanisterOptions<_SERVICE>) => SnsLedgerCanister` | - -##### :gear: metadata - -The token metadata (name, symbol, etc.). - -| Method | Type | -| ---------- | ------------------------------------------------------------ | -| `metadata` | `(params: QueryParams) => Promise` | - -##### :gear: transactionFee - -The ledger transaction fees. - -| Method | Type | -| ---------------- | ------------------------------------------ | -| `transactionFee` | `(params: QueryParams) => Promise` | - -##### :gear: balance - -Returns the balance of the given account. - -| Method | Type | -| --------- | -------------------------------------------- | -| `balance` | `(params: BalanceParams) => Promise` | - -Parameters: - -- `params`: The parameters to get the balance of an account. - -##### :gear: transfer - -Transfers tokens from the sender to the given account. - -| Method | Type | -| ---------- | --------------------------------------------- | -| `transfer` | `(params: TransferParams) => Promise` | - -Parameters: - -- `params`: The parameters to transfer tokens. - ### :factory: SnsRootCanister #### Constructors `public` -Parameters: - -- `id` -- `service` -- `certifiedService` - #### Methods - [create](#gear-create) @@ -454,12 +343,6 @@ Source code: https://github.com/dfinity/ic/blob/master/rs/sns/root/src/lib.rs `public` -Parameters: - -- `id` -- `service` -- `certifiedService` - #### Methods - [create](#gear-create) @@ -490,12 +373,6 @@ Index Canister only holds the transactions ids in state, not the whole transacti `public` -Parameters: - -- `id` -- `service` -- `certifiedService` - #### Methods - [create](#gear-create) @@ -529,9 +406,9 @@ Notify of the user participating in the swap Get user commitment -| Method | Type | -| ------------------- | ----------------------------------------------------------------------- | -| `getUserCommitment` | `(params: GetBuyerStateRequest and QueryParams) => Promise` | +| Method | Type | +| ------------------- | -------------------------------------- | +| `getUserCommitment` | `(params: any) => Promise` | ### :factory: SnsWrapper @@ -609,9 +486,9 @@ Parameters: ##### :gear: metadata -| Method | Type | -| ---------- | ------------------------------------------------------------------------------------------------------ | -| `metadata` | `(params: Omit) => Promise<[GetMetadataResponse, SnsTokenMetadataResponse]>` | +| Method | Type | +| ---------- | ------------------------------------------------------------------------------------------------------- | +| `metadata` | `(params: Omit) => Promise<[GetMetadataResponse, IcrcTokenMetadataResponse]>` | ##### :gear: nervousSystemParameters @@ -621,27 +498,27 @@ Parameters: ##### :gear: ledgerMetadata -| Method | Type | -| ---------------- | ------------------------------------------------------------------------------- | -| `ledgerMetadata` | `(params: Omit) => Promise` | +| Method | Type | +| ---------------- | -------------------------------------------------------------------------------- | +| `ledgerMetadata` | `(params: Omit) => Promise` | ##### :gear: transactionFee -| Method | Type | -| ---------------- | ------------------------------------------------------------- | -| `transactionFee` | `(params: Omit) => Promise` | +| Method | Type | +| ---------------- | ----------------------------------------------------------------- | +| `transactionFee` | `(params: Omit) => Promise` | ##### :gear: balance -| Method | Type | -| --------- | --------------------------------------------------------------- | -| `balance` | `(params: Omit) => Promise` | +| Method | Type | +| --------- | ------------------------------------------------------------------- | +| `balance` | `(params: Omit) => Promise` | ##### :gear: transfer -| Method | Type | -| ---------- | --------------------------------------------- | -| `transfer` | `(params: TransferParams) => Promise` | +| Method | Type | +| ---------- | ----------------------------------------------------- | +| `transfer` | `(params: TransferParams) => Promise` | ##### :gear: getNeuron @@ -669,9 +546,9 @@ If the neuron does not exist for that subaccount, then we use it for the next ne The index is used in the memo of the transfer and when claiming the neuron. This is how the backend can identify which neuron is being claimed. -| Method | Type | -| ------------------- | ----------------------------------------------------------------------------- | -| `nextNeuronAccount` | `(controller: Principal) => Promise<{ account: SnsAccount; index: bigint; }>` | +| Method | Type | +| ------------------- | ------------------------------------------------------------------------------ | +| `nextNeuronAccount` | `(controller: Principal) => Promise<{ account: IcrcAccount; index: bigint; }>` | ##### :gear: stakeNeuron @@ -699,9 +576,9 @@ This is a convenient method that transfers the stake to the neuron subaccount an ##### :gear: getNeuronBalance -| Method | Type | -| ------------------ | ----------------------------------------- | -| `getNeuronBalance` | `(neuronId: NeuronId) => Promise` | +| Method | Type | +| ------------------ | --------------------------------------------- | +| `getNeuronBalance` | `(neuronId: NeuronId) => Promise` | ##### :gear: addNeuronPermissions diff --git a/packages/sns/package.json b/packages/sns/package.json index 31623008..c73dfc39 100644 --- a/packages/sns/package.json +++ b/packages/sns/package.json @@ -36,6 +36,7 @@ "sns" ], "peerDependencies": { + "@dfinity/ledger": "^0.0.1", "@dfinity/utils": "^0.0.8" }, "dependencies": { diff --git a/packages/sns/src/converters/governance.converters.ts b/packages/sns/src/converters/governance.converters.ts index 7a1d019f..9b90ba82 100644 --- a/packages/sns/src/converters/governance.converters.ts +++ b/packages/sns/src/converters/governance.converters.ts @@ -1,3 +1,4 @@ +import type { IcrcAccount } from "@dfinity/ledger"; import { toNullable } from "@dfinity/utils"; import type { Account, @@ -20,7 +21,6 @@ import type { SnsSetTopicFollowees, SnsSplitNeuronParams, } from "../types/governance.params"; -import type { SnsAccount } from "../types/ledger.responses"; // Helper for building `ManageNeuron` structure const toManageNeuronCommand = ({ @@ -54,7 +54,7 @@ const toManageNeuronConfigureCommand = ({ export const toCandidAccount = ({ owner, subaccount, -}: SnsAccount): Account => ({ +}: IcrcAccount): Account => ({ owner: toNullable(owner), subaccount: subaccount === undefined ? [] : toNullable({ subaccount }), }); diff --git a/packages/sns/src/converters/sns-index.converters.ts b/packages/sns/src/converters/sns-index.converters.ts index c354f135..720599b9 100644 --- a/packages/sns/src/converters/sns-index.converters.ts +++ b/packages/sns/src/converters/sns-index.converters.ts @@ -1,7 +1,15 @@ +import type { IcrcAccount } from "@dfinity/ledger/src"; import { toNullable } from "@dfinity/utils"; -import type { GetAccountTransactionsArgs } from "../../candid/sns_index"; +import type { + Account, + GetAccountTransactionsArgs, +} from "../../candid/sns_index"; import type { GetAccountTransactionsParams } from "../types/sns-index.params"; -import { toCandidAccount } from "./ledger.converters"; + +const toCandidAccount = ({ owner, subaccount }: IcrcAccount): Account => ({ + owner, + subaccount: toNullable(subaccount), +}); export const toGetTransactionsArgs = ({ account, diff --git a/packages/sns/src/governance.canister.ts b/packages/sns/src/governance.canister.ts index 459bf97d..4f04ceeb 100644 --- a/packages/sns/src/governance.canister.ts +++ b/packages/sns/src/governance.canister.ts @@ -1,6 +1,12 @@ import { assertPercentageNumber } from "@dfinity/nns/src/utils/number.utils"; import type { Principal } from "@dfinity/principal"; -import { createServices, fromNullable, toNullable } from "@dfinity/utils"; +import type { QueryParams } from "@dfinity/utils"; +import { + Canister, + createServices, + fromNullable, + toNullable, +} from "@dfinity/utils"; import type { GetMetadataResponse, ListNervousSystemFunctionsResponse, @@ -32,7 +38,6 @@ import { toStopDissolvingNeuronRequest, } from "./converters/governance.converters"; import { SnsGovernanceError } from "./errors/governance.errors"; -import { Canister } from "./services/canister"; import type { SnsCanisterOptions } from "./types/canister.options"; import type { SnsClaimNeuronParams, @@ -49,7 +54,6 @@ import type { SnsSetTopicFollowees, SnsSplitNeuronParams, } from "./types/governance.params"; -import type { QueryParams } from "./types/query.params"; export class SnsGovernanceCanister extends Canister { /** @@ -140,9 +144,7 @@ export class SnsGovernanceCanister extends Canister { /** * Get the neuron of the Sns */ - getNeuron = async ( - params: SnsGetNeuronParams & QueryParams - ): Promise => { + getNeuron = async (params: SnsGetNeuronParams): Promise => { const { neuronId } = params; const { result } = await this.caller(params).get_neuron({ @@ -161,7 +163,7 @@ export class SnsGovernanceCanister extends Canister { * Same as `getNeuron` but returns undefined instead of raising error when not found. */ queryNeuron = async ( - params: SnsGetNeuronParams & QueryParams + params: SnsGetNeuronParams ): Promise => { try { return await this.getNeuron(params); diff --git a/packages/sns/src/index.ts b/packages/sns/src/index.ts index 4421dd9e..3bec27df 100644 --- a/packages/sns/src/index.ts +++ b/packages/sns/src/index.ts @@ -1,7 +1,3 @@ -export type { - TransferArg as SnsTransferArg, - TransferError as SnsTransferVariatError, -} from "../candid/icrc1_ledger"; export type { Action as SnsAction, Ballot as SnsBallot, @@ -38,9 +34,7 @@ export type { export * from "./enums/governance.enums"; export * from "./enums/swap.enums"; export * from "./errors/governance.errors"; -export * from "./errors/ledger.errors"; export { SnsGovernanceCanister } from "./governance.canister"; -export { SnsLedgerCanister } from "./ledger.canister"; export { SnsRootCanister } from "./root.canister"; export * from "./sns"; export { SnsIndexCanister } from "./sns-index.canister"; @@ -48,7 +42,4 @@ export * from "./sns.wrapper"; export { SnsSwapCanister } from "./swap.canister"; export type { SnsCanisterOptions } from "./types/canister.options"; export * from "./types/governance.params"; -export * from "./types/ledger.responses"; -export type { QueryParams } from "./types/query.params"; export * from "./utils/governance.utils"; -export * from "./utils/ledger.utils"; diff --git a/packages/sns/src/mocks/ledger.mock.ts b/packages/sns/src/mocks/ledger.mock.ts index 70f6d184..674cd2d3 100644 --- a/packages/sns/src/mocks/ledger.mock.ts +++ b/packages/sns/src/mocks/ledger.mock.ts @@ -1,15 +1,15 @@ +import type { IcrcValue } from "@dfinity/ledger"; +import { IcrcMetadataResponseEntries } from "@dfinity/ledger"; import { Principal } from "@dfinity/principal"; -import type { Value } from "../../candid/icrc1_ledger"; -import { SnsMetadataResponseEntries } from "../types/ledger.responses"; export const tokeMetadataResponseMock: [ - string | SnsMetadataResponseEntries, - Value + string | IcrcMetadataResponseEntries, + IcrcValue ][] = [ - [SnsMetadataResponseEntries.DECIMALS, { Nat: BigInt(8) }], - [SnsMetadataResponseEntries.NAME, { Text: "Beta Test" }], - [SnsMetadataResponseEntries.SYMBOL, { Text: "BTA" }], - [SnsMetadataResponseEntries.FEE, { Nat: BigInt(1000) }], + [IcrcMetadataResponseEntries.DECIMALS, { Nat: BigInt(8) }], + [IcrcMetadataResponseEntries.NAME, { Text: "Beta Test" }], + [IcrcMetadataResponseEntries.SYMBOL, { Text: "BTA" }], + [IcrcMetadataResponseEntries.FEE, { Nat: BigInt(1000) }], ]; export const mockPrincipalText = diff --git a/packages/sns/src/root.canister.ts b/packages/sns/src/root.canister.ts index c071b24f..ab5c4b04 100644 --- a/packages/sns/src/root.canister.ts +++ b/packages/sns/src/root.canister.ts @@ -1,11 +1,10 @@ -import { createServices } from "@dfinity/utils"; +import { Canister, createServices } from "@dfinity/utils"; import type { ListSnsCanistersResponse, _SERVICE as SnsRootService, } from "../candid/sns_root"; import { idlFactory as certifiedIdlFactory } from "../candid/sns_root.certified.idl"; import { idlFactory } from "../candid/sns_root.idl"; -import { Canister } from "./services/canister"; import type { SnsCanisterOptions } from "./types/canister.options"; export class SnsRootCanister extends Canister { diff --git a/packages/sns/src/sns-index.canister.spec.ts b/packages/sns/src/sns-index.canister.spec.ts index 8ea1bb8a..b9deaa0b 100644 --- a/packages/sns/src/sns-index.canister.spec.ts +++ b/packages/sns/src/sns-index.canister.spec.ts @@ -1,4 +1,5 @@ import type { ActorSubclass } from "@dfinity/agent"; +import { IcrcAccount } from "@dfinity/ledger"; import { Principal } from "@dfinity/principal"; import { mock } from "jest-mock-extended"; import type { @@ -9,12 +10,11 @@ import type { import { SnsIndexError } from "./errors/sns-index.errors"; import { swapCanisterIdMock } from "./mocks/sns.mock"; import { SnsIndexCanister } from "./sns-index.canister"; -import { SnsAccount } from "./types/ledger.responses"; describe("Index canister", () => { afterEach(() => jest.clearAllMocks()); - const fakeSnsAccount: SnsAccount = { + const fakeSnsAccount: IcrcAccount = { owner: Principal.fromText("aaaaa-aa"), }; diff --git a/packages/sns/src/sns-index.canister.ts b/packages/sns/src/sns-index.canister.ts index fdf0fe7d..2939fd35 100644 --- a/packages/sns/src/sns-index.canister.ts +++ b/packages/sns/src/sns-index.canister.ts @@ -1,4 +1,4 @@ -import { createServices } from "@dfinity/utils"; +import { Canister, createServices } from "@dfinity/utils"; import type { GetTransactions, _SERVICE as SnsIndexService, @@ -7,7 +7,6 @@ import { idlFactory as certifiedIdlFactory } from "../candid/sns_index.certified import { idlFactory } from "../candid/sns_index.idl"; import { toGetTransactionsArgs } from "./converters/sns-index.converters"; import { SnsIndexError } from "./errors/sns-index.errors"; -import { Canister } from "./services/canister"; import type { SnsCanisterOptions } from "./types/canister.options"; import type { GetAccountTransactionsParams } from "./types/sns-index.params"; diff --git a/packages/sns/src/sns.ts b/packages/sns/src/sns.ts index e6fb4568..8223778c 100644 --- a/packages/sns/src/sns.ts +++ b/packages/sns/src/sns.ts @@ -1,18 +1,18 @@ import type { Agent } from "@dfinity/agent"; +import { IcrcLedgerCanister } from "@dfinity/ledger"; import type { Principal } from "@dfinity/principal"; +import type { QueryParams } from "@dfinity/utils"; import { assertNonNullish, fromNullable } from "@dfinity/utils"; import type { ListSnsCanistersResponse, _SERVICE as SnsRootService, } from "../candid/sns_root"; import { SnsGovernanceCanister } from "./governance.canister"; -import { SnsLedgerCanister } from "./ledger.canister"; import { SnsRootCanister } from "./root.canister"; import { SnsIndexCanister } from "./sns-index.canister"; import { SnsWrapper } from "./sns.wrapper"; import { SnsSwapCanister } from "./swap.canister"; import type { SnsCanisterOptions } from "./types/canister.options"; -import type { QueryParams } from "./types/query.params"; /** * Options to discover and initialize all canisters of a Sns. @@ -60,7 +60,7 @@ export const initSnsWrapper: InitSnsWrapper = async ({ canisterId: governanceCanisterId, agent, }), - ledger: SnsLedgerCanister.create({ canisterId: ledgerCanisterId, agent }), + ledger: IcrcLedgerCanister.create({ canisterId: ledgerCanisterId, agent }), swap: SnsSwapCanister.create({ canisterId: swapCanisterId, agent }), index: SnsIndexCanister.create({ canisterId: indexCanisterId, agent }), certified, diff --git a/packages/sns/src/sns.wrapper.spec.ts b/packages/sns/src/sns.wrapper.spec.ts index 92d6a387..352fd155 100644 --- a/packages/sns/src/sns.wrapper.spec.ts +++ b/packages/sns/src/sns.wrapper.spec.ts @@ -1,11 +1,16 @@ +import { IcrcLedgerCanister } from "@dfinity/ledger"; import { Principal } from "@dfinity/principal"; import { arrayOfNumberToUint8Array } from "@dfinity/utils"; import { mock } from "jest-mock-extended"; +import { + mockPrincipal, + tokeMetadataResponseMock, +} from "../../ledger/src/mocks/ledger.mock"; +import { TransferParams } from "../../ledger/src/types/ledger.params"; import { ManageNeuronResponse, NeuronId } from "../candid/sns_governance"; import { SnsNeuronPermissionType } from "./enums/governance.enums"; import { SnsGovernanceError } from "./errors/governance.errors"; import { SnsGovernanceCanister } from "./governance.canister"; -import { SnsLedgerCanister } from "./ledger.canister"; import { metadataMock, neuronIdMock, @@ -13,13 +18,11 @@ import { neuronsMock, proposalIdMock, } from "./mocks/governance.mock"; -import { mockPrincipal, tokeMetadataResponseMock } from "./mocks/ledger.mock"; import { SnsRootCanister } from "./root.canister"; import { SnsIndexCanister } from "./sns-index.canister"; import { SnsWrapper } from "./sns.wrapper"; import { SnsSwapCanister } from "./swap.canister"; import type { SnsDisburseNeuronParams } from "./types/governance.params"; -import { TransferParams } from "./types/ledger.params"; describe("SnsWrapper", () => { const mockGovernanceCanister = mock(); @@ -41,10 +44,10 @@ describe("SnsWrapper", () => { swap: [], derived: [], }); - const mockLedgerCanister = mock(); + const mockLedgerCanister = mock(); mockLedgerCanister.metadata.mockResolvedValue(tokeMetadataResponseMock); - const mockCertifiedLedgerCanister = mock(); + const mockCertifiedLedgerCanister = mock(); mockCertifiedLedgerCanister.metadata.mockResolvedValue( tokeMetadataResponseMock ); diff --git a/packages/sns/src/sns.wrapper.ts b/packages/sns/src/sns.wrapper.ts index 83cf92ce..8621d87f 100644 --- a/packages/sns/src/sns.wrapper.ts +++ b/packages/sns/src/sns.wrapper.ts @@ -1,6 +1,15 @@ +import type { + BalanceParams, + IcrcAccount, + IcrcBlockIndex, + IcrcLedgerCanister, + IcrcTokenMetadataResponse, + IcrcTokens, + TransferParams, +} from "@dfinity/ledger"; import type { Principal } from "@dfinity/principal"; +import type { QueryParams } from "@dfinity/utils"; import { bigIntToUint8Array, toNullable } from "@dfinity/utils"; -import type { BlockIndex, Tokens } from "../candid/icrc1_ledger"; import type { GetMetadataResponse, ListNervousSystemFunctionsResponse, @@ -19,7 +28,6 @@ import type { import { MAX_NEURONS_SUBACCOUNTS } from "./constants/governance.constants"; import { SnsGovernanceError } from "./errors/governance.errors"; import type { SnsGovernanceCanister } from "./governance.canister"; -import type { SnsLedgerCanister } from "./ledger.canister"; import type { SnsRootCanister } from "./root.canister"; import type { SnsIndexCanister } from "./sns-index.canister"; import type { SnsSwapCanister } from "./swap.canister"; @@ -40,12 +48,6 @@ import type { SnsSplitNeuronParams, SnsStakeNeuronParams, } from "./types/governance.params"; -import type { BalanceParams, TransferParams } from "./types/ledger.params"; -import type { - SnsAccount, - SnsTokenMetadataResponse, -} from "./types/ledger.responses"; -import type { QueryParams } from "./types/query.params"; import type { GetAccountTransactionsParams } from "./types/sns-index.params"; import { neuronSubaccount } from "./utils/governance.utils"; @@ -55,7 +57,7 @@ interface SnsWrapperOptions { /** The wrapper for the "governance" canister of the particular Sns */ governance: SnsGovernanceCanister; /** The wrapper for the "ledger" canister of the particular Sns */ - ledger: SnsLedgerCanister; + ledger: IcrcLedgerCanister; /** The wrapper for the "swap" canister of the particular Sns */ swap: SnsSwapCanister; /** The wrapper for the "index" canister of the particular Sns */ @@ -73,7 +75,7 @@ interface SnsWrapperOptions { export class SnsWrapper { private readonly root: SnsRootCanister; private readonly governance: SnsGovernanceCanister; - private readonly ledger: SnsLedgerCanister; + private readonly ledger: IcrcLedgerCanister; private readonly swap: SnsSwapCanister; private readonly index: SnsIndexCanister; private readonly certified: boolean; @@ -135,7 +137,7 @@ export class SnsWrapper { metadata = ( params: Omit - ): Promise<[GetMetadataResponse, SnsTokenMetadataResponse]> => + ): Promise<[GetMetadataResponse, IcrcTokenMetadataResponse]> => Promise.all([ this.governance.metadata(this.mergeParams(params)), this.ledger.metadata(this.mergeParams(params)), @@ -148,17 +150,19 @@ export class SnsWrapper { ledgerMetadata = ( params: Omit - ): Promise => + ): Promise => this.ledger.metadata(this.mergeParams(params)); - transactionFee = (params: Omit): Promise => + transactionFee = ( + params: Omit + ): Promise => this.ledger.transactionFee(this.mergeParams(params)); - balance = (params: Omit): Promise => + balance = (params: Omit): Promise => this.ledger.balance(this.mergeParams(params)); // Always certified - transfer = (params: TransferParams): Promise => + transfer = (params: TransferParams): Promise => this.ledger.transfer(params); getNeuron = ( @@ -188,7 +192,7 @@ export class SnsWrapper { */ nextNeuronAccount = async ( controller: Principal - ): Promise<{ account: SnsAccount; index: bigint }> => { + ): Promise<{ account: IcrcAccount; index: bigint }> => { // TODO: try parallilizing requests to improve performance // OR use binary search https://dfinity.atlassian.net/browse/FOLLOW-825 for (let index = 0; index < MAX_NEURONS_SUBACCOUNTS; index++) { @@ -298,7 +302,7 @@ export class SnsWrapper { return this.governance.refreshNeuron(neuronId); }; - getNeuronBalance = async (neuronId: NeuronId): Promise => { + getNeuronBalance = async (neuronId: NeuronId): Promise => { const account = { ...this.owner, subaccount: neuronId.id, @@ -400,7 +404,7 @@ export class SnsWrapper { * * @private */ - private get owner(): SnsAccount { + private get owner(): IcrcAccount { return { owner: this.canisterIds.governanceCanisterId, }; diff --git a/packages/sns/src/swap.canister.ts b/packages/sns/src/swap.canister.ts index d05799c5..f6d33572 100644 --- a/packages/sns/src/swap.canister.ts +++ b/packages/sns/src/swap.canister.ts @@ -1,4 +1,5 @@ -import { createServices, fromNullable } from "@dfinity/utils"; +import type { QueryParams } from "@dfinity/utils"; +import { Canister, createServices, fromNullable } from "@dfinity/utils"; import type { BuyerState, GetBuyerStateRequest, @@ -8,9 +9,7 @@ import type { } from "../candid/sns_swap"; import { idlFactory as certifiedIdlFactory } from "../candid/sns_swap.certified.idl"; import { idlFactory } from "../candid/sns_swap.idl"; -import { Canister } from "./services/canister"; import type { SnsCanisterOptions } from "./types/canister.options"; -import type { QueryParams } from "./types/query.params"; export class SnsSwapCanister extends Canister { static create(options: SnsCanisterOptions) { diff --git a/packages/sns/src/types/governance.params.ts b/packages/sns/src/types/governance.params.ts index 2339e927..96ffaf15 100644 --- a/packages/sns/src/types/governance.params.ts +++ b/packages/sns/src/types/governance.params.ts @@ -1,5 +1,6 @@ +import type { IcrcAccount, IcrcSubaccount, IcrcTokens } from "@dfinity/ledger"; import type { Principal } from "@dfinity/principal"; -import type { Subaccount, Tokens } from "../../candid/icrc1_ledger"; +import type { QueryParams } from "@dfinity/utils"; import type { NeuronId, ProposalId } from "../../candid/sns_governance"; import type { SnsNeuronPermissionType, @@ -7,8 +8,6 @@ import type { SnsProposalRewardStatus, } from "../enums/governance.enums"; import type { E8s } from "./common"; -import type { SnsAccount } from "./ledger.responses"; -import type { QueryParams } from "./query.params"; /** * The parameters available to list Sns neurons @@ -56,15 +55,15 @@ export interface SnsGetProposalParams extends QueryParams { } /** - * The parameters to get an sns neuron + * The parameters to get a Sns neuron */ export interface SnsGetNeuronParams extends QueryParams { neuronId: NeuronId; } export interface SnsStakeNeuronParams extends Omit { - stakeE8s: Tokens; - source: SnsAccount; + stakeE8s: IcrcTokens; + source: IcrcAccount; controller: Principal; // Same as createdAt from ledger's TransferParams createdAt?: bigint; @@ -72,8 +71,8 @@ export interface SnsStakeNeuronParams extends Omit { export interface SnsIncreaseStakeNeuronParams extends Omit { - stakeE8s: Tokens; - source: SnsAccount; + stakeE8s: IcrcTokens; + source: IcrcAccount; neuronId: NeuronId; } @@ -112,7 +111,7 @@ export interface SnsSplitNeuronParams extends SnsNeuronManagementParams { */ export interface SnsDisburseNeuronParams extends SnsNeuronManagementParams { amount?: E8s; - toAccount?: SnsAccount; + toAccount?: IcrcAccount; } /** @@ -145,7 +144,7 @@ export interface SnsSetTopicFollowees extends SnsNeuronManagementParams { export interface SnsClaimNeuronParams { memo: bigint; controller: Principal; - subaccount: Subaccount; + subaccount: IcrcSubaccount; } /** diff --git a/packages/sns/src/types/sns-index.params.ts b/packages/sns/src/types/sns-index.params.ts index d487f962..d819f8cb 100644 --- a/packages/sns/src/types/sns-index.params.ts +++ b/packages/sns/src/types/sns-index.params.ts @@ -1,8 +1,8 @@ +import type { IcrcAccount } from "@dfinity/ledger"; import type { TxId } from "../../candid/sns_index"; -import type { SnsAccount } from "./ledger.responses"; export interface GetAccountTransactionsParams { max_results: bigint; start?: TxId; - account: SnsAccount; + account: IcrcAccount; } diff --git a/packages/sns/src/utils/governance.utils.ts b/packages/sns/src/utils/governance.utils.ts index a9c058e9..71686862 100644 --- a/packages/sns/src/utils/governance.utils.ts +++ b/packages/sns/src/utils/governance.utils.ts @@ -1,7 +1,7 @@ +import type { IcrcSubaccount } from "@dfinity/ledger"; import type { Principal } from "@dfinity/principal"; import { asciiStringToByteArray, numberToUint8Array } from "@dfinity/utils"; import { sha256 } from "js-sha256"; -import type { Subaccount } from "../../candid/icrc1_ledger"; /** * Neuron subaccount is calculated as "sha256(0x0c . “neuron-stake” . controller . i)" @@ -17,7 +17,7 @@ export const neuronSubaccount = ({ }: { index: number; controller: Principal; -}): Subaccount => { +}): IcrcSubaccount => { const padding = asciiStringToByteArray("neuron-stake"); const data = [ 0x0c, diff --git a/packages/utils/README.md b/packages/utils/README.md index d7a02cc9..174a3adb 100644 --- a/packages/utils/README.md +++ b/packages/utils/README.md @@ -164,6 +164,18 @@ Tags after patch version are ignored, e.g. 1.0.0-beta.1 is considered equal to 1 | ---------------- | ----------------------------------------------------------------------------------------------- | | `smallerVersion` | `({ minVersion, currentVersion, }: { minVersion: string; currentVersion: string; }) => boolean` | +### :factory: Canister + +#### Constructors + +`public` + +Parameters: + +- `id` +- `service` +- `certifiedService` + ### :factory: NullishError #### Constructors diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index 02db0d4d..6128f67c 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -1,4 +1,6 @@ +export * from "./services/canister"; export type { CanisterOptions } from "./types/canister.options"; +export type { QueryParams } from "./types/query.params"; export * from "./utils/actor.utils"; export * from "./utils/agent.utils"; export * from "./utils/arrays.utils"; diff --git a/packages/sns/src/services/canister.ts b/packages/utils/src/services/canister.ts similarity index 100% rename from packages/sns/src/services/canister.ts rename to packages/utils/src/services/canister.ts diff --git a/packages/sns/src/types/query.params.ts b/packages/utils/src/types/query.params.ts similarity index 74% rename from packages/sns/src/types/query.params.ts rename to packages/utils/src/types/query.params.ts index 86542830..64850cc0 100644 --- a/packages/sns/src/types/query.params.ts +++ b/packages/utils/src/types/query.params.ts @@ -1,5 +1,5 @@ /** - * The common parameters to query Sns features + * The common parameters to query features */ export interface QueryParams { /** Perform update calls (certified) or query calls (not certified). */ diff --git a/scripts/compile-idl-js b/scripts/compile-idl-js index e066efbb..4f761ff6 100755 --- a/scripts/compile-idl-js +++ b/scripts/compile-idl-js @@ -16,6 +16,7 @@ did_files_to_compile() { did_files_to_compile_for_pkg "nns" did_files_to_compile_for_pkg "sns" did_files_to_compile_for_pkg "cmc" + did_files_to_compile_for_pkg "ledger" } # Normal API access. diff --git a/scripts/docs.js b/scripts/docs.js index a30137d7..4982e986 100644 --- a/scripts/docs.js +++ b/scripts/docs.js @@ -15,20 +15,23 @@ const nnsInputFiles = [ const snsInputFiles = [ "./packages/sns/src/governance.canister.ts", - "./packages/sns/src/ledger.canister.ts", "./packages/sns/src/governance.canister.ts", "./packages/sns/src/root.canister.ts", "./packages/sns/src/sns-index.canister.ts", "./packages/sns/src/sns.ts", "./packages/sns/src/sns.wrapper.ts", "./packages/sns/src/swap.canister.ts", - "./packages/sns/src/utils/ledger.utils.ts", ]; const utilsInputFiles = ["./packages/utils/src/index.ts"]; const cmcInputFiles = ["./packages/cmc/src/cmc.canister.ts"]; +const ledgerInputFiles = [ + "./packages/ledger/src/ledger.canister.ts", + "./packages/ledger/src/utils/ledger.utils.ts", +]; + generateDocumentation({ inputFiles: nnsInputFiles, outputFile: "./packages/nns/README.md", @@ -47,6 +50,12 @@ generateDocumentation({ markdownOptions: { headingLevel: "###" }, }); +generateDocumentation({ + inputFiles: ledgerInputFiles, + outputFile: "./packages/ledger/README.md", + markdownOptions: { headingLevel: "###" }, +}); + generateDocumentation({ inputFiles: utilsInputFiles, outputFile: "./packages/utils/README.md", diff --git a/scripts/import-candid b/scripts/import-candid index 89ab621e..62421995 100755 --- a/scripts/import-candid +++ b/scripts/import-candid @@ -61,7 +61,6 @@ import_did "rs/nns/gtc/canister/gtc.did" "genesis_token.did" "nns" import_did "rs/nns/sns-wasm/canister/sns-wasm.did" "sns_wasm.did" "nns" mkdir -p packages/sns/candid -import_did "rs/rosetta-api/icrc1/ledger/icrc1.did" "icrc1_ledger.did" "sns" import_did "rs/sns/swap/canister/swap.did" "sns_swap.did" "sns" import_did "rs/sns/root/canister/root.did" "sns_root.did" "sns" import_did "rs/sns/governance/canister/governance.did" "sns_governance.did" "sns" @@ -69,4 +68,7 @@ import_did "rs/rosetta-api/icrc1/index/index.did" "sns_index.did" "sns" mkdir -p packages/cmc/candid import_did "rs/nns/cmc/cmc.did" "cmc.did" "cmc" + +mkdir -p packages/ledger/candid +import_did "rs/rosetta-api/icrc1/ledger/icrc1.did" "icrc1_ledger.did" "ledger" : Fin