dash-platform-sdk 1.6.0-dev.7 → 1.6.0-dev.9

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 (65) hide show
  1. package/README.md +14 -14
  2. package/bundle.min.js +1 -1
  3. package/package.json +2 -2
  4. package/proto/generated/platform.client.d.ts +10 -0
  5. package/proto/generated/platform.client.js +7 -0
  6. package/proto/generated/platform.d.ts +137 -0
  7. package/proto/generated/platform.js +279 -1
  8. package/src/QueryExecutor.d.ts +40 -4
  9. package/src/QueryExecutor.js +61 -8
  10. package/src/constants.d.ts +7 -1
  11. package/src/constants.js +9 -2
  12. package/src/contestedResources/getContestedResourceVoteState.js +14 -6
  13. package/src/contestedResources/getVotePollsByEndDate.js +7 -2
  14. package/src/dataContracts/getDataContractByIdentifier.js +3 -3
  15. package/src/documents/index.d.ts +4 -1
  16. package/src/documents/index.js +6 -2
  17. package/src/documents/query.js +4 -4
  18. package/src/documents/queryAggregate.js +2 -3
  19. package/src/documents/queryJoined.js +6 -7
  20. package/src/documents/queryRanked.js +2 -3
  21. package/src/documents/v1.d.ts +2 -2
  22. package/src/documents/v1.js +2 -3
  23. package/src/grpcConnectionPool.d.ts +9 -2
  24. package/src/grpcConnectionPool.js +7 -8
  25. package/src/identities/getIdentityBalance.js +1 -2
  26. package/src/identities/getIdentityByIdentifier.js +1 -2
  27. package/src/identities/getIdentityByNonUniquePublicKeyHash.js +2 -3
  28. package/src/identities/getIdentityByPublicKeyHash.js +1 -2
  29. package/src/identities/getIdentityContractNonce.js +1 -2
  30. package/src/identities/getIdentityNonce.js +1 -2
  31. package/src/identities/getIdentityPublicKeys.js +1 -2
  32. package/src/names/index.d.ts +1 -1
  33. package/src/names/index.js +1 -1
  34. package/src/names/registerName.js +5 -2
  35. package/src/node/epochInfos.js +1 -2
  36. package/src/node/finalizedEpochInfos.js +1 -2
  37. package/src/node/getPathElements.d.ts +4 -0
  38. package/src/node/getPathElements.js +27 -0
  39. package/src/node/getProtocolVersion.d.ts +9 -0
  40. package/src/node/getProtocolVersion.js +29 -0
  41. package/src/node/index.d.ts +20 -0
  42. package/src/node/index.js +25 -0
  43. package/src/node/totalCredits.js +3 -3
  44. package/src/platformAddresses/getAddressInfo.js +1 -2
  45. package/src/platformAddresses/getAddressesBranchState.js +1 -2
  46. package/src/platformAddresses/getAddressesInfos.js +1 -2
  47. package/src/platformAddresses/getAddressesTrunkState.js +1 -2
  48. package/src/platformAddresses/getRecentAddressBalanceChanges.js +2 -2
  49. package/src/platformAddresses/getRecentCompactedAddressBalanceChanges.js +2 -2
  50. package/src/shielded/getMostRecentShieldedAnchor.js +1 -2
  51. package/src/shielded/getShieldedAnchors.js +1 -2
  52. package/src/shielded/getShieldedEncryptedNotes.js +2 -2
  53. package/src/shielded/getShieldedNotesCount.js +1 -2
  54. package/src/shielded/getShieldedNullifiers.js +1 -2
  55. package/src/shielded/getShieldedPoolState.js +1 -2
  56. package/src/stateTransitions/waitForStateTransitionResult.js +13 -11
  57. package/src/tokens/getIdentitiesTokenBalances.js +1 -2
  58. package/src/tokens/getIdentityTokensBalances.js +1 -2
  59. package/src/tokens/getTokenContractInfo.js +1 -2
  60. package/src/tokens/getTokenDirectPurchasePrices.js +1 -2
  61. package/src/tokens/getTokenTotalSupply.js +1 -2
  62. package/test/integration/MainnetCompatibility.spec.d.ts +1 -0
  63. package/test/integration/MainnetCompatibility.spec.js +373 -0
  64. package/test/unit/Node.spec.js +17 -0
  65. package/test/unit/SDK.spec.js +38 -0
@@ -1,7 +1,6 @@
1
1
  import { IdentifierWASM, verifyTokensBalancesForIdentityProof } from 'pshenmic-dpp';
2
2
  import { GetIdentityTokenBalancesRequest } from '../../proto/generated/platform.js';
3
3
  import QueryExecutor from '../QueryExecutor.js';
4
- import { LATEST_PLATFORM_VERSION } from '../constants.js';
5
4
  export default async function getIdentityTokensBalances(grpcPool, quorumKeyProvider, identifier, tokenIdentifiers) {
6
5
  const id = new IdentifierWASM(identifier);
7
6
  const tokenIds = tokenIdentifiers.map(tokenIdentifier => new IdentifierWASM(tokenIdentifier));
@@ -17,7 +16,7 @@ export default async function getIdentityTokensBalances(grpcPool, quorumKeyProvi
17
16
  });
18
17
  return await QueryExecutor.build(grpcPool, quorumKeyProvider)
19
18
  .setGrpcRequest('getIdentityTokenBalances', getIdentityTokenBalancesRequest)
20
- .setProofVerifier(verifyTokensBalancesForIdentityProof, tokenIds, id, true, LATEST_PLATFORM_VERSION)
19
+ .setProofVerifier(verifyTokensBalancesForIdentityProof, (_, platformVersion) => [tokenIds, id, true, platformVersion])
21
20
  .mapResponse(data => {
22
21
  const balances = data.proved
23
22
  ? data.verified.balances
@@ -1,7 +1,6 @@
1
1
  import { GetTokenContractInfoRequest } from '../../proto/generated/platform.js';
2
2
  import { IdentifierWASM, verifyTokenContractInfoProof } from 'pshenmic-dpp';
3
3
  import QueryExecutor from '../QueryExecutor.js';
4
- import { LATEST_PLATFORM_VERSION } from '../constants.js';
5
4
  export default async function getTokenContractInfo(grpcPool, quorumKeyProvider, tokenIdentifier) {
6
5
  const tokenId = new IdentifierWASM(tokenIdentifier);
7
6
  const getTokenContractInfoRequest = GetTokenContractInfoRequest.create({
@@ -15,7 +14,7 @@ export default async function getTokenContractInfo(grpcPool, quorumKeyProvider,
15
14
  });
16
15
  return await QueryExecutor.build(grpcPool, quorumKeyProvider)
17
16
  .setGrpcRequest('getTokenContractInfo', getTokenContractInfoRequest)
18
- .setProofVerifier(verifyTokenContractInfoProof, tokenId, true, LATEST_PLATFORM_VERSION)
17
+ .setProofVerifier(verifyTokenContractInfoProof, (_, platformVersion) => [tokenId, true, platformVersion])
19
18
  .mapResponse(data => {
20
19
  const contractInfo = data.proved ? data.verified.contractInfo : data.result.data;
21
20
  if (contractInfo == null) {
@@ -1,7 +1,6 @@
1
1
  import { IdentifierWASM, verifyTokenDirectPurchasePrices, TokenPricingScheduleWASM } from 'pshenmic-dpp';
2
2
  import QueryExecutor from '../QueryExecutor.js';
3
3
  import { GetTokenDirectPurchasePricesRequest } from '../../proto/generated/platform.js';
4
- import { LATEST_PLATFORM_VERSION } from '../constants.js';
5
4
  export default async function getTokenDirectPurchasePrices(grpcPool, quorumKeyProvider, tokenIdentifiers) {
6
5
  const tokenIds = tokenIdentifiers.map(tokenId => new IdentifierWASM(tokenId).bytes());
7
6
  const request = GetTokenDirectPurchasePricesRequest.create({
@@ -15,7 +14,7 @@ export default async function getTokenDirectPurchasePrices(grpcPool, quorumKeyPr
15
14
  });
16
15
  return await QueryExecutor.build(grpcPool, quorumKeyProvider)
17
16
  .setGrpcRequest('getTokenDirectPurchasePrices', request)
18
- .setProofVerifier(verifyTokenDirectPurchasePrices, tokenIds, true, LATEST_PLATFORM_VERSION)
17
+ .setProofVerifier(verifyTokenDirectPurchasePrices, (_, platformVersion) => [tokenIds, true, platformVersion])
19
18
  .mapResponse(data => {
20
19
  if (data.proved) {
21
20
  if (data.verified.prices == null) {
@@ -1,7 +1,6 @@
1
1
  import { GetTokenTotalSupplyRequest } from '../../proto/generated/platform.js';
2
2
  import { IdentifierWASM, verifyTokenTotalSupplyProof } from 'pshenmic-dpp';
3
3
  import QueryExecutor from '../QueryExecutor.js';
4
- import { LATEST_PLATFORM_VERSION } from '../constants.js';
5
4
  export default async function getTokenTotalSupply(grpcPool, quorumKeyProvider, tokenIdentifier) {
6
5
  const tokenId = new IdentifierWASM(tokenIdentifier);
7
6
  const getTokenTotalSupplyRequest = GetTokenTotalSupplyRequest.create({
@@ -15,7 +14,7 @@ export default async function getTokenTotalSupply(grpcPool, quorumKeyProvider, t
15
14
  });
16
15
  return await QueryExecutor.build(grpcPool, quorumKeyProvider)
17
16
  .setGrpcRequest('getTokenTotalSupply', getTokenTotalSupplyRequest)
18
- .setProofVerifier(verifyTokenTotalSupplyProof, tokenId, true, LATEST_PLATFORM_VERSION)
17
+ .setProofVerifier(verifyTokenTotalSupplyProof, (_, platformVersion) => [tokenId, true, platformVersion])
19
18
  .mapResponse(data => {
20
19
  const [totalSystemAmount, totalAggregatedAmountInUserAccounts] = data.proved
21
20
  ? [data.verified.totalBalance.tokenSupply, data.verified.totalBalance.aggregatedTokenAccountBalances]
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,373 @@
1
+ import { KeyType, PlatformAddressWASM, StateTransitionWASM } from 'pshenmic-dpp';
2
+ import { DashPlatformSDK } from '../../src/DashPlatformSDK.js';
3
+ import { ContestedStateResultType } from '../../types.js';
4
+ import stringToIndexValueBytes from '../../src/utils/stringToIndexValueBytes.js';
5
+ const mainnet = process.env.MAINNET_COMPATIBILITY === '1' ? describe : describe.skip;
6
+ const dapiUrl = process.env.MAINNET_DAPI_URL ?? 'https://153.80.206.97:443';
7
+ const contractId = process.env.MAINNET_CONTRACT_ID ?? 'GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec';
8
+ const documentType = process.env.MAINNET_DOCUMENT_TYPE ?? 'domain';
9
+ // Published Platform system contracts and a token observed in mainnet token-history transfers.
10
+ const dashpayContractId = 'Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7';
11
+ const documentHistoryId = '6voHRaoiPcfmMhbqCA9dixH98xcgPQ9UEcuaXjpVu3LD';
12
+ const tokenId = process.env.MAINNET_TOKEN_ID ?? 'DYqxCsuDgYsEAJ2ADnimkwNdL7C4xbe4No4so19X9mmd';
13
+ const transitionHex = process.env.MAINNET_STATE_TRANSITION_HEX;
14
+ mainnet('Mainnet public SDK reads (explicit endpoint; no writes)', () => {
15
+ let sdk;
16
+ let status;
17
+ let documents;
18
+ let identities;
19
+ let fixtureError;
20
+ const outcomes = [];
21
+ const registered = new Set();
22
+ // Unsupported methods remain FAILED Jest tests, not successful compatibility assertions.
23
+ const check = (method, run, variant) => {
24
+ registered.add(method);
25
+ test(`${method}${variant != null ? `: ${variant}` : ''}`, async () => {
26
+ try {
27
+ await run();
28
+ outcomes.push({ method: variant != null ? `${method} (${variant})` : method, status: 'PASS' });
29
+ }
30
+ catch (error) {
31
+ const message = error instanceof Error ? error.message : String(error);
32
+ const code = error != null && typeof error === 'object' && 'code' in error ? error.code : undefined;
33
+ const detail = decodeURIComponent(message);
34
+ const outcome = code === 'UNIMPLEMENTED' || /not yet implemented|not implemented/.test(detail)
35
+ ? 'UNSUPPORTED'
36
+ : /PREPARATION:|non indexed property|indexOnly inner/.test(detail) ? 'FIXTURE LIMITATION' : 'FAIL';
37
+ outcomes.push({ method, status: outcome, detail });
38
+ throw error;
39
+ }
40
+ });
41
+ };
42
+ beforeAll(async () => {
43
+ sdk = new DashPlatformSDK({ network: 'mainnet', grpc: { dapiUrl } });
44
+ status = await sdk.node.status();
45
+ console.info('Mainnet target:', JSON.stringify({ endpoint: dapiUrl, version: status.version, chainId: status.network?.chainId, discoveryCovered: false }));
46
+ expect(status.network?.chainId).toBe('evo1');
47
+ expect(status.version?.software?.drive).toMatch(/^4\./);
48
+ expect(status.chain?.catchingUp).toBe(false);
49
+ try {
50
+ // Fixture discovery uses public SDK methods, including their real proof verification.
51
+ documents = await sdk.documents.query(contractId, documentType, undefined, undefined, 10);
52
+ if (documents.length === 0)
53
+ throw new Error('No documents; configure MAINNET_CONTRACT_ID and MAINNET_DOCUMENT_TYPE');
54
+ const owners = process.env.MAINNET_IDENTITY_ID != null
55
+ ? [process.env.MAINNET_IDENTITY_ID]
56
+ : [...new Set(documents.map(document => document.ownerId.base58()))];
57
+ identities = [];
58
+ for (const owner of owners)
59
+ identities.push(await sdk.identities.getIdentityByIdentifier(owner));
60
+ console.info('Verified SDK fixtures:', JSON.stringify({ contractId, documentType, tokenId, identityIds: identities.map(identity => identity.id.base58()) }));
61
+ }
62
+ catch (error) {
63
+ fixtureError = new Error(`PREPARATION: SDK fixture discovery failed: ${String(error)}`);
64
+ }
65
+ }, 120000);
66
+ afterAll(() => {
67
+ for (const outcome of outcomes) {
68
+ console.info(`${outcome.status} ${outcome.method}${outcome.detail != null ? `: ${decodeURIComponent(outcome.detail)}` : ''}`);
69
+ }
70
+ console.info('Scope: public SDK network reads only; no broadcasts, registration, signing or spending. Local builders/utilities are covered by unit tests. Default protocol-14 discovery is not covered.');
71
+ });
72
+ const fixture = () => {
73
+ if (fixtureError != null)
74
+ throw fixtureError;
75
+ return identities[0];
76
+ };
77
+ const keyFixture = (unique) => {
78
+ fixture();
79
+ const key = identities.flatMap(identity => identity.getPublicKeys()).find(key => {
80
+ const isUnique = key.keyTypeNumber === KeyType.ECDSA_SECP256K1 || key.keyTypeNumber === KeyType.BLS12_381;
81
+ return isUnique === unique && key.disabledAt == null;
82
+ });
83
+ if (key == null)
84
+ throw new Error(`PREPARATION: No ${unique ? 'unique' : 'non-unique'} key; set MAINNET_IDENTITY_ID`);
85
+ return key;
86
+ };
87
+ const address = async () => {
88
+ if (process.env.MAINNET_ADDRESS != null)
89
+ return PlatformAddressWASM.fromBech32m(process.env.MAINNET_ADDRESS);
90
+ const { trunk } = await sdk.platformAddresses.getAddressesTrunkState();
91
+ const entry = trunk.elements.find(entry => entry.element.type === 'ItemWithSumItem');
92
+ if (entry == null)
93
+ throw new Error('PREPARATION: No funded address in trunk; set MAINNET_ADDRESS');
94
+ return PlatformAddressWASM.fromBytes(entry.key);
95
+ };
96
+ const recentHeight = () => BigInt(status.chain?.latestBlockHeight ?? '0') - 1n;
97
+ check('node.status', async () => {
98
+ const result = await sdk.node.status();
99
+ expect(result.network?.chainId).toBe('evo1');
100
+ expect(result.version?.protocol?.drive?.current).toBeLessThan(14);
101
+ expect(BigInt(result.chain?.latestBlockHeight ?? '0')).toBeGreaterThan(0n);
102
+ });
103
+ check('node.totalCredits', async () => { expect(await sdk.node.totalCredits()).toBeGreaterThan(0n); });
104
+ check('node.getCurrentQuorumsInfo', async () => {
105
+ const result = await sdk.node.getCurrentQuorumsInfo();
106
+ expect(result.currentQuorumHash).toMatch(/^[0-9a-f]{64}$/);
107
+ expect(result.validatorSets.length).toBeGreaterThan(0);
108
+ });
109
+ for (const ascending of [true, false]) {
110
+ check('node.getEpochsInfo', async () => {
111
+ const epoch = status.time?.epoch ?? -1;
112
+ expect(epoch).toBeGreaterThan(1);
113
+ const result = await sdk.node.getEpochsInfo(2, ascending, ascending ? epoch - 1 : epoch);
114
+ // The proof verifier returns epochs in ascending order for either query direction.
115
+ expect(result.map(info => info.number)).toEqual([epoch - 1, epoch]);
116
+ }, ascending ? 'ascending' : 'descending');
117
+ }
118
+ check('node.getFinalizedEpochsInfo', async () => {
119
+ const epoch = status.time?.epoch ?? -1;
120
+ expect(epoch).toBeGreaterThan(1);
121
+ expect((await sdk.node.getFinalizedEpochsInfo(epoch - 1, true, epoch, false)).map(info => info.epochIndex)).toEqual([epoch - 1]);
122
+ });
123
+ check('dataContracts.getDataContractByIdentifier', async () => {
124
+ const result = await sdk.dataContracts.getDataContractByIdentifier(dashpayContractId);
125
+ expect(result.id.base58()).toBe(dashpayContractId);
126
+ expect(Object.keys(result.getSchemas()).length).toBeGreaterThan(0);
127
+ }, 'on-chain DashPay, not cached DPNS');
128
+ check('identities.getIdentityByIdentifier', async () => {
129
+ const expected = fixture();
130
+ const result = await sdk.identities.getIdentityByIdentifier(expected.id);
131
+ expect(result.id.base58()).toBe(expected.id.base58());
132
+ expect(result.getPublicKeys().length).toBeGreaterThan(0);
133
+ });
134
+ check('identities.getIdentityBalance', async () => { expect(await sdk.identities.getIdentityBalance(fixture().id)).toBeGreaterThanOrEqual(0n); });
135
+ check('identities.getIdentityNonce', async () => { expect(await sdk.identities.getIdentityNonce(fixture().id)).toBeGreaterThanOrEqual(0n); });
136
+ check('identities.getIdentityContractNonce', async () => { expect(await sdk.identities.getIdentityContractNonce(fixture().id, contractId)).toBeGreaterThanOrEqual(0n); });
137
+ check('identities.getIdentityPublicKeys', async () => {
138
+ const result = await sdk.identities.getIdentityPublicKeys(fixture().id);
139
+ expect(result.map(key => key.keyId)).toEqual(expect.arrayContaining(fixture().getPublicKeys().map(key => key.keyId)));
140
+ });
141
+ check('identities.getIdentityPublicKeys', async () => {
142
+ const key = fixture().getPublicKeys()[0];
143
+ const result = await sdk.identities.getIdentityPublicKeys(fixture().id, [key.keyId]);
144
+ expect(result.map(key => key.keyId)).toEqual([key.keyId]);
145
+ }, 'specific key');
146
+ check('identities.getIdentityByPublicKeyHash', async () => {
147
+ const key = keyFixture(true);
148
+ const expected = identities.find(identity => identity.getPublicKeys().some(candidate => candidate.data === key.data && candidate.keyTypeNumber === key.keyTypeNumber));
149
+ expect(expected).toBeDefined();
150
+ const result = await sdk.identities.getIdentityByPublicKeyHash(key.getPublicKeyHash());
151
+ expect(result.id.base58()).toBe(expected?.id.base58());
152
+ });
153
+ check('identities.getIdentityByNonUniquePublicKeyHash', async () => {
154
+ const hash = keyFixture(false).getPublicKeyHash();
155
+ const result = await sdk.identities.getIdentityByNonUniquePublicKeyHash(hash);
156
+ expect(result.getPublicKeys().some(key => key.getPublicKeyHash() === hash)).toBe(true);
157
+ expect((await sdk.identities.getIdentityByIdentifier(result.id)).id.base58()).toBe(result.id.base58());
158
+ });
159
+ check('documents.query', async () => {
160
+ const result = await sdk.documents.query(contractId, documentType, undefined, undefined, 10);
161
+ expect(result.length).toBeGreaterThan(0);
162
+ expect(result.every(document => document.dataContractId.base58() === contractId)).toBe(true);
163
+ });
164
+ for (const inclusive of [true, false]) {
165
+ check('documents.query', async () => {
166
+ fixture();
167
+ const first = documents[0];
168
+ const result = await sdk.documents.query(contractId, documentType, undefined, undefined, 2, inclusive ? first.id : undefined, inclusive ? undefined : first.id);
169
+ expect(result.length).toBeGreaterThan(0);
170
+ expect(result[0].id.base58()).toBe(documents[inclusive ? 0 : 1].id.base58());
171
+ }, inclusive ? 'startAt' : 'startAfter');
172
+ }
173
+ check('documents.query', async () => {
174
+ const result = await sdk.documents.query(contractId, documentType, [['normalizedParentDomainName', '==', 'dash'], ['normalizedLabel', 'in', ['dash', 'pshenmic']]], [['normalizedLabel', 'asc']], 5);
175
+ expect(result.length).toBeGreaterThan(0);
176
+ expect(result.every(document => ['dash', 'pshenmic'].includes(document.properties.normalizedLabel))).toBe(true);
177
+ }, 'where and orderBy');
178
+ check('documents.count', async () => {
179
+ const result = await sdk.documents.count(documentHistoryId, { documentTypeName: 'transfer' });
180
+ expect(result.entries.length).toBeGreaterThan(0);
181
+ expect(result.entries[0].count).toBeGreaterThan(0n);
182
+ });
183
+ for (const method of ['sum', 'average']) {
184
+ check(`documents.${method}`, async () => {
185
+ const result = await sdk.documents[method](documentHistoryId, { documentTypeName: 'priceUpdate', where: [['dataContractId', '==', contractId], ['$createdAt', '>', 0]] }, 'price');
186
+ expect(result.entries.length).toBeGreaterThan(0);
187
+ expect(typeof result.entries[0].sum).toBe('bigint');
188
+ if (method === 'average')
189
+ expect(typeof result.entries[0].count).toBe('bigint');
190
+ });
191
+ }
192
+ check('documents.ranked', async () => {
193
+ const result = await sdk.documents.ranked(documentHistoryId, { documentTypeName: 'transfer', select: { function: 'count' }, groupBy: ['dataContractId'], where: [['dataContractId', 'in', [contractId, documentHistoryId]]], orderBy: [['$count', 'desc']] });
194
+ expect(Array.isArray(result.entries)).toBe(true);
195
+ });
196
+ check('documents.having', async () => {
197
+ const result = await sdk.documents.having(documentHistoryId, { documentTypeName: 'transfer', select: { function: 'count' }, groupBy: ['dataContractId'], where: [['dataContractId', 'in', [contractId, documentHistoryId]]], having: [{ function: 'count', operator: '>=', value: 1 }], limit: 2 });
198
+ expect(Array.isArray(result)).toBe(true);
199
+ });
200
+ check('documents.chained', async () => {
201
+ const result = await sdk.documents.chained(contractId, { documentTypeName: documentType, where: [['normalizedParentDomainName', '==', 'dash']], limit: 2 }, 'records.identity', documentType);
202
+ expect(Array.isArray(result.innerDocuments)).toBe(true);
203
+ expect(Array.isArray(result.outerDocuments)).toBe(true);
204
+ });
205
+ check('documents.composite', async () => {
206
+ const result = await sdk.documents.composite(documentHistoryId, { documentTypeName: 'transfer', where: [['dataContractId', '==', contractId]], orderBy: [['$createdAt', 'asc']], limit: 2 }, [{ documentTypeName: 'purchase', where: [['dataContractId', '==', contractId]], limit: 1, binding: { source: 'page', sourceProperty: 'documentId', field: 'documentId' } }]);
207
+ expect(result.pageDocuments.length).toBe(2);
208
+ expect(result.subResults.length).toBe(1);
209
+ });
210
+ check('documents.getActionFeeAgreement', async () => {
211
+ const result = await sdk.documents.getActionFeeAgreement(contractId, documentType, 'create');
212
+ expect(result === undefined || typeof result === 'object').toBe(true);
213
+ });
214
+ check('names.searchByName', async () => {
215
+ const [domain] = await sdk.documents.query(contractId, documentType, [['normalizedParentDomainName', '==', 'dash']], [['normalizedLabel', 'asc']], 1);
216
+ if (domain == null)
217
+ throw new Error('PREPARATION: No registered DPNS name');
218
+ const result = await sdk.names.searchByName(`${String(domain.properties.label)}.dash`);
219
+ expect(result.some(document => document.id.base58() === domain.id.base58())).toBe(true);
220
+ });
221
+ check('names.searchByIdentity', async () => {
222
+ fixture();
223
+ const domain = documents.find(document => document.properties.records?.identity != null);
224
+ if (domain == null)
225
+ throw new Error('PREPARATION: No DPNS identity record in fixtures');
226
+ const result = await sdk.names.searchByIdentity(domain.properties.records.identity);
227
+ expect(result.some(document => document.id.base58() === domain.id.base58())).toBe(true);
228
+ });
229
+ check('contestedResources.getContestedResourceVoteState', async () => {
230
+ const contract = await sdk.dataContracts.getDataContractByIdentifier(contractId);
231
+ const [domain] = await sdk.documents.query(contractId, documentType, [['normalizedParentDomainName', '==', 'dash']], [['normalizedLabel', 'asc']], 1);
232
+ const label = process.env.MAINNET_CONTESTED_LABEL ?? domain?.properties.normalizedLabel;
233
+ if (typeof label !== 'string')
234
+ throw new Error('PREPARATION: Set MAINNET_CONTESTED_LABEL to a mainnet contest');
235
+ const result = await sdk.contestedResources.getContestedResourceVoteState(contract, documentType, 'parentNameAndLabel', ['dash', label].map(stringToIndexValueBytes), ContestedStateResultType.DOCUMENTS_AND_VOTE_TALLY, true, undefined, 10);
236
+ expect(Array.isArray(result.contenders)).toBe(true);
237
+ expect(typeof result.skipped).toBe('boolean');
238
+ });
239
+ check('tokens.getTokenContractInfo', async () => {
240
+ const result = await sdk.tokens.getTokenContractInfo(tokenId);
241
+ expect(result.dataContractId.bytes()).toHaveLength(32);
242
+ expect(result.tokenContractPosition).toBeGreaterThanOrEqual(0);
243
+ });
244
+ check('tokens.getTokenTotalSupply', async () => {
245
+ const result = await sdk.tokens.getTokenTotalSupply(tokenId);
246
+ expect(result.tokenId.base58()).toBe(tokenId);
247
+ expect(result.totalSystemAmount).toBeGreaterThanOrEqual(0n);
248
+ expect(result.totalAggregatedAmountInUserAccounts).toBeGreaterThanOrEqual(0n);
249
+ });
250
+ check('tokens.getIdentityTokensBalances', async () => {
251
+ const result = await sdk.tokens.getIdentityTokensBalances(fixture().id, [tokenId]);
252
+ expect(result).toHaveLength(1);
253
+ expect(result[0].tokenId.base58()).toBe(tokenId);
254
+ expect(result[0].balance == null || result[0].balance >= 0n).toBe(true);
255
+ });
256
+ check('tokens.getIdentitiesTokenBalances', async () => {
257
+ const identity = fixture();
258
+ const result = await sdk.tokens.getIdentitiesTokenBalances([identity.id], tokenId);
259
+ expect(result).toHaveLength(1);
260
+ expect(result[0].identityId.base58()).toBe(identity.id.base58());
261
+ expect(result[0].balance == null || result[0].balance >= 0n).toBe(true);
262
+ });
263
+ check('tokens.getTokensDirectPurchasePrice', async () => {
264
+ const result = await sdk.tokens.getTokensDirectPurchasePrice([process.env.MAINNET_PURCHASABLE_TOKEN_ID ?? tokenId]);
265
+ expect(Array.isArray(result)).toBe(true);
266
+ for (const price of result)
267
+ expect(price.tokenId.bytes()).toHaveLength(32);
268
+ });
269
+ check('tokens.createBaseTransition', async () => {
270
+ const result = await sdk.tokens.createBaseTransition(tokenId, fixture().id);
271
+ expect(result).toBeDefined();
272
+ }, 'reads contract and nonce; builds locally, never broadcasts');
273
+ check('platformAddresses.getAddressInfo', async () => {
274
+ const expected = await address();
275
+ const result = await sdk.platformAddresses.getAddressInfo(expected);
276
+ expect(result.address.bytes()).toEqual(expected.bytes());
277
+ expect(result.balance).toBeGreaterThanOrEqual(0n);
278
+ });
279
+ check('platformAddresses.getAddressesInfos', async () => {
280
+ const result = await sdk.platformAddresses.getAddressesInfos([await address()]);
281
+ expect(result).toHaveLength(1);
282
+ expect(result[0].balance).toBeGreaterThanOrEqual(0n);
283
+ });
284
+ check('platformAddresses.getAddressesTrunkState', async () => {
285
+ const result = await sdk.platformAddresses.getAddressesTrunkState();
286
+ expect(result.trunk.rootHash).toHaveLength(32);
287
+ expect(BigInt(result.metadata.height)).toBeGreaterThan(0n);
288
+ });
289
+ check('platformAddresses.getAddressesBranchState', async () => {
290
+ const { trunk, metadata } = await sdk.platformAddresses.getAddressesTrunkState();
291
+ const leaf = trunk.leafKeys[0];
292
+ if (leaf == null)
293
+ throw new Error('PREPARATION: Address trunk has no branch fixture; branch method untested');
294
+ const result = await sdk.platformAddresses.getAddressesBranchState(leaf.key, trunk.chunkDepths[0] + 1, BigInt(metadata.height), leaf.hash);
295
+ expect(result.branchRootHash).toEqual(leaf.hash);
296
+ });
297
+ check('platformAddresses.getRecentAddressBalanceChanges', async () => {
298
+ const result = await sdk.platformAddresses.getRecentAddressBalanceChanges(recentHeight());
299
+ expect(Array.isArray(result)).toBe(true);
300
+ for (const block of result)
301
+ expect(block.blockHeight).toBeGreaterThanOrEqual(recentHeight());
302
+ });
303
+ check('platformAddresses.getRecentCompactedAddressBalanceChanges', async () => {
304
+ const result = await sdk.platformAddresses.getRecentCompactedAddressBalanceChanges(recentHeight());
305
+ expect(Array.isArray(result)).toBe(true);
306
+ for (const range of result)
307
+ expect(range.endBlockHeight).toBeGreaterThanOrEqual(range.startBlockHeight);
308
+ });
309
+ check('shielded.getShieldedEncryptedNotes', async () => {
310
+ const result = await sdk.shielded.getShieldedEncryptedNotes(0n, 1);
311
+ expect(Array.isArray(result)).toBe(true);
312
+ for (const note of result)
313
+ expect(note.cmx).toHaveLength(32);
314
+ });
315
+ check('shielded.getShieldedAnchors', async () => {
316
+ const result = await sdk.shielded.getShieldedAnchors();
317
+ expect(Array.isArray(result)).toBe(true);
318
+ for (const anchor of result)
319
+ expect(anchor).toHaveLength(32);
320
+ });
321
+ check('shielded.getMostRecentShieldedAnchor', async () => {
322
+ const result = await sdk.shielded.getMostRecentShieldedAnchor();
323
+ if (result != null)
324
+ expect(result).toHaveLength(32);
325
+ });
326
+ check('shielded.getShieldedPoolState', async () => {
327
+ const result = await sdk.shielded.getShieldedPoolState();
328
+ if (result != null)
329
+ expect(result).toBeGreaterThanOrEqual(0n);
330
+ });
331
+ check('shielded.getShieldedNotesCount', async () => {
332
+ const result = await sdk.shielded.getShieldedNotesCount();
333
+ if (result != null)
334
+ expect(result).toBeGreaterThanOrEqual(0n);
335
+ });
336
+ check('shielded.getShieldedNullifiers', async () => {
337
+ // Public absence query, not a wallet secret or spending operation.
338
+ const nullifier = new Uint8Array(32);
339
+ const result = await sdk.shielded.getShieldedNullifiers([nullifier]);
340
+ expect(result).toHaveLength(1);
341
+ expect(result[0].nullifier).toEqual(nullifier);
342
+ expect(typeof result[0].isSpent).toBe('boolean');
343
+ });
344
+ registered.add('stateTransitions.waitForStateTransitionResult');
345
+ if (transitionHex != null) {
346
+ check('stateTransitions.waitForStateTransitionResult', async () => {
347
+ const result = await sdk.stateTransitions.waitForStateTransitionResult(StateTransitionWASM.fromHex(transitionHex));
348
+ if (result != null)
349
+ expect(result).toBeGreaterThanOrEqual(0n);
350
+ });
351
+ }
352
+ else {
353
+ test.skip('stateTransitions.waitForStateTransitionResult: UNTESTED, requires MAINNET_STATE_TRANSITION_HEX for an already executed transition', () => { });
354
+ outcomes.push({ method: 'stateTransitions.waitForStateTransitionResult', status: 'UNTESTED', detail: 'No historical transition bytes; never submits a new transition' });
355
+ }
356
+ test('every public SDK network-read method has an explicit case', () => {
357
+ const controllers = ['node', 'identities', 'dataContracts', 'documents', 'names', 'tokens', 'contestedResources', 'platformAddresses', 'shielded', 'stateTransitions'];
358
+ const localOrWriteMethods = new Set([
359
+ 'create', 'createStateTransition', 'broadcast', 'registerName', 'testNameContested', 'normalizeLabel', 'validateName',
360
+ 'init', 'getShieldedBuilder', 'recoverNotes', 'buildSpendableNotes'
361
+ ]);
362
+ const missing = [];
363
+ for (const controller of controllers) {
364
+ for (const method of Object.getOwnPropertyNames(Object.getPrototypeOf(sdk[controller]))) {
365
+ if (method === 'constructor' || localOrWriteMethods.has(method))
366
+ continue;
367
+ if (!registered.has(`${controller}.${method}`))
368
+ missing.push(`${controller}.${method}`);
369
+ }
370
+ }
371
+ expect(missing).toEqual([]);
372
+ });
373
+ });
@@ -1,3 +1,4 @@
1
+ import { base58 } from '@scure/base';
1
2
  import { DashPlatformSDK } from '../../src/DashPlatformSDK.js';
2
3
  let sdk;
3
4
  describe('Node', () => {
@@ -82,4 +83,20 @@ describe('Node', () => {
82
83
  }
83
84
  }
84
85
  });
86
+ test('should be able to call getPathElements', async () => {
87
+ // root tree key of identity balances
88
+ const balancesKey = new Uint8Array([96]);
89
+ const missingKey = new Uint8Array([255]);
90
+ const rootElements = await sdk.node.getPathElements([], [balancesKey, missingKey]);
91
+ // absence of the missing key is proven, but it is not returned
92
+ expect(rootElements.length).toEqual(1);
93
+ expect(rootElements[0].key).toEqual(balancesKey);
94
+ expect(rootElements[0].element?.type).toEqual('SumTree');
95
+ expect(rootElements[0].element?.sum).toEqual(expect.any(BigInt));
96
+ const identifier = 'QMfCRPcjXoTnZa9sA9JR2KWgGxZXMRJ4akgS3Uia1Qv';
97
+ const [balanceElement] = await sdk.node.getPathElements([balancesKey], [base58.decode(identifier)]);
98
+ const balance = await sdk.identities.getIdentityBalance(identifier);
99
+ expect(balanceElement.element?.type).toEqual('SumItem');
100
+ expect(balanceElement.element?.sum).toEqual(balance);
101
+ });
85
102
  });
@@ -1,5 +1,8 @@
1
1
  import { DashPlatformSDK } from '../../src/DashPlatformSDK.js';
2
2
  import { PlatformExplorerQuorumKeyProvider } from '../../src/quorumKeyProvider.js';
3
+ import { getVerifierVersion } from '../../src/QueryExecutor.js';
4
+ import { DocumentWASM, PlatformVersionWASM } from 'pshenmic-dpp';
5
+ import { DPNS_DATA_CONTRACT_ID, LATEST_PLATFORM_VERSION, MIN_PROTOCOL_VERSION } from '../../src/constants.js';
3
6
  let sdk;
4
7
  const identifier = 'QMfCRPcjXoTnZa9sA9JR2KWgGxZXMRJ4akgS3Uia1Qv';
5
8
  // takes quorum public keys from DAPI validator sets, so proofs can be verified without Platform Explorer
@@ -49,6 +52,41 @@ describe('DashPlatformSDK', () => {
49
52
  customSdk.setQuorumKeyProvider();
50
53
  expect(customSdk.quorumKeyProvider).toEqual(expect.any(PlatformExplorerQuorumKeyProvider));
51
54
  });
55
+ test('should learn protocol version of the network from verified responses', async () => {
56
+ const customSdk = new DashPlatformSDK({ network: 'testnet' });
57
+ expect(customSdk.grpcPool.protocolVersion).toEqual(MIN_PROTOCOL_VERSION.testnet);
58
+ await customSdk.identities.getIdentityBalance(identifier);
59
+ expect(customSdk.grpcPool.protocolVersion).toEqual(LATEST_PLATFORM_VERSION);
60
+ });
61
+ test('should not learn protocol version from unverified responses', async () => {
62
+ const customSdk = new DashPlatformSDK({ network: 'testnet', proofs: false });
63
+ await customSdk.identities.getIdentityBalance(identifier);
64
+ expect(customSdk.grpcPool.protocolVersion).toEqual(MIN_PROTOCOL_VERSION.testnet);
65
+ });
66
+ test('should learn protocol version of the network with proofs disabled', async () => {
67
+ const customSdk = new DashPlatformSDK({ network: 'testnet', proofs: false });
68
+ expect(await customSdk.node.getProtocolVersion()).toEqual(LATEST_PLATFORM_VERSION);
69
+ expect(customSdk.grpcPool.protocolVersion).toEqual(LATEST_PLATFORM_VERSION);
70
+ });
71
+ test('should create documents with id of the protocol version of the network', () => {
72
+ const customSdk = new DashPlatformSDK({ network: 'testnet' });
73
+ const nonce = 5n;
74
+ for (const protocolVersion of [PlatformVersionWASM.PLATFORM_V13, PlatformVersionWASM.PLATFORM_V14]) {
75
+ customSdk.grpcPool.protocolVersion = protocolVersion;
76
+ const document = customSdk.documents.create(DPNS_DATA_CONTRACT_ID, 'preorder', { saltedDomainHash: new Uint8Array(32) }, identifier, nonce);
77
+ const expectedId = DocumentWASM.generateId('preorder', identifier, DPNS_DATA_CONTRACT_ID, document.entropy, nonce, protocolVersion);
78
+ expect(document.id.base58()).toEqual(expectedId.base58());
79
+ }
80
+ });
81
+ test('should select platform version to verify proofs with', () => {
82
+ // newer signed version is used
83
+ expect(getVerifierVersion(13, 14)).toEqual(14);
84
+ // older signed version is not
85
+ expect(getVerifierVersion(14, 13)).toEqual(14);
86
+ expect(getVerifierVersion(13, 0)).toEqual(13);
87
+ // unknown version falls back to the latest known one
88
+ expect(getVerifierVersion(13, LATEST_PLATFORM_VERSION + 1)).toEqual(LATEST_PLATFORM_VERSION);
89
+ });
52
90
  test('should be able to deserialize consensus error', () => {
53
91
  const err = sdk.utils.deserializeConsensusError('AwIiSW52YWxpZCBTdGF0ZSBUcmFuc2l0aW9uIHNpZ25hdHVyZQ');
54
92
  expect(err).toEqual('Invalid State Transition signature');