@autonomys/auto-utils 1.5.2 → 1.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/address.d.ts +54 -0
  2. package/dist/address.d.ts.map +1 -1
  3. package/dist/address.js +54 -0
  4. package/dist/api.d.ts +148 -0
  5. package/dist/api.d.ts.map +1 -1
  6. package/dist/api.js +148 -0
  7. package/dist/crypto.d.ts +28 -0
  8. package/dist/crypto.d.ts.map +1 -1
  9. package/dist/crypto.js +28 -0
  10. package/dist/network.d.ts +150 -0
  11. package/dist/network.d.ts.map +1 -1
  12. package/dist/network.js +150 -0
  13. package/dist/number.d.ts +91 -0
  14. package/dist/number.d.ts.map +1 -1
  15. package/dist/number.js +91 -0
  16. package/dist/string.d.ts +110 -0
  17. package/dist/string.d.ts.map +1 -1
  18. package/dist/string.js +110 -0
  19. package/dist/utils/detectTxSuccess.d.ts +31 -0
  20. package/dist/utils/detectTxSuccess.d.ts.map +1 -1
  21. package/dist/utils/detectTxSuccess.js +31 -0
  22. package/dist/utils/events.d.ts +75 -0
  23. package/dist/utils/events.d.ts.map +1 -1
  24. package/dist/utils/events.js +76 -0
  25. package/dist/utils/format.d.ts +8 -0
  26. package/dist/utils/format.d.ts.map +1 -1
  27. package/dist/utils/ready.d.ts +8 -0
  28. package/dist/utils/ready.d.ts.map +1 -1
  29. package/dist/utils/sign.d.ts +66 -0
  30. package/dist/utils/sign.d.ts.map +1 -1
  31. package/dist/utils/sign.js +58 -0
  32. package/dist/utils/signAndSendTx.d.ts +71 -0
  33. package/dist/utils/signAndSendTx.d.ts.map +1 -1
  34. package/dist/utils/signAndSendTx.js +71 -0
  35. package/dist/utils/validateEvents.d.ts +67 -0
  36. package/dist/utils/validateEvents.d.ts.map +1 -1
  37. package/dist/utils/validateEvents.js +68 -1
  38. package/dist/utils/verify.d.ts +8 -0
  39. package/dist/utils/verify.d.ts.map +1 -1
  40. package/dist/wallet.d.ts +204 -0
  41. package/dist/wallet.d.ts.map +1 -1
  42. package/dist/wallet.js +204 -0
  43. package/package.json +2 -2
package/dist/string.js CHANGED
@@ -2,13 +2,123 @@
2
2
  // file: src/string.ts
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.fixLengthEntryId = exports.capitalizeFirstLetter = exports.shortString = exports.stringify = void 0;
5
+ /**
6
+ * Converts any value to a JSON string with BigInt support.
7
+ *
8
+ * This function extends JSON.stringify to handle BigInt values by converting them to strings.
9
+ * It's particularly useful when working with blockchain data that often includes large numbers
10
+ * represented as BigInt values.
11
+ *
12
+ * @param value - Any value to be stringified, including objects with BigInt properties.
13
+ * @returns A JSON string representation of the value with BigInt values converted to strings.
14
+ *
15
+ * @example
16
+ * import { stringify } from '@autonomys/auto-utils'
17
+ *
18
+ * // Stringify object with BigInt values
19
+ * const data = {
20
+ * balance: BigInt('1000000000000000000'),
21
+ * timestamp: Date.now(),
22
+ * address: '5GmS1wtCfR4tK5SSgnZbVT4kYw5W8NmxmijcsxCQE6oLW6A8'
23
+ * }
24
+ *
25
+ * const jsonString = stringify(data)
26
+ * console.log(jsonString)
27
+ * // Output: {"balance":"1000000000000000000","timestamp":1672531200000,"address":"5G..."}
28
+ *
29
+ * // Compare with regular JSON.stringify which would throw an error
30
+ * // JSON.stringify(data) // TypeError: Do not know how to serialize a BigInt
31
+ */
5
32
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
6
33
  const stringify = (value) => JSON.stringify(value, (_, value) => (typeof value === 'bigint' ? value.toString() : value));
7
34
  exports.stringify = stringify;
35
+ /**
36
+ * Truncates a string by keeping the beginning and end characters with ellipsis in the middle.
37
+ *
38
+ * This function is commonly used to display long addresses, transaction hashes, or other
39
+ * identifiers in a compact format while preserving recognizable parts of the original string.
40
+ *
41
+ * @param value - The string to truncate.
42
+ * @param initialLength - Number of characters to keep from the beginning. Defaults to 6.
43
+ * @param endLength - Number of characters to keep from the end (negative number). Defaults to -4.
44
+ * @returns The truncated string with ellipsis in the middle.
45
+ *
46
+ * @example
47
+ * import { shortString } from '@autonomys/auto-utils'
48
+ *
49
+ * // Truncate a long address
50
+ * const address = '5GmS1wtCfR4tK5SSgnZbVT4kYw5W8NmxmijcsxCQE6oLW6A8'
51
+ * const short = shortString(address)
52
+ * console.log(short) // Output: "5GmS1w...W6A8"
53
+ *
54
+ * // Custom truncation lengths
55
+ * const customShort = shortString(address, 8, -6)
56
+ * console.log(customShort) // Output: "5GmS1wtC...oLW6A8"
57
+ *
58
+ * // Truncate transaction hash
59
+ * const txHash = '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'
60
+ * const shortHash = shortString(txHash, 10, -8)
61
+ * console.log(shortHash) // Output: "0x12345678...90abcdef"
62
+ */
8
63
  const shortString = (value, initialLength = 6, endLength = -4) => `${value.slice(0, initialLength)}...${value.slice(endLength)}`;
9
64
  exports.shortString = shortString;
65
+ /**
66
+ * Capitalizes the first letter of a string.
67
+ *
68
+ * This utility function converts the first character of a string to uppercase while
69
+ * leaving the rest of the string unchanged. It handles empty strings gracefully.
70
+ *
71
+ * @param string - The string to capitalize.
72
+ * @returns The string with the first letter capitalized, or empty string if input is empty.
73
+ *
74
+ * @example
75
+ * import { capitalizeFirstLetter } from '@autonomys/auto-utils'
76
+ *
77
+ * // Capitalize network names
78
+ * console.log(capitalizeFirstLetter('mainnet')) // Output: "Mainnet"
79
+ * console.log(capitalizeFirstLetter('gemini-3h')) // Output: "Gemini-3h"
80
+ *
81
+ * // Handle edge cases
82
+ * console.log(capitalizeFirstLetter('')) // Output: ""
83
+ * console.log(capitalizeFirstLetter('a')) // Output: "A"
84
+ * console.log(capitalizeFirstLetter('UPPERCASE')) // Output: "UPPERCASE"
85
+ */
10
86
  const capitalizeFirstLetter = (string) => string ? string.charAt(0).toUpperCase() + string.slice(1) : '';
11
87
  exports.capitalizeFirstLetter = capitalizeFirstLetter;
88
+ /**
89
+ * Creates a fixed-length entry identifier for blockchain events or transactions.
90
+ *
91
+ * This function generates a standardized identifier format used for indexing blockchain
92
+ * entries, combining block height with optional transaction index. Both values are
93
+ * zero-padded to ensure consistent string length for sorting and indexing.
94
+ *
95
+ * @param blockHeight - The block height as a BigInt.
96
+ * @param indexInBlock - Optional transaction index within the block as a BigInt.
97
+ * @returns A zero-padded string identifier, either "blockHeight" or "blockHeight-indexInBlock".
98
+ *
99
+ * @example
100
+ * import { fixLengthEntryId } from '@autonomys/auto-utils'
101
+ *
102
+ * // Create block identifier
103
+ * const blockId = fixLengthEntryId(BigInt(12345))
104
+ * console.log(blockId) // Output: "00000000000000000000000000012345"
105
+ *
106
+ * // Create transaction identifier
107
+ * const txId = fixLengthEntryId(BigInt(12345), BigInt(7))
108
+ * console.log(txId) // Output: "00000000000000000000000000012345-00000000000000000000000000000007"
109
+ *
110
+ * // Use with large numbers
111
+ * const largeBlockId = fixLengthEntryId(BigInt('1000000000000000000'))
112
+ * console.log(largeBlockId) // Output: "00000000000001000000000000000000"
113
+ *
114
+ * // Useful for creating sortable identifiers
115
+ * const ids = [
116
+ * fixLengthEntryId(BigInt(100)),
117
+ * fixLengthEntryId(BigInt(50)),
118
+ * fixLengthEntryId(BigInt(200))
119
+ * ]
120
+ * ids.sort() // Will sort correctly due to zero-padding
121
+ */
12
122
  const fixLengthEntryId = (blockHeight, indexInBlock) => {
13
123
  const totalLength = 32;
14
124
  const str1 = blockHeight.toString().padStart(totalLength, '0');
@@ -1,3 +1,34 @@
1
1
  import type { EventRecord } from '../types/event';
2
+ /**
3
+ * Detects if a transaction was successful by checking for success events.
4
+ *
5
+ * This function examines the events emitted by a transaction to determine
6
+ * if it was successful. It looks for events that are known to indicate
7
+ * successful transaction execution, such as 'system.ExtrinsicSuccess'.
8
+ *
9
+ * @param events - Array of EventRecord objects emitted by the transaction.
10
+ * @returns True if the transaction was successful, false otherwise.
11
+ *
12
+ * @example
13
+ * import { detectTxSuccess } from '@autonomys/auto-utils'
14
+ *
15
+ * // Check transaction success from events
16
+ * const events = [] // events from transaction result
17
+ * const isSuccessful = detectTxSuccess(events)
18
+ *
19
+ * if (isSuccessful) {
20
+ * console.log('Transaction completed successfully')
21
+ * } else {
22
+ * console.log('Transaction failed or had no success events')
23
+ * }
24
+ *
25
+ * // Use with signAndSend result
26
+ * tx.signAndSend(sender, (result) => {
27
+ * if (result.status.isInBlock) {
28
+ * const success = detectTxSuccess(result.events)
29
+ * console.log('Transaction success:', success)
30
+ * }
31
+ * })
32
+ */
2
33
  export declare const detectTxSuccess: (events: EventRecord[]) => boolean;
3
34
  //# sourceMappingURL=detectTxSuccess.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"detectTxSuccess.d.ts","sourceRoot":"","sources":["../../src/utils/detectTxSuccess.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAGjD,eAAO,MAAM,eAAe,GAAI,QAAQ,WAAW,EAAE,KAAG,OAMvD,CAAA"}
1
+ {"version":3,"file":"detectTxSuccess.d.ts","sourceRoot":"","sources":["../../src/utils/detectTxSuccess.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAGjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,eAAO,MAAM,eAAe,GAAI,QAAQ,WAAW,EAAE,KAAG,OAMvD,CAAA"}
@@ -3,6 +3,37 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.detectTxSuccess = void 0;
5
5
  const events_1 = require("./events");
6
+ /**
7
+ * Detects if a transaction was successful by checking for success events.
8
+ *
9
+ * This function examines the events emitted by a transaction to determine
10
+ * if it was successful. It looks for events that are known to indicate
11
+ * successful transaction execution, such as 'system.ExtrinsicSuccess'.
12
+ *
13
+ * @param events - Array of EventRecord objects emitted by the transaction.
14
+ * @returns True if the transaction was successful, false otherwise.
15
+ *
16
+ * @example
17
+ * import { detectTxSuccess } from '@autonomys/auto-utils'
18
+ *
19
+ * // Check transaction success from events
20
+ * const events = [] // events from transaction result
21
+ * const isSuccessful = detectTxSuccess(events)
22
+ *
23
+ * if (isSuccessful) {
24
+ * console.log('Transaction completed successfully')
25
+ * } else {
26
+ * console.log('Transaction failed or had no success events')
27
+ * }
28
+ *
29
+ * // Use with signAndSend result
30
+ * tx.signAndSend(sender, (result) => {
31
+ * if (result.status.isInBlock) {
32
+ * const success = detectTxSuccess(result.events)
33
+ * console.log('Transaction success:', success)
34
+ * }
35
+ * })
36
+ */
6
37
  const detectTxSuccess = (events) => {
7
38
  events.forEach(({ event: { method, section } }) => {
8
39
  if (events_1.expectSuccessfulTxEvent.indexOf(`${section}.${method}`) > -1)
@@ -1,11 +1,86 @@
1
+ /**
2
+ * Enumeration of blockchain event types for categorizing events.
3
+ *
4
+ * This enum provides a structured way to reference different categories of
5
+ * blockchain events, making event handling more organized and type-safe.
6
+ */
1
7
  export declare const enum Type {
2
8
  system = "system"
3
9
  }
10
+ /**
11
+ * Creates a standardized event name by combining type and event name.
12
+ *
13
+ * This utility function creates consistent event names following the pattern
14
+ * "type.eventName", which matches the format used by Polkadot.js for blockchain events.
15
+ *
16
+ * @param type - The event type category from the Type enum.
17
+ * @param event - The specific event name within that category.
18
+ * @returns A formatted event name string in the format "type.event".
19
+ *
20
+ * @example
21
+ * import { eventName, Type } from '@autonomys/auto-utils'
22
+ *
23
+ * // Create system event names
24
+ * const successEvent = eventName(Type.system, 'ExtrinsicSuccess')
25
+ * console.log(successEvent) // Output: "system.ExtrinsicSuccess"
26
+ *
27
+ * const failureEvent = eventName(Type.system, 'ExtrinsicFailed')
28
+ * console.log(failureEvent) // Output: "system.ExtrinsicFailed"
29
+ *
30
+ * // Use in event validation
31
+ * const expectedEvents = [
32
+ * eventName(Type.system, 'ExtrinsicSuccess'),
33
+ * 'balances.Transfer' // Can also use direct strings
34
+ * ]
35
+ */
4
36
  export declare const eventName: (type: Type, event: string) => string;
37
+ /**
38
+ * Organized collection of event groups by category.
39
+ *
40
+ * This object provides structured access to different categories of blockchain
41
+ * events, making it easier to reference and validate specific event types
42
+ * in transaction monitoring and testing scenarios.
43
+ *
44
+ * @example
45
+ * import { eventsGroup } from '@autonomys/auto-utils'
46
+ *
47
+ * // Access system events
48
+ * console.log(eventsGroup.system.success) // Output: "system.ExtrinsicSuccess"
49
+ * console.log(eventsGroup.system.failure) // Output: "system.ExtrinsicFailed"
50
+ *
51
+ * // Use in transaction validation
52
+ * const expectedSystemEvents = [
53
+ * eventsGroup.system.success,
54
+ * eventsGroup.system.newAccount
55
+ * ]
56
+ */
5
57
  export declare const eventsGroup: {
6
58
  system: {
7
59
  [key: string]: string;
8
60
  };
9
61
  };
62
+ /**
63
+ * Default array of events expected for successful transactions.
64
+ *
65
+ * This array contains the standard events that indicate a transaction was
66
+ * successfully executed. It's used as the default expected events list
67
+ * in transaction signing and validation functions.
68
+ *
69
+ * @example
70
+ * import { expectSuccessfulTxEvent, signAndSendTx } from '@autonomys/auto-utils'
71
+ *
72
+ * // Use as default expected events (this is automatic)
73
+ * const result = await signAndSendTx(sender, tx)
74
+ *
75
+ * // Or explicitly specify (same as default)
76
+ * const result2 = await signAndSendTx(sender, tx, {}, expectSuccessfulTxEvent)
77
+ *
78
+ * // Combine with custom events
79
+ * const customExpectedEvents = [
80
+ * ...expectSuccessfulTxEvent,
81
+ * 'balances.Transfer',
82
+ * 'domains.OperatorNominated'
83
+ * ]
84
+ */
10
85
  export declare const expectSuccessfulTxEvent: string[];
11
86
  //# sourceMappingURL=events.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/utils/events.ts"],"names":[],"mappings":"AAGA,0BAAkB,IAAI;IACpB,MAAM,WAAW;CAClB;AAGD,eAAO,MAAM,SAAS,GAAI,MAAM,IAAI,EAAE,OAAO,MAAM,WAAuB,CAAA;AAY1E,eAAO,MAAM,WAAW;;;;CAEvB,CAAA;AAGD,eAAO,MAAM,uBAAuB,UAAmB,CAAA"}
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/utils/events.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AAEH,0BAAkB,IAAI;IACpB,MAAM,WAAW;CAClB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,eAAO,MAAM,SAAS,GAAI,MAAM,IAAI,EAAE,OAAO,MAAM,WAAuB,CAAA;AAkB1E;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,eAAO,MAAM,WAAW;;;;CAEvB,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,eAAO,MAAM,uBAAuB,UAAmB,CAAA"}
@@ -2,18 +2,94 @@
2
2
  // file: src/utils/events.ts
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.expectSuccessfulTxEvent = exports.eventsGroup = exports.eventName = void 0;
5
+ /**
6
+ * Creates a standardized event name by combining type and event name.
7
+ *
8
+ * This utility function creates consistent event names following the pattern
9
+ * "type.eventName", which matches the format used by Polkadot.js for blockchain events.
10
+ *
11
+ * @param type - The event type category from the Type enum.
12
+ * @param event - The specific event name within that category.
13
+ * @returns A formatted event name string in the format "type.event".
14
+ *
15
+ * @example
16
+ * import { eventName, Type } from '@autonomys/auto-utils'
17
+ *
18
+ * // Create system event names
19
+ * const successEvent = eventName(Type.system, 'ExtrinsicSuccess')
20
+ * console.log(successEvent) // Output: "system.ExtrinsicSuccess"
21
+ *
22
+ * const failureEvent = eventName(Type.system, 'ExtrinsicFailed')
23
+ * console.log(failureEvent) // Output: "system.ExtrinsicFailed"
24
+ *
25
+ * // Use in event validation
26
+ * const expectedEvents = [
27
+ * eventName(Type.system, 'ExtrinsicSuccess'),
28
+ * 'balances.Transfer' // Can also use direct strings
29
+ * ]
30
+ */
5
31
  // Utility Function for Event Names
6
32
  const eventName = (type, event) => `${type}.${event}`;
7
33
  exports.eventName = eventName;
34
+ /**
35
+ * Collection of system-level blockchain events.
36
+ *
37
+ * This object contains standardized names for system events that are common
38
+ * across all Polkadot-based blockchains, providing easy access to frequently
39
+ * used event names for transaction monitoring and validation.
40
+ */
8
41
  // System Events
9
42
  const system = {
10
43
  failure: (0, exports.eventName)("system" /* Type.system */, 'ExtrinsicFailed'),
11
44
  newAccount: (0, exports.eventName)("system" /* Type.system */, 'NewAccount'),
12
45
  success: (0, exports.eventName)("system" /* Type.system */, 'ExtrinsicSuccess'),
13
46
  };
47
+ /**
48
+ * Organized collection of event groups by category.
49
+ *
50
+ * This object provides structured access to different categories of blockchain
51
+ * events, making it easier to reference and validate specific event types
52
+ * in transaction monitoring and testing scenarios.
53
+ *
54
+ * @example
55
+ * import { eventsGroup } from '@autonomys/auto-utils'
56
+ *
57
+ * // Access system events
58
+ * console.log(eventsGroup.system.success) // Output: "system.ExtrinsicSuccess"
59
+ * console.log(eventsGroup.system.failure) // Output: "system.ExtrinsicFailed"
60
+ *
61
+ * // Use in transaction validation
62
+ * const expectedSystemEvents = [
63
+ * eventsGroup.system.success,
64
+ * eventsGroup.system.newAccount
65
+ * ]
66
+ */
14
67
  // Group of Events
15
68
  exports.eventsGroup = {
16
69
  system,
17
70
  };
71
+ /**
72
+ * Default array of events expected for successful transactions.
73
+ *
74
+ * This array contains the standard events that indicate a transaction was
75
+ * successfully executed. It's used as the default expected events list
76
+ * in transaction signing and validation functions.
77
+ *
78
+ * @example
79
+ * import { expectSuccessfulTxEvent, signAndSendTx } from '@autonomys/auto-utils'
80
+ *
81
+ * // Use as default expected events (this is automatic)
82
+ * const result = await signAndSendTx(sender, tx)
83
+ *
84
+ * // Or explicitly specify (same as default)
85
+ * const result2 = await signAndSendTx(sender, tx, {}, expectSuccessfulTxEvent)
86
+ *
87
+ * // Combine with custom events
88
+ * const customExpectedEvents = [
89
+ * ...expectSuccessfulTxEvent,
90
+ * 'balances.Transfer',
91
+ * 'domains.OperatorNominated'
92
+ * ]
93
+ */
18
94
  // Export a default success event
19
95
  exports.expectSuccessfulTxEvent = [system.success];
@@ -1,3 +1,11 @@
1
1
  import { stringToU8a, u8aToHex } from '@polkadot/util';
2
+ /**
3
+ * Essential data format conversion utilities re-exported from Polkadot.js for convenience.
4
+ *
5
+ * These functions provide conversion capabilities between different data formats
6
+ * commonly used in Autonomys Network applications.
7
+ *
8
+ * @see {@link https://polkadot.js.org/docs/ | Polkadot.js Documentation} for complete API details.
9
+ */
2
10
  export { stringToU8a, u8aToHex };
3
11
  //# sourceMappingURL=format.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../src/utils/format.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAEtD,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAA"}
1
+ {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../src/utils/format.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAEtD;;;;;;;GAOG;AACH,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAA"}
@@ -1,3 +1,11 @@
1
1
  import { cryptoWaitReady } from '@polkadot/util-crypto';
2
+ /**
3
+ * Cryptographic initialization utility re-exported from Polkadot.js for convenience.
4
+ *
5
+ * Ensures that all cryptographic operations are ready before use. Essential to call
6
+ * before performing any cryptographic operations in WebAssembly environments.
7
+ *
8
+ * @see {@link https://polkadot.js.org/docs/ | Polkadot.js Documentation} for complete API details.
9
+ */
2
10
  export { cryptoWaitReady };
3
11
  //# sourceMappingURL=ready.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ready.d.ts","sourceRoot":"","sources":["../../src/utils/ready.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAEvD,OAAO,EAAE,eAAe,EAAE,CAAA"}
1
+ {"version":3,"file":"ready.d.ts","sourceRoot":"","sources":["../../src/utils/ready.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAEvD;;;;;;;GAOG;AACH,OAAO,EAAE,eAAe,EAAE,CAAA"}
@@ -1,6 +1,72 @@
1
1
  import { signatureVerify } from '@polkadot/util-crypto';
2
2
  import type { Signer } from '../types/wallet';
3
+ /**
4
+ * Signs arbitrary data using a Polkadot.js extension signer.
5
+ *
6
+ * This function uses the raw signing capability of a Polkadot.js extension to sign
7
+ * arbitrary byte data. It's commonly used for authentication, message signing,
8
+ * or creating signatures for off-chain verification.
9
+ *
10
+ * @param signer - The Polkadot.js extension signer interface.
11
+ * @param address - The address of the account to sign with.
12
+ * @param data - The data to sign as a string (will be encoded as bytes).
13
+ * @returns Promise resolving to the signature result containing the signature and other metadata.
14
+ *
15
+ * @example
16
+ * import { signMessage } from '@autonomys/auto-utils'
17
+ * import { web3FromAddress } from '@polkadot/extension-dapp'
18
+ *
19
+ * // Sign a message with extension wallet
20
+ * const address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'
21
+ * const injector = await web3FromAddress(address)
22
+ *
23
+ * const message = 'Hello, Autonomys Network!'
24
+ * const signature = await signMessage(injector.signer, address, message)
25
+ *
26
+ * console.log('Signature:', signature.signature)
27
+ * console.log('Signed by:', signature.id)
28
+ *
29
+ * // Sign authentication challenge
30
+ * const challenge = `Login to dApp at ${Date.now()}`
31
+ * const authSignature = await signMessage(injector.signer, address, challenge)
32
+ *
33
+ * // Use signature for verification later
34
+ * const isValid = signatureVerify(challenge, authSignature.signature, address)
35
+ * console.log('Signature valid:', isValid.isValid)
36
+ *
37
+ * @throws {Error} When the signer doesn't support raw signing or signing fails.
38
+ */
3
39
  export declare const signMessage: (signer: Signer, address: string, data: string) => Promise<import("@polkadot/types/types/extrinsic").SignerResult>;
40
+ /**
41
+ * Converts a public key to a hexadecimal string representation.
42
+ *
43
+ * This utility function converts a Uint8Array public key into its hexadecimal
44
+ * string representation, which is useful for display, logging, or storage purposes.
45
+ *
46
+ * @param publicKey - The public key as a Uint8Array.
47
+ * @returns The public key as a hexadecimal string with '0x' prefix.
48
+ *
49
+ * @example
50
+ * import { signingKey } from '@autonomys/auto-utils'
51
+ *
52
+ * // Convert KeyringPair public key to hex
53
+ * const wallet = setupWallet({ uri: '//Alice' })
54
+ * const publicKeyHex = signingKey(wallet.keyringPair.publicKey)
55
+ * console.log('Public key:', publicKeyHex) // Output: "0x..."
56
+ *
57
+ * // Use with signature verification
58
+ * const publicKeyBytes = new Uint8Array(32) // 32-byte public key
59
+ * const hexKey = signingKey(publicKeyBytes)
60
+ * console.log('Hex public key:', hexKey)
61
+ */
4
62
  export declare const signingKey: (publicKey: Uint8Array) => `0x${string}`;
63
+ /**
64
+ * Signature verification utility re-exported from Polkadot.js for convenience.
65
+ *
66
+ * Verifies that a signature was created by a specific public key for the given data.
67
+ * Essential for validating signatures in authentication flows and off-chain verification.
68
+ *
69
+ * @see {@link https://polkadot.js.org/docs/ | Polkadot.js Documentation} for complete API details.
70
+ */
5
71
  export { signatureVerify };
6
72
  //# sourceMappingURL=sign.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sign.d.ts","sourceRoot":"","sources":["../../src/utils/sign.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AACvD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAG7C,eAAO,MAAM,WAAW,GAAU,QAAQ,MAAM,EAAE,SAAS,MAAM,EAAE,MAAM,MAAM,oEAQ9E,CAAA;AAED,eAAO,MAAM,UAAU,GAAI,WAAW,UAAU,kBAAwB,CAAA;AAExE,OAAO,EAAE,eAAe,EAAE,CAAA"}
1
+ {"version":3,"file":"sign.d.ts","sourceRoot":"","sources":["../../src/utils/sign.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AACvD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAG7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,eAAO,MAAM,WAAW,GAAU,QAAQ,MAAM,EAAE,SAAS,MAAM,EAAE,MAAM,MAAM,oEAQ9E,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,UAAU,GAAI,WAAW,UAAU,kBAAwB,CAAA;AAExE;;;;;;;GAOG;AACH,OAAO,EAAE,eAAe,EAAE,CAAA"}
@@ -13,6 +13,42 @@ exports.signatureVerify = exports.signingKey = exports.signMessage = void 0;
13
13
  const util_crypto_1 = require("@polkadot/util-crypto");
14
14
  Object.defineProperty(exports, "signatureVerify", { enumerable: true, get: function () { return util_crypto_1.signatureVerify; } });
15
15
  const format_1 = require("./format");
16
+ /**
17
+ * Signs arbitrary data using a Polkadot.js extension signer.
18
+ *
19
+ * This function uses the raw signing capability of a Polkadot.js extension to sign
20
+ * arbitrary byte data. It's commonly used for authentication, message signing,
21
+ * or creating signatures for off-chain verification.
22
+ *
23
+ * @param signer - The Polkadot.js extension signer interface.
24
+ * @param address - The address of the account to sign with.
25
+ * @param data - The data to sign as a string (will be encoded as bytes).
26
+ * @returns Promise resolving to the signature result containing the signature and other metadata.
27
+ *
28
+ * @example
29
+ * import { signMessage } from '@autonomys/auto-utils'
30
+ * import { web3FromAddress } from '@polkadot/extension-dapp'
31
+ *
32
+ * // Sign a message with extension wallet
33
+ * const address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'
34
+ * const injector = await web3FromAddress(address)
35
+ *
36
+ * const message = 'Hello, Autonomys Network!'
37
+ * const signature = await signMessage(injector.signer, address, message)
38
+ *
39
+ * console.log('Signature:', signature.signature)
40
+ * console.log('Signed by:', signature.id)
41
+ *
42
+ * // Sign authentication challenge
43
+ * const challenge = `Login to dApp at ${Date.now()}`
44
+ * const authSignature = await signMessage(injector.signer, address, challenge)
45
+ *
46
+ * // Use signature for verification later
47
+ * const isValid = signatureVerify(challenge, authSignature.signature, address)
48
+ * console.log('Signature valid:', isValid.isValid)
49
+ *
50
+ * @throws {Error} When the signer doesn't support raw signing or signing fails.
51
+ */
16
52
  const signMessage = (signer, address, data) => __awaiter(void 0, void 0, void 0, function* () {
17
53
  if (!signer.signRaw)
18
54
  throw new Error('signRaw not available on the signer');
@@ -23,5 +59,27 @@ const signMessage = (signer, address, data) => __awaiter(void 0, void 0, void 0,
23
59
  });
24
60
  });
25
61
  exports.signMessage = signMessage;
62
+ /**
63
+ * Converts a public key to a hexadecimal string representation.
64
+ *
65
+ * This utility function converts a Uint8Array public key into its hexadecimal
66
+ * string representation, which is useful for display, logging, or storage purposes.
67
+ *
68
+ * @param publicKey - The public key as a Uint8Array.
69
+ * @returns The public key as a hexadecimal string with '0x' prefix.
70
+ *
71
+ * @example
72
+ * import { signingKey } from '@autonomys/auto-utils'
73
+ *
74
+ * // Convert KeyringPair public key to hex
75
+ * const wallet = setupWallet({ uri: '//Alice' })
76
+ * const publicKeyHex = signingKey(wallet.keyringPair.publicKey)
77
+ * console.log('Public key:', publicKeyHex) // Output: "0x..."
78
+ *
79
+ * // Use with signature verification
80
+ * const publicKeyBytes = new Uint8Array(32) // 32-byte public key
81
+ * const hexKey = signingKey(publicKeyBytes)
82
+ * console.log('Hex public key:', hexKey)
83
+ */
26
84
  const signingKey = (publicKey) => (0, format_1.u8aToHex)(publicKey);
27
85
  exports.signingKey = signingKey;
@@ -1,6 +1,77 @@
1
1
  import type { SubmittableResult } from '@polkadot/api';
2
2
  import { KeyringPair } from '@polkadot/keyring/types';
3
3
  import type { AddressOrPair, Events, ISubmittableResult, SignerOptions, SubmittableExtrinsic, TransactionSignedAndSend } from '../types';
4
+ /**
5
+ * Signs and sends a transaction to the Autonomys Network, with comprehensive error handling and event validation.
6
+ *
7
+ * This function handles the complete transaction lifecycle: signing, sending, monitoring for inclusion,
8
+ * and validating expected events. It provides detailed error handling and supports custom error mapping
9
+ * for domain-specific error handling. The function waits for the transaction to be included in a block
10
+ * and validates that expected events were emitted.
11
+ *
12
+ * @param sender - The account to sign and send the transaction. Can be a KeyringPair, address string, or AddressOrPair.
13
+ * @param tx - The submittable extrinsic to sign and send.
14
+ * @param options - Optional signer options including nonce, tip, and other transaction parameters.
15
+ * @param eventsExpected - Array of expected event names to validate. Defaults to successful transaction events.
16
+ * @param log - Whether to log transaction progress to console. Defaults to false.
17
+ * @param mapErrorCodeToEnum - Optional function to map error codes to custom error enums for better error handling.
18
+ * @returns Promise resolving to transaction results including success status, hashes, events, and receipt.
19
+ *
20
+ * @example
21
+ * import { signAndSendTx, activate, setupWallet } from '@autonomys/auto-utils'
22
+ *
23
+ * // Basic transaction signing and sending
24
+ * const api = await activate({ networkId: 'taurus' })
25
+ * const wallet = setupWallet({ uri: '//Alice' })
26
+ *
27
+ * const tx = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000000000n)
28
+ *
29
+ * const result = await signAndSendTx(wallet.keyringPair, tx)
30
+ * if (result.success) {
31
+ * console.log('Transaction successful')
32
+ * console.log('Transaction hash:', result.txHash)
33
+ * console.log('Block hash:', result.blockHash)
34
+ * }
35
+ *
36
+ * // With custom options and event validation
37
+ * const transferTx = api.tx.balances.transfer(receiverAddress, amount)
38
+ * const transferResult = await signAndSendTx(
39
+ * senderKeyringPair,
40
+ * transferTx,
41
+ * { tip: 1000000000000000n }, // Custom tip
42
+ * ['balances.Transfer'], // Expected events
43
+ * true // Enable logging
44
+ * )
45
+ *
46
+ * // With error mapping for custom error handling
47
+ * const stakingTx = api.tx.domains.nominateOperator(operatorId, amount)
48
+ * const stakingResult = await signAndSendTx(
49
+ * nominatorKeyringPair,
50
+ * stakingTx,
51
+ * {},
52
+ * ['domains.OperatorNominated'],
53
+ * false,
54
+ * (errorCode) => {
55
+ * // Map error codes to custom error types
56
+ * switch (errorCode) {
57
+ * case '0': return 'InsufficientBalance'
58
+ * case '1': return 'OperatorNotFound'
59
+ * default: return undefined
60
+ * }
61
+ * }
62
+ * )
63
+ *
64
+ * // Handle Auto-ID registration with identifier extraction
65
+ * const autoIdTx = api.tx.autoId.registerAutoId(autoIdData)
66
+ * const autoIdResult = await signAndSendTx(sender, autoIdTx)
67
+ * if (autoIdResult.identifier) {
68
+ * console.log('Auto-ID registered with identifier:', autoIdResult.identifier)
69
+ * }
70
+ *
71
+ * @throws {Error} When the transaction fails, times out, or expected events are not found.
72
+ * @throws {Error} When the transaction is retracted, dropped, or invalid.
73
+ * @throws {Error} When custom error mapping indicates a specific error condition.
74
+ */
4
75
  export declare const signAndSendTx: <TError>(sender: AddressOrPair | KeyringPair, tx: SubmittableExtrinsic<"promise", ISubmittableResult>, options?: Partial<SignerOptions>, eventsExpected?: Events, log?: boolean, mapErrorCodeToEnum?: (errorCode: string) => TError | undefined) => Promise<TransactionSignedAndSend & {
5
76
  receipt: SubmittableResult;
6
77
  identifier?: string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"signAndSendTx.d.ts","sourceRoot":"","sources":["../../src/utils/signAndSendTx.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AACrD,OAAO,KAAK,EACV,aAAa,EACb,MAAM,EAEN,kBAAkB,EAClB,aAAa,EACb,oBAAoB,EACpB,wBAAwB,EACzB,MAAM,UAAU,CAAA;AAKjB,eAAO,MAAM,aAAa,GAAU,MAAM,EACxC,QAAQ,aAAa,GAAG,WAAW,EACnC,IAAI,oBAAoB,CAAC,SAAS,EAAE,kBAAkB,CAAC,EACvD,UAAS,OAAO,CAAC,aAAa,CAAM,EACpC,iBAAgB,MAAgC,EAChD,MAAK,OAAe,EACpB,qBAAqB,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,KAC7D,OAAO,CACR,wBAAwB,GAAG;IAAE,OAAO,EAAE,iBAAiB,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CA6DtF,CAAA"}
1
+ {"version":3,"file":"signAndSendTx.d.ts","sourceRoot":"","sources":["../../src/utils/signAndSendTx.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AACrD,OAAO,KAAK,EACV,aAAa,EACb,MAAM,EAEN,kBAAkB,EAClB,aAAa,EACb,oBAAoB,EACpB,wBAAwB,EACzB,MAAM,UAAU,CAAA;AAKjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;AACH,eAAO,MAAM,aAAa,GAAU,MAAM,EACxC,QAAQ,aAAa,GAAG,WAAW,EACnC,IAAI,oBAAoB,CAAC,SAAS,EAAE,kBAAkB,CAAC,EACvD,UAAS,OAAO,CAAC,aAAa,CAAM,EACpC,iBAAgB,MAAgC,EAChD,MAAK,OAAe,EACpB,qBAAqB,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,KAC7D,OAAO,CACR,wBAAwB,GAAG;IAAE,OAAO,EAAE,iBAAiB,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CA6DtF,CAAA"}