@cheqd/sdk-esm 5.3.4-develop.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 (68) hide show
  1. package/build/index.d.ts +140 -0
  2. package/build/index.d.ts.map +1 -0
  3. package/build/index.js +182 -0
  4. package/build/index.js.map +1 -0
  5. package/build/modules/_.d.ts +62 -0
  6. package/build/modules/_.d.ts.map +1 -0
  7. package/build/modules/_.js +75 -0
  8. package/build/modules/_.js.map +1 -0
  9. package/build/modules/did.d.ts +386 -0
  10. package/build/modules/did.d.ts.map +1 -0
  11. package/build/modules/did.js +1013 -0
  12. package/build/modules/did.js.map +1 -0
  13. package/build/modules/feeabstraction.d.ts +409 -0
  14. package/build/modules/feeabstraction.d.ts.map +1 -0
  15. package/build/modules/feeabstraction.js +462 -0
  16. package/build/modules/feeabstraction.js.map +1 -0
  17. package/build/modules/feemarket.d.ts +242 -0
  18. package/build/modules/feemarket.d.ts.map +1 -0
  19. package/build/modules/feemarket.js +296 -0
  20. package/build/modules/feemarket.js.map +1 -0
  21. package/build/modules/resource.d.ts +204 -0
  22. package/build/modules/resource.d.ts.map +1 -0
  23. package/build/modules/resource.js +297 -0
  24. package/build/modules/resource.js.map +1 -0
  25. package/build/package.json +64 -0
  26. package/build/querier.d.ts +62 -0
  27. package/build/querier.d.ts.map +1 -0
  28. package/build/querier.js +86 -0
  29. package/build/querier.js.map +1 -0
  30. package/build/registry.d.ts +18 -0
  31. package/build/registry.d.ts.map +1 -0
  32. package/build/registry.js +23 -0
  33. package/build/registry.js.map +1 -0
  34. package/build/signer.d.ts +190 -0
  35. package/build/signer.d.ts.map +1 -0
  36. package/build/signer.js +547 -0
  37. package/build/signer.js.map +1 -0
  38. package/build/types/index.d.ts +140 -0
  39. package/build/types/index.d.ts.map +1 -0
  40. package/build/types/modules/_.d.ts +62 -0
  41. package/build/types/modules/_.d.ts.map +1 -0
  42. package/build/types/modules/did.d.ts +386 -0
  43. package/build/types/modules/did.d.ts.map +1 -0
  44. package/build/types/modules/feeabstraction.d.ts +409 -0
  45. package/build/types/modules/feeabstraction.d.ts.map +1 -0
  46. package/build/types/modules/feemarket.d.ts +242 -0
  47. package/build/types/modules/feemarket.d.ts.map +1 -0
  48. package/build/types/modules/resource.d.ts +204 -0
  49. package/build/types/modules/resource.d.ts.map +1 -0
  50. package/build/types/querier.d.ts +62 -0
  51. package/build/types/querier.d.ts.map +1 -0
  52. package/build/types/registry.d.ts +18 -0
  53. package/build/types/registry.d.ts.map +1 -0
  54. package/build/types/signer.d.ts +190 -0
  55. package/build/types/signer.d.ts.map +1 -0
  56. package/build/types/types.d.ts +196 -0
  57. package/build/types/types.d.ts.map +1 -0
  58. package/build/types/utils.d.ts +223 -0
  59. package/build/types/utils.d.ts.map +1 -0
  60. package/build/types.d.ts +196 -0
  61. package/build/types.d.ts.map +1 -0
  62. package/build/types.js +43 -0
  63. package/build/types.js.map +1 -0
  64. package/build/utils.d.ts +223 -0
  65. package/build/utils.d.ts.map +1 -0
  66. package/build/utils.js +541 -0
  67. package/build/utils.js.map +1 -0
  68. package/package.json +64 -0
@@ -0,0 +1,547 @@
1
+ import { isOfflineDirectSigner, encodePubkey, makeSignDoc, } from '@cosmjs/proto-signing';
2
+ import { SigningStargateClient, calculateFee, createProtobufRpcClient, TimeoutError, } from '@cosmjs/stargate';
3
+ import { connectComet } from '@cosmjs/tendermint-rpc';
4
+ import { createDefaultCheqdRegistry } from './registry.js';
5
+ import { MsgCreateDidDocPayload, MsgUpdateDidDocPayload, MsgDeactivateDidDocPayload, } from '@cheqd/ts-proto/cheqd/did/v2/index.js';
6
+ import { VerificationMethods } from './types.js';
7
+ import { base64ToBytes, EdDSASigner, hexToBytes, ES256Signer, ES256KSigner } from 'did-jwt';
8
+ import { assert, assertDefined, sleep } from '@cosmjs/utils';
9
+ import { encodeSecp256k1Pubkey } from '@cosmjs/amino';
10
+ import { Int53, Uint53 } from '@cosmjs/math';
11
+ import { fromBase64 } from '@cosmjs/encoding';
12
+ import { AuthInfo, Fee, Tx, TxBody, TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx.js';
13
+ import { SignMode } from 'cosmjs-types/cosmos/tx/signing/v1beta1/signing.js';
14
+ import { ServiceClientImpl, SimulateRequest, } from 'cosmjs-types/cosmos/tx/v1beta1/service.js';
15
+ import { CheqdQuerier } from './querier.js';
16
+ /**
17
+ * Calculates the transaction fee for DID operations using gas limit and gas price.
18
+ *
19
+ * @param gasLimit - Maximum amount of gas units that can be consumed by the transaction
20
+ * @param gasPrice - Price per gas unit, either as a string or GasPrice object
21
+ * @returns DidStdFee object containing the calculated fee structure
22
+ */
23
+ export function calculateDidFee(gasLimit, gasPrice) {
24
+ return calculateFee(gasLimit, gasPrice);
25
+ }
26
+ /**
27
+ * Creates SignerInfo objects for transaction authentication from signer data.
28
+ * Each signer info contains the public key, sequence number, and signing mode.
29
+ *
30
+ * @param signers - Array of signer objects containing public keys and sequence numbers
31
+ * @param signMode - Signing mode to use (e.g., SIGN_MODE_DIRECT)
32
+ * @returns Array of SignerInfo objects for transaction authentication
33
+ */
34
+ export function makeSignerInfos(signers, signMode) {
35
+ return signers.map(({ pubkey, sequence }) => ({
36
+ publicKey: pubkey,
37
+ modeInfo: {
38
+ single: { mode: signMode },
39
+ },
40
+ sequence: BigInt(sequence),
41
+ }));
42
+ }
43
+ /**
44
+ * Creates encoded AuthInfo bytes for DID transactions with fee payer support.
45
+ * The AuthInfo contains signer information, fee details, and gas limit.
46
+ *
47
+ * @param signers - Array of signer objects with public keys and sequence numbers
48
+ * @param feeAmount - Array of coins representing the transaction fee
49
+ * @param gasLimit - Maximum gas units that can be consumed
50
+ * @param feePayer - Address of the account paying the transaction fees
51
+ * @param signMode - Signing mode to use, defaults to SIGN_MODE_DIRECT
52
+ * @returns Encoded AuthInfo as Uint8Array for transaction construction
53
+ */
54
+ export function makeDidAuthInfoBytes(signers, feeAmount, gasLimit, feePayer, signMode = SignMode.SIGN_MODE_DIRECT) {
55
+ const authInfo = {
56
+ signerInfos: makeSignerInfos(signers, signMode),
57
+ fee: {
58
+ amount: [...feeAmount],
59
+ gasLimit: gasLimit,
60
+ payer: feePayer,
61
+ },
62
+ };
63
+ return AuthInfo.encode(AuthInfo.fromPartial(authInfo)).finish();
64
+ }
65
+ /**
66
+ * Extended SigningStargateClient specifically designed for Cheqd blockchain operations.
67
+ * Provides enhanced transaction signing, broadcasting, and DID-specific functionality
68
+ * with support for custom fee payers and advanced retry mechanisms.
69
+ */
70
+ export class CheqdSigningStargateClient extends SigningStargateClient {
71
+ /** Map of DID signing algorithms for different verification method types */
72
+ didSigners = {};
73
+ /** Gas price configuration for transaction fee calculation */
74
+ _gasPrice;
75
+ /** Offline signer instance for transaction signing */
76
+ _signer;
77
+ /** RPC endpoint URL for blockchain communication */
78
+ endpoint;
79
+ /** Maximum gas limit allowed for transactions */
80
+ static maxGasLimit = Number.MAX_SAFE_INTEGER;
81
+ /**
82
+ * Creates a new CheqdSigningStargateClient by establishing a connection to the specified endpoint.
83
+ * This is the primary factory method for creating a signing client instance.
84
+ *
85
+ * @param endpoint - RPC endpoint URL or HttpEndpoint object to connect to
86
+ * @param signer - Offline signer for transaction signing
87
+ * @param options - Additional client configuration options including registry and gas price
88
+ * @returns Promise resolving to a connected CheqdSigningStargateClient instance
89
+ */
90
+ static async connectWithSigner(endpoint, signer, options) {
91
+ const cometClient = await connectComet(endpoint);
92
+ return new CheqdSigningStargateClient(cometClient, signer, {
93
+ registry: options?.registry ? options.registry : createDefaultCheqdRegistry(),
94
+ endpoint: options?.endpoint
95
+ ? typeof options.endpoint === 'string'
96
+ ? options.endpoint
97
+ : options.endpoint.url
98
+ : undefined,
99
+ ...options,
100
+ });
101
+ }
102
+ /**
103
+ * Constructs a new CheqdSigningStargateClient instance with the provided Comet client and signer.
104
+ *
105
+ * @param cometClient - Comet client for blockchain communication
106
+ * @param signer - Offline signer for transaction signing
107
+ * @param options - Additional configuration options including registry, gas price, and endpoint
108
+ */
109
+ constructor(cometClient, signer, options = {}) {
110
+ super(cometClient, signer, options);
111
+ this._signer = signer;
112
+ this._gasPrice = options.gasPrice;
113
+ this.endpoint = options.endpoint;
114
+ }
115
+ /**
116
+ * Signs and broadcasts a transaction to the blockchain network.
117
+ * Supports automatic fee calculation and custom fee payer functionality.
118
+ *
119
+ * @param signerAddress - Address of the account signing the transaction
120
+ * @param messages - Array of messages to include in the transaction
121
+ * @param fee - Fee configuration: 'auto' for automatic calculation, number for multiplier, or DidStdFee object
122
+ * @param memo - Optional transaction memo string
123
+ * @returns Promise resolving to DeliverTxResponse with transaction results
124
+ * @throws Error if gas price is not set when using automatic fee calculation
125
+ */
126
+ async signAndBroadcast(signerAddress, messages, fee, memo = '') {
127
+ let usedFee;
128
+ if (fee == 'auto' || typeof fee === 'number') {
129
+ assertDefined(this._gasPrice, 'Gas price must be set in the client options when auto gas is used.');
130
+ const gasEstimation = await this.simulate(signerAddress, messages, memo);
131
+ const multiplier = typeof fee === 'number' ? fee : 1.3;
132
+ usedFee = calculateDidFee(Math.round(gasEstimation * multiplier), this._gasPrice);
133
+ usedFee.payer = signerAddress;
134
+ }
135
+ else {
136
+ usedFee = fee;
137
+ assertDefined(usedFee.payer, 'Payer address must be set when fee is not auto.');
138
+ signerAddress = usedFee.payer;
139
+ }
140
+ const txRaw = await this.sign(signerAddress, messages, usedFee, memo);
141
+ const txBytes = TxRaw.encode(txRaw).finish();
142
+ return this.broadcastTx(txBytes, this.broadcastTimeoutMs, this.broadcastPollIntervalMs);
143
+ }
144
+ /**
145
+ * Signs a transaction without broadcasting it to the network.
146
+ * Creates a signed transaction that can be broadcast later.
147
+ *
148
+ * @param signerAddress - Address of the account signing the transaction
149
+ * @param messages - Array of messages to include in the transaction
150
+ * @param fee - Fee configuration for the transaction
151
+ * @param memo - Transaction memo string
152
+ * @param explicitSignerData - Optional explicit signer data to avoid querying the chain
153
+ * @returns Promise resolving to TxRaw containing the signed transaction
154
+ */
155
+ async sign(signerAddress, messages, fee, memo, explicitSignerData) {
156
+ let signerData;
157
+ if (explicitSignerData) {
158
+ signerData = explicitSignerData;
159
+ }
160
+ else {
161
+ const { accountNumber, sequence } = await this.getSequence(signerAddress);
162
+ const chainId = await this.getChainId();
163
+ signerData = {
164
+ accountNumber: accountNumber,
165
+ sequence: sequence,
166
+ chainId: chainId,
167
+ };
168
+ }
169
+ return this._signDirect(signerAddress, messages, fee, memo, signerData);
170
+ }
171
+ /**
172
+ * Internal method for direct signing of transactions using SIGN_MODE_DIRECT.
173
+ * Handles the low-level transaction construction and signing process.
174
+ *
175
+ * @param signerAddress - Address of the account signing the transaction
176
+ * @param messages - Array of messages to include in the transaction
177
+ * @param fee - Fee configuration for the transaction
178
+ * @param memo - Transaction memo string
179
+ * @param signerData - Account data including number, sequence, and chain ID
180
+ * @returns Promise resolving to TxRaw containing the signed transaction
181
+ * @private
182
+ */
183
+ async _signDirect(signerAddress, messages, fee, memo, { accountNumber, sequence, chainId }) {
184
+ assert(isOfflineDirectSigner(this._signer));
185
+ const accountFromSigner = (await this._signer.getAccounts()).find((account) => account.address === signerAddress);
186
+ if (!accountFromSigner) {
187
+ throw new Error('Failed to retrieve account from signer');
188
+ }
189
+ const pubkey = encodePubkey(encodeSecp256k1Pubkey(accountFromSigner.pubkey));
190
+ const txBodyEncodeObject = {
191
+ typeUrl: '/cosmos.tx.v1beta1.TxBody',
192
+ value: {
193
+ messages: messages,
194
+ memo: memo,
195
+ },
196
+ };
197
+ const txBodyBytes = this.registry.encode(txBodyEncodeObject);
198
+ const gasLimit = Int53.fromString(fee.gas).toNumber();
199
+ const authInfoBytes = makeDidAuthInfoBytes([{ pubkey, sequence }], fee.amount, BigInt(gasLimit), fee.payer);
200
+ const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber);
201
+ const { signature, signed } = await this._signer.signDirect(signerAddress, signDoc);
202
+ return TxRaw.fromPartial({
203
+ bodyBytes: signed.bodyBytes,
204
+ authInfoBytes: signed.authInfoBytes,
205
+ signatures: [fromBase64(signature.signature)],
206
+ });
207
+ }
208
+ /**
209
+ * Broadcasts a signed transaction to the network and monitors its inclusion in a block,
210
+ * with support for retrying on failure and graceful timeout handling.
211
+ *
212
+ * ## Optimizations over base implementation:
213
+ * - Implements a retry policy (`maxRetries`, default: 3) to handle transient broadcast errors.
214
+ * - Prevents double spend by reusing the exact same signed transaction (immutable `Uint8Array`).
215
+ * - Tracks and returns the last known transaction hash (`txId`), even in the case of timeout or failure.
216
+ * - Throws a `TimeoutError` if the transaction is not found within `timeoutMs`, attaching the `txHash` if known.
217
+ * - Polling frequency and timeout are customizable via `pollIntervalMs` and `timeoutMs` parameters.
218
+ *
219
+ * @param tx - The signed transaction bytes to broadcast.
220
+ * @param timeoutMs - Maximum duration (in milliseconds) to wait for block inclusion. Defaults to 60,000 ms.
221
+ * @param pollIntervalMs - Polling interval (in milliseconds) when checking for transaction inclusion. Defaults to 3,000 ms.
222
+ * @param maxRetries - Maximum number of times to retry `broadcastTxSync` on failure. Defaults to 3.
223
+ *
224
+ * @returns A `Promise` that resolves to `DeliverTxResponse` upon successful inclusion in a block.
225
+ * @throws `BroadcastTxError` if the transaction is rejected by the node during CheckTx.
226
+ * @throws `TimeoutError` if the transaction is not found on-chain within the timeout window. Includes `txHash` if available.
227
+ */
228
+ async broadcastTx(tx, timeoutMs = 60_000, pollIntervalMs = 3_000, maxRetries = 3) {
229
+ // define polling callback
230
+ const pollForTx = async (txId, startTime) => {
231
+ // define immutable timeout
232
+ const timedOut = Date.now() - startTime > timeoutMs;
233
+ // check if timed out
234
+ if (timedOut) {
235
+ // if so, throw timeout error with txId (or transaction hash)
236
+ throw new TimeoutError(`Transaction with ID ${txId} was submitted but was not yet found on the chain. Waited ${timeoutMs / 1000} seconds.`, txId);
237
+ }
238
+ // otherwise, poll for tx
239
+ await sleep(pollIntervalMs);
240
+ // query for tx
241
+ const result = await this.getTx(txId);
242
+ // return result if found, otherwise poll again
243
+ return result
244
+ ? {
245
+ code: result.code,
246
+ height: result.height,
247
+ txIndex: result.txIndex,
248
+ events: result.events,
249
+ rawLog: result.rawLog,
250
+ transactionHash: txId,
251
+ msgResponses: result.msgResponses,
252
+ gasUsed: result.gasUsed,
253
+ gasWanted: result.gasWanted,
254
+ }
255
+ : pollForTx(txId, startTime);
256
+ };
257
+ // define immutable array of errors
258
+ const errors = [];
259
+ // define last known transaction hash
260
+ let lastKnownTxHash;
261
+ // attempt to broadcast tx until maxRetries or tx is found
262
+ for (const attempt of Array.from({ length: maxRetries }, (_, i) => i + 1)) {
263
+ try {
264
+ // broadcast tx
265
+ const txId = await this.broadcastTxSync(tx);
266
+ // set last known transaction hash
267
+ lastKnownTxHash = txId;
268
+ // recompute start time
269
+ const startTime = Date.now();
270
+ // poll for tx
271
+ const result = await pollForTx(txId, startTime);
272
+ // if successful, return result
273
+ return result;
274
+ }
275
+ catch (error) {
276
+ // if error, push to errors array
277
+ errors.push(error);
278
+ // define last error
279
+ const lastError = error;
280
+ // if error is not a TimeoutError, throw it
281
+ if (lastError.name !== 'TimeoutError')
282
+ throw lastError;
283
+ // define whether final attempt
284
+ const isFinalAttempt = attempt === maxRetries;
285
+ // define enriched error, attaching last known transaction hash
286
+ const enrichedError = isFinalAttempt && lastKnownTxHash && lastError.name === 'TimeoutError'
287
+ ? new TimeoutError(`Transaction broadcast failed after ${maxRetries} attempts. Transaction hash: ${lastKnownTxHash}`, lastKnownTxHash)
288
+ : lastError;
289
+ // if final attempt and error does not have txHash, throw the last error
290
+ if (isFinalAttempt)
291
+ throw lastError;
292
+ // otherwise, brief backoff before retrying
293
+ await sleep(1000);
294
+ }
295
+ }
296
+ // should not reach here
297
+ throw new TimeoutError(`Broadcast failed unexpectedly. Last known transaction hash: ${lastKnownTxHash ?? 'unknown'}`, lastKnownTxHash || 'unknown');
298
+ }
299
+ async simulate(signerAddress, messages, memo) {
300
+ if (!this.endpoint) {
301
+ throw new Error('querier: endpoint is not set');
302
+ }
303
+ const querier = await CheqdQuerier.connect(this.endpoint);
304
+ const anyMsgs = messages.map((msg) => this.registry.encodeAsAny(msg));
305
+ const accountFromSigner = (await this._signer.getAccounts()).find((account) => account.address === signerAddress);
306
+ if (!accountFromSigner) {
307
+ throw new Error('Failed to retrieve account from signer');
308
+ }
309
+ const pubkey = encodeSecp256k1Pubkey(accountFromSigner.pubkey);
310
+ const { sequence } = await this.getSequence(signerAddress);
311
+ const gasLimit = this.endpoint.includes('localhost')
312
+ ? CheqdSigningStargateClient.maxGasLimit
313
+ : (await CheqdQuerier.getConsensusParameters(this.endpoint)).block.maxGas;
314
+ const { gasInfo } = await (await this.constructSimulateExtension(querier)).tx.simulate(anyMsgs, memo, pubkey, signerAddress, sequence, gasLimit);
315
+ assertDefined(gasInfo);
316
+ return Uint53.fromString(gasInfo.gasUsed.toString()).toNumber();
317
+ }
318
+ async constructSimulateExtension(querier) {
319
+ // setup rpc client
320
+ const rpc = createProtobufRpcClient(querier);
321
+ // setup query tx query service
322
+ const queryService = new ServiceClientImpl(rpc);
323
+ // setup + return tx extension
324
+ return {
325
+ tx: {
326
+ getTx: async (txId) => {
327
+ // construct request
328
+ const request = { hash: txId };
329
+ // query + return tx
330
+ return await queryService.GetTx(request);
331
+ },
332
+ simulate: async (messages, memo, signer, signerAddress, sequence, gasLimit) => {
333
+ // encode public key
334
+ const publicKey = encodePubkey(signer);
335
+ // construct max gas limit
336
+ const maxGasLimit = Int53.fromString(gasLimit.toString()).toNumber();
337
+ // construct unsigned tx
338
+ const tx = Tx.fromPartial({
339
+ body: TxBody.fromPartial({
340
+ messages: Array.from(messages),
341
+ memo,
342
+ }),
343
+ authInfo: AuthInfo.fromPartial({
344
+ fee: Fee.fromPartial({
345
+ amount: [],
346
+ gasLimit: BigInt(maxGasLimit),
347
+ payer: signerAddress,
348
+ }),
349
+ signerInfos: [
350
+ {
351
+ publicKey,
352
+ modeInfo: {
353
+ single: { mode: SignMode.SIGN_MODE_DIRECT },
354
+ },
355
+ sequence: BigInt(sequence),
356
+ },
357
+ ],
358
+ }),
359
+ signatures: [new Uint8Array()],
360
+ });
361
+ // construct request
362
+ const request = SimulateRequest.fromPartial({
363
+ txBytes: Tx.encode(tx).finish(),
364
+ });
365
+ // query + return simulation response
366
+ return await queryService.Simulate(request);
367
+ },
368
+ },
369
+ };
370
+ }
371
+ /**
372
+ * Batches multiple messages into optimal groups based on gas limits.
373
+ * Simulates each message individually and groups them to maximize throughput
374
+ * while staying within gas constraints.
375
+ *
376
+ * @param messages - Array of messages to batch
377
+ * @param signerAddress - Address of the account that will sign the transactions
378
+ * @param memo - Optional transaction memo
379
+ * @param maxGasLimit - Maximum gas limit per batch, defaults to 30,000,000
380
+ * @returns Promise resolving to MessageBatch with grouped messages and gas estimates
381
+ */
382
+ async batchMessages(messages, signerAddress, memo, maxGasLimit = 30000000 // default gas limit, use consensus params if available
383
+ ) {
384
+ // simulate
385
+ const gasEstimates = await Promise.all(messages.map(async (message) => this.simulate(signerAddress, [message], memo)));
386
+ // batch messages
387
+ const { batches, gasPerBatch, currentBatch, currentBatchGas } = gasEstimates.reduce((acc, gasUsed, index) => {
388
+ // finalise current batch, if limit is surpassed
389
+ if (acc.currentBatchGas + gasUsed > maxGasLimit) {
390
+ return {
391
+ batches: [...acc.batches, acc.currentBatch],
392
+ gasPerBatch: [...acc.gasPerBatch, acc.currentBatchGas],
393
+ currentBatch: [messages[index]],
394
+ currentBatchGas: gasUsed,
395
+ };
396
+ }
397
+ // otherwise, add to current batch
398
+ return {
399
+ batches: acc.batches,
400
+ gasPerBatch: acc.gasPerBatch,
401
+ currentBatch: [...acc.currentBatch, messages[index]],
402
+ currentBatchGas: acc.currentBatchGas + gasUsed,
403
+ };
404
+ }, {
405
+ batches: [],
406
+ gasPerBatch: [],
407
+ currentBatch: [],
408
+ currentBatchGas: 0,
409
+ });
410
+ // push final batch to batches, if not empty + return
411
+ return currentBatch.length > 0
412
+ ? {
413
+ batches: [...batches, currentBatch],
414
+ gas: [...gasPerBatch, currentBatchGas],
415
+ }
416
+ : {
417
+ batches,
418
+ gas: gasPerBatch,
419
+ };
420
+ }
421
+ /**
422
+ * Validates and initializes DID signers for the provided verification methods.
423
+ * Ensures that all verification method types are supported and assigns appropriate signers.
424
+ *
425
+ * @param verificationMethods - Array of verification methods to validate
426
+ * @returns Promise resolving to the configured signer algorithm map
427
+ * @throws Error if no verification methods are provided or unsupported types are found
428
+ */
429
+ async checkDidSigners(verificationMethods = []) {
430
+ if (verificationMethods.length === 0) {
431
+ throw new Error('No verification methods provided');
432
+ }
433
+ verificationMethods.forEach((verificationMethod) => {
434
+ if (!Object.values(VerificationMethods).includes(verificationMethod.verificationMethodType ?? '')) {
435
+ throw new Error(`Unsupported verification method type: ${verificationMethod.verificationMethodType}`);
436
+ }
437
+ if (!this.didSigners[verificationMethod.verificationMethodType ?? '']) {
438
+ this.didSigners[verificationMethod.verificationMethodType ?? ''] = EdDSASigner;
439
+ }
440
+ });
441
+ return this.didSigners;
442
+ }
443
+ /**
444
+ * Retrieves the appropriate DID signer for a specific verification method.
445
+ * Looks up the verification method by ID and returns the corresponding signer function.
446
+ *
447
+ * @param verificationMethodId - ID of the verification method to get signer for
448
+ * @param verificationMethods - Array of available verification methods
449
+ * @returns Promise resolving to a signer function that takes a secret key
450
+ * @throws Error if the verification method is not found
451
+ */
452
+ async getDidSigner(verificationMethodId, verificationMethods) {
453
+ await this.checkDidSigners(verificationMethods);
454
+ const verificationMethod = verificationMethods.find((method) => method.id === verificationMethodId)?.verificationMethodType;
455
+ if (!verificationMethod) {
456
+ throw new Error(`Verification method for ${verificationMethodId} not found`);
457
+ }
458
+ return this.didSigners[verificationMethod];
459
+ }
460
+ /**
461
+ * Signs a CreateDidDoc transaction payload using the provided signing inputs.
462
+ * Validates verification methods and creates signatures for each signing input.
463
+ *
464
+ * @param signInputs - Array of signing inputs containing verification method IDs and private keys
465
+ * @param payload - CreateDidDoc payload to sign
466
+ * @returns Promise resolving to array of SignInfo objects with signatures
467
+ */
468
+ async signCreateDidDocTx(signInputs, payload) {
469
+ await this.checkDidSigners(payload?.verificationMethod);
470
+ const signBytes = MsgCreateDidDocPayload.encode(payload).finish();
471
+ const signInfos = await Promise.all(signInputs.map(async (signInput) => {
472
+ return {
473
+ verificationMethodId: signInput.verificationMethodId,
474
+ signature: base64ToBytes((await (await this.getDidSigner(signInput.verificationMethodId, payload.verificationMethod))(hexToBytes(signInput.privateKeyHex))(signBytes))),
475
+ };
476
+ }));
477
+ return signInfos;
478
+ }
479
+ async signUpdateDidDocTx(signInputs, payload, externalControllers, previousDidDocument) {
480
+ await this.checkDidSigners(payload?.verificationMethod);
481
+ const signBytes = MsgUpdateDidDocPayload.encode(payload).finish();
482
+ const signInfos = await Promise.all(signInputs.map(async (signInput) => {
483
+ return {
484
+ verificationMethodId: signInput.verificationMethodId,
485
+ signature: base64ToBytes((await (await this.getDidSigner(signInput.verificationMethodId, payload.verificationMethod
486
+ .concat(externalControllers
487
+ ?.flatMap((controller) => controller.verificationMethod)
488
+ .map((vm) => {
489
+ return {
490
+ id: vm.id,
491
+ verificationMethodType: vm.type,
492
+ controller: vm.controller,
493
+ verificationMaterial: '<ignored>',
494
+ };
495
+ }) ?? [])
496
+ .concat(previousDidDocument?.verificationMethod?.map((vm) => {
497
+ return {
498
+ id: vm.id,
499
+ verificationMethodType: vm.type,
500
+ controller: vm.controller,
501
+ verificationMaterial: '<ignored>',
502
+ };
503
+ }) ?? [])))(hexToBytes(signInput.privateKeyHex))(signBytes))),
504
+ };
505
+ }));
506
+ return signInfos;
507
+ }
508
+ async signDeactivateDidDocTx(signInputs, payload, verificationMethod) {
509
+ await this.checkDidSigners(verificationMethod);
510
+ const signBytes = MsgDeactivateDidDocPayload.encode(payload).finish();
511
+ const signInfos = await Promise.all(signInputs.map(async (signInput) => {
512
+ return {
513
+ verificationMethodId: signInput.verificationMethodId,
514
+ signature: base64ToBytes((await (await this.getDidSigner(signInput.verificationMethodId, verificationMethod))(hexToBytes(signInput.privateKeyHex))(signBytes))),
515
+ };
516
+ }));
517
+ return signInfos;
518
+ }
519
+ static async signIdentityTx(signBytes, signInputs) {
520
+ let signInfos = [];
521
+ for (let signInput of signInputs) {
522
+ if (typeof signInput.keyType === undefined) {
523
+ throw new Error('Key type is not defined');
524
+ }
525
+ let signature;
526
+ switch (signInput.keyType) {
527
+ case 'Ed25519':
528
+ signature = (await EdDSASigner(hexToBytes(signInput.privateKeyHex))(signBytes));
529
+ break;
530
+ case 'Secp256k1':
531
+ signature = (await ES256KSigner(hexToBytes(signInput.privateKeyHex))(signBytes));
532
+ break;
533
+ case 'P256':
534
+ signature = (await ES256Signer(hexToBytes(signInput.privateKeyHex))(signBytes));
535
+ break;
536
+ default:
537
+ throw new Error(`Unsupported signature type: ${signInput.keyType}`);
538
+ }
539
+ signInfos.push({
540
+ verificationMethodId: signInput.verificationMethodId,
541
+ signature: base64ToBytes(signature),
542
+ });
543
+ }
544
+ return signInfos;
545
+ }
546
+ }
547
+ //# sourceMappingURL=signer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signer.js","sourceRoot":"","sources":["../src/signer.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,qBAAqB,EAErB,YAAY,EAEZ,WAAW,GACX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAIN,qBAAqB,EAErB,YAAY,EAEZ,uBAAuB,EACvB,YAAY,GACZ,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAe,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,0BAA0B,EAAE,MAAM,eAAe,CAAC;AAC3D,OAAO,EACN,sBAAsB,EAEtB,sBAAsB,EACtB,0BAA0B,GAE1B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAkE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjH,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAU,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACpG,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,KAAK,EAAE,MAAM,eAA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