dash-platform-sdk 1.3.0-dev.5 → 1.3.0-dev.6

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 (91) hide show
  1. package/bundle.min.js +17 -17
  2. package/index.js +2 -0
  3. package/package.json +4 -4
  4. package/proto/generated/google/protobuf/wrappers.js +615 -0
  5. package/proto/generated/platform.client.js +175 -0
  6. package/proto/generated/platform.js +8277 -0
  7. package/src/DashPlatformSDK.js +101 -0
  8. package/src/constants.js +10 -0
  9. package/src/contestedResources/createStateTransition.js +6 -0
  10. package/src/contestedResources/getContestedResourceVoteState.js +72 -0
  11. package/src/contestedResources/index.js +30 -0
  12. package/src/dataContracts/create.js +11 -0
  13. package/src/dataContracts/createStateTransition.js +19 -0
  14. package/src/dataContracts/getDataContractByIdentifier.js +44 -0
  15. package/src/dataContracts/index.js +57 -0
  16. package/src/documents/create.js +4 -0
  17. package/src/documents/createStateTransition.js +52 -0
  18. package/src/documents/index.js +83 -0
  19. package/src/documents/query.js +62 -0
  20. package/src/grpcConnectionPool.js +79 -0
  21. package/src/identities/createStateTransition.js +34 -0
  22. package/src/identities/getIdentityBalance.js +40 -0
  23. package/src/identities/getIdentityByIdentifier.js +40 -0
  24. package/src/identities/getIdentityByNonUniquePublicKeyHash.js +44 -0
  25. package/src/identities/getIdentityByPublicKeyHash.js +40 -0
  26. package/src/identities/getIdentityContractNonce.js +43 -0
  27. package/src/identities/getIdentityNonce.js +41 -0
  28. package/src/identities/getIdentityPublicKeys.js +47 -0
  29. package/src/identities/index.js +141 -0
  30. package/src/keyPair/deriveChild.js +3 -0
  31. package/src/keyPair/derivePath.js +3 -0
  32. package/src/keyPair/index.js +89 -0
  33. package/src/keyPair/mnemonicToSeed.js +4 -0
  34. package/src/names/index.js +102 -0
  35. package/src/names/registerName.js +64 -0
  36. package/src/names/searchByIdentity.js +5 -0
  37. package/src/names/searchByName.js +16 -0
  38. package/src/names/testNameContested.js +3 -0
  39. package/src/names/validateName.js +11 -0
  40. package/src/node/epochs.js +46 -0
  41. package/src/node/index.js +43 -0
  42. package/src/node/status.js +41 -0
  43. package/src/node/totalCredits.js +35 -0
  44. package/src/signer/AbstractSigner.js +1 -0
  45. package/src/signer/PrivateKeySigner.d.ts +0 -0
  46. package/src/signer/PrivateKeySigner.js +64 -0
  47. package/src/signer/setSigner.js +5 -0
  48. package/src/stateTransitions/broadcast.js +10 -0
  49. package/src/stateTransitions/index.js +34 -0
  50. package/src/stateTransitions/waitForStateTransitionResult.js +8 -0
  51. package/src/tokens/createStateTransition.js +67 -0
  52. package/src/tokens/getIdentitiesTokenBalances.js +43 -0
  53. package/src/tokens/getIdentityTokensBalances.js +43 -0
  54. package/src/tokens/getTokenContractInfo.js +43 -0
  55. package/src/tokens/getTokenDirectPurchasePrices.js +40 -0
  56. package/src/tokens/getTokenTotalSupply.js +41 -0
  57. package/src/tokens/index.js +108 -0
  58. package/src/types.js +15 -0
  59. package/src/utils/base58ToBytes.js +4 -0
  60. package/src/utils/bytesToHex.js +3 -0
  61. package/src/utils/bytesToTypedArray.js +3 -0
  62. package/src/utils/calculateMsgHash.js +31 -0
  63. package/src/utils/calculateSignHash.js +8 -0
  64. package/src/utils/calculateStateIdHash.js +10 -0
  65. package/src/utils/convertToHomographSafeChars.js +11 -0
  66. package/src/utils/createVoterIdentityId.js +13 -0
  67. package/src/utils/getEvonodeList.js +12 -0
  68. package/src/utils/getQuorumPublicKey.js +18 -0
  69. package/src/utils/getRandomArrayItem.js +3 -0
  70. package/src/utils/getRandomBytes.js +4 -0
  71. package/src/utils/hexToBytes.js +3 -0
  72. package/src/utils/index.js +61 -0
  73. package/src/utils/indexBytesToString.js +4 -0
  74. package/src/utils/sha256.js +15 -0
  75. package/src/utils/signHash.js +22 -0
  76. package/src/utils/signRequestId.js +19 -0
  77. package/src/utils/sleep.js +3 -0
  78. package/src/utils/stringToIndexValueBytes.js +10 -0
  79. package/src/utils/verifyTenderdashProof.js +26 -0
  80. package/src/voting/createStateTransition.js +6 -0
  81. package/src/voting/createVote.js +5 -0
  82. package/src/voting/index.js +55 -0
  83. package/test/unit/ContestedResources.spec.js +259 -0
  84. package/test/unit/DataContract.spec.js +75 -0
  85. package/test/unit/Document.spec.js +109 -0
  86. package/test/unit/Identity.spec.js +232 -0
  87. package/test/unit/KeyPair.spec.js +34 -0
  88. package/test/unit/Names.spec.js +33 -0
  89. package/test/unit/Node.spec.js +58 -0
  90. package/test/unit/SDK.spec.js +10 -0
  91. package/test/unit/Tokens.spec.js +121 -0
@@ -0,0 +1,34 @@
1
+ import { IdentityCreateTransitionWASM, IdentityTopUpTransitionWASM, IdentityUpdateTransitionWASM } from 'pshenmic-dpp';
2
+ const identityTransitionsMap = {
3
+ create: {
4
+ class: IdentityCreateTransitionWASM,
5
+ arguments: ['publicKeys', 'assetLockProof'],
6
+ optionalArguments: ['signature', 'userFeeIncrease']
7
+ },
8
+ topUp: {
9
+ class: IdentityTopUpTransitionWASM,
10
+ arguments: ['assetLockProof', 'identityId'],
11
+ optionalArguments: ['userFeeIncrease']
12
+ },
13
+ update: {
14
+ class: IdentityUpdateTransitionWASM,
15
+ arguments: ['identityId', 'revision', 'identityNonce', 'addPublicKeys', 'disablePublicKeyIds'],
16
+ optionalArguments: ['userFeeIncrease']
17
+ }
18
+ };
19
+ export default function createStateTransition(type, params) {
20
+ const { class: TransitionClass, arguments: classArguments, optionalArguments } = identityTransitionsMap[type];
21
+ if (TransitionClass == null) {
22
+ throw new Error(`Unimplemented transition type: ${type}`);
23
+ }
24
+ const [missingArgument] = classArguments
25
+ .filter((classArgument) => params[classArgument] == null &&
26
+ !(optionalArguments).includes(classArgument));
27
+ if (missingArgument != null) {
28
+ throw new Error(`Token transition param "${missingArgument}" is missing`);
29
+ }
30
+ const transitionParams = classArguments.map((classArgument) => params[classArgument]);
31
+ // @ts-expect-error
32
+ const identityTransition = new TransitionClass(...transitionParams);
33
+ return identityTransition.toStateTransition();
34
+ }
@@ -0,0 +1,40 @@
1
+ import { GetIdentityBalanceRequest } from '../../proto/generated/platform';
2
+ import { IdentifierWASM, PlatformVersionWASM, verifyIdentityBalanceProof } from 'pshenmic-dpp';
3
+ import verifyTenderdashProof from '../utils/verifyTenderdashProof';
4
+ import { getQuorumPublicKey } from '../utils/getQuorumPublicKey';
5
+ import bytesToHex from '../utils/bytesToHex';
6
+ export default async function getIdentityBalance(grpcPool, identifier) {
7
+ const id = new IdentifierWASM(identifier);
8
+ const getIdentityBalanceRequest = GetIdentityBalanceRequest.create({
9
+ version: {
10
+ oneofKind: 'v0',
11
+ v0: {
12
+ id: id.bytes(),
13
+ prove: true
14
+ }
15
+ }
16
+ });
17
+ const { response } = await grpcPool.getClient().getIdentityBalance(getIdentityBalanceRequest);
18
+ const { version } = response;
19
+ if (version.oneofKind !== 'v0') {
20
+ throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
21
+ }
22
+ const { v0 } = version;
23
+ if (v0.result.oneofKind !== 'proof') {
24
+ throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
25
+ }
26
+ const { result: { proof }, metadata } = v0;
27
+ if (metadata == null) {
28
+ throw new Error('Metadata not found');
29
+ }
30
+ const { rootHash, balance } = verifyIdentityBalanceProof(proof.grovedbProof, id.bytes(), true, PlatformVersionWASM.PLATFORM_V9);
31
+ if (balance == null) {
32
+ throw new Error(`Failed to fetch balance for identifier ${id.base58()}`);
33
+ }
34
+ const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
35
+ const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
36
+ if (!verify) {
37
+ throw new Error('Failed to verify query');
38
+ }
39
+ return BigInt(balance);
40
+ }
@@ -0,0 +1,40 @@
1
+ import { GetIdentityRequest } from '../../proto/generated/platform';
2
+ import { IdentifierWASM, PlatformVersionWASM, verifyIdentityByIdentifierProof } from 'pshenmic-dpp';
3
+ import { getQuorumPublicKey } from '../utils/getQuorumPublicKey';
4
+ import bytesToHex from '../utils/bytesToHex';
5
+ import verifyTenderdashProof from '../utils/verifyTenderdashProof';
6
+ export default async function getIdentityByIdentifier(grpcPool, identifier) {
7
+ const id = new IdentifierWASM(identifier);
8
+ const getIdentityRequest = GetIdentityRequest.create({
9
+ version: {
10
+ oneofKind: 'v0',
11
+ v0: {
12
+ id: id.bytes(),
13
+ prove: true
14
+ }
15
+ }
16
+ });
17
+ const { response } = await grpcPool.getClient().getIdentity(getIdentityRequest);
18
+ const { version } = response;
19
+ if (version.oneofKind !== 'v0') {
20
+ throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
21
+ }
22
+ const { v0 } = version;
23
+ if (v0.result.oneofKind !== 'proof') {
24
+ throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
25
+ }
26
+ const { result: { proof }, metadata } = v0;
27
+ if (metadata == null) {
28
+ throw new Error('Metadata not found');
29
+ }
30
+ const { rootHash, identity } = verifyIdentityByIdentifierProof(proof.grovedbProof, id, true, PlatformVersionWASM.PLATFORM_V9);
31
+ if (identity == null) {
32
+ throw new Error(`Identity with identifier ${id.base58()} not found`);
33
+ }
34
+ const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
35
+ const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
36
+ if (!verify) {
37
+ throw new Error('Failed to verify query');
38
+ }
39
+ return identity;
40
+ }
@@ -0,0 +1,44 @@
1
+ import { GetIdentityByNonUniquePublicKeyHashRequest } from '../../proto/generated/platform';
2
+ import { PlatformVersionWASM, verifyIdentifierByNonUniquePublicKeyHashProof } from 'pshenmic-dpp';
3
+ import hexToBytes from '../utils/hexToBytes';
4
+ import { getQuorumPublicKey } from '../utils/getQuorumPublicKey';
5
+ import bytesToHex from '../utils/bytesToHex';
6
+ import verifyTenderdashProof from '../utils/verifyTenderdashProof';
7
+ import getIdentityByIdentifier from './getIdentityByIdentifier';
8
+ export default async function getIdentityByNonUniquePublicKeyHash(grpcPool, hex) {
9
+ const getIdentityByNonUniquePublicKeyHashRequest = GetIdentityByNonUniquePublicKeyHashRequest.create({
10
+ version: {
11
+ oneofKind: 'v0',
12
+ v0: {
13
+ publicKeyHash: hexToBytes(hex),
14
+ prove: true
15
+ }
16
+ }
17
+ });
18
+ const { response } = await grpcPool.getClient().getIdentityByNonUniquePublicKeyHash(getIdentityByNonUniquePublicKeyHashRequest);
19
+ const { version } = response;
20
+ if (version.oneofKind !== 'v0') {
21
+ throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
22
+ }
23
+ const { v0 } = version;
24
+ if (v0.result.oneofKind !== 'proof') {
25
+ throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
26
+ }
27
+ const { result: { proof }, metadata } = v0;
28
+ if (metadata == null) {
29
+ throw new Error('Metadata not found');
30
+ }
31
+ if (proof.grovedbIdentityPublicKeyHashProof == null) {
32
+ throw new Error('GroveDB proof not found for identity by non unique public key request');
33
+ }
34
+ const { rootHash, identifier } = verifyIdentifierByNonUniquePublicKeyHashProof(proof.grovedbIdentityPublicKeyHashProof.grovedbProof, false, hexToBytes(hex), undefined, PlatformVersionWASM.PLATFORM_V9);
35
+ if (identifier == null) {
36
+ throw new Error(`Identity with non unique public key hash ${hex} not found`);
37
+ }
38
+ const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.grovedbIdentityPublicKeyHashProof.quorumType, bytesToHex(proof.grovedbIdentityPublicKeyHashProof.quorumHash));
39
+ const verify = await verifyTenderdashProof(proof.grovedbIdentityPublicKeyHashProof, metadata, rootHash, quorumPublicKey);
40
+ if (!verify) {
41
+ throw new Error('Failed to verify query');
42
+ }
43
+ return await getIdentityByIdentifier(grpcPool, identifier);
44
+ }
@@ -0,0 +1,40 @@
1
+ import { GetIdentityByPublicKeyHashRequest } from '../../proto/generated/platform';
2
+ import { PlatformVersionWASM, verifyIdentityByUniqueKeyHashProof } from 'pshenmic-dpp';
3
+ import hexToBytes from '../utils/hexToBytes';
4
+ import { getQuorumPublicKey } from '../utils/getQuorumPublicKey';
5
+ import bytesToHex from '../utils/bytesToHex';
6
+ import verifyTenderdashProof from '../utils/verifyTenderdashProof';
7
+ export default async function getIdentityByPublicKeyHash(grpcPool, hex) {
8
+ const getIdentityByPublicKeyHashRequest = GetIdentityByPublicKeyHashRequest.create({
9
+ version: {
10
+ oneofKind: 'v0',
11
+ v0: {
12
+ publicKeyHash: hexToBytes(hex),
13
+ prove: true
14
+ }
15
+ }
16
+ });
17
+ const { response } = await grpcPool.getClient().getIdentityByPublicKeyHash(getIdentityByPublicKeyHashRequest);
18
+ const { version } = response;
19
+ if (version.oneofKind !== 'v0') {
20
+ throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
21
+ }
22
+ const { v0 } = version;
23
+ if (v0.result.oneofKind !== 'proof') {
24
+ throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
25
+ }
26
+ const { result: { proof }, metadata } = v0;
27
+ if (metadata == null) {
28
+ throw new Error('Metadata not found');
29
+ }
30
+ const { rootHash, identity } = verifyIdentityByUniqueKeyHashProof(proof.grovedbProof, hexToBytes(hex), PlatformVersionWASM.PLATFORM_V9);
31
+ if (identity == null) {
32
+ throw new Error(`Identity with public key hash ${hex} not found`);
33
+ }
34
+ const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
35
+ const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
36
+ if (!verify) {
37
+ throw new Error('Failed to verify query');
38
+ }
39
+ return identity;
40
+ }
@@ -0,0 +1,43 @@
1
+ import { GetIdentityContractNonceRequest } from '../../proto/generated/platform';
2
+ import { IdentifierWASM, PlatformVersionWASM, verifyIdentityContractNonceProof } from 'pshenmic-dpp';
3
+ import { getQuorumPublicKey } from '../utils/getQuorumPublicKey';
4
+ import bytesToHex from '../utils/bytesToHex';
5
+ import verifyTenderdashProof from '../utils/verifyTenderdashProof';
6
+ const IDENTITY_CONTRACT_NONCE_VALUE_FILTER = BigInt(0xFFFFFFFFFF);
7
+ export default async function getIdentityContractNonce(grpcPool, identity, dataContract) {
8
+ const identityIdentifier = new IdentifierWASM(identity);
9
+ const dataContractIdentifier = new IdentifierWASM(dataContract);
10
+ const getIdentityContractNonceRequest = GetIdentityContractNonceRequest.create({
11
+ version: {
12
+ oneofKind: 'v0',
13
+ v0: {
14
+ identityId: identityIdentifier.bytes(),
15
+ contractId: dataContractIdentifier.bytes(),
16
+ prove: true
17
+ }
18
+ }
19
+ });
20
+ const { response } = await grpcPool.getClient().getIdentityContractNonce(getIdentityContractNonceRequest);
21
+ const { version } = response;
22
+ if (version.oneofKind !== 'v0') {
23
+ throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
24
+ }
25
+ const { v0 } = version;
26
+ if (v0.result.oneofKind !== 'proof') {
27
+ throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
28
+ }
29
+ const { result: { proof }, metadata } = v0;
30
+ if (metadata == null) {
31
+ throw new Error('Metadata not found');
32
+ }
33
+ const { rootHash, contractNonce } = verifyIdentityContractNonceProof(proof.grovedbProof, identityIdentifier.bytes(), dataContractIdentifier.bytes(), true, PlatformVersionWASM.PLATFORM_V9);
34
+ if (contractNonce == null) {
35
+ return BigInt(0);
36
+ }
37
+ const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
38
+ const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
39
+ if (!verify) {
40
+ throw new Error('Failed to verify query');
41
+ }
42
+ return BigInt(contractNonce) & IDENTITY_CONTRACT_NONCE_VALUE_FILTER;
43
+ }
@@ -0,0 +1,41 @@
1
+ import { GetIdentityNonceRequest } from '../../proto/generated/platform';
2
+ import { IdentifierWASM, PlatformVersionWASM, verifyIdentityNonceProof } from 'pshenmic-dpp';
3
+ import { getQuorumPublicKey } from '../utils/getQuorumPublicKey';
4
+ import bytesToHex from '../utils/bytesToHex';
5
+ import verifyTenderdashProof from '../utils/verifyTenderdashProof';
6
+ const IDENTITY_NONCE_VALUE_FILTER = BigInt(0xFFFFFFFFFF);
7
+ export default async function getIdentityNonce(grpcPool, identifier) {
8
+ const id = new IdentifierWASM(identifier);
9
+ const getIdentityNonceRequest = GetIdentityNonceRequest.create({
10
+ version: {
11
+ oneofKind: 'v0',
12
+ v0: {
13
+ identityId: id.bytes(),
14
+ prove: true
15
+ }
16
+ }
17
+ });
18
+ const { response } = await grpcPool.getClient().getIdentityNonce(getIdentityNonceRequest);
19
+ const { version } = response;
20
+ if (version.oneofKind !== 'v0') {
21
+ throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
22
+ }
23
+ const { v0 } = version;
24
+ if (v0.result.oneofKind !== 'proof') {
25
+ throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
26
+ }
27
+ const { result: { proof }, metadata } = v0;
28
+ if (metadata == null) {
29
+ throw new Error('Metadata not found');
30
+ }
31
+ const { rootHash, nonce } = verifyIdentityNonceProof(proof.grovedbProof, id.bytes(), true, PlatformVersionWASM.PLATFORM_V9);
32
+ if (nonce == null) {
33
+ return BigInt(0);
34
+ }
35
+ const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
36
+ const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
37
+ if (!verify) {
38
+ throw new Error('Failed to verify query');
39
+ }
40
+ return BigInt(nonce) & IDENTITY_NONCE_VALUE_FILTER;
41
+ }
@@ -0,0 +1,47 @@
1
+ import { GetIdentityKeysRequest, KeyRequestType } from '../../proto/generated/platform';
2
+ import { IdentifierWASM, PlatformVersionWASM, verifyIdentityKeysByIdentifierProof } from 'pshenmic-dpp';
3
+ import { getQuorumPublicKey } from '../utils/getQuorumPublicKey';
4
+ import bytesToHex from '../utils/bytesToHex';
5
+ import verifyTenderdashProof from '../utils/verifyTenderdashProof';
6
+ export default async function getIdentityPublicKeys(grpcPool, identifier) {
7
+ const id = new IdentifierWASM(identifier);
8
+ const getIdentityKeysRequest = GetIdentityKeysRequest.create({
9
+ version: {
10
+ oneofKind: 'v0',
11
+ v0: {
12
+ identityId: id.bytes(),
13
+ requestType: KeyRequestType.create({
14
+ request: {
15
+ oneofKind: 'allKeys',
16
+ allKeys: {}
17
+ }
18
+ }),
19
+ prove: true
20
+ }
21
+ }
22
+ });
23
+ const { response } = await grpcPool.getClient().getIdentityKeys(getIdentityKeysRequest);
24
+ const { version } = response;
25
+ if (version.oneofKind !== 'v0') {
26
+ throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
27
+ }
28
+ const { v0 } = version;
29
+ if (v0.result.oneofKind !== 'proof') {
30
+ throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
31
+ }
32
+ const { result: { proof }, metadata } = v0;
33
+ if (metadata == null) {
34
+ throw new Error('Metadata not found');
35
+ }
36
+ const { rootHash, identity } = verifyIdentityKeysByIdentifierProof(proof.grovedbProof, id.bytes(), null, false, false, true, null, null, PlatformVersionWASM.PLATFORM_V9);
37
+ if (identity == null) {
38
+ throw new Error(`Identity with identifier ${id.base58()} not found`);
39
+ }
40
+ const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
41
+ const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
42
+ if (!verify) {
43
+ throw new Error('Failed to verify query');
44
+ }
45
+ const loadedKeysIds = Object.keys(identity.loadedPublicKeys);
46
+ return loadedKeysIds.map((id) => identity.loadedPublicKeys[id]);
47
+ }
@@ -0,0 +1,141 @@
1
+ import getIdentityContractNonce from './getIdentityContractNonce';
2
+ import getIdentityPublicKeys from './getIdentityPublicKeys';
3
+ import getIdentityNonce from './getIdentityNonce';
4
+ import getIdentityBalance from './getIdentityBalance';
5
+ import getIdentityByPublicKeyHash from './getIdentityByPublicKeyHash';
6
+ import getIdentityByIdentifier from './getIdentityByIdentifier';
7
+ import { AssetLockProofWASM, ContractBoundsWASM, IdentifierWASM, IdentityPublicKeyInCreationWASM, OutPointWASM } from 'pshenmic-dpp';
8
+ import createStateTransition from './createStateTransition';
9
+ import getIdentityByNonUniquePublicKeyHash from './getIdentityByNonUniquePublicKeyHash';
10
+ import hexToBytes from '../utils/hexToBytes';
11
+ /**
12
+ * Collection of methods to query identities and its related data
13
+ *
14
+ * @hideconstructor
15
+ */
16
+ export class IdentitiesController {
17
+ /** @ignore */
18
+ grpcPool;
19
+ constructor(grpcPool) {
20
+ this.grpcPool = grpcPool;
21
+ }
22
+ /**
23
+ * Get current balance of your Identity by identifier
24
+ *
25
+ * @param identifier {IdentifierLike} Identifier of an identity
26
+ *
27
+ * @return {Promise<bigint>}
28
+ */
29
+ async getIdentityBalance(identifier) {
30
+ return await getIdentityBalance(this.grpcPool, identifier);
31
+ }
32
+ /**
33
+ * Retrieves an Identity from the network by give public key hash
34
+ *
35
+ * @param hex {string} public key hash value in hex, should be a length of 40
36
+ *
37
+ * @return {Promise<IdentityWASM>}
38
+ */
39
+ async getIdentityByPublicKeyHash(hex) {
40
+ if (hex.length !== 40) {
41
+ throw new Error('Public key hash should equal 40');
42
+ }
43
+ return await getIdentityByPublicKeyHash(this.grpcPool, hex);
44
+ }
45
+ /**
46
+ * Retrieves an Identity from the network by non-unique public key hash (like Voter Identity, SHA160)
47
+ *
48
+ * @param hex {string} public key hash value in hex, should be a length of 40
49
+ *
50
+ * @return {Promise<IdentityWASM>}
51
+ */
52
+ async getIdentityByNonUniquePublicKeyHash(hex) {
53
+ if (hex.length !== 40) {
54
+ throw new Error('Public key hash should equal 40');
55
+ }
56
+ return await getIdentityByNonUniquePublicKeyHash(this.grpcPool, hex);
57
+ }
58
+ /**
59
+ * Retrieves Identity by identifier from the network
60
+ * @param identifier {IdentifierLike} identifier
61
+ *
62
+ * @return {Promise<IdentityWASM>}
63
+ */
64
+ async getIdentityByIdentifier(identifier) {
65
+ return await getIdentityByIdentifier(this.grpcPool, identifier);
66
+ }
67
+ /**
68
+ * Get Identity Nonce (usually used by Identity transitions)
69
+ * @param identifier
70
+ */
71
+ async getIdentityNonce(identifier) {
72
+ return await getIdentityNonce(this.grpcPool, identifier);
73
+ }
74
+ /**
75
+ * Get Identity Contract Nonce (usually used by Document transitions)
76
+ * @param identifier
77
+ * @param dataContract
78
+ *
79
+ * @return {Promise<bigint>}
80
+ */
81
+ async getIdentityContractNonce(identifier, dataContract) {
82
+ return await getIdentityContractNonce(this.grpcPool, identifier, dataContract);
83
+ }
84
+ /**
85
+ * Retrieve given Identity's public keys
86
+ * @param identifier
87
+ *
88
+ * @return {Promise<IdentityPublicKeyWASM[]>}
89
+ */
90
+ async getIdentityPublicKeys(identifier) {
91
+ return await getIdentityPublicKeys(this.grpcPool, identifier);
92
+ }
93
+ /**
94
+ * Helper function for creating {StateTransitionWASM} for Identity transitions
95
+ *
96
+ * To create an IdentityCreateTransition, you should pass a params.assetLockProof object containing
97
+ * all necessary AssetLockProof data to make the transaction.
98
+ * Both InstantSend and ChainLock AssetLock proofs supported
99
+ *
100
+ * @param type {string} type of transition, must be a one of ('create' | 'update' | 'topUp')
101
+ * @param params {IdentityTransitionParams} params
102
+ */
103
+ createStateTransition(type, params) {
104
+ if (params.identityId != null) {
105
+ params.identityId = new IdentifierWASM(params.identityId);
106
+ }
107
+ if (params.disablePublicKeyIds == null) {
108
+ params.disablePublicKeyIds = [];
109
+ }
110
+ if (params.assetLockProof != null) {
111
+ const { type } = params.assetLockProof;
112
+ if (type === 'chainLock') {
113
+ const { txid, outputIndex, coreChainLockedHeight } = params.assetLockProof;
114
+ // @ts-expect-error
115
+ params.assetLockProof = AssetLockProofWASM.createChainAssetLockProof(coreChainLockedHeight, new OutPointWASM(txid, outputIndex));
116
+ }
117
+ else if (type === 'instantLock') {
118
+ const { transaction, outputIndex, instantLock } = params.assetLockProof;
119
+ // @ts-expect-error
120
+ params.assetLockProof = AssetLockProofWASM.createInstantAssetLockProof(hexToBytes(instantLock), hexToBytes(transaction), outputIndex);
121
+ }
122
+ else if (type == null) {
123
+ throw new Error('Missing Asset Lock type in the params');
124
+ }
125
+ else {
126
+ throw new Error(`Unknown Asset Lock type: ${type}`);
127
+ }
128
+ }
129
+ if (params.addPublicKeys != null) {
130
+ // @ts-expect-error
131
+ params.addPublicKeys = params.addPublicKeys
132
+ .map(({ id, purpose, securityLevel, keyType, readOnly, data, signature, contractBounds }) => new IdentityPublicKeyInCreationWASM(id, purpose, securityLevel, keyType, readOnly, data, signature, (contractBounds != null) ? new ContractBoundsWASM(contractBounds.dataContractId, contractBounds.documentType) : undefined));
133
+ }
134
+ if (params.publicKeys != null) {
135
+ // @ts-expect-error
136
+ params.publicKeys = params.publicKeys
137
+ .map(({ id, purpose, securityLevel, keyType, readOnly, data, signature, contractBounds }) => new IdentityPublicKeyInCreationWASM(id, purpose, securityLevel, keyType, readOnly, data, signature, (contractBounds != null) ? new ContractBoundsWASM(contractBounds.dataContractId, contractBounds.documentType) : undefined));
138
+ }
139
+ return createStateTransition(type, params);
140
+ }
141
+ }
@@ -0,0 +1,3 @@
1
+ export default function deriveChild(hdKey, index) {
2
+ return hdKey.deriveChild(index);
3
+ }
@@ -0,0 +1,3 @@
1
+ export default function derivePath(hdKey, path) {
2
+ return hdKey.derive(path);
3
+ }
@@ -0,0 +1,89 @@
1
+ import { HDKey } from '@scure/bip32';
2
+ import mnemonicToSeed from './mnemonicToSeed';
3
+ import deriveChild from './deriveChild';
4
+ import derivePath from './derivePath';
5
+ import { p2pkh } from '@scure/btc-signer';
6
+ const DASH_VERSIONS = {
7
+ mainnet: { pubKeyHash: 0x4c, scriptHash: 0x10, bech32: 'dc', wif: 0xcc, private: 0x0488ade4, public: 0x0488b21e },
8
+ testnet: { pubKeyHash: 0x8c, scriptHash: 0x13, bech32: 'dc', wif: 0xef, private: 0x04358394, public: 0x043587cf }
9
+ };
10
+ /**
11
+ * Collection of functions to work with private keys and seed phrases
12
+ *
13
+ * @hideconstructor
14
+ */
15
+ export class KeyPairController {
16
+ /**
17
+ * Returns seed from mnemonic phrase
18
+ *
19
+ * @param mnemonic {string} - The BIP39 mnemonic phrase.
20
+ * @param salt {string=} - Optional salt for seed derivation.
21
+ *
22
+ * @return {Uint8Array} Seed bytes
23
+ */
24
+ mnemonicToSeed(mnemonic, salt) {
25
+ return mnemonicToSeed(mnemonic, salt);
26
+ }
27
+ /**
28
+ * Returns seed from mnemonic phrase
29
+ *
30
+ * @param seed {Uint8Array}
31
+ * @param network {Network} network
32
+ *
33
+ * @return {HDKey} HDKey
34
+ */
35
+ seedToHdKey(seed, network = 'mainnet') {
36
+ return HDKey.fromMasterSeed(seed, DASH_VERSIONS[network]);
37
+ }
38
+ /**
39
+ * Allows to derive child HD Key
40
+ *
41
+ * @param hdKey {HDKey} - The HDKey parent instance
42
+ * @param index {number} - Index of child
43
+ *
44
+ * @return {Promise<HDKey>} A promise that resolves child key
45
+ */
46
+ async deriveChild(hdKey, index) {
47
+ return deriveChild(hdKey, index);
48
+ }
49
+ /**
50
+ * Allows to derive HD key by path
51
+ *
52
+ * @param hdKey {HDKey} - The HDKey parent instance
53
+ * @param path {string} - Path of children
54
+ *
55
+ * @return {Promise<HDKey>} A promise that resolves key by path
56
+ */
57
+ async derivePath(hdKey, path) {
58
+ return derivePath(hdKey, path);
59
+ }
60
+ /**
61
+ * Derives an {HDKey} child by identity index and key index from an {HDKey}
62
+ *
63
+ * Usually used to get a identity private key from seed
64
+ *
65
+ * @param hdKey {HDKey}
66
+ * @param identityIndex {number}
67
+ * @param keyIndex {number}
68
+ * @param network {Network}
69
+ *
70
+ * @returns {HDKey}
71
+ */
72
+ deriveIdentityPrivateKey(hdKey, identityIndex, keyIndex, network) {
73
+ const networkIndex = network === 'mainnet' ? 5 : 1;
74
+ const pathPostfix = `/5'/0'/0'/${identityIndex}'/${keyIndex}'`;
75
+ return derivePath(hdKey, `m/9'/${networkIndex}'${pathPostfix}`);
76
+ }
77
+ /**
78
+ * Converts {PublicKey} to a Dash network address (P2PKH)
79
+ *
80
+ * @param publicKey {Uint8Array}
81
+ * @param network {Network}
82
+ *
83
+ * @returns {string}
84
+ */
85
+ p2pkhAddress(publicKey, network) {
86
+ const P2PKH = p2pkh(publicKey, DASH_VERSIONS[network]);
87
+ return P2PKH.address;
88
+ }
89
+ }
@@ -0,0 +1,4 @@
1
+ import { mnemonicToSeedSync as func } from '@scure/bip39';
2
+ export default function mnemonicToSeed(mnemonic, salt) {
3
+ return func(mnemonic, salt);
4
+ }