@beclab/olaresid 0.1.6 → 0.1.8

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.
package/src/index.ts CHANGED
@@ -38,12 +38,7 @@ export {
38
38
  getDIDFromMnemonic,
39
39
  generateDIDKeyData,
40
40
  deriveDIDFromMnemonic,
41
- getEd25519JwkFromMnemonic,
42
- // Cross-platform encoding utilities
43
- base64ToUint8Array,
44
- uint8ArrayToHex,
45
- hexToUint8Array,
46
- uint8ArrayToBase64
41
+ getEd25519JwkFromMnemonic
47
42
  } from './business';
48
43
 
49
44
  type Domain = PackageDomain.Domain;
@@ -518,6 +513,76 @@ export class DIDConsole implements DIDTag.ABITypeProviderHolder {
518
513
  throw new Error(parsedError.message);
519
514
  }
520
515
  }
516
+
517
+ /**
518
+ * Transfer contract ownership to a new owner
519
+ * Only the current contract owner can call this method
520
+ * The new owner must call acceptOwnership() to complete the transfer
521
+ * @param newOwner The address of the new owner
522
+ * @returns Transaction result
523
+ */
524
+ async transferOwnership(newOwner: string): Promise<TransactionResult> {
525
+ try {
526
+ const contract = this.getSignerContractDID();
527
+ const tx = await contract.transferOwnership(newOwner);
528
+ const receipt = await tx.wait();
529
+
530
+ return {
531
+ success: true,
532
+ transactionHash: receipt.hash,
533
+ gasUsed: receipt.gasUsed,
534
+ blockNumber: receipt.blockNumber
535
+ };
536
+ } catch (error) {
537
+ const parsedError = parseContractError(error);
538
+
539
+ // Always throw network errors
540
+ if (parsedError.isNetworkError) {
541
+ throw new Error(`Network error: ${parsedError.message}`);
542
+ }
543
+
544
+ // Return friendly contract error
545
+ return {
546
+ success: false,
547
+ transactionHash: '',
548
+ error: parsedError.message
549
+ };
550
+ }
551
+ }
552
+
553
+ /**
554
+ * Accept ownership transfer
555
+ * Must be called by the pending owner to complete the ownership transfer
556
+ * @returns Transaction result
557
+ */
558
+ async acceptOwnership(): Promise<TransactionResult> {
559
+ try {
560
+ const contract = this.getSignerContractDID();
561
+ const tx = await contract.acceptOwnership();
562
+ const receipt = await tx.wait();
563
+
564
+ return {
565
+ success: true,
566
+ transactionHash: receipt.hash,
567
+ gasUsed: receipt.gasUsed,
568
+ blockNumber: receipt.blockNumber
569
+ };
570
+ } catch (error) {
571
+ const parsedError = parseContractError(error);
572
+
573
+ // Always throw network errors
574
+ if (parsedError.isNetworkError) {
575
+ throw new Error(`Network error: ${parsedError.message}`);
576
+ }
577
+
578
+ // Return friendly contract error
579
+ return {
580
+ success: false,
581
+ transactionHash: '',
582
+ error: parsedError.message
583
+ };
584
+ }
585
+ }
521
586
  }
522
587
 
523
588
  namespace OlaresID {
package/src/tag/tuple.ts CHANGED
@@ -76,8 +76,8 @@ export class Tuple extends Box {
76
76
  // indexInBox = index
77
77
  // }
78
78
 
79
- tag.setFieldNames(names, indexInBox);
80
- index++;
79
+ const nextIndex = tag.setFieldNames(names, index);
80
+ index = nextIndex;
81
81
  }
82
82
  // if (tag instanceof Box) {
83
83
  // // console.log(tag)
@@ -6,13 +6,13 @@
6
6
  * compatibility across the entire Olares ecosystem.
7
7
  */
8
8
 
9
+ import * as bip39 from 'bip39';
9
10
  import * as varint from 'varint';
10
11
  import { base58btc } from 'multiformats/bases/base58';
11
12
  import { base64url } from 'multiformats/bases/base64';
12
13
 
13
14
  // Browser globals type declaration
14
15
  declare const window: any;
15
- declare const atob: (input: string) => string;
16
16
  declare const btoa: (input: string) => string;
17
17
 
18
18
  export interface RSAPublicKeyData {
@@ -26,61 +26,6 @@ export interface DIDKeyData {
26
26
  mnemonic: string;
27
27
  }
28
28
 
29
- // ============================================================================
30
- // Cross-platform encoding utilities (Browser + Node.js compatible)
31
- // ============================================================================
32
-
33
- /**
34
- * Convert base64 string to Uint8Array (cross-platform)
35
- * Works in both browser and Node.js environments
36
- * @param base64 base64 encoded string
37
- * @returns Uint8Array
38
- */
39
- export function base64ToUint8Array(base64: string): Uint8Array {
40
- const binaryString = atob(base64);
41
- const bytes = new Uint8Array(binaryString.length);
42
- for (let i = 0; i < binaryString.length; i++) {
43
- bytes[i] = binaryString.charCodeAt(i);
44
- }
45
- return bytes;
46
- }
47
-
48
- /**
49
- * Convert Uint8Array to hex string (cross-platform)
50
- * @param bytes Uint8Array to convert
51
- * @returns hex string without '0x' prefix
52
- */
53
- export function uint8ArrayToHex(bytes: Uint8Array): string {
54
- return Array.from(bytes)
55
- .map((b) => b.toString(16).padStart(2, '0'))
56
- .join('');
57
- }
58
-
59
- /**
60
- * Convert hex string to Uint8Array (cross-platform)
61
- * @param hex hex string (with or without '0x' prefix)
62
- * @returns Uint8Array
63
- */
64
- export function hexToUint8Array(hex: string): Uint8Array {
65
- const cleanHex = hex.startsWith('0x') ? hex.slice(2) : hex;
66
- const bytes = new Uint8Array(cleanHex.length / 2);
67
- for (let i = 0; i < cleanHex.length; i += 2) {
68
- bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);
69
- }
70
- return bytes;
71
- }
72
-
73
- /**
74
- * Convert Uint8Array to base64 string (cross-platform)
75
- * Works in both browser and Node.js environments
76
- * @param bytes Uint8Array to convert
77
- * @returns base64 encoded string
78
- */
79
- export function uint8ArrayToBase64(bytes: Uint8Array): string {
80
- const binaryString = String.fromCharCode(...bytes);
81
- return btoa(binaryString);
82
- }
83
-
84
29
  // ============================================================================
85
30
  // Trust Wallet Core Management
86
31
  // ============================================================================
@@ -92,7 +37,6 @@ let loadingPromise: Promise<any> | null = null;
92
37
  /**
93
38
  * Load Trust Wallet Core (lazy loading)
94
39
  * Works in both Node.js and browser environments
95
- * Handles different module export formats (CommonJS vs ESM)
96
40
  */
97
41
  async function loadWalletCore(): Promise<any> {
98
42
  // Return cached instance if already loaded
@@ -108,33 +52,18 @@ async function loadWalletCore(): Promise<any> {
108
52
  // Start loading
109
53
  loadingPromise = (async () => {
110
54
  try {
111
- // Dynamic import works in both Node.js ESM and browser ESM
112
- const WalletCoreModule = await import('@trustwallet/wallet-core');
113
-
114
- // Handle different export formats (CommonJS vs ESM)
115
- let initWasmFunc: any;
116
- if (WalletCoreModule.initWasm) {
117
- // ESM named export
118
- initWasmFunc = WalletCoreModule.initWasm;
119
- } else if (
120
- WalletCoreModule.default &&
121
- (WalletCoreModule.default as any).initWasm
55
+ // Check if running in browser or Node.js
56
+ if (
57
+ typeof window !== 'undefined' &&
58
+ typeof require === 'undefined'
122
59
  ) {
123
- // ESM default export with initWasm
124
- initWasmFunc = (WalletCoreModule.default as any).initWasm;
125
- } else if (WalletCoreModule.default) {
126
- // Default export is the function itself
127
- initWasmFunc = WalletCoreModule.default;
128
- } else {
129
- // Module itself is the function
130
- initWasmFunc = WalletCoreModule as any;
131
- }
132
-
133
- // Call the init function
134
- if (typeof initWasmFunc === 'function') {
135
- walletCore = await initWasmFunc();
60
+ // Browser environment with ES modules
61
+ const { initWasm } = await import('@trustwallet/wallet-core');
62
+ walletCore = await initWasm();
136
63
  } else {
137
- throw new Error('initWasm is not a function');
64
+ // Node.js environment
65
+ const { initWasm } = require('@trustwallet/wallet-core');
66
+ walletCore = await initWasm();
138
67
  }
139
68
 
140
69
  walletCoreLoaded = true;
@@ -155,38 +84,23 @@ async function loadWalletCore(): Promise<any> {
155
84
  // multicodec code for Ed25519 keys (0xed)
156
85
  const ED25519_CODEC_ID = varint.encode(parseInt('0xed', 16));
157
86
 
158
- /**
159
- * Simple mnemonic validation (checks word count)
160
- * @param mnemonic BIP39 mnemonic phrase
161
- * @returns true if mnemonic has valid word count (12, 15, 18, 21, or 24 words)
162
- */
163
- function validateMnemonic(mnemonic: string): boolean {
164
- const words = mnemonic.trim().split(/\s+/);
165
- const validWordCounts = [12, 15, 18, 21, 24];
166
- return validWordCounts.includes(words.length);
167
- }
168
-
169
87
  // ============================================================================
170
88
  // Mnemonic and Key Derivation Functions
171
89
  // ============================================================================
172
90
 
173
91
  /**
174
- * Generate a random BIP39 mnemonic phrase using Trust Wallet Core
175
- * Works in both Node.js and browser environments
176
- *
92
+ * Generate a random BIP39 mnemonic phrase
177
93
  * @param wordCount Number of words (12, 15, 18, 21, or 24), default is 12
178
- * @returns A promise that resolves to a mnemonic phrase string
94
+ * @returns A mnemonic phrase string
179
95
  *
180
96
  * @example
181
97
  * ```typescript
182
- * const mnemonic = await generateMnemonic(12);
98
+ * const mnemonic = generateMnemonic(12);
183
99
  * console.log(mnemonic);
184
100
  * // Output: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
185
101
  * ```
186
102
  */
187
- export async function generateMnemonic(
188
- wordCount: number = 12
189
- ): Promise<string> {
103
+ export function generateMnemonic(wordCount: number = 12): string {
190
104
  // Convert word count to entropy bits
191
105
  // 12 words = 128 bits, 15 words = 160 bits, etc.
192
106
  const strengthMap: Record<number, number> = {
@@ -204,14 +118,7 @@ export async function generateMnemonic(
204
118
  );
205
119
  }
206
120
 
207
- // Ensure Wallet Core is loaded
208
- const core = await loadWalletCore();
209
- const { HDWallet } = core;
210
-
211
- const wallet = HDWallet.create(strength, '');
212
- const mnemonic = wallet.mnemonic();
213
-
214
- return mnemonic;
121
+ return bip39.generateMnemonic(strength);
215
122
  }
216
123
 
217
124
  /**
@@ -231,10 +138,8 @@ export async function getEthereumAddressFromMnemonic(
231
138
  mnemonic: string
232
139
  ): Promise<string> {
233
140
  // Validate mnemonic
234
- if (!validateMnemonic(mnemonic)) {
235
- throw new Error(
236
- 'Invalid mnemonic phrase: must have 12, 15, 18, 21, or 24 words'
237
- );
141
+ if (!bip39.validateMnemonic(mnemonic)) {
142
+ throw new Error('Invalid mnemonic phrase');
238
143
  }
239
144
 
240
145
  const core = await loadWalletCore();
@@ -262,10 +167,8 @@ export async function getEVMPrivateKeyFromMnemonic(
262
167
  mnemonic: string
263
168
  ): Promise<string> {
264
169
  // Validate mnemonic
265
- if (!validateMnemonic(mnemonic)) {
266
- throw new Error(
267
- 'Invalid mnemonic phrase: must have 12, 15, 18, 21, or 24 words'
268
- );
170
+ if (!bip39.validateMnemonic(mnemonic)) {
171
+ throw new Error('Invalid mnemonic phrase');
269
172
  }
270
173
 
271
174
  const core = await loadWalletCore();
@@ -276,9 +179,9 @@ export async function getEVMPrivateKeyFromMnemonic(
276
179
  // Get private key for Ethereum
277
180
  const privateKeyData = wallet.getKeyForCoin(CoinType.ethereum);
278
181
 
279
- // Convert to hex string with 0x prefix (cross-platform)
280
- const privateKeyBytes = new Uint8Array(privateKeyData.data());
281
- const privateKeyHex = '0x' + uint8ArrayToHex(privateKeyBytes);
182
+ // Convert to hex string with 0x prefix
183
+ const privateKeyHex =
184
+ '0x' + Buffer.from(privateKeyData.data()).toString('hex');
282
185
 
283
186
  return privateKeyHex;
284
187
  }
@@ -327,10 +230,8 @@ async function getID(mnemonic: string): Promise<string> {
327
230
  */
328
231
  export async function getDIDFromMnemonic(mnemonic: string): Promise<string> {
329
232
  // Validate mnemonic
330
- if (!validateMnemonic(mnemonic)) {
331
- throw new Error(
332
- 'Invalid mnemonic phrase: must have 12, 15, 18, 21, or 24 words'
333
- );
233
+ if (!bip39.validateMnemonic(mnemonic)) {
234
+ throw new Error('Invalid mnemonic phrase');
334
235
  }
335
236
 
336
237
  const id = await getID(mnemonic);
@@ -377,10 +278,8 @@ export async function getEd25519JwkFromMnemonic(mnemonic: string): Promise<{
377
278
  privateJwk: any;
378
279
  }> {
379
280
  // Validate mnemonic
380
- if (!validateMnemonic(mnemonic)) {
381
- throw new Error(
382
- 'Invalid mnemonic phrase: must have 12, 15, 18, 21, or 24 words'
383
- );
281
+ if (!bip39.validateMnemonic(mnemonic)) {
282
+ throw new Error('Invalid mnemonic phrase');
384
283
  }
385
284
 
386
285
  const core = await loadWalletCore();
@@ -443,10 +342,8 @@ export async function deriveDIDFromMnemonic(mnemonic: string): Promise<{
443
342
  did: string;
444
343
  }> {
445
344
  // Validate mnemonic once upfront
446
- if (!validateMnemonic(mnemonic)) {
447
- throw new Error(
448
- 'Invalid mnemonic phrase: must have 12, 15, 18, 21, or 24 words'
449
- );
345
+ if (!bip39.validateMnemonic(mnemonic)) {
346
+ throw new Error('Invalid mnemonic phrase');
450
347
  }
451
348
 
452
349
  // Derive both in parallel for better performance
@@ -475,7 +372,7 @@ export async function deriveDIDFromMnemonic(mnemonic: string): Promise<{
475
372
  export async function generateDIDKeyData(
476
373
  wordCount: number = 12
477
374
  ): Promise<DIDKeyData> {
478
- const mnemonic = await generateMnemonic(wordCount);
375
+ const mnemonic = generateMnemonic(wordCount);
479
376
  const { owner, did } = await deriveDIDFromMnemonic(mnemonic);
480
377
 
481
378
  return {
@@ -1,96 +0,0 @@
1
- /**
2
- * Test encoding utilities exported from olaresid
3
- */
4
-
5
- import {
6
- base64ToUint8Array,
7
- uint8ArrayToHex,
8
- hexToUint8Array,
9
- uint8ArrayToBase64
10
- } from '../src/index';
11
-
12
- async function main() {
13
- console.log('============================================================');
14
- console.log('Testing Cross-platform Encoding Utilities');
15
- console.log(
16
- '============================================================\n'
17
- );
18
-
19
- // Test data
20
- const testString = 'Hello, Olares!';
21
- const testBytes = new TextEncoder().encode(testString);
22
-
23
- console.log('📝 Original text:', testString);
24
- console.log('📦 Original bytes:', testBytes);
25
- console.log('');
26
-
27
- // Test 1: Uint8Array to Hex
28
- console.log('🔄 Test 1: uint8ArrayToHex()');
29
- console.log('------------------------------------------------------------');
30
- const hexString = uint8ArrayToHex(testBytes);
31
- console.log('✅ Hex string:', hexString);
32
- console.log('');
33
-
34
- // Test 2: Hex to Uint8Array
35
- console.log('🔄 Test 2: hexToUint8Array()');
36
- console.log('------------------------------------------------------------');
37
- const bytesFromHex = hexToUint8Array(hexString);
38
- console.log('✅ Bytes from hex:', bytesFromHex);
39
- console.log(
40
- '✅ Matches original:',
41
- JSON.stringify(bytesFromHex) === JSON.stringify(testBytes)
42
- );
43
- console.log('');
44
-
45
- // Test 3: Uint8Array to Base64
46
- console.log('🔄 Test 3: uint8ArrayToBase64()');
47
- console.log('------------------------------------------------------------');
48
- const base64String = uint8ArrayToBase64(testBytes);
49
- console.log('✅ Base64 string:', base64String);
50
- console.log('');
51
-
52
- // Test 4: Base64 to Uint8Array
53
- console.log('🔄 Test 4: base64ToUint8Array()');
54
- console.log('------------------------------------------------------------');
55
- const bytesFromBase64 = base64ToUint8Array(base64String);
56
- console.log('✅ Bytes from base64:', bytesFromBase64);
57
- console.log(
58
- '✅ Matches original:',
59
- JSON.stringify(bytesFromBase64) === JSON.stringify(testBytes)
60
- );
61
- console.log('');
62
-
63
- // Test 5: Round-trip conversion
64
- console.log('🔄 Test 5: Round-trip conversion (hex)');
65
- console.log('------------------------------------------------------------');
66
- const hex1 = uint8ArrayToHex(testBytes);
67
- const bytes1 = hexToUint8Array(hex1);
68
- const hex2 = uint8ArrayToHex(bytes1);
69
- console.log('✅ Round-trip hex successful:', hex1 === hex2);
70
- console.log('');
71
-
72
- console.log('🔄 Test 6: Round-trip conversion (base64)');
73
- console.log('------------------------------------------------------------');
74
- const b64_1 = uint8ArrayToBase64(testBytes);
75
- const bytes2 = base64ToUint8Array(b64_1);
76
- const b64_2 = uint8ArrayToBase64(bytes2);
77
- console.log('✅ Round-trip base64 successful:', b64_1 === b64_2);
78
- console.log('');
79
-
80
- // Test 7: Hex with 0x prefix
81
- console.log('🔄 Test 7: Hex with 0x prefix');
82
- console.log('------------------------------------------------------------');
83
- const hexWithPrefix = '0x' + hexString;
84
- const bytesFromPrefixedHex = hexToUint8Array(hexWithPrefix);
85
- console.log(
86
- '✅ Can handle 0x prefix:',
87
- JSON.stringify(bytesFromPrefixedHex) === JSON.stringify(testBytes)
88
- );
89
- console.log('');
90
-
91
- console.log('============================================================');
92
- console.log('✅ All encoding utility tests passed!');
93
- console.log('============================================================');
94
- }
95
-
96
- main().catch(console.error);
@@ -1,40 +0,0 @@
1
- # Dependencies
2
- node_modules
3
- npm-debug.log*
4
- yarn-debug.log*
5
- yarn-error.log*
6
- pnpm-debug.log*
7
-
8
- # Build output
9
- dist
10
- .vite
11
-
12
- # Environment files
13
- .env
14
- .env.local
15
- .env.*.local
16
-
17
- # IDE
18
- .vscode
19
- .idea
20
- *.swp
21
- *.swo
22
- *~
23
-
24
- # OS
25
- .DS_Store
26
- Thumbs.db
27
-
28
- # Git
29
- .git
30
- .gitignore
31
- .github
32
-
33
- # Documentation
34
- README.md
35
- QUICKSTART.md
36
- *.md
37
-
38
- # Logs
39
- logs
40
- *.log