dash-platform-sdk 1.5.3 → 1.6.0-dev.2

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 (60) hide show
  1. package/README.md +15 -15
  2. package/bundle.min.js +1 -1
  3. package/package.json +3 -4
  4. package/proto/generated/platform.client.d.ts +20 -60
  5. package/proto/generated/platform.client.js +41 -69
  6. package/proto/generated/platform.d.ts +2330 -1650
  7. package/proto/generated/platform.js +4992 -3467
  8. package/src/constants.d.ts +1 -1
  9. package/src/constants.js +1 -1
  10. package/src/documents/create.d.ts +1 -1
  11. package/src/documents/create.js +2 -2
  12. package/src/documents/createStateTransition.d.ts +2 -2
  13. package/src/documents/createStateTransition.js +6 -6
  14. package/src/documents/getActionFeeAgreement.d.ts +4 -0
  15. package/src/documents/getActionFeeAgreement.js +21 -0
  16. package/src/documents/index.d.ts +99 -4
  17. package/src/documents/index.js +117 -3
  18. package/src/documents/query.js +13 -52
  19. package/src/documents/queryAggregate.d.ts +4 -0
  20. package/src/documents/queryAggregate.js +32 -0
  21. package/src/documents/queryJoined.d.ts +16 -0
  22. package/src/documents/queryJoined.js +44 -0
  23. package/src/documents/queryRanked.d.ts +12 -0
  24. package/src/documents/queryRanked.js +37 -0
  25. package/src/documents/v1.d.ts +33 -0
  26. package/src/documents/v1.js +233 -0
  27. package/src/identities/getIdentityByNonUniquePublicKeyHash.js +6 -10
  28. package/src/names/index.d.ts +4 -1
  29. package/src/names/index.js +5 -2
  30. package/src/names/registerName.d.ts +1 -1
  31. package/src/names/registerName.js +55 -35
  32. package/src/shielded/getMostRecentShieldedAnchor.d.ts +2 -1
  33. package/src/shielded/getMostRecentShieldedAnchor.js +6 -4
  34. package/src/shielded/getShieldedAnchors.d.ts +2 -1
  35. package/src/shielded/getShieldedAnchors.js +6 -4
  36. package/src/shielded/getShieldedEncryptedNotes.d.ts +2 -1
  37. package/src/shielded/getShieldedEncryptedNotes.js +6 -4
  38. package/src/shielded/getShieldedNotesCount.d.ts +2 -1
  39. package/src/shielded/getShieldedNotesCount.js +6 -4
  40. package/src/shielded/getShieldedNullifiers.d.ts +2 -1
  41. package/src/shielded/getShieldedNullifiers.js +6 -4
  42. package/src/shielded/getShieldedPoolState.d.ts +2 -1
  43. package/src/shielded/getShieldedPoolState.js +6 -4
  44. package/src/shielded/index.d.ts +17 -7
  45. package/src/shielded/index.js +22 -12
  46. package/src/stateTransitions/index.d.ts +6 -2
  47. package/src/stateTransitions/index.js +5 -1
  48. package/src/stateTransitions/waitForStateTransitionResult.d.ts +1 -1
  49. package/src/stateTransitions/waitForStateTransitionResult.js +4 -2
  50. package/test/unit/DataContract.spec.js +2 -1
  51. package/test/unit/Document.spec.js +9 -9
  52. package/test/unit/DocumentActionFees.spec.d.ts +1 -0
  53. package/test/unit/DocumentActionFees.spec.js +99 -0
  54. package/test/unit/DocumentQueries.spec.d.ts +1 -0
  55. package/test/unit/DocumentQueries.spec.js +178 -0
  56. package/test/unit/DocumentsV1.spec.d.ts +1 -0
  57. package/test/unit/DocumentsV1.spec.js +75 -0
  58. package/test/unit/Names.spec.js +30 -0
  59. package/test/unit/Node.spec.js +11 -8
  60. package/types.d.ts +20 -1
@@ -0,0 +1,33 @@
1
+ import { GetDocumentsRequest_DocumentFieldValue, GetDocumentsRequest_GetDocumentsRequestV1, GetDocumentsRequest_GetDocumentsRequestV1_SubQuery, GetDocumentsRequest_HavingClause, GetDocumentsRequest_OrderClause, GetDocumentsRequest_WhereClause, Proof, ResponseMetadata } from '../../proto/generated/platform.js';
2
+ import { AggregateSelect, CompositeSubQuery, HavingClause, IdentifierLike, IdentifierWASM, WhereClause } from 'pshenmic-dpp';
3
+ import { GRPCPool } from '../grpcConnectionPool.js';
4
+ type DocumentFieldValue = GetDocumentsRequest_DocumentFieldValue;
5
+ /**
6
+ * Converts a JS value of a where / having clause into a typed v1 document field value
7
+ */
8
+ export declare function toFieldValue(value: unknown): DocumentFieldValue;
9
+ /**
10
+ * Converts `[field, operator, value]` where clauses into typed v1 where clauses
11
+ */
12
+ export declare function toWhereClauses(where?: WhereClause[] | null): GetDocumentsRequest_WhereClause[];
13
+ /**
14
+ * Converts `[field, 'asc' | 'desc']` order by clauses into typed v1 order clauses.
15
+ * For ranked queries the selected aggregate is ordered by its field, or by `$count` for `count`
16
+ */
17
+ export declare function toOrderClauses(orderBy?: string[][] | null): GetDocumentsRequest_OrderClause[];
18
+ export declare function toSelect(select: AggregateSelect): GetDocumentsRequest_GetDocumentsRequestV1['selects'];
19
+ export declare function toHavingClauses(having: HavingClause[]): GetDocumentsRequest_HavingClause[];
20
+ export declare function toSubQueries(subQueries: CompositeSubQuery[], dataContractId: IdentifierWASM): GetDocumentsRequest_GetDocumentsRequestV1_SubQuery[];
21
+ export declare function toStart(startAt?: IdentifierLike | null, startAtIncluded?: boolean): GetDocumentsRequest_GetDocumentsRequestV1['start'];
22
+ /**
23
+ * Sends a v1 getDocuments request with a proof and returns the proof with the response metadata
24
+ */
25
+ export declare function getDocumentsV1Proof(grpcPool: GRPCPool, v1: Partial<GetDocumentsRequest_GetDocumentsRequestV1>): Promise<{
26
+ proof: Proof;
27
+ metadata: ResponseMetadata;
28
+ }>;
29
+ /**
30
+ * Verifies the quorum signature of a proof whose GroveDB part produced the given root hash
31
+ */
32
+ export declare function verifyDocumentsV1Signature(grpcPool: GRPCPool, proof: Proof, metadata: ResponseMetadata, rootHash: Uint8Array): Promise<void>;
33
+ export {};
@@ -0,0 +1,233 @@
1
+ import { GetDocumentsRequest, GetDocumentsRequest_GetDocumentsRequestV1, GetDocumentsRequest_GetDocumentsRequestV1_Select_Function, GetDocumentsRequest_GetDocumentsRequestV1_SubQuery_Kind, GetDocumentsRequest_HavingAggregate_Function, GetDocumentsRequest_HavingClause_Operator, GetDocumentsRequest_IntegerRangeSelection, GetDocumentsRequest_TimeRangeSelection, GetDocumentsRequest_TimeRangeSelection_Selector, GetDocumentsRequest_WhereClause, GetDocumentsRequest_WhereOperator } from '../../proto/generated/platform.js';
2
+ import { IdentifierWASM } from 'pshenmic-dpp';
3
+ import { getQuorumPublicKey } from '../utils/getQuorumPublicKey.js';
4
+ import bytesToHex from '../utils/bytesToHex.js';
5
+ import verifyTenderdashProof from '../utils/verifyTenderdashProof.js';
6
+ const WHERE_OPERATORS = {
7
+ '=': GetDocumentsRequest_WhereOperator.EQUAL,
8
+ '==': GetDocumentsRequest_WhereOperator.EQUAL,
9
+ '>': GetDocumentsRequest_WhereOperator.GREATER_THAN,
10
+ '>=': GetDocumentsRequest_WhereOperator.GREATER_THAN_OR_EQUALS,
11
+ '<': GetDocumentsRequest_WhereOperator.LESS_THAN,
12
+ '<=': GetDocumentsRequest_WhereOperator.LESS_THAN_OR_EQUALS,
13
+ between: GetDocumentsRequest_WhereOperator.BETWEEN,
14
+ betweenexcludebounds: GetDocumentsRequest_WhereOperator.BETWEEN_EXCLUDE_BOUNDS,
15
+ betweenexcludeleft: GetDocumentsRequest_WhereOperator.BETWEEN_EXCLUDE_LEFT,
16
+ betweenexcluderight: GetDocumentsRequest_WhereOperator.BETWEEN_EXCLUDE_RIGHT,
17
+ in: GetDocumentsRequest_WhereOperator.IN,
18
+ startswith: GetDocumentsRequest_WhereOperator.STARTS_WITH,
19
+ contains: GetDocumentsRequest_WhereOperator.CONTAINS,
20
+ containsany: GetDocumentsRequest_WhereOperator.CONTAINS_ANY,
21
+ intimerange: GetDocumentsRequest_WhereOperator.IN_TIME_RANGE,
22
+ inintegerrange: GetDocumentsRequest_WhereOperator.IN_INTEGER_RANGE
23
+ };
24
+ const HAVING_OPERATORS = {
25
+ '=': GetDocumentsRequest_HavingClause_Operator.EQUAL,
26
+ '!=': GetDocumentsRequest_HavingClause_Operator.NOT_EQUAL,
27
+ '>': GetDocumentsRequest_HavingClause_Operator.GREATER_THAN,
28
+ '>=': GetDocumentsRequest_HavingClause_Operator.GREATER_THAN_OR_EQUALS,
29
+ '<': GetDocumentsRequest_HavingClause_Operator.LESS_THAN,
30
+ '<=': GetDocumentsRequest_HavingClause_Operator.LESS_THAN_OR_EQUALS,
31
+ between: GetDocumentsRequest_HavingClause_Operator.BETWEEN,
32
+ betweenexcludebounds: GetDocumentsRequest_HavingClause_Operator.BETWEEN_EXCLUDE_BOUNDS,
33
+ betweenexcludeleft: GetDocumentsRequest_HavingClause_Operator.BETWEEN_EXCLUDE_LEFT,
34
+ betweenexcluderight: GetDocumentsRequest_HavingClause_Operator.BETWEEN_EXCLUDE_RIGHT,
35
+ in: GetDocumentsRequest_HavingClause_Operator.IN
36
+ };
37
+ const SELECT_FUNCTIONS = {
38
+ count: GetDocumentsRequest_GetDocumentsRequestV1_Select_Function.COUNT,
39
+ sum: GetDocumentsRequest_GetDocumentsRequestV1_Select_Function.SUM,
40
+ avg: GetDocumentsRequest_GetDocumentsRequestV1_Select_Function.AVG,
41
+ min: GetDocumentsRequest_GetDocumentsRequestV1_Select_Function.MIN,
42
+ max: GetDocumentsRequest_GetDocumentsRequestV1_Select_Function.MAX
43
+ };
44
+ const HAVING_FUNCTIONS = {
45
+ count: GetDocumentsRequest_HavingAggregate_Function.COUNT,
46
+ sum: GetDocumentsRequest_HavingAggregate_Function.SUM,
47
+ avg: GetDocumentsRequest_HavingAggregate_Function.AVG
48
+ };
49
+ function normalizeOperator(operator) {
50
+ return operator.toLowerCase().replace(/_/g, '');
51
+ }
52
+ /**
53
+ * Converts a JS value of a where / having clause into a typed v1 document field value
54
+ */
55
+ export function toFieldValue(value) {
56
+ if (value == null) {
57
+ return { variant: { oneofKind: 'nullValue', nullValue: true } };
58
+ }
59
+ if (typeof value === 'boolean') {
60
+ return { variant: { oneofKind: 'boolValue', boolValue: value } };
61
+ }
62
+ if (typeof value === 'bigint' || (typeof value === 'number' && Number.isInteger(value))) {
63
+ return value < 0
64
+ ? { variant: { oneofKind: 'int64Value', int64Value: value.toString() } }
65
+ : { variant: { oneofKind: 'uint64Value', uint64Value: value.toString() } };
66
+ }
67
+ if (typeof value === 'number') {
68
+ return { variant: { oneofKind: 'doubleValue', doubleValue: value } };
69
+ }
70
+ if (typeof value === 'string') {
71
+ return { variant: { oneofKind: 'text', text: value } };
72
+ }
73
+ if (value instanceof Uint8Array) {
74
+ return { variant: { oneofKind: 'bytesValue', bytesValue: value } };
75
+ }
76
+ if (Array.isArray(value)) {
77
+ return { variant: { oneofKind: 'list', list: { values: value.map(toFieldValue) } } };
78
+ }
79
+ throw new Error(`Unsupported where clause value: ${String(value)}`);
80
+ }
81
+ function toTimeRangeSelection(selection) {
82
+ if (selection === 'newest' || selection === 'oldest') {
83
+ return GetDocumentsRequest_TimeRangeSelection.create({
84
+ selector: selection === 'newest'
85
+ ? GetDocumentsRequest_TimeRangeSelection_Selector.NEWEST
86
+ : GetDocumentsRequest_TimeRangeSelection_Selector.OLDEST
87
+ });
88
+ }
89
+ if (typeof selection === 'bigint') {
90
+ return GetDocumentsRequest_TimeRangeSelection.create({
91
+ selector: GetDocumentsRequest_TimeRangeSelection_Selector.BY_START,
92
+ startMs: selection.toString()
93
+ });
94
+ }
95
+ const selectors = {
96
+ newest: GetDocumentsRequest_TimeRangeSelection_Selector.NEWEST,
97
+ oldest: GetDocumentsRequest_TimeRangeSelection_Selector.OLDEST,
98
+ byStart: GetDocumentsRequest_TimeRangeSelection_Selector.BY_START
99
+ };
100
+ return GetDocumentsRequest_TimeRangeSelection.create({
101
+ selector: selectors[selection.selector ?? 'byStart'],
102
+ startMs: selection.startMs?.toString(),
103
+ grid: selection.grid != null
104
+ ? {
105
+ range: selection.grid.rangeSeconds.toString(),
106
+ step: selection.grid.stepSeconds.toString(),
107
+ phase: (selection.grid.phaseSeconds ?? 0).toString()
108
+ }
109
+ : undefined
110
+ });
111
+ }
112
+ function toIntegerRangeSelection(selection) {
113
+ if (typeof selection === 'bigint' || typeof selection === 'number') {
114
+ return GetDocumentsRequest_IntegerRangeSelection.create({ start: toFieldValue(selection) });
115
+ }
116
+ return GetDocumentsRequest_IntegerRangeSelection.create({
117
+ start: toFieldValue(selection.start),
118
+ grid: selection.grid != null
119
+ ? {
120
+ range: selection.grid.range.toString(),
121
+ step: selection.grid.step.toString(),
122
+ phase: (selection.grid.phase ?? 0).toString()
123
+ }
124
+ : undefined
125
+ });
126
+ }
127
+ /**
128
+ * Converts `[field, operator, value]` where clauses into typed v1 where clauses
129
+ */
130
+ export function toWhereClauses(where) {
131
+ return (where ?? []).map(([field, operator, value]) => {
132
+ const op = WHERE_OPERATORS[normalizeOperator(operator)];
133
+ if (op == null) {
134
+ throw new Error(`Unsupported where clause operator: ${operator}`);
135
+ }
136
+ if (op === GetDocumentsRequest_WhereOperator.IN_TIME_RANGE) {
137
+ return GetDocumentsRequest_WhereClause.create({ field, operator: op, timeRange: toTimeRangeSelection(value) });
138
+ }
139
+ if (op === GetDocumentsRequest_WhereOperator.IN_INTEGER_RANGE) {
140
+ return GetDocumentsRequest_WhereClause.create({ field, operator: op, integerRange: toIntegerRangeSelection(value) });
141
+ }
142
+ return GetDocumentsRequest_WhereClause.create({ field, operator: op, value: toFieldValue(value) });
143
+ });
144
+ }
145
+ /**
146
+ * Converts `[field, 'asc' | 'desc']` order by clauses into typed v1 order clauses.
147
+ * For ranked queries the selected aggregate is ordered by its field, or by `$count` for `count`
148
+ */
149
+ export function toOrderClauses(orderBy) {
150
+ return (orderBy ?? []).map(([field, direction]) => ({
151
+ target: { oneofKind: 'field', field },
152
+ ascending: direction?.toLowerCase() !== 'desc'
153
+ }));
154
+ }
155
+ export function toSelect(select) {
156
+ return [{ function: SELECT_FUNCTIONS[select.function], field: select.field ?? '' }];
157
+ }
158
+ export function toHavingClauses(having) {
159
+ return having.map(clause => {
160
+ const operator = HAVING_OPERATORS[normalizeOperator(clause.operator)];
161
+ if (operator == null) {
162
+ throw new Error(`Unsupported having clause operator: ${clause.operator}`);
163
+ }
164
+ return {
165
+ aggregate: { function: HAVING_FUNCTIONS[clause.function], field: clause.field ?? '' },
166
+ operator,
167
+ right: { oneofKind: 'value', value: toFieldValue(clause.value) }
168
+ };
169
+ });
170
+ }
171
+ export function toSubQueries(subQueries, dataContractId) {
172
+ return subQueries.map(subQuery => ({
173
+ dataContractId: (subQuery.dataContract?.id ?? dataContractId).bytes(),
174
+ documentType: subQuery.documentTypeName,
175
+ whereClauses: toWhereClauses(subQuery.where),
176
+ orderBy: toOrderClauses(subQuery.orderBy),
177
+ limit: subQuery.limit,
178
+ kind: subQuery.kind === 'count'
179
+ ? GetDocumentsRequest_GetDocumentsRequestV1_SubQuery_Kind.COUNT
180
+ : GetDocumentsRequest_GetDocumentsRequestV1_SubQuery_Kind.DOCUMENTS,
181
+ // on the wire `0` is the page and `n` is `subQueries[n - 1]`
182
+ bind: subQuery.binding != null
183
+ ? {
184
+ source: subQuery.binding.source === 'page' ? 0 : subQuery.binding.source + 1,
185
+ sourceProperty: subQuery.binding.sourceProperty,
186
+ field: subQuery.binding.field
187
+ }
188
+ : undefined
189
+ }));
190
+ }
191
+ export function toStart(startAt, startAtIncluded) {
192
+ if (startAt == null) {
193
+ return { oneofKind: undefined };
194
+ }
195
+ const bytes = new IdentifierWASM(startAt).bytes();
196
+ return startAtIncluded === false
197
+ ? { oneofKind: 'startAfter', startAfter: bytes }
198
+ : { oneofKind: 'startAt', startAt: bytes };
199
+ }
200
+ /**
201
+ * Sends a v1 getDocuments request with a proof and returns the proof with the response metadata
202
+ */
203
+ export async function getDocumentsV1Proof(grpcPool, v1) {
204
+ const getDocumentsRequest = GetDocumentsRequest.create({
205
+ version: {
206
+ oneofKind: 'v1',
207
+ v1: GetDocumentsRequest_GetDocumentsRequestV1.create({ ...v1, prove: true })
208
+ }
209
+ });
210
+ const { response } = await (await grpcPool.getClient()).getDocuments(getDocumentsRequest);
211
+ const { version } = response;
212
+ if (version.oneofKind !== 'v1') {
213
+ throw new Error('Unexpected oneOf type returned from DAPI (must be v1)');
214
+ }
215
+ const { v1: { result, metadata } } = version;
216
+ if (result.oneofKind !== 'proof') {
217
+ throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
218
+ }
219
+ if (metadata == null) {
220
+ throw new Error('Metadata not found');
221
+ }
222
+ return { proof: result.proof, metadata };
223
+ }
224
+ /**
225
+ * Verifies the quorum signature of a proof whose GroveDB part produced the given root hash
226
+ */
227
+ export async function verifyDocumentsV1Signature(grpcPool, proof, metadata, rootHash) {
228
+ const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
229
+ const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
230
+ if (!verify) {
231
+ throw new Error('Failed to verify query');
232
+ }
233
+ }
@@ -1,10 +1,9 @@
1
1
  import { GetIdentityByNonUniquePublicKeyHashRequest } from '../../proto/generated/platform.js';
2
- import { verifyIdentifierByNonUniquePublicKeyHashProof } from 'pshenmic-dpp';
2
+ import { verifyFullIdentityByNonUniquePublicKeyHashProof } from 'pshenmic-dpp';
3
3
  import hexToBytes from '../utils/hexToBytes.js';
4
4
  import { getQuorumPublicKey } from '../utils/getQuorumPublicKey.js';
5
5
  import bytesToHex from '../utils/bytesToHex.js';
6
6
  import verifyTenderdashProof from '../utils/verifyTenderdashProof.js';
7
- import getIdentityByIdentifier from './getIdentityByIdentifier.js';
8
7
  import { LATEST_PLATFORM_VERSION } from '../constants.js';
9
8
  export default async function getIdentityByNonUniquePublicKeyHash(grpcPool, hex) {
10
9
  const getIdentityByNonUniquePublicKeyHashRequest = GetIdentityByNonUniquePublicKeyHashRequest.create({
@@ -29,17 +28,14 @@ export default async function getIdentityByNonUniquePublicKeyHash(grpcPool, hex)
29
28
  if (metadata == null) {
30
29
  throw new Error('Metadata not found');
31
30
  }
32
- if (proof.grovedbIdentityPublicKeyHashProof == null) {
33
- throw new Error('GroveDB proof not found for identity by non unique public key request');
34
- }
35
- const { rootHash, identifier } = verifyIdentifierByNonUniquePublicKeyHashProof(proof.grovedbIdentityPublicKeyHashProof.grovedbProof, false, hexToBytes(hex), undefined, LATEST_PLATFORM_VERSION);
36
- if (identifier == null) {
31
+ const { rootHash, identity } = verifyFullIdentityByNonUniquePublicKeyHashProof(proof.grovedbProof, hexToBytes(hex), undefined, metadata.protocolVersion, LATEST_PLATFORM_VERSION);
32
+ if (identity == null) {
37
33
  throw new Error(`Identity with non unique public key hash ${hex} not found`);
38
34
  }
39
- const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.grovedbIdentityPublicKeyHashProof.quorumType, bytesToHex(proof.grovedbIdentityPublicKeyHashProof.quorumHash));
40
- const verify = await verifyTenderdashProof(proof.grovedbIdentityPublicKeyHashProof, metadata, rootHash, quorumPublicKey);
35
+ const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
36
+ const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
41
37
  if (!verify) {
42
38
  throw new Error('Failed to verify query');
43
39
  }
44
- return await getIdentityByIdentifier(grpcPool, identifier);
40
+ return identity;
45
41
  }
@@ -43,8 +43,11 @@ export declare class NamesController {
43
43
  * @param name {string} username (ex. pshenmic.dash)
44
44
  * @param identityId {IdentifierLike} identity identifier
45
45
  * @param privateKey {PrivateKeyWASM} Authentication / High private key from your identity
46
+ * @param preorderSalt {Uint8Array=} Optional 32 bytes salt of already existing preorder document. If provided, preorder step is skipped
47
+ *
48
+ * @return {Promise<Uint8Array>} preorder salt (also attached as `preorderSalt` to the error if domain broadcast fails)
46
49
  */
47
- registerName(name: string, identityId: IdentifierLike, privateKey: PrivateKeyWASM): Promise<void>;
50
+ registerName(name: string, identityId: IdentifierLike, privateKey: PrivateKeyWASM, preorderSalt?: Uint8Array): Promise<Uint8Array>;
48
51
  /**
49
52
  * Converts DPNS name to normalized format (ex. alice.dash -> al1ce.dash)
50
53
  *
@@ -67,14 +67,17 @@ export class NamesController {
67
67
  * @param name {string} username (ex. pshenmic.dash)
68
68
  * @param identityId {IdentifierLike} identity identifier
69
69
  * @param privateKey {PrivateKeyWASM} Authentication / High private key from your identity
70
+ * @param preorderSalt {Uint8Array=} Optional 32 bytes salt of already existing preorder document. If provided, preorder step is skipped
71
+ *
72
+ * @return {Promise<Uint8Array>} preorder salt (also attached as `preorderSalt` to the error if domain broadcast fails)
70
73
  */
71
- async registerName(name, identityId, privateKey) {
74
+ async registerName(name, identityId, privateKey, preorderSalt) {
72
75
  const validation = validateName(name);
73
76
  if (validation != null) {
74
77
  throw new Error(validation);
75
78
  }
76
79
  const identity = await getIdentityByIdentifier(this.grpcPool, identityId);
77
- await registerName(this.grpcPool, name, identity, privateKey);
80
+ return await registerName(this.grpcPool, name, identity, privateKey, preorderSalt);
78
81
  }
79
82
  /**
80
83
  * Converts DPNS name to normalized format (ex. alice.dash -> al1ce.dash)
@@ -1,3 +1,3 @@
1
1
  import { IdentityWASM, PrivateKeyWASM } from 'pshenmic-dpp';
2
2
  import { GRPCPool } from '../grpcConnectionPool.js';
3
- export default function registerName(grpcPool: GRPCPool, name: string, identity: IdentityWASM, privateKey: PrivateKeyWASM): Promise<void>;
3
+ export default function registerName(grpcPool: GRPCPool, name: string, identity: IdentityWASM, privateKey: PrivateKeyWASM, preorderSalt?: Uint8Array): Promise<Uint8Array>;
@@ -9,7 +9,7 @@ import broadcast from '../stateTransitions/broadcast.js';
9
9
  import waitForStateTransitionResult from '../stateTransitions/waitForStateTransitionResult.js';
10
10
  import testNameContested from './testNameContested.js';
11
11
  import { DPNS_DATA_CONTRACT_ID } from '../constants.js';
12
- export default async function registerName(grpcPool, name, identity, privateKey) {
12
+ export default async function registerName(grpcPool, name, identity, privateKey, preorderSalt) {
13
13
  const [identityPublicKey] = identity.getPublicKeys().filter(identityPublicKey => identityPublicKey.getPublicKeyHash() === privateKey.getPublicKeyHash());
14
14
  if (identityPublicKey == null) {
15
15
  throw new Error('Private key does not match the identity');
@@ -17,8 +17,11 @@ export default async function registerName(grpcPool, name, identity, privateKey)
17
17
  if (identityPublicKey.securityLevel !== 'HIGH' && identityPublicKey.purpose !== 'AUTHENTICATION') {
18
18
  throw new Error('Wrong private key, must be from AUTHENTICATION HIGH identity public key');
19
19
  }
20
+ if (preorderSalt != null && preorderSalt.length !== 32) {
21
+ throw new Error('Preorder salt must be 32 bytes length');
22
+ }
20
23
  const [label, parentDomainName] = name.split('.');
21
- const salt = getRandomBytes(32);
24
+ const salt = preorderSalt ?? getRandomBytes(32);
22
25
  const normalizedParentDomainName = convertToHomographSafeChars(parentDomainName);
23
26
  const normalizedLabel = convertToHomographSafeChars(label);
24
27
  const normalizedFullDomainName = `${normalizedLabel}.${normalizedParentDomainName}`;
@@ -26,39 +29,56 @@ export default async function registerName(grpcPool, name, identity, privateKey)
26
29
  ...salt,
27
30
  ...new TextEncoder().encode(normalizedFullDomainName)
28
31
  ])));
29
- let document;
30
- let stateTransition;
31
- // 1. Create preorder document
32
- const preorderData = {
33
- saltedDomainHash: Array.from(saltedDomainHash)
34
- };
35
32
  const identityContractNonce = await getIdentityContractNonce(grpcPool, identity.id, DPNS_DATA_CONTRACT_ID);
36
- document = createDocument(DPNS_DATA_CONTRACT_ID, 'preorder', preorderData, identity.id.base58());
37
- stateTransition = createStateTransition(document, 'create', { identityContractNonce: identityContractNonce + BigInt(1) });
38
- await stateTransition.sign(privateKey, identityPublicKey);
39
- await broadcast(grpcPool, stateTransition);
40
- // wait for state transition confirmation before next broadcast
41
- await waitForStateTransitionResult(grpcPool, stateTransition);
42
- // 2. Create domain document
43
- const domainData = {
44
- label,
45
- normalizedLabel,
46
- parentDomainName,
47
- normalizedParentDomainName,
48
- preorderSalt: Array.from(salt),
49
- records: {
50
- identity: Array.from(identity.id.bytes())
51
- },
52
- subdomainRules: {
53
- allowSubdomains: false
33
+ // skip preorder if salt of existing preorder is provided
34
+ const domainNonce = identityContractNonce + BigInt(preorderSalt == null ? 2 : 1);
35
+ // salt is exposed in the error only once preorder exists (passed in or its broadcast accepted),
36
+ // so registration can be retried with it without creating (and paying for) a new preorder
37
+ let preorderSent = preorderSalt != null;
38
+ try {
39
+ // 1. Create preorder document
40
+ if (preorderSalt == null) {
41
+ const preorderData = {
42
+ saltedDomainHash
43
+ };
44
+ const preorderDocument = createDocument(DPNS_DATA_CONTRACT_ID, 'preorder', preorderData, identity.id.base58(), identityContractNonce + BigInt(1));
45
+ const preorderStateTransition = createStateTransition(preorderDocument, 'create', { identityContractNonce: identityContractNonce + BigInt(1) });
46
+ await preorderStateTransition.sign(privateKey, identityPublicKey);
47
+ await broadcast(grpcPool, preorderStateTransition);
48
+ preorderSent = true;
49
+ // wait for state transition confirmation before next broadcast
50
+ await waitForStateTransitionResult(grpcPool, preorderStateTransition);
51
+ }
52
+ // 2. Create domain document
53
+ const domainData = {
54
+ label,
55
+ normalizedLabel,
56
+ parentDomainName,
57
+ normalizedParentDomainName,
58
+ preorderSalt: salt,
59
+ records: {
60
+ identity: identity.id.bytes()
61
+ },
62
+ subdomainRules: {
63
+ allowSubdomains: false
64
+ }
65
+ };
66
+ const domainDocument = createDocument(DPNS_DATA_CONTRACT_ID, 'domain', domainData, identity.id.base58(), domainNonce);
67
+ const domainStateTransition = createStateTransition(domainDocument, 'create', {
68
+ identityContractNonce: domainNonce,
69
+ // @ts-expect-error
70
+ prefundedVotingBalance: testNameContested(normalizedLabel) ? new PrefundedVotingBalanceWASM('parentNameAndLabel', BigInt(20000000000)) : undefined
71
+ });
72
+ await domainStateTransition.sign(privateKey, identityPublicKey);
73
+ await broadcast(grpcPool, domainStateTransition);
74
+ // wait for the domain too, so the next transition reads a nonce past it
75
+ await waitForStateTransitionResult(grpcPool, domainStateTransition);
76
+ }
77
+ catch (e) {
78
+ if (preorderSent && e instanceof Error) {
79
+ Object.assign(e, { preorderSalt: salt });
54
80
  }
55
- };
56
- document = createDocument(DPNS_DATA_CONTRACT_ID, 'domain', domainData, identity.id.base58());
57
- stateTransition = createStateTransition(document, 'create', {
58
- identityContractNonce: identityContractNonce + BigInt(2),
59
- // @ts-expect-error
60
- prefundedVotingBalance: testNameContested(normalizedLabel) ? new PrefundedVotingBalanceWASM('parentNameAndLabel', BigInt(20000000000)) : undefined
61
- });
62
- await stateTransition.sign(privateKey, identityPublicKey);
63
- await broadcast(grpcPool, stateTransition);
81
+ throw e;
82
+ }
83
+ return salt;
64
84
  }
@@ -1,2 +1,3 @@
1
1
  import { GRPCPool } from '../grpcConnectionPool.js';
2
- export default function getMostRecentShieldedAnchor(grpcPool: GRPCPool): Promise<Uint8Array | undefined>;
2
+ import { IdentifierLike } from 'pshenmic-dpp';
3
+ export default function getMostRecentShieldedAnchor(grpcPool: GRPCPool, tokenIdentifier?: IdentifierLike): Promise<Uint8Array | undefined>;
@@ -1,15 +1,17 @@
1
1
  import { GetMostRecentShieldedAnchorRequest } from '../../proto/generated/platform.js';
2
- import { verifyMostRecentShieldedAnchorProof } from "pshenmic-dpp";
2
+ import { IdentifierWASM, verifyMostRecentShieldedAnchorProof } from 'pshenmic-dpp';
3
3
  import { LATEST_PLATFORM_VERSION } from "../constants.js";
4
4
  import { getQuorumPublicKey } from "../utils/getQuorumPublicKey.js";
5
5
  import bytesToHex from "../utils/bytesToHex.js";
6
6
  import verifyTenderdashProof from "../utils/verifyTenderdashProof.js";
7
- export default async function getMostRecentShieldedAnchor(grpcPool) {
7
+ export default async function getMostRecentShieldedAnchor(grpcPool, tokenIdentifier) {
8
+ const tokenId = tokenIdentifier != null ? new IdentifierWASM(tokenIdentifier) : undefined;
8
9
  const getMostRecentShieldedAnchorRequest = GetMostRecentShieldedAnchorRequest.create({
9
10
  version: {
10
11
  oneofKind: 'v0',
11
12
  v0: {
12
- prove: true
13
+ prove: true,
14
+ tokenId: tokenId?.bytes()
13
15
  }
14
16
  }
15
17
  });
@@ -26,7 +28,7 @@ export default async function getMostRecentShieldedAnchor(grpcPool) {
26
28
  if (metadata == null) {
27
29
  throw new Error('Metadata not found');
28
30
  }
29
- const { rootHash, anchor } = verifyMostRecentShieldedAnchorProof(proof.grovedbProof, true, LATEST_PLATFORM_VERSION);
31
+ const { rootHash, anchor } = verifyMostRecentShieldedAnchorProof(proof.grovedbProof, true, LATEST_PLATFORM_VERSION, tokenId);
30
32
  const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
31
33
  const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
32
34
  if (!verify) {
@@ -1,2 +1,3 @@
1
1
  import { GRPCPool } from '../grpcConnectionPool.js';
2
- export default function getShieldedAnchors(grpcPool: GRPCPool): Promise<Uint8Array[]>;
2
+ import { IdentifierLike } from 'pshenmic-dpp';
3
+ export default function getShieldedAnchors(grpcPool: GRPCPool, tokenIdentifier?: IdentifierLike): Promise<Uint8Array[]>;
@@ -1,15 +1,17 @@
1
1
  import { GetShieldedAnchorsRequest } from '../../proto/generated/platform.js';
2
- import { verifyShieldedAnchorsProof } from "pshenmic-dpp";
2
+ import { IdentifierWASM, verifyShieldedAnchorsProof } from 'pshenmic-dpp';
3
3
  import { LATEST_PLATFORM_VERSION } from "../constants.js";
4
4
  import { getQuorumPublicKey } from "../utils/getQuorumPublicKey.js";
5
5
  import bytesToHex from "../utils/bytesToHex.js";
6
6
  import verifyTenderdashProof from "../utils/verifyTenderdashProof.js";
7
- export default async function getShieldedAnchors(grpcPool) {
7
+ export default async function getShieldedAnchors(grpcPool, tokenIdentifier) {
8
+ const tokenId = tokenIdentifier != null ? new IdentifierWASM(tokenIdentifier) : undefined;
8
9
  const getShieldedAnchorsRequest = GetShieldedAnchorsRequest.create({
9
10
  version: {
10
11
  oneofKind: 'v0',
11
12
  v0: {
12
- prove: true
13
+ prove: true,
14
+ tokenId: tokenId?.bytes()
13
15
  }
14
16
  }
15
17
  });
@@ -26,7 +28,7 @@ export default async function getShieldedAnchors(grpcPool) {
26
28
  if (metadata == null) {
27
29
  throw new Error('Metadata not found');
28
30
  }
29
- const { rootHash, anchors } = verifyShieldedAnchorsProof(proof.grovedbProof, true, LATEST_PLATFORM_VERSION);
31
+ const { rootHash, anchors } = verifyShieldedAnchorsProof(proof.grovedbProof, true, LATEST_PLATFORM_VERSION, tokenId);
30
32
  const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
31
33
  const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
32
34
  if (!verify) {
@@ -1,3 +1,4 @@
1
1
  import { GRPCPool } from '../grpcConnectionPool.js';
2
2
  import { ShieldedEncryptedNote } from '../../types.js';
3
- export default function getShieldedEncryptedNotes(grpcPool: GRPCPool, startIndex: bigint, count: number): Promise<ShieldedEncryptedNote[]>;
3
+ import { IdentifierLike } from 'pshenmic-dpp';
4
+ export default function getShieldedEncryptedNotes(grpcPool: GRPCPool, startIndex: bigint, count: number, tokenIdentifier?: IdentifierLike): Promise<ShieldedEncryptedNote[]>;
@@ -1,17 +1,19 @@
1
1
  import { GetShieldedEncryptedNotesRequest } from '../../proto/generated/platform.js';
2
- import { verifyShieldedEncryptedNotesProof } from "pshenmic-dpp";
2
+ import { IdentifierWASM, verifyShieldedEncryptedNotesProof } from 'pshenmic-dpp';
3
3
  import { LATEST_PLATFORM_VERSION, SHIELDED_MAX_NOTES_PER_QUERY } from "../constants.js";
4
4
  import { getQuorumPublicKey } from "../utils/getQuorumPublicKey.js";
5
5
  import bytesToHex from "../utils/bytesToHex.js";
6
6
  import verifyTenderdashProof from "../utils/verifyTenderdashProof.js";
7
- export default async function getShieldedEncryptedNotes(grpcPool, startIndex, count) {
7
+ export default async function getShieldedEncryptedNotes(grpcPool, startIndex, count, tokenIdentifier) {
8
+ const tokenId = tokenIdentifier != null ? new IdentifierWASM(tokenIdentifier) : undefined;
8
9
  const getShieldedEncryptedNotesRequest = GetShieldedEncryptedNotesRequest.create({
9
10
  version: {
10
11
  oneofKind: 'v0',
11
12
  v0: {
12
13
  startIndex: startIndex.toString(),
13
14
  count,
14
- prove: true
15
+ prove: true,
16
+ tokenId: tokenId?.bytes()
15
17
  }
16
18
  }
17
19
  });
@@ -28,7 +30,7 @@ export default async function getShieldedEncryptedNotes(grpcPool, startIndex, co
28
30
  if (metadata == null) {
29
31
  throw new Error('Metadata not found');
30
32
  }
31
- const { rootHash, notes } = verifyShieldedEncryptedNotesProof(proof.grovedbProof, startIndex, count, SHIELDED_MAX_NOTES_PER_QUERY, true, LATEST_PLATFORM_VERSION);
33
+ const { rootHash, notes } = verifyShieldedEncryptedNotesProof(proof.grovedbProof, startIndex, count, SHIELDED_MAX_NOTES_PER_QUERY, true, LATEST_PLATFORM_VERSION, tokenId);
32
34
  const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
33
35
  const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
34
36
  if (!verify) {
@@ -1,2 +1,3 @@
1
1
  import { GRPCPool } from '../grpcConnectionPool.js';
2
- export default function getShieldedNotesCount(grpcPool: GRPCPool): Promise<bigint | undefined>;
2
+ import { IdentifierLike } from 'pshenmic-dpp';
3
+ export default function getShieldedNotesCount(grpcPool: GRPCPool, tokenIdentifier?: IdentifierLike): Promise<bigint | undefined>;
@@ -1,15 +1,17 @@
1
1
  import { GetShieldedNotesCountRequest } from '../../proto/generated/platform.js';
2
- import { verifyShieldedNotesCountProof } from "pshenmic-dpp";
2
+ import { IdentifierWASM, verifyShieldedNotesCountProof } from 'pshenmic-dpp';
3
3
  import { LATEST_PLATFORM_VERSION } from "../constants.js";
4
4
  import { getQuorumPublicKey } from "../utils/getQuorumPublicKey.js";
5
5
  import bytesToHex from "../utils/bytesToHex.js";
6
6
  import verifyTenderdashProof from "../utils/verifyTenderdashProof.js";
7
- export default async function getShieldedNotesCount(grpcPool) {
7
+ export default async function getShieldedNotesCount(grpcPool, tokenIdentifier) {
8
+ const tokenId = tokenIdentifier != null ? new IdentifierWASM(tokenIdentifier) : undefined;
8
9
  const getShieldedNotesCountRequest = GetShieldedNotesCountRequest.create({
9
10
  version: {
10
11
  oneofKind: 'v0',
11
12
  v0: {
12
- prove: true
13
+ prove: true,
14
+ tokenId: tokenId?.bytes()
13
15
  }
14
16
  }
15
17
  });
@@ -26,7 +28,7 @@ export default async function getShieldedNotesCount(grpcPool) {
26
28
  if (metadata == null) {
27
29
  throw new Error('Metadata not found');
28
30
  }
29
- const { rootHash, count } = verifyShieldedNotesCountProof(proof.grovedbProof, true, LATEST_PLATFORM_VERSION);
31
+ const { rootHash, count } = verifyShieldedNotesCountProof(proof.grovedbProof, true, LATEST_PLATFORM_VERSION, tokenId);
30
32
  const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
31
33
  const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
32
34
  if (!verify) {
@@ -1,3 +1,4 @@
1
1
  import { GRPCPool } from '../grpcConnectionPool.js';
2
2
  import { ShieldedNullifierStatus } from '../../types.js';
3
- export default function getShieldedNullifiers(grpcPool: GRPCPool, nullifiers: Uint8Array[]): Promise<ShieldedNullifierStatus[]>;
3
+ import { IdentifierLike } from 'pshenmic-dpp';
4
+ export default function getShieldedNullifiers(grpcPool: GRPCPool, nullifiers: Uint8Array[], tokenIdentifier?: IdentifierLike): Promise<ShieldedNullifierStatus[]>;