@dfinity/nns 0.1.6 → 0.2.0

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.
Files changed (74) hide show
  1. package/README.md +10 -11
  2. package/dist/cjs/index.cjs.js +869 -0
  3. package/dist/cjs/index.cjs.js.map +7 -0
  4. package/dist/esm/account_identifier.js +2 -0
  5. package/dist/esm/account_identifier.js.map +7 -0
  6. package/dist/esm/chunk-4FZAJTYF.js +2 -0
  7. package/dist/esm/chunk-4FZAJTYF.js.map +7 -0
  8. package/dist/esm/chunk-AM5HOKAH.js +2 -0
  9. package/dist/esm/chunk-AM5HOKAH.js.map +7 -0
  10. package/dist/esm/chunk-FVDRR6PO.js +17 -0
  11. package/dist/esm/chunk-FVDRR6PO.js.map +7 -0
  12. package/dist/esm/chunk-HFWTAZD7.js +825 -0
  13. package/dist/esm/chunk-HFWTAZD7.js.map +7 -0
  14. package/dist/esm/chunk-IQ5S76MI.js +4 -0
  15. package/dist/esm/chunk-IQ5S76MI.js.map +7 -0
  16. package/dist/esm/chunk-LNMGZ6W7.js +3 -0
  17. package/dist/esm/chunk-LNMGZ6W7.js.map +7 -0
  18. package/dist/esm/chunk-NYI672WX.js +14 -0
  19. package/dist/esm/chunk-NYI672WX.js.map +7 -0
  20. package/dist/esm/chunk-SO23SIWX.js +3 -0
  21. package/dist/esm/chunk-SO23SIWX.js.map +7 -0
  22. package/dist/esm/chunk-X2SHUWG3.js +2 -0
  23. package/dist/esm/chunk-X2SHUWG3.js.map +7 -0
  24. package/dist/esm/governance.js +2 -0
  25. package/dist/esm/governance.js.map +7 -0
  26. package/dist/esm/icp.js +2 -0
  27. package/dist/esm/icp.js.map +7 -0
  28. package/dist/esm/index.js +2 -0
  29. package/dist/esm/index.js.map +7 -0
  30. package/dist/esm/ledger.js +2 -0
  31. package/dist/esm/ledger.js.map +7 -0
  32. package/dist/index.cjs.js +1 -0
  33. package/dist/index.js +1 -12
  34. package/dist/{account_identifier.d.ts → types/account_identifier.d.ts} +5 -2
  35. package/dist/types/canisters/governance/payloads.d.ts +3 -0
  36. package/dist/types/canisters/governance/request.converters.d.ts +26 -0
  37. package/dist/types/canisters/governance/response.converters.d.ts +35 -0
  38. package/dist/types/constants/canister_ids.d.ts +4 -0
  39. package/dist/types/constants/constants.d.ts +5 -0
  40. package/dist/types/governance.d.ts +29 -0
  41. package/dist/{icp.d.ts → types/icp.d.ts} +2 -5
  42. package/dist/types/index.d.ts +8 -0
  43. package/dist/types/ledger.d.ts +33 -0
  44. package/dist/types/types/common.d.ts +8 -0
  45. package/dist/types/types/governance.d.ts +9 -0
  46. package/dist/types/types/governance_converters.d.ts +532 -0
  47. package/dist/types/types/icp.d.ts +4 -0
  48. package/dist/types/types/ledger.d.ts +30 -0
  49. package/dist/types/types/option.d.ts +1 -0
  50. package/dist/types/utils/agent.utils.d.ts +5 -0
  51. package/dist/types/utils/converter.utils.d.ts +18 -0
  52. package/dist/{utils/proto.d.ts → types/utils/proto.utils.d.ts} +0 -0
  53. package/package.json +47 -36
  54. package/candid/governance.certified.did +0 -12
  55. package/candid/governance.certified.idl.d.ts +0 -2
  56. package/candid/governance.certified.idl.js +0 -18
  57. package/candid/governance.did +0 -10
  58. package/candid/governance.idl.d.ts +0 -5
  59. package/candid/governance.idl.js +0 -18
  60. package/candid/governanceTypes.d.ts +0 -16
  61. package/dist/account_identifier.js +0 -95
  62. package/dist/governance.d.ts +0 -30
  63. package/dist/governance.js +0 -55
  64. package/dist/icp.js +0 -65
  65. package/dist/index.d.ts +0 -4
  66. package/dist/ledger.d.ts +0 -54
  67. package/dist/ledger.js +0 -131
  68. package/dist/utils/proto.js +0 -59
  69. package/proto/base_types.proto +0 -60
  70. package/proto/base_types_pb.d.ts +0 -144
  71. package/proto/base_types_pb.js +0 -1142
  72. package/proto/ledger.proto +0 -277
  73. package/proto/ledger_pb.d.ts +0 -911
  74. package/proto/ledger_pb.js +0 -7151
package/package.json CHANGED
@@ -1,41 +1,42 @@
1
1
  {
2
2
  "name": "@dfinity/nns",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "description": "A library for interfacing with the Internet Computer's Network Nervous System.",
5
- "keywords": [
6
- "internet computer",
7
- "internet-computer",
8
- "ic",
9
- "dfinity",
10
- "dfx",
11
- "canister",
12
- "candid",
13
- "motoko",
14
- "javascript",
15
- "typescript",
16
- "blockchain",
17
- "crypto",
18
- "nns",
19
- "network nervous system",
20
- "network-nervous-system"
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"
21
13
  ],
22
- "main": "dist/index.js",
23
14
  "scripts": {
24
- "build": "tsc",
15
+ "rmdir": "node ./scripts/rmdir.mjs",
16
+ "ts-declaration": "tsc --emitDeclarationOnly --outDir dist/types",
17
+ "did": "scripts/compile-idl-js",
18
+ "build": "npm run rmdir && node esbuild.mjs && npm run ts-declaration",
25
19
  "test": "jest",
26
20
  "doc": "typedoc ./src/index.ts",
27
21
  "lint": "eslint --max-warnings 0 .",
28
22
  "format": "prettier --write .",
29
23
  "update_proto": "bash ./scripts/update_proto.sh"
30
24
  },
25
+ "dependencies": {
26
+ "@dfinity/agent": "^0.10.2",
27
+ "@dfinity/candid": "^0.10.2",
28
+ "@dfinity/principal": "^0.10.2",
29
+ "crc": "^3.8.0",
30
+ "crc-32": "^1.2.0",
31
+ "google-protobuf": "^3.19.1",
32
+ "js-sha256": "^0.9.0"
33
+ },
31
34
  "devDependencies": {
32
- "@babel/preset-env": "^7.16.11",
33
35
  "@types/google-protobuf": "^3.15.5",
34
36
  "@types/jest": "^27.0.3",
35
37
  "@types/text-encoding": "^0.0.36",
36
38
  "@typescript-eslint/eslint-plugin": "^5.4.0",
37
- "babel-jest": "^27.4.6",
38
- "babelify": "^10.0.0",
39
+ "esbuild": "^0.14.14",
39
40
  "eslint": "^7.29.0",
40
41
  "eslint-config-standard": "^16.0.3",
41
42
  "eslint-plugin-import": "^2.23.4",
@@ -44,6 +45,7 @@
44
45
  "jest": "^27.3.1",
45
46
  "jest-mock-extended": "^2.0.4",
46
47
  "prettier": "^2.5.0",
48
+ "prettier-plugin-organize-imports": "^2.3.4",
47
49
  "text-encoding": "^0.7.0",
48
50
  "ts-jest": "^27.0.7",
49
51
  "ts-protoc-gen": "^0.15.0",
@@ -51,19 +53,28 @@
51
53
  "typescript": "^4.5.2",
52
54
  "whatwg-fetch": "^3.6.2"
53
55
  },
54
- "dependencies": {
55
- "@dfinity/agent": "^0.10.2",
56
- "@dfinity/candid": "^0.10.2",
57
- "@dfinity/principal": "^0.10.2",
58
- "crc-32": "^1.2.0",
59
- "google-protobuf": "^3.19.1",
60
- "js-sha256": "^0.9.0"
56
+ "repository": {
57
+ "type": "git",
58
+ "url": "git+https://github.com/dfinity/nns-js.git"
59
+ },
60
+ "bugs": {
61
+ "url": "https://github.com/dfinity/nns-js"
61
62
  },
62
- "browserify": {
63
- "transform": [
64
- [
65
- "babelify"
66
- ]
67
- ]
68
- }
63
+ "keywords": [
64
+ "internet computer",
65
+ "internet-computer",
66
+ "ic",
67
+ "dfinity",
68
+ "dfx",
69
+ "canister",
70
+ "candid",
71
+ "motoko",
72
+ "javascript",
73
+ "typescript",
74
+ "blockchain",
75
+ "crypto",
76
+ "nns",
77
+ "network nervous system",
78
+ "network-nervous-system"
79
+ ]
69
80
  }
@@ -1,12 +0,0 @@
1
- # The candid to interact with the governance canister using update calls in place of queries for additional security.
2
-
3
- type KnownNeuron = record {
4
- id : opt NeuronId;
5
- known_neuron_data : opt KnownNeuronData;
6
- };
7
- type KnownNeuronData = record { name : text; description : opt text };
8
- type ListKnownNeuronsResponse = record { known_neurons : vec KnownNeuron };
9
- type NeuronId = record { id : nat64 };
10
- service : {
11
- list_known_neurons : () -> (ListKnownNeuronsResponse);
12
- }
@@ -1,2 +0,0 @@
1
- import type { IDL } from "@dfinity/candid";
2
- export const idlFactory: IDL.InterfaceFactory;
@@ -1,18 +0,0 @@
1
- export const idlFactory = ({ IDL }) => {
2
- const NeuronId = IDL.Record({ 'id' : IDL.Nat64 });
3
- const KnownNeuronData = IDL.Record({
4
- 'name' : IDL.Text,
5
- 'description' : IDL.Opt(IDL.Text),
6
- });
7
- const KnownNeuron = IDL.Record({
8
- 'id' : IDL.Opt(NeuronId),
9
- 'known_neuron_data' : IDL.Opt(KnownNeuronData),
10
- });
11
- const ListKnownNeuronsResponse = IDL.Record({
12
- 'known_neurons' : IDL.Vec(KnownNeuron),
13
- });
14
- return IDL.Service({
15
- 'list_known_neurons' : IDL.Func([], [ListKnownNeuronsResponse], []),
16
- });
17
- };
18
- export const init = ({ IDL }) => { return []; };
@@ -1,10 +0,0 @@
1
- type KnownNeuron = record {
2
- id : opt NeuronId;
3
- known_neuron_data : opt KnownNeuronData;
4
- };
5
- type KnownNeuronData = record { name : text; description : opt text };
6
- type ListKnownNeuronsResponse = record { known_neurons : vec KnownNeuron };
7
- type NeuronId = record { id : nat64 };
8
- service : {
9
- list_known_neurons : () -> (ListKnownNeuronsResponse) query;
10
- }
@@ -1,5 +0,0 @@
1
- import type { IDL } from "@dfinity/candid";
2
- export const idlFactory: IDL.InterfaceFactory;
3
-
4
- import { _SERVICE } from "./governanceTypes";
5
- export { _SERVICE as GovernanceService };
@@ -1,18 +0,0 @@
1
- export const idlFactory = ({ IDL }) => {
2
- const NeuronId = IDL.Record({ 'id' : IDL.Nat64 });
3
- const KnownNeuronData = IDL.Record({
4
- 'name' : IDL.Text,
5
- 'description' : IDL.Opt(IDL.Text),
6
- });
7
- const KnownNeuron = IDL.Record({
8
- 'id' : IDL.Opt(NeuronId),
9
- 'known_neuron_data' : IDL.Opt(KnownNeuronData),
10
- });
11
- const ListKnownNeuronsResponse = IDL.Record({
12
- 'known_neurons' : IDL.Vec(KnownNeuron),
13
- });
14
- return IDL.Service({
15
- 'list_known_neurons' : IDL.Func([], [ListKnownNeuronsResponse], ['query']),
16
- });
17
- };
18
- export const init = ({ IDL }) => { return []; };
@@ -1,16 +0,0 @@
1
- import type { Principal } from '@dfinity/principal';
2
- export interface KnownNeuron {
3
- 'id' : [] | [NeuronId],
4
- 'known_neuron_data' : [] | [KnownNeuronData],
5
- }
6
- export interface KnownNeuronData {
7
- 'name' : string,
8
- 'description' : [] | [string],
9
- }
10
- export interface ListKnownNeuronsResponse {
11
- 'known_neurons' : Array<KnownNeuron>,
12
- }
13
- export interface NeuronId { 'id' : bigint }
14
- export interface _SERVICE {
15
- 'list_known_neurons' : () => Promise<ListKnownNeuronsResponse>,
16
- }
@@ -1,95 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
- Object.defineProperty(o, "default", { enumerable: true, value: v });
11
- }) : function(o, v) {
12
- o["default"] = v;
13
- });
14
- var __importStar = (this && this.__importStar) || function (mod) {
15
- if (mod && mod.__esModule) return mod;
16
- var result = {};
17
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
- __setModuleDefault(result, mod);
19
- return result;
20
- };
21
- Object.defineProperty(exports, "__esModule", { value: true });
22
- exports.SubAccount = exports.AccountIdentifier = void 0;
23
- const ledger_pb_1 = require("../proto/ledger_pb");
24
- const js_sha256_1 = require("js-sha256");
25
- const crc = __importStar(require("crc-32"));
26
- class AccountIdentifier {
27
- constructor(bytes) {
28
- this.bytes = bytes;
29
- }
30
- static fromHex(hex) {
31
- return new AccountIdentifier(Uint8Array.from(Buffer.from(hex, "hex")));
32
- }
33
- static fromPrincipal(principal, subAccount = SubAccount.ZERO) {
34
- // Hash (sha224) the principal, the subAccount and some padding
35
- const padding = asciiStringToByteArray("\x0Aaccount-id");
36
- const shaObj = js_sha256_1.sha224.create();
37
- shaObj.update([
38
- ...padding,
39
- ...principal.toUint8Array(),
40
- ...subAccount.toUint8Array(),
41
- ]);
42
- const hash = new Uint8Array(shaObj.array());
43
- // Prepend the checksum of the hash and convert to a hex string
44
- const checksum = calculateCrc32(hash);
45
- const bytes = new Uint8Array([...checksum, ...hash]);
46
- return new AccountIdentifier(bytes);
47
- }
48
- /**
49
- * @returns An AccountIdentifier protobuf object.
50
- */
51
- toProto() {
52
- const accountIdentifier = new ledger_pb_1.AccountIdentifier();
53
- accountIdentifier.setHash(this.bytes);
54
- return accountIdentifier;
55
- }
56
- toHex() {
57
- return toHexString(this.bytes);
58
- }
59
- }
60
- exports.AccountIdentifier = AccountIdentifier;
61
- class SubAccount {
62
- constructor(bytes) {
63
- this.bytes = bytes;
64
- }
65
- static fromBytes(bytes) {
66
- if (bytes.length != 32) {
67
- return Error("Subaccount length must be 32-bytes");
68
- }
69
- return new SubAccount(bytes);
70
- }
71
- static fromPrincipal(principal) {
72
- const bytes = new Uint8Array(32).fill(0);
73
- const principalBytes = principal.toUint8Array();
74
- bytes[0] = principalBytes.length;
75
- for (let i = 0; i < principalBytes.length; i++) {
76
- bytes[1 + i] = principalBytes[i];
77
- }
78
- return new SubAccount(bytes);
79
- }
80
- toUint8Array() {
81
- return this.bytes;
82
- }
83
- }
84
- exports.SubAccount = SubAccount;
85
- SubAccount.ZERO = new SubAccount(new Uint8Array(32).fill(0));
86
- const asciiStringToByteArray = (text) => {
87
- return Array.from(text).map((c) => c.charCodeAt(0));
88
- };
89
- const toHexString = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
90
- const calculateCrc32 = (bytes) => {
91
- const checksumArrayBuf = new ArrayBuffer(4);
92
- const view = new DataView(checksumArrayBuf);
93
- view.setUint32(0, crc.buf(Buffer.from(bytes)), false);
94
- return Buffer.from(checksumArrayBuf);
95
- };
@@ -1,30 +0,0 @@
1
- import { Agent } from "@dfinity/agent";
2
- import { Principal } from "@dfinity/principal";
3
- import { GovernanceService } from "../candid/governance.idl";
4
- declare type NeuronId = bigint;
5
- export declare type KnownNeuron = {
6
- id: NeuronId;
7
- name: string;
8
- description: string | undefined;
9
- };
10
- export interface GovernanceCanisterOptions {
11
- agent?: Agent;
12
- canisterId?: Principal;
13
- serviceOverride?: GovernanceService;
14
- certifiedServiceOverride?: GovernanceService;
15
- }
16
- export declare class GovernanceCanister {
17
- private readonly service;
18
- private readonly certifiedService;
19
- private constructor();
20
- static create(options?: GovernanceCanisterOptions): GovernanceCanister;
21
- /**
22
- * Returns the list of neurons who have been approved by the community to
23
- * appear as the default followee options.
24
- *
25
- * If `certified` is true, the request is fetched as an update call, otherwise
26
- * it is fetched using a query call.
27
- */
28
- listKnownNeurons: (certified?: boolean) => Promise<KnownNeuron[]>;
29
- }
30
- export {};
@@ -1,55 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GovernanceCanister = void 0;
4
- const agent_1 = require("@dfinity/agent");
5
- const principal_1 = require("@dfinity/principal");
6
- const governance_idl_1 = require("../candid/governance.idl");
7
- const governance_certified_idl_1 = require("../candid/governance.certified.idl");
8
- const MAINNET_GOVERNANCE_CANISTER_ID = principal_1.Principal.fromText("rrkah-fqaaa-aaaaa-aaaaq-cai");
9
- class GovernanceCanister {
10
- constructor(service, certifiedService) {
11
- this.service = service;
12
- this.certifiedService = certifiedService;
13
- /**
14
- * Returns the list of neurons who have been approved by the community to
15
- * appear as the default followee options.
16
- *
17
- * If `certified` is true, the request is fetched as an update call, otherwise
18
- * it is fetched using a query call.
19
- */
20
- this.listKnownNeurons = async (certified = true) => {
21
- const service = certified ? this.certifiedService : this.service;
22
- const response = await service.list_known_neurons();
23
- return response.known_neurons.map(n => ({
24
- id: n.id[0]?.id ?? BigInt(0),
25
- name: n.known_neuron_data[0]?.name ?? "",
26
- description: n.known_neuron_data[0]?.description[0]
27
- }));
28
- };
29
- }
30
- static create(options = {}) {
31
- const agent = options.agent ?? defaultAgent();
32
- const canisterId = options.canisterId ?? MAINNET_GOVERNANCE_CANISTER_ID;
33
- const service = options.serviceOverride ??
34
- agent_1.Actor.createActor(governance_idl_1.idlFactory, {
35
- agent,
36
- canisterId,
37
- });
38
- const certifiedService = options.certifiedServiceOverride ??
39
- agent_1.Actor.createActor(governance_certified_idl_1.idlFactory, {
40
- agent,
41
- canisterId,
42
- });
43
- return new GovernanceCanister(service, certifiedService);
44
- }
45
- }
46
- exports.GovernanceCanister = GovernanceCanister;
47
- /**
48
- * @returns The default agent to use. An agent that connects to mainnet with the anonymous identity.
49
- */
50
- function defaultAgent() {
51
- return new agent_1.HttpAgent({
52
- host: "https://ic0.app",
53
- identity: new agent_1.AnonymousIdentity(),
54
- });
55
- }
package/dist/icp.js DELETED
@@ -1,65 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FromStringError = exports.ICP = void 0;
4
- const ledger_pb_1 = require("../proto/ledger_pb");
5
- const E8S_PER_ICP = BigInt(100000000);
6
- class ICP {
7
- constructor(e8s) {
8
- this.e8s = e8s;
9
- }
10
- static fromE8s(amount) {
11
- return new ICP(amount);
12
- }
13
- /**
14
- * Initialize from a string. Accepted formats:
15
- *
16
- * 1234567.8901
17
- * 1'234'567.8901
18
- * 1,234,567.8901
19
- */
20
- static fromString(amount) {
21
- // Remove all instances of "," and "'".
22
- amount = amount.trim().replace(/[,']/g, "");
23
- // Verify that the string is of the format 1234.5678
24
- const regexMatch = amount.match(/\d*(\.\d*)?/);
25
- if (!regexMatch || regexMatch[0] !== amount) {
26
- return FromStringError.INVALID_FORMAT;
27
- }
28
- const [integral, fractional] = amount.split(".");
29
- let e8s = BigInt(0);
30
- if (integral) {
31
- try {
32
- e8s += BigInt(integral) * E8S_PER_ICP;
33
- }
34
- catch {
35
- return FromStringError.INVALID_FORMAT;
36
- }
37
- }
38
- if (fractional) {
39
- if (fractional.length > 8) {
40
- return FromStringError.FRACTIONAL_MORE_THAN_8_DECIMALS;
41
- }
42
- try {
43
- e8s += BigInt(fractional.padEnd(8, "0"));
44
- }
45
- catch {
46
- return FromStringError.INVALID_FORMAT;
47
- }
48
- }
49
- return new ICP(e8s);
50
- }
51
- toE8s() {
52
- return this.e8s;
53
- }
54
- toProto() {
55
- const proto = new ledger_pb_1.ICPTs();
56
- proto.setE8s(this.e8s.toString());
57
- return proto;
58
- }
59
- }
60
- exports.ICP = ICP;
61
- var FromStringError;
62
- (function (FromStringError) {
63
- FromStringError[FromStringError["FRACTIONAL_MORE_THAN_8_DECIMALS"] = 0] = "FRACTIONAL_MORE_THAN_8_DECIMALS";
64
- FromStringError[FromStringError["INVALID_FORMAT"] = 1] = "INVALID_FORMAT";
65
- })(FromStringError = exports.FromStringError || (exports.FromStringError = {}));
package/dist/index.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export { GovernanceCanister, KnownNeuron } from "./governance";
2
- export { LedgerCanister } from "./ledger";
3
- export { AccountIdentifier, SubAccount } from "./account_identifier";
4
- export { ICP } from "./icp";
package/dist/ledger.d.ts DELETED
@@ -1,54 +0,0 @@
1
- import { Agent } from "@dfinity/agent";
2
- import { Principal } from "@dfinity/principal";
3
- import { AccountIdentifier } from "./account_identifier";
4
- import { ICP } from "./icp";
5
- declare type BlockHeight = bigint;
6
- export declare type TransferError = InvalidSender | InsufficientFunds | TxTooOld | TxCreatedInFuture | TxDuplicate | BadFee;
7
- export declare class InvalidSender {
8
- }
9
- export declare class BadFee {
10
- }
11
- export declare class InsufficientFunds {
12
- readonly balance: ICP;
13
- constructor(balance: ICP);
14
- }
15
- export declare class TxTooOld {
16
- readonly allowed_window_secs: number;
17
- constructor(allowed_window_secs: number);
18
- }
19
- export declare class TxCreatedInFuture {
20
- }
21
- export declare class TxDuplicate {
22
- readonly duplicateOf: BlockHeight;
23
- constructor(duplicateOf: BlockHeight);
24
- }
25
- declare type Fetcher = (agent: Agent, canisterId: Principal, methodName: string, arg: ArrayBuffer) => Promise<Uint8Array | Error>;
26
- export interface LedgerCanisterOptions {
27
- agent?: Agent;
28
- canisterId?: Principal;
29
- updateCallOverride?: Fetcher;
30
- queryCallOverride?: Fetcher;
31
- }
32
- export declare class LedgerCanister {
33
- private readonly agent;
34
- private readonly canisterId;
35
- private readonly updateFetcher;
36
- private readonly queryFetcher;
37
- private constructor();
38
- static create(options?: LedgerCanisterOptions): LedgerCanister;
39
- /**
40
- * Returns the balance of the specified account identifier.
41
- *
42
- * If `certified` is true, the request is fetched as an update call, otherwise
43
- * it is fetched using a query call.
44
- */
45
- accountBalance: (accountIdentifier: AccountIdentifier, certified?: boolean) => Promise<ICP>;
46
- /**
47
- * Transfer ICP from the caller to the destination `accountIdentifier`.
48
- * Returns the index of the block containing the tx if it was successful.
49
- *
50
- * TODO: support remaining options (subaccounts, memos, etc.)
51
- */
52
- transfer: (to: AccountIdentifier, amount: ICP, memo?: bigint | undefined) => Promise<BlockHeight | TransferError>;
53
- }
54
- export {};
package/dist/ledger.js DELETED
@@ -1,131 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LedgerCanister = exports.TxDuplicate = exports.TxCreatedInFuture = exports.TxTooOld = exports.InsufficientFunds = exports.BadFee = exports.InvalidSender = void 0;
4
- const agent_1 = require("@dfinity/agent");
5
- const principal_1 = require("@dfinity/principal");
6
- const ledger_pb_1 = require("../proto/ledger_pb");
7
- const icp_1 = require("./icp");
8
- const proto_1 = require("./utils/proto");
9
- const MAINNET_LEDGER_CANISTER_ID = principal_1.Principal.fromText("ryjl3-tyaaa-aaaaa-aaaba-cai");
10
- class InvalidSender {
11
- }
12
- exports.InvalidSender = InvalidSender;
13
- class BadFee {
14
- }
15
- exports.BadFee = BadFee;
16
- class InsufficientFunds {
17
- constructor(balance) {
18
- this.balance = balance;
19
- }
20
- }
21
- exports.InsufficientFunds = InsufficientFunds;
22
- class TxTooOld {
23
- constructor(allowed_window_secs) {
24
- this.allowed_window_secs = allowed_window_secs;
25
- }
26
- }
27
- exports.TxTooOld = TxTooOld;
28
- class TxCreatedInFuture {
29
- }
30
- exports.TxCreatedInFuture = TxCreatedInFuture;
31
- class TxDuplicate {
32
- constructor(duplicateOf) {
33
- this.duplicateOf = duplicateOf;
34
- }
35
- }
36
- exports.TxDuplicate = TxDuplicate;
37
- class LedgerCanister {
38
- constructor(agent, canisterId, updateFetcher, queryFetcher) {
39
- this.agent = agent;
40
- this.canisterId = canisterId;
41
- this.updateFetcher = updateFetcher;
42
- this.queryFetcher = queryFetcher;
43
- /**
44
- * Returns the balance of the specified account identifier.
45
- *
46
- * If `certified` is true, the request is fetched as an update call, otherwise
47
- * it is fetched using a query call.
48
- */
49
- this.accountBalance = async (accountIdentifier, certified = true) => {
50
- const callMethod = certified ? this.updateFetcher : this.queryFetcher;
51
- const request = new ledger_pb_1.AccountBalanceRequest();
52
- request.setAccount(accountIdentifier.toProto());
53
- const responseBytes = await callMethod(this.agent, this.canisterId, "account_balance_pb", request.serializeBinary());
54
- if (responseBytes instanceof Error) {
55
- // An error is never expected from this endpoint.
56
- throw Error;
57
- }
58
- return icp_1.ICP.fromE8s(BigInt(ledger_pb_1.ICPTs.deserializeBinary(new Uint8Array(responseBytes)).getE8s()));
59
- };
60
- /**
61
- * Transfer ICP from the caller to the destination `accountIdentifier`.
62
- * Returns the index of the block containing the tx if it was successful.
63
- *
64
- * TODO: support remaining options (subaccounts, memos, etc.)
65
- */
66
- this.transfer = async (to, amount, memo) => {
67
- const request = new ledger_pb_1.SendRequest();
68
- request.setTo(to.toProto());
69
- const payment = new ledger_pb_1.Payment();
70
- payment.setReceiverGets(amount.toProto());
71
- request.setPayment(payment);
72
- if (memo) {
73
- const memo = new ledger_pb_1.Memo();
74
- memo.setMemo(memo.toString());
75
- request.setMemo(memo);
76
- }
77
- const responseBytes = await this.updateFetcher(this.agent, this.canisterId, "send_pb", request.serializeBinary());
78
- if (responseBytes instanceof Error) {
79
- if (responseBytes.message.includes("Reject code: 5")) {
80
- // Match against the different error types.
81
- // This string matching is fragile. It's a stop-gap solution until
82
- // we migrate to the candid interface.
83
- if (responseBytes.message.match(/Sending from (.*) is not allowed/)) {
84
- return new InvalidSender();
85
- }
86
- {
87
- const m = responseBytes.message.match(/transaction.*duplicate.* in block (\d+)/);
88
- if (m && m.length > 1) {
89
- return new TxDuplicate(BigInt(m[1]));
90
- }
91
- }
92
- {
93
- const m = responseBytes.message.match(/debit account.*, current balance: (\d*(\.\d*)?)/);
94
- if (m && m.length > 1) {
95
- const balance = icp_1.ICP.fromString(m[1]);
96
- if (balance instanceof icp_1.ICP) {
97
- return new InsufficientFunds(balance);
98
- }
99
- }
100
- }
101
- if (responseBytes.message.includes("is in future")) {
102
- return new TxCreatedInFuture();
103
- }
104
- {
105
- const m = responseBytes.message.match(/older than (\d+)/);
106
- if (m && m.length > 1) {
107
- return new TxTooOld(Number.parseInt(m[1]));
108
- }
109
- }
110
- }
111
- // Unknown error. Throw as-is.
112
- throw responseBytes;
113
- }
114
- // Successful tx. Return the block height.
115
- return BigInt(ledger_pb_1.BlockHeight.deserializeBinary(responseBytes).getHeight());
116
- };
117
- }
118
- static create(options = {}) {
119
- return new LedgerCanister(options.agent ?? defaultAgent(), options.canisterId ?? MAINNET_LEDGER_CANISTER_ID, options.updateCallOverride ?? proto_1.updateCall, options.queryCallOverride ?? proto_1.queryCall);
120
- }
121
- }
122
- exports.LedgerCanister = LedgerCanister;
123
- /**
124
- * @returns The default agent to use. An agent that connects to mainnet with the anonymous identity.
125
- */
126
- function defaultAgent() {
127
- return new agent_1.HttpAgent({
128
- host: "https://ic0.app",
129
- identity: new agent_1.AnonymousIdentity(),
130
- });
131
- }