dash-platform-sdk 1.5.0-dev.1 → 1.5.0-dev.11

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 (43) hide show
  1. package/README.md +15 -14
  2. package/bundle.min.js +1 -21
  3. package/package.json +5 -4
  4. package/proto/generated/platform.client.d.ts +50 -0
  5. package/proto/generated/platform.client.js +53 -18
  6. package/proto/generated/platform.d.ts +888 -0
  7. package/proto/generated/platform.js +2216 -417
  8. package/src/constants.d.ts +1 -1
  9. package/src/constants.js +1 -1
  10. package/src/documents/query.js +1 -1
  11. package/src/identities/createStateTransition.js +2 -2
  12. package/src/keyPair/index.d.ts +63 -1
  13. package/src/keyPair/index.js +96 -1
  14. package/src/node/{epochs.d.ts → epochInfos.d.ts} +1 -1
  15. package/src/node/{epochs.js → epochInfos.js} +1 -1
  16. package/src/node/finalizedEpochInfos.d.ts +21 -0
  17. package/src/node/finalizedEpochInfos.js +54 -0
  18. package/src/node/index.d.ts +9 -1
  19. package/src/node/index.js +11 -1
  20. package/src/platformAddresses/createStateTransition.d.ts +12 -0
  21. package/src/platformAddresses/createStateTransition.js +62 -0
  22. package/src/platformAddresses/getAddressesBranchState.d.ts +3 -0
  23. package/src/platformAddresses/getAddressesBranchState.js +21 -0
  24. package/src/platformAddresses/getAddressesTrunkState.d.ts +3 -0
  25. package/src/platformAddresses/getAddressesTrunkState.js +33 -0
  26. package/src/platformAddresses/getRecentAddressBalanceChanges.d.ts +3 -0
  27. package/src/platformAddresses/getRecentAddressBalanceChanges.js +38 -0
  28. package/src/platformAddresses/getRecentCompactedAddressBalanceChanges.d.ts +3 -0
  29. package/src/platformAddresses/getRecentCompactedAddressBalanceChanges.js +37 -0
  30. package/src/platformAddresses/index.d.ts +63 -2
  31. package/src/platformAddresses/index.js +76 -0
  32. package/src/shielded/createStateTransition.d.ts +1 -1
  33. package/src/shielded/createStateTransition.js +7 -2
  34. package/src/shielded/index.d.ts +7 -6
  35. package/src/shielded/index.js +10 -8
  36. package/src/utils/verifyTenderdashProof.js +3 -0
  37. package/test/unit/Identity.spec.js +1 -1
  38. package/test/unit/KeyPair.spec.js +49 -1
  39. package/test/unit/Node.spec.js +6 -0
  40. package/test/unit/PlatformAddress.spec.js +155 -1
  41. package/test/unit/Shielded.spec.js +17 -16
  42. package/types.d.ts +69 -2
  43. package/types.js +1 -1
@@ -1,6 +1,6 @@
1
1
  import GRPCConnectionPool from '../grpcConnectionPool.js';
2
- import { PlatformAddressLike } from 'pshenmic-dpp';
3
- import { PlatformAddressInfo } from '../../types.js';
2
+ import { BlockAddressBalanceChanges, CompactedBlockAddressBalanceChanges, PlatformAddressLike, StateTransitionWASM, VerifiedAddressesBranchState } from 'pshenmic-dpp';
3
+ import { PlatformAddressesTrunkState, PlatformAddressInfo, PlatformAddressTransitionParamsMap, PlatformAddressTransitionType } from '../../types.js';
4
4
  export declare class PlatformAddressesController {
5
5
  /** @ignore **/
6
6
  grpcPool: GRPCConnectionPool;
@@ -19,4 +19,65 @@ export declare class PlatformAddressesController {
19
19
  * @return {Promise<PlatformAddressInfo[]>}
20
20
  */
21
21
  getAddressesInfos(addresses: PlatformAddressLike[]): Promise<PlatformAddressInfo[]>;
22
+ /**
23
+ * Makes a query for the trunk chunk of the address funds tree, used as the entry point
24
+ * for client-side sync of the address funds state
25
+ *
26
+ * Returns the verified trunk state (elements, leaf keys and helpers for descending into
27
+ * branches) along with the response metadata, whose height is the checkpoint height for
28
+ * subsequent branch queries
29
+ *
30
+ * @return {Promise<PlatformAddressesTrunkState>}
31
+ */
32
+ getAddressesTrunkState(): Promise<PlatformAddressesTrunkState>;
33
+ /**
34
+ * Makes a query for a branch chunk of the address funds tree at the given key and depth,
35
+ * anchored to the checkpoint height returned by the trunk state query
36
+ *
37
+ * The branch proof carries no root hash of its own - it is verified against
38
+ * expectedRootHash, the hash the parent trunk (or branch) reported for this key
39
+ * via its leaf info
40
+ *
41
+ * @param key {Uint8Array} key that was navigated to in the tree
42
+ * @param depth {number} depth of the branch to return
43
+ * @param checkpointHeight {bigint} block height from the trunk response metadata
44
+ * @param expectedRootHash {Uint8Array} hash reported for this key by the parent trunk or branch
45
+ * @return {Promise<VerifiedAddressesBranchState>}
46
+ */
47
+ getAddressesBranchState(key: Uint8Array, depth: number, checkpointHeight: bigint, expectedRootHash: Uint8Array): Promise<VerifiedAddressesBranchState>;
48
+ /**
49
+ * Makes a query for recent address balance changes starting from the given block height,
50
+ * returns an array of per-block change sets
51
+ *
52
+ * @param startHeight {bigint} block height to start from
53
+ * @param startHeightExclusive {boolean} [startHeightExclusive=false] use exclusive start (RangeAfter) instead of inclusive (RangeFrom)
54
+ * @return {Promise<BlockAddressBalanceChanges[]>}
55
+ */
56
+ getRecentAddressBalanceChanges(startHeight: bigint, startHeightExclusive?: boolean): Promise<BlockAddressBalanceChanges[]>;
57
+ /**
58
+ * Makes a query for recent compacted address balance changes starting from the given
59
+ * block height, returns an array of compacted (block range) change sets
60
+ *
61
+ * @param startBlockHeight {bigint} block height to start from
62
+ * @return {Promise<CompactedBlockAddressBalanceChanges[]>}
63
+ */
64
+ getRecentCompactedAddressBalanceChanges(startBlockHeight: bigint): Promise<CompactedBlockAddressBalanceChanges[]>;
65
+ /**
66
+ * Helper function for creating {StateTransitionWASM} for Platform Address transitions
67
+ *
68
+ * Unlike identity transitions (which are signed after construction), address transitions carry
69
+ * their signature material as constructor input (the `inputWitness` param, and a `signature`
70
+ * setter on the asset-lock variant), so this builder is pure and only assembles the transition
71
+ * from already-built params - producing witnesses stays the caller's responsibility.
72
+ *
73
+ * Please refer to PlatformAddress.spec.ts or README for example commands
74
+ *
75
+ * @param type {string} type of transition, must be a one of ('identityCreditTransferToAddresses' |
76
+ * 'identityCreateFromAddresses' | 'identityTopUpFromAddresses' | 'addressFundsTransfer' |
77
+ * 'addressFundingFromAssetLock' | 'addressCreditWithdrawal')
78
+ * @param params {PlatformAddressTransitionParamsMap[K]} params required by that transition type
79
+ *
80
+ * @return {StateTransitionWASM}
81
+ */
82
+ createStateTransition<K extends PlatformAddressTransitionType>(type: K, params: PlatformAddressTransitionParamsMap[K]): StateTransitionWASM;
22
83
  }
@@ -1,5 +1,10 @@
1
1
  import { getAddressInfo } from './getAddressInfo.js';
2
2
  import { getAddressesInfos } from './getAddressesInfos.js';
3
+ import { getAddressesTrunkState } from './getAddressesTrunkState.js';
4
+ import { getAddressesBranchState } from './getAddressesBranchState.js';
5
+ import { getRecentAddressBalanceChanges } from './getRecentAddressBalanceChanges.js';
6
+ import { getRecentCompactedAddressBalanceChanges } from './getRecentCompactedAddressBalanceChanges.js';
7
+ import createStateTransition from './createStateTransition.js';
3
8
  export class PlatformAddressesController {
4
9
  /** @ignore **/
5
10
  grpcPool;
@@ -24,4 +29,75 @@ export class PlatformAddressesController {
24
29
  async getAddressesInfos(addresses) {
25
30
  return await getAddressesInfos(this.grpcPool, addresses);
26
31
  }
32
+ /**
33
+ * Makes a query for the trunk chunk of the address funds tree, used as the entry point
34
+ * for client-side sync of the address funds state
35
+ *
36
+ * Returns the verified trunk state (elements, leaf keys and helpers for descending into
37
+ * branches) along with the response metadata, whose height is the checkpoint height for
38
+ * subsequent branch queries
39
+ *
40
+ * @return {Promise<PlatformAddressesTrunkState>}
41
+ */
42
+ async getAddressesTrunkState() {
43
+ return await getAddressesTrunkState(this.grpcPool);
44
+ }
45
+ /**
46
+ * Makes a query for a branch chunk of the address funds tree at the given key and depth,
47
+ * anchored to the checkpoint height returned by the trunk state query
48
+ *
49
+ * The branch proof carries no root hash of its own - it is verified against
50
+ * expectedRootHash, the hash the parent trunk (or branch) reported for this key
51
+ * via its leaf info
52
+ *
53
+ * @param key {Uint8Array} key that was navigated to in the tree
54
+ * @param depth {number} depth of the branch to return
55
+ * @param checkpointHeight {bigint} block height from the trunk response metadata
56
+ * @param expectedRootHash {Uint8Array} hash reported for this key by the parent trunk or branch
57
+ * @return {Promise<VerifiedAddressesBranchState>}
58
+ */
59
+ async getAddressesBranchState(key, depth, checkpointHeight, expectedRootHash) {
60
+ return await getAddressesBranchState(this.grpcPool, key, depth, checkpointHeight, expectedRootHash);
61
+ }
62
+ /**
63
+ * Makes a query for recent address balance changes starting from the given block height,
64
+ * returns an array of per-block change sets
65
+ *
66
+ * @param startHeight {bigint} block height to start from
67
+ * @param startHeightExclusive {boolean} [startHeightExclusive=false] use exclusive start (RangeAfter) instead of inclusive (RangeFrom)
68
+ * @return {Promise<BlockAddressBalanceChanges[]>}
69
+ */
70
+ async getRecentAddressBalanceChanges(startHeight, startHeightExclusive = false) {
71
+ return await getRecentAddressBalanceChanges(this.grpcPool, startHeight, startHeightExclusive);
72
+ }
73
+ /**
74
+ * Makes a query for recent compacted address balance changes starting from the given
75
+ * block height, returns an array of compacted (block range) change sets
76
+ *
77
+ * @param startBlockHeight {bigint} block height to start from
78
+ * @return {Promise<CompactedBlockAddressBalanceChanges[]>}
79
+ */
80
+ async getRecentCompactedAddressBalanceChanges(startBlockHeight) {
81
+ return await getRecentCompactedAddressBalanceChanges(this.grpcPool, startBlockHeight);
82
+ }
83
+ /**
84
+ * Helper function for creating {StateTransitionWASM} for Platform Address transitions
85
+ *
86
+ * Unlike identity transitions (which are signed after construction), address transitions carry
87
+ * their signature material as constructor input (the `inputWitness` param, and a `signature`
88
+ * setter on the asset-lock variant), so this builder is pure and only assembles the transition
89
+ * from already-built params - producing witnesses stays the caller's responsibility.
90
+ *
91
+ * Please refer to PlatformAddress.spec.ts or README for example commands
92
+ *
93
+ * @param type {string} type of transition, must be a one of ('identityCreditTransferToAddresses' |
94
+ * 'identityCreateFromAddresses' | 'identityTopUpFromAddresses' | 'addressFundsTransfer' |
95
+ * 'addressFundingFromAssetLock' | 'addressCreditWithdrawal')
96
+ * @param params {PlatformAddressTransitionParamsMap[K]} params required by that transition type
97
+ *
98
+ * @return {StateTransitionWASM}
99
+ */
100
+ createStateTransition(type, params) {
101
+ return createStateTransition(type, params);
102
+ }
27
103
  }
@@ -1,3 +1,3 @@
1
1
  import { ShieldedBuilderWASM, StateTransitionWASM } from 'pshenmic-dpp';
2
2
  import { ShieldedTransitionParamsMap, ShieldedTransitionType } from '../../types.js';
3
- export default function createStateTransition<K extends ShieldedTransitionType>(builder: ShieldedBuilderWASM, type: K, params: ShieldedTransitionParamsMap[K]): StateTransitionWASM;
3
+ export default function createStateTransition<K extends ShieldedTransitionType>(builder: ShieldedBuilderWASM, type: K, params: ShieldedTransitionParamsMap[K]): Promise<StateTransitionWASM>;
@@ -26,13 +26,18 @@ const shieldedTransitionsMap = {
26
26
  arguments: ['spends', 'recipient', 'transferAmount', 'changeAddress', 'seed', 'coinType', 'account', 'anchor', 'memo'],
27
27
  optionalArguments: []
28
28
  },
29
+ shieldedTransferMulti: {
30
+ method: ShieldedBuilderWASM.prototype.shieldedTransferMulti,
31
+ arguments: ['spends', 'outputs', 'changeAddress', 'seed', 'coinType', 'account', 'anchor'],
32
+ optionalArguments: []
33
+ },
29
34
  identityCreateFromShieldedPool: {
30
35
  method: ShieldedBuilderWASM.prototype.identityCreateFromShieldedPool,
31
36
  arguments: ['publicKeys', 'privateKeys', 'denomination', 'sendToAddressOnCreationFailure', 'spends', 'changeAddress', 'seed', 'coinType', 'account', 'anchor', 'memo'],
32
37
  optionalArguments: []
33
38
  }
34
39
  };
35
- export default function createStateTransition(builder, type, params) {
40
+ export default async function createStateTransition(builder, type, params) {
36
41
  const { method: builderMethod, arguments: classArguments, optionalArguments } = shieldedTransitionsMap[type];
37
42
  if (builderMethod == null) {
38
43
  throw new Error(`Unimplemented shielded transition type: ${type}`);
@@ -43,7 +48,7 @@ export default function createStateTransition(builder, type, params) {
43
48
  throw new Error(`Shielded transition param "${missingArgument}" is missing`);
44
49
  }
45
50
  const transitionParams = classArguments.concat(optionalArguments).map((classArgument) => params[classArgument]);
46
- const result = builderMethod.apply(builder, [...transitionParams, params.platformVersion ?? LATEST_PLATFORM_VERSION]);
51
+ const result = await builderMethod.apply(builder, [...transitionParams, params.platformVersion ?? LATEST_PLATFORM_VERSION]);
47
52
  if (result instanceof StateTransitionWASM) {
48
53
  return result;
49
54
  }
@@ -16,14 +16,14 @@ export declare class ShieldedController {
16
16
  * Set bindings instance of builder
17
17
  * Needed for custom builder load, because ShieldedBuilderWASM inits very slow on old hardware
18
18
  */
19
- init(builder?: ShieldedBuilderWASM): ShieldedBuilderWASM;
19
+ init(builder?: ShieldedBuilderWASM): Promise<ShieldedBuilderWASM>;
20
20
  /**
21
21
  * Lazily constructs and caches a {ShieldedBuilderWASM}. Construction builds
22
22
  * the Halo 2 proving key (~seconds), so the instance is created once and reused.
23
23
  *
24
24
  * @ignore
25
25
  */
26
- getShieldedBuilder(): ShieldedBuilderWASM;
26
+ getShieldedBuilder(): Promise<ShieldedBuilderWASM>;
27
27
  /**
28
28
  * Retrieves a batch of shielded encrypted notes from the shielded pool,
29
29
  * starting from the given note index.
@@ -110,21 +110,22 @@ export declare class ShieldedController {
110
110
  };
111
111
  /**
112
112
  * Helper function for building and proving shielded (Orchard) transitions.
113
- * It may be used to create any of 6 shielded transition actions:
113
+ * It may be used to create any of 7 shielded transition actions:
114
114
  *
115
115
  * 1) shield - transparent platform addresses -> pool (deposit)
116
116
  * 2) shieldFromAssetLock - asset lock -> pool (deposit)
117
117
  * 3) shieldedWithdrawal - pool -> core L1 (spend)
118
118
  * 4) unshield - pool -> platform identity balance (spend)
119
119
  * 5) shieldedTransfer - pool -> pool (spend)
120
- * 6) identityCreateFromShieldedPool - pool -> new identity (spend)
120
+ * 6) shieldedTransferMulti - pool -> pool, several recipients, each with its own memo (spend)
121
+ * 7) identityCreateFromShieldedPool - pool -> new identity (spend)
121
122
  *
122
123
  * Spends require a {SpendableNoteWASM} witnessed against an on-chain anchor.
123
124
  *
124
- * @param type {string} Type of the shielded transition, must be one of ('shield' | 'shieldFromAssetLock' | 'shieldedWithdrawal' | 'unshield' | 'shieldedTransfer' | 'identityCreateFromShieldedPool')
125
+ * @param type {string} Type of the shielded transition, must be one of ('shield' | 'shieldFromAssetLock' | 'shieldedWithdrawal' | 'unshield' | 'shieldedTransfer' | 'shieldedTransferMulti' | 'identityCreateFromShieldedPool')
125
126
  * @param params {ShieldedTransitionParams} params
126
127
  *
127
128
  * @return {StateTransitionWASM}
128
129
  */
129
- createStateTransition<K extends ShieldedTransitionType>(type: K, params: ShieldedTransitionParamsMap[K]): StateTransitionWASM;
130
+ createStateTransition<K extends ShieldedTransitionType>(type: K, params: ShieldedTransitionParamsMap[K]): Promise<StateTransitionWASM>;
130
131
  }
@@ -23,8 +23,9 @@ export class ShieldedController {
23
23
  * Set bindings instance of builder
24
24
  * Needed for custom builder load, because ShieldedBuilderWASM inits very slow on old hardware
25
25
  */
26
- init(builder) {
26
+ async init(builder) {
27
27
  this.shieldedBuilder = builder ?? new ShieldedBuilderWASM();
28
+ await this.shieldedBuilder.init();
28
29
  return this.shieldedBuilder;
29
30
  }
30
31
  /**
@@ -33,9 +34,9 @@ export class ShieldedController {
33
34
  *
34
35
  * @ignore
35
36
  */
36
- getShieldedBuilder() {
37
+ async getShieldedBuilder() {
37
38
  if (this.shieldedBuilder == null) {
38
- return this.init();
39
+ return await this.init();
39
40
  }
40
41
  return this.shieldedBuilder;
41
42
  }
@@ -156,23 +157,24 @@ export class ShieldedController {
156
157
  }
157
158
  /**
158
159
  * Helper function for building and proving shielded (Orchard) transitions.
159
- * It may be used to create any of 6 shielded transition actions:
160
+ * It may be used to create any of 7 shielded transition actions:
160
161
  *
161
162
  * 1) shield - transparent platform addresses -> pool (deposit)
162
163
  * 2) shieldFromAssetLock - asset lock -> pool (deposit)
163
164
  * 3) shieldedWithdrawal - pool -> core L1 (spend)
164
165
  * 4) unshield - pool -> platform identity balance (spend)
165
166
  * 5) shieldedTransfer - pool -> pool (spend)
166
- * 6) identityCreateFromShieldedPool - pool -> new identity (spend)
167
+ * 6) shieldedTransferMulti - pool -> pool, several recipients, each with its own memo (spend)
168
+ * 7) identityCreateFromShieldedPool - pool -> new identity (spend)
167
169
  *
168
170
  * Spends require a {SpendableNoteWASM} witnessed against an on-chain anchor.
169
171
  *
170
- * @param type {string} Type of the shielded transition, must be one of ('shield' | 'shieldFromAssetLock' | 'shieldedWithdrawal' | 'unshield' | 'shieldedTransfer' | 'identityCreateFromShieldedPool')
172
+ * @param type {string} Type of the shielded transition, must be one of ('shield' | 'shieldFromAssetLock' | 'shieldedWithdrawal' | 'unshield' | 'shieldedTransfer' | 'shieldedTransferMulti' | 'identityCreateFromShieldedPool')
171
173
  * @param params {ShieldedTransitionParams} params
172
174
  *
173
175
  * @return {StateTransitionWASM}
174
176
  */
175
- createStateTransition(type, params) {
177
+ async createStateTransition(type, params) {
176
178
  // @ts-expect-error a plain string memo is normalized to ShieldedMemoWASM (empty when omitted)
177
179
  params.memo = typeof params.memo === 'string' ? ShieldedMemoWASM.fromString(params.memo) : ShieldedMemoWASM.empty();
178
180
  if (type === 'identityCreateFromShieldedPool') {
@@ -181,6 +183,6 @@ export class ShieldedController {
181
183
  identityParams.publicKeys = identityParams.publicKeys
182
184
  .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));
183
185
  }
184
- return createStateTransition(this.getShieldedBuilder(), type, params);
186
+ return await createStateTransition(await this.getShieldedBuilder(), type, params);
185
187
  }
186
188
  }
@@ -4,6 +4,9 @@ import { calculateStateIdHash } from './calculateStateIdHash.js';
4
4
  import { verifySignatureDigest } from 'pshenmic-dpp';
5
5
  import hexToBytes from './hexToBytes.js';
6
6
  export default async function verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey) {
7
+ if ((new Date().getTime() - new Date(metadata.timeMs).getTime()) > 15 * 60 * 60 * 1000) {
8
+ throw new Error('Request is stalled (over 15 minutes)');
9
+ }
7
10
  const stateId = StateId.create({
8
11
  appVersion: String(metadata.protocolVersion),
9
12
  coreChainLockedHeight: metadata.coreChainLockedHeight,
@@ -259,7 +259,7 @@ describe('Identity', () => {
259
259
  const recipientId = 'HT3pUBM1Uv2mKgdPEN1gxa7A4PdsvNY89aJbdSKQb5wR';
260
260
  const amount = 100000n;
261
261
  const identityNonce = await sdk.identities.getIdentityNonce(identityId);
262
- const stateTransition = sdk.identities.createStateTransition('creditTransfer', { identityId, recipientId, amount, identityNonce });
262
+ const stateTransition = sdk.identities.createStateTransition('withdrawal', { identityId, recipientId, amount, identityNonce });
263
263
  expect(stateTransition).toEqual(expect.any(StateTransitionWASM));
264
264
  });
265
265
  });
@@ -1,4 +1,4 @@
1
- import { OrchardAddressWASM } from 'pshenmic-dpp';
1
+ import { OrchardAddressWASM, PlatformAddressWASM } from 'pshenmic-dpp';
2
2
  import { DashPlatformSDK } from '../../src/DashPlatformSDK.js';
3
3
  let sdk;
4
4
  let mnemonic;
@@ -63,4 +63,52 @@ describe('KeyPair', () => {
63
63
  expect(ovk).toEqual(sdk.keyPair.deriveShieldedOutgoingViewingKey(seed, 'testnet', account));
64
64
  });
65
65
  });
66
+ describe('platform addresses', () => {
67
+ const account = 0;
68
+ // Reference values produced by the dash-platform-extension derivation utils
69
+ // (proven byte-identical to on-chain / desktop-wallet addresses) for the
70
+ // fixed mnemonic above, testnet, account 0.
71
+ const expectedXpub = 'tpubDH6WaqMU1YHJMbPG413my6Dx5DwnsuuL6EzbetEZQac6ixmkByzCGgiibue3HQmHX5JGVUm2fBHKGttJpVkx3NrK5Em9br8GyLd1fVGm7ud';
72
+ const expectedAddresses = [
73
+ 'tdash1kr0xt5wj85ht5u464rfysjrq75rewz9mysjwf59p',
74
+ 'tdash1kqgy7ngm2wf0zsv20k4mc62s5rapw26yeg6em4jq',
75
+ 'tdash1kzlatzl0u06uxrqz8hkc7naz9d2g3v8g7gw83ew3'
76
+ ];
77
+ test('derives the DIP-17 account xpub matching the reference', async () => {
78
+ const seed = sdk.keyPair.mnemonicToSeed(mnemonic);
79
+ const xpub = await sdk.keyPair.derivePlatformAccountXpub(seed, 'testnet', account);
80
+ expect(xpub).toEqual(expectedXpub);
81
+ });
82
+ test('derives seed-based addresses matching the reference', async () => {
83
+ const seed = sdk.keyPair.mnemonicToSeed(mnemonic);
84
+ for (let index = 0; index < expectedAddresses.length; index++) {
85
+ const address = await sdk.keyPair.derivePlatformAddress(seed, 'testnet', account, index);
86
+ expect(address).toEqual(expect.any(PlatformAddressWASM));
87
+ expect(address.isP2PKH()).toBe(true);
88
+ expect(address.toBech32m('testnet')).toEqual(expectedAddresses[index]);
89
+ }
90
+ });
91
+ test('xpub-based public derivation reproduces the seed-based addresses', async () => {
92
+ const seed = sdk.keyPair.mnemonicToSeed(mnemonic);
93
+ const xpub = await sdk.keyPair.derivePlatformAccountXpub(seed, 'testnet', account);
94
+ for (let index = 0; index < expectedAddresses.length; index++) {
95
+ const fromXpub = sdk.keyPair.derivePlatformAddressFromXpub(xpub, 'testnet', index);
96
+ expect(fromXpub.toBech32m('testnet')).toEqual(expectedAddresses[index]);
97
+ }
98
+ });
99
+ test('private key derivation yields the same pubkey hash as the address', async () => {
100
+ const seed = sdk.keyPair.mnemonicToSeed(mnemonic);
101
+ for (let index = 0; index < expectedAddresses.length; index++) {
102
+ const privateKey = await sdk.keyPair.derivePlatformAddressPrivateKey(seed, 'testnet', account, index);
103
+ const address = await sdk.keyPair.derivePlatformAddress(seed, 'testnet', account, index);
104
+ expect(privateKey.getPublicKeyHash()).toEqual(Buffer.from(address.hash()).toString('hex'));
105
+ }
106
+ });
107
+ test('derives distinct addresses per network', async () => {
108
+ const seed = sdk.keyPair.mnemonicToSeed(mnemonic);
109
+ const mainnet = await sdk.keyPair.derivePlatformAddress(seed, 'mainnet', account, 0);
110
+ const testnet = await sdk.keyPair.derivePlatformAddress(seed, 'testnet', account, 0);
111
+ expect(mainnet.bytes()).not.toEqual(testnet.bytes());
112
+ });
113
+ });
66
114
  });
@@ -51,6 +51,12 @@ describe('Node', () => {
51
51
  expect(epochsInfo.length).toEqual(10);
52
52
  expect(epochsInfo.map(epochInfo => epochInfo.number)).toEqual(expectedEpochsNumbers);
53
53
  });
54
+ test('should be able to call getFinalizedEpochInfos', async () => {
55
+ const epochsInfo = await sdk.node.getFinalizedEpochsInfo(17100, true, 17110, false);
56
+ const expectedEpochsNumbers = Array.from({ length: 10 }, (_val, index) => 17100 + index);
57
+ expect(epochsInfo.length).toEqual(10);
58
+ expect(epochsInfo.map(epochInfo => epochInfo.epochIndex)).toEqual(expectedEpochsNumbers);
59
+ });
54
60
  test('should be able to call getTotalCreditsInPlatform', async () => {
55
61
  const totalCredits = await sdk.node.totalCredits();
56
62
  expect(Number(totalCredits)).toBeGreaterThan(0);
@@ -1,3 +1,5 @@
1
+ import { AddressFundsFeeStrategyStepWASM, AddressWitnessWASM, AssetLockProofWASM, CoreScriptWASM, IdentityPublicKeyInCreationWASM, InputAddressWASM, OutputAddressWASM, OutputAddressNullableCreditsWASM, KeyType, OutPointWASM, PlatformAddressWASM, PrivateKeyWASM, Purpose, SecurityLevel, StateTransitionWASM } from 'pshenmic-dpp';
2
+ import { base58 } from '@scure/base';
1
3
  import { DashPlatformSDK } from '../../src/DashPlatformSDK.js';
2
4
  let sdk;
3
5
  describe('PlatformAddress', () => {
@@ -14,9 +16,161 @@ describe('PlatformAddress', () => {
14
16
  const addresses = [
15
17
  'tdash1kzg5azscav69z7m6dfzr9ner0a5vt7pn9ca4sz8d',
16
18
  'tdash1kqr3cxhgel75ru0yrhj5eq8j8jt92m5enqrfajxw',
17
- 'tdash1kq9plfyacx9q26dtaxgwuw9lt78nyu2mzc3xwcxv'
19
+ 'tdash1kzpjkv364ez6yyaqyvxfdgzcdet2h4mumqcjd2yx'
18
20
  ];
19
21
  const info = await sdk.platformAddresses.getAddressesInfos(addresses);
20
22
  expect(info).toHaveLength(addresses.length);
21
23
  });
24
+ test('getAddressesTrunkState', async () => {
25
+ const { trunk, metadata } = await sdk.platformAddresses.getAddressesTrunkState();
26
+ expect(trunk.rootHash).toEqual(expect.any(Uint8Array));
27
+ expect(trunk.elements.length).toBeGreaterThan(0);
28
+ expect(trunk.chunkDepths.length).toBeGreaterThan(0);
29
+ expect(metadata.height).toBeDefined();
30
+ });
31
+ test('getAddressesBranchState', async () => {
32
+ const { trunk, metadata } = await sdk.platformAddresses.getAddressesTrunkState();
33
+ // The whole tree fits in the trunk when it is small enough - nothing to descend into
34
+ if (trunk.leafKeys.length === 0) {
35
+ return;
36
+ }
37
+ const [leaf] = trunk.leafKeys;
38
+ const depth = trunk.chunkDepths[1] ?? trunk.chunkDepths[0];
39
+ const branch = await sdk.platformAddresses.getAddressesBranchState(leaf.key, depth, BigInt(metadata.height), leaf.hash);
40
+ expect(branch.branchRootHash).toEqual(leaf.hash);
41
+ expect(branch.elements.length).toBeGreaterThan(0);
42
+ });
43
+ test('getRecentAddressBalanceChanges', async () => {
44
+ const blocks = await sdk.platformAddresses.getRecentAddressBalanceChanges(1n);
45
+ expect(Array.isArray(blocks)).toBe(true);
46
+ for (const block of blocks) {
47
+ expect(block.blockHeight).toEqual(expect.any(BigInt));
48
+ for (const change of block.changes) {
49
+ expect(change.address).toEqual(expect.any(PlatformAddressWASM));
50
+ expect(['setCredits', 'addToCredits']).toContain(change.operation);
51
+ expect(change.credits).toEqual(expect.any(BigInt));
52
+ }
53
+ }
54
+ });
55
+ test('getRecentCompactedAddressBalanceChanges', async () => {
56
+ const ranges = await sdk.platformAddresses.getRecentCompactedAddressBalanceChanges(1n);
57
+ expect(Array.isArray(ranges)).toBe(true);
58
+ for (const range of ranges) {
59
+ expect(range.startBlockHeight).toEqual(expect.any(BigInt));
60
+ expect(range.endBlockHeight).toBeGreaterThanOrEqual(range.startBlockHeight);
61
+ for (const change of range.changes) {
62
+ expect(change.address).toEqual(expect.any(PlatformAddressWASM));
63
+ expect(['setCredits', 'addToCreditsOperations']).toContain(change.operation);
64
+ }
65
+ }
66
+ });
67
+ describe('createStateTransition', () => {
68
+ const identityId = 'QMfCRPcjXoTnZa9sA9JR2KWgGxZXMRJ4akgS3Uia1Qv';
69
+ const addressA = PlatformAddressWASM.fromBech32m('tdash1kzg5azscav69z7m6dfzr9ner0a5vt7pn9ca4sz8d');
70
+ const addressB = PlatformAddressWASM.fromBech32m('tdash1kqr3cxhgel75ru0yrhj5eq8j8jt92m5enqrfajxw');
71
+ const inputs = [new InputAddressWASM(addressA, 0, 100000n)];
72
+ const outputs = [new OutputAddressWASM(addressB, 50000n)];
73
+ const recipients = [new OutputAddressWASM(addressB, 50000n)];
74
+ const nullableOutputs = [new OutputAddressNullableCreditsWASM(addressB)];
75
+ const feeStrategy = [AddressFundsFeeStrategyStepWASM.DeductFromInput(1)];
76
+ const inputWitness = [AddressWitnessWASM.P2PKH(new Uint8Array(65))];
77
+ const output = new OutputAddressWASM(addressA, 10000n);
78
+ const nonce = 1n;
79
+ const privateKey = PrivateKeyWASM.fromHex('a1286dd195e2b8e1f6bdc946c56a53e0c544750d6452ddc0f4c593ef311f21af', 'testnet');
80
+ const publicKeys = [
81
+ new IdentityPublicKeyInCreationWASM(0, Purpose.AUTHENTICATION, SecurityLevel.MASTER, KeyType.ECDSA_SECP256K1, false, privateKey.getPublicKey().bytes())
82
+ ];
83
+ const assetLockProof = AssetLockProofWASM.createChainAssetLockProof(1337, new OutPointWASM('61aede830477254876d435a317241ad46753c4b1350dc991a45ebcf19ab80a11', 0));
84
+ const withdrawalAddress = 'yjHVQ3dj37UJwXFmvMTKR9ZVfoJSc3opTD';
85
+ const outputScript = CoreScriptWASM.newP2PKH(base58.decode(withdrawalAddress).slice(1, 21));
86
+ test('should be able to create identityCreditTransferToAddresses', () => {
87
+ const stateTransition = sdk.platformAddresses.createStateTransition('identityCreditTransferToAddresses', {
88
+ identityId, recipients, nonce
89
+ });
90
+ expect(stateTransition).toEqual(expect.any(StateTransitionWASM));
91
+ });
92
+ test('should throw when identityCreditTransferToAddresses is missing recipients', () => {
93
+ // @ts-expect-error testing the runtime missing-param check
94
+ expect(() => sdk.platformAddresses.createStateTransition('identityCreditTransferToAddresses', {
95
+ identityId, nonce
96
+ })).toThrow('Platform address transition param "recipients" is missing');
97
+ });
98
+ test('should be able to create identityCreateFromAddresses', () => {
99
+ const stateTransition = sdk.platformAddresses.createStateTransition('identityCreateFromAddresses', {
100
+ publicKeys, inputs, feeStrategy, inputWitness
101
+ });
102
+ expect(stateTransition).toEqual(expect.any(StateTransitionWASM));
103
+ });
104
+ test('should throw when identityCreateFromAddresses is missing publicKeys', () => {
105
+ // @ts-expect-error testing the runtime missing-param check
106
+ expect(() => sdk.platformAddresses.createStateTransition('identityCreateFromAddresses', {
107
+ inputs, feeStrategy, inputWitness
108
+ })).toThrow('Platform address transition param "publicKeys" is missing');
109
+ });
110
+ test('should be able to create identityTopUpFromAddresses', () => {
111
+ const stateTransition = sdk.platformAddresses.createStateTransition('identityTopUpFromAddresses', {
112
+ identityId, inputs, feeStrategy, inputWitness
113
+ });
114
+ expect(stateTransition).toEqual(expect.any(StateTransitionWASM));
115
+ });
116
+ test('should throw when identityTopUpFromAddresses is missing identityId', () => {
117
+ // @ts-expect-error testing the runtime missing-param check
118
+ expect(() => sdk.platformAddresses.createStateTransition('identityTopUpFromAddresses', {
119
+ inputs, feeStrategy, inputWitness
120
+ })).toThrow('Platform address transition param "identityId" is missing');
121
+ });
122
+ test('should be able to create addressFundsTransfer', () => {
123
+ const stateTransition = sdk.platformAddresses.createStateTransition('addressFundsTransfer', {
124
+ inputs, feeStrategy, inputWitness, outputs
125
+ });
126
+ expect(stateTransition).toEqual(expect.any(StateTransitionWASM));
127
+ });
128
+ test('should throw when addressFundsTransfer is missing outputs', () => {
129
+ // @ts-expect-error testing the runtime missing-param check
130
+ expect(() => sdk.platformAddresses.createStateTransition('addressFundsTransfer', {
131
+ inputs, feeStrategy, inputWitness
132
+ })).toThrow('Platform address transition param "outputs" is missing');
133
+ });
134
+ test('should be able to create addressFundingFromAssetLock', () => {
135
+ const stateTransition = sdk.platformAddresses.createStateTransition('addressFundingFromAssetLock', {
136
+ assetLockProof, inputs, feeStrategy, inputWitness, outputs: nullableOutputs
137
+ });
138
+ expect(stateTransition).toEqual(expect.any(StateTransitionWASM));
139
+ });
140
+ test('should throw when addressFundingFromAssetLock is missing assetLockProof', () => {
141
+ // @ts-expect-error testing the runtime missing-param check
142
+ expect(() => sdk.platformAddresses.createStateTransition('addressFundingFromAssetLock', {
143
+ inputs, feeStrategy, inputWitness, outputs: nullableOutputs
144
+ })).toThrow('Platform address transition param "assetLockProof" is missing');
145
+ });
146
+ test('should be able to create addressCreditWithdrawal', () => {
147
+ const stateTransition = sdk.platformAddresses.createStateTransition('addressCreditWithdrawal', {
148
+ inputs, feeStrategy, coreFeePerByte: 1, pooling: 'Standard', outputScript, inputWitness
149
+ });
150
+ expect(stateTransition).toEqual(expect.any(StateTransitionWASM));
151
+ });
152
+ test('should be able to create addressCreditWithdrawal with optional output', () => {
153
+ const stateTransition = sdk.platformAddresses.createStateTransition('addressCreditWithdrawal', {
154
+ inputs, feeStrategy, coreFeePerByte: 1, pooling: 'Standard', outputScript, inputWitness, output
155
+ });
156
+ expect(stateTransition).toEqual(expect.any(StateTransitionWASM));
157
+ });
158
+ test('should throw when addressCreditWithdrawal is missing outputScript', () => {
159
+ // @ts-expect-error testing the runtime missing-param check
160
+ expect(() => sdk.platformAddresses.createStateTransition('addressCreditWithdrawal', {
161
+ inputs, feeStrategy, coreFeePerByte: 1, pooling: 'Standard', inputWitness
162
+ })).toThrow('Platform address transition param "outputScript" is missing');
163
+ });
164
+ test('should default userFeeIncrease to 0 when omitted', () => {
165
+ const stateTransition = sdk.platformAddresses.createStateTransition('addressFundsTransfer', {
166
+ inputs, feeStrategy, inputWitness, outputs
167
+ });
168
+ expect(stateTransition).toEqual(expect.any(StateTransitionWASM));
169
+ });
170
+ test('should throw on unimplemented transition type', () => {
171
+ expect(() => sdk.platformAddresses.createStateTransition(
172
+ // @ts-expect-error testing an unknown transition type
173
+ 'unknownTransition', {})).toThrow('Unimplemented transition type: unknownTransition');
174
+ });
175
+ });
22
176
  });