gun-eth 1.3.6 → 2.0.0

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 (52) hide show
  1. package/README.md +18 -207
  2. package/dist/gun-eth-protocol.cjs.js +11528 -0
  3. package/dist/gun-eth-protocol.esm.js +11503 -0
  4. package/dist/gun-eth-protocol.js +18 -0
  5. package/dist/gun-eth-protocol.react.js +11503 -0
  6. package/dist/gun-eth-protocol.umd.js +18 -0
  7. package/jsdoc.json +7 -0
  8. package/package.json +28 -25
  9. package/rollup.config.js +80 -0
  10. package/src/index.js +160 -512
  11. package/src/lib/authentication/index.js +13 -0
  12. package/src/lib/authentication/isAuthenticated.js +20 -0
  13. package/src/lib/authentication/login.js +25 -0
  14. package/src/lib/authentication/register.js +58 -0
  15. package/src/lib/blockchain/ethereum.js +74 -0
  16. package/src/lib/blockchain/shine.js +204 -0
  17. package/src/lib/certificates/friendsCertificates.js +92 -0
  18. package/src/lib/certificates/index.js +44 -0
  19. package/src/lib/certificates/messagingCertificates.js +94 -0
  20. package/src/lib/friends/acceptFriendRequest.js +69 -0
  21. package/src/lib/friends/addFriendRequest.js +49 -0
  22. package/src/lib/friends/friendRequests.js +51 -0
  23. package/src/lib/friends/friendsList.js +57 -0
  24. package/src/lib/friends/index.js +36 -0
  25. package/src/lib/friends/rejectFriendRequest.js +31 -0
  26. package/src/lib/messaging/chatsList.js +42 -0
  27. package/src/lib/messaging/createChat.js +132 -0
  28. package/src/lib/messaging/index.js +36 -0
  29. package/src/lib/messaging/messageList.js +106 -0
  30. package/src/lib/messaging/sendMessage.js +132 -0
  31. package/src/lib/messaging/sendVoiceMessage.js +119 -0
  32. package/src/lib/notes/createNote.js +41 -0
  33. package/src/lib/notes/deleteNote.js +12 -0
  34. package/src/lib/notes/getNote.js +25 -0
  35. package/src/lib/notes/getUserNote.js +59 -0
  36. package/src/lib/notes/index.js +8 -0
  37. package/src/lib/notes/updateNotes.js +35 -0
  38. package/src/lib/post/createPost.js +17 -0
  39. package/src/lib/post/decryptPost.js +14 -0
  40. package/src/lib/post/deletePost.js +13 -0
  41. package/src/lib/post/encryptPost,js +16 -0
  42. package/src/lib/post/getPost.js +36 -0
  43. package/src/lib/post/index.js +9 -0
  44. package/src/lib/post/updatePost.js +16 -0
  45. package/src/state/gun.js +33 -0
  46. package/types/types.d.ts +244 -0
  47. package/TUTORIAL.md +0 -103
  48. package/src/examples/eth2gun.html +0 -163
  49. package/src/examples/gun2eth.html +0 -164
  50. package/src/examples/shine.html +0 -256
  51. /package/src/{abis → lib/blockchain/abis}/SHINE.json +0 -0
  52. /package/src/{contracts → lib/blockchain/contracts}/SHINE.sol +0 -0
@@ -0,0 +1,244 @@
1
+ /**
2
+ * This contains a subscribable function that will return a boolean of whether or not the user is authenticated or not.
3
+ */
4
+ declare var isAuthenticated: any;
5
+
6
+ /**
7
+ * This function will check and see whether the user is authenticated or not.
8
+ */
9
+ declare function checkAuth(): void;
10
+
11
+ /**
12
+ * This function will authenticate a user who has registered.
13
+ * @param credentials - The users authentication credentials that they used when registering.
14
+ * @param callback - The callback function returns error messages or a success message.
15
+ */
16
+ declare function loginUser(credentials: {
17
+ username: any;
18
+ password: any;
19
+ }, callback: (...params: any[]) => any): void;
20
+
21
+ /**
22
+ * This function will check to see if the email is already in use.
23
+ * @returns Promise<boolean>
24
+ */
25
+ declare function checkUsernameInUse(username: string): any;
26
+
27
+ /**
28
+ * This function will create a user.
29
+ * @param credentials - The users authentication credentials that they want to use when logging in.
30
+ * @param callback - The callback function returns error messages or a success message.
31
+ */
32
+ declare function registerUser(credentials: {
33
+ username: any;
34
+ password: any;
35
+ }, callback: (...params: any[]) => any): void;
36
+
37
+ /**
38
+ * Genera un certificato per le richieste di amicizia.
39
+ * @param callback - Funzione di callback chiamata al completamento dell'operazione.
40
+ */
41
+ declare function generateFriendRequestsCertificate(callback: (...params: any[]) => any): Promise<void>;
42
+
43
+ /**
44
+ * Genera un certificato per aggiungere un amico.
45
+ * @param publicKey - Chiave pubblica dell'amico da aggiungere.
46
+ * @param callback - Funzione di callback chiamata al completamento dell'operazione.
47
+ */
48
+ declare function generateAddFriendCertificate(publicKey: string, callback: (...params: any[]) => any): Promise<void>;
49
+
50
+ /**
51
+ * Modulo per la gestione dei certificati nell'applicazione.
52
+ */
53
+ declare module "certificates" { }
54
+
55
+ /**
56
+ * Crea un certificato per le chat con un utente specifico.
57
+ * @param publicKey - La chiave pubblica dell'utente per cui creare il certificato.
58
+ * @param [callback] - Funzione di callback opzionale chiamata al completamento dell'operazione.
59
+ */
60
+ declare function createChatsCertificate(publicKey: string, callback?: (...params: any[]) => any): Promise<void>;
61
+
62
+ /**
63
+ * Crea un certificato per i messaggi con un utente specifico.
64
+ * @param publicKey - La chiave pubblica dell'utente per cui creare il certificato.
65
+ * @param [callback] - Funzione di callback opzionale chiamata al completamento dell'operazione.
66
+ */
67
+ declare function createMessagesCertificate(publicKey: string, callback?: (...params: any[]) => any): Promise<void>;
68
+
69
+ /**
70
+ * Accetta una richiesta di amicizia.
71
+ * @param params - Parametri della funzione.
72
+ * @param params.key - Chiave della richiesta di amicizia.
73
+ * @param params.publicKey - Chiave pubblica dell'utente che ha inviato la richiesta.
74
+ * @param [callback] - Funzione di callback opzionale.
75
+ */
76
+ declare function acceptFriendRequest(params: {
77
+ key: string;
78
+ publicKey: string;
79
+ }, callback?: (...params: any[]) => any): void;
80
+
81
+ /**
82
+ * Invia una richiesta di amicizia a un utente specifico.
83
+ * @param publicKey - La chiave pubblica dell'utente a cui inviare la richiesta di amicizia.
84
+ * @param [callback] - Funzione di callback opzionale chiamata al completamento dell'operazione.
85
+ */
86
+ declare function addFriendRequest(publicKey: string, callback?: (...params: any[]) => any): Promise<void>;
87
+
88
+ /**
89
+ * Questo Observable emette oggetti contenenti informazioni sulle richieste di amicizia.
90
+ Ogni oggetto emesso può avere le seguenti proprietà:
91
+ - key: La chiave della richiesta di amicizia
92
+ - pub: La chiave pubblica dell'utente che ha inviato la richiesta
93
+ - alias: L'alias dell'utente che ha inviato la richiesta
94
+ - displayName: Il nome visualizzato dell'utente (se disponibile)
95
+ - about: Informazioni aggiuntive sull'utente (se disponibili)
96
+
97
+ Se non ci sono richieste di amicizia, l'Observable emetterà `undefined`.
98
+ */
99
+ declare var friendRequests: Observable;
100
+
101
+ /**
102
+ * Modulo per la gestione della lista degli amici.
103
+ */
104
+ declare module "friendsList" {
105
+ /**
106
+ * Questo Observable emette oggetti contenenti informazioni sugli amici dell'utente.
107
+ Ogni oggetto emesso può avere le seguenti proprietà:
108
+ - key: La chiave dell'amico
109
+ - pub: La chiave pubblica dell'amico
110
+ - alias: L'alias dell'amico
111
+ - displayName: Il nome visualizzato dell'amico (se disponibile)
112
+ - about: Informazioni aggiuntive sull'amico (se disponibili)
113
+
114
+ Se non ci sono amici nella lista, l'Observable emetterà `undefined`.
115
+ */
116
+ var friendsList: Observable;
117
+ }
118
+
119
+ /**
120
+ * Modulo per la gestione delle amicizie
121
+ */
122
+ declare module "friends" {
123
+ /**
124
+ * Aggiunge una richiesta di amicizia
125
+ */
126
+ var addFriendRequest: any;
127
+ /**
128
+ * Accetta una richiesta di amicizia
129
+ */
130
+ var acceptFriendRequest: any;
131
+ /**
132
+ * Rifiuta una richiesta di amicizia
133
+ */
134
+ var rejectFriendRequest: any;
135
+ /**
136
+ * Ottiene l'elenco delle richieste di amicizia
137
+ */
138
+ var friendRequests: any;
139
+ /**
140
+ * Ottiene l'elenco degli amici
141
+ */
142
+ var friendsList: any;
143
+ }
144
+
145
+ /**
146
+ * Rifiuta una richiesta di amicizia.
147
+ * @param key - La chiave della richiesta di amicizia da rifiutare.
148
+ * @param [callback] - Funzione di callback opzionale chiamata al completamento dell'operazione.
149
+ */
150
+ declare function rejectFriendRequest(key: string, callback?: (...params: any[]) => any): void;
151
+
152
+ /**
153
+ * Questo Observable si sottoscrive ai cambiamenti nella lista delle chat dell'utente
154
+ e emette un nuovo oggetto per ogni chat aggiornata. Ogni oggetto chat contiene:
155
+ - roomId: l'identificatore univoco della stanza di chat
156
+ - pub: la chiave pubblica associata alla chat
157
+ - latestMessage: l'ultimo messaggio nella chat
158
+ * @example
159
+ * chatsList.subscribe(chat => {
160
+ console.log('Chat aggiornata:', chat);
161
+ });
162
+ */
163
+ declare var chatsList: Observable;
164
+
165
+ /**
166
+ * Modulo per la creazione di una nuova chat.
167
+ */
168
+ declare module "createChat" {
169
+ /**
170
+ * Questa funzione crea una nuova chat tra l'utente corrente e un altro utente specificato dalla sua chiave pubblica.
171
+ Verifica prima se la chat esiste già, poi controlla i certificati necessari e infine crea la chat per entrambi gli utenti.
172
+ * @example
173
+ * createChat("chiavePubblicaUtente", (result) => {
174
+ if (result.success) {
175
+ console.log("Chat creata:", result.chat);
176
+ } else {
177
+ console.error("Errore:", result.errMessage);
178
+ }
179
+ });
180
+ * @param publicKey - La chiave pubblica dell'utente con cui creare la chat.
181
+ * @param [callback] - Funzione di callback opzionale chiamata al completamento dell'operazione.
182
+ */
183
+ function createChat(publicKey: string, callback?: (...params: any[]) => any): Promise<void>;
184
+ }
185
+
186
+ /**
187
+ * Modulo per la gestione dei messaggi e delle chat
188
+ */
189
+ declare module "messaging" {
190
+ /**
191
+ * Crea una nuova chat
192
+ */
193
+ var createChat: any;
194
+ /**
195
+ * Ottiene la lista delle chat
196
+ */
197
+ var chatsList: any;
198
+ /**
199
+ * Ottiene la lista dei messaggi di una chat
200
+ */
201
+ var messageList: any;
202
+ /**
203
+ * Invia un messaggio di testo
204
+ */
205
+ var sendMessage: any;
206
+ /**
207
+ * Invia un messaggio vocale
208
+ */
209
+ var sendVoiceMessage: any;
210
+ }
211
+
212
+ /**
213
+ * Questa funzione crea un Observable che si sottoscrive ai messaggi di una specifica chat.
214
+ Decripta i messaggi utilizzando la chiave pubblica dell'altro utente e emette sia un array iniziale
215
+ di messaggi che singoli messaggi man mano che vengono ricevuti.
216
+ * @example
217
+ * const messages$ = messageList('room123', 'publicKey123');
218
+ messages$.subscribe(({ initial, individual }) => {
219
+ if (initial) {
220
+ console.log('Messaggi iniziali:', initial);
221
+ } else if (individual) {
222
+ console.log('Nuovo messaggio:', individual);
223
+ }
224
+ });
225
+ * @param roomId - L'identificatore univoco della stanza di chat.
226
+ * @param pub - La chiave pubblica dell'altro utente nella chat.
227
+ * @returns Un Observable che emette oggetti contenenti messaggi iniziali e individuali.
228
+ */
229
+ declare function messageList(roomId: string, pub: string): Observable;
230
+
231
+ /**
232
+ * Modulo per l'inizializzazione e la configurazione di Gun.js
233
+ */
234
+ declare module "gun" {
235
+ /**
236
+ * Inizializza un'istanza di Gun con configurazioni specifiche
237
+ */
238
+ var gun: Gun;
239
+ /**
240
+ * Inizializza un utente Gun e richiama la sessione da sessionStorage
241
+ */
242
+ var user: GunUser;
243
+ }
244
+
package/TUTORIAL.md DELETED
@@ -1,103 +0,0 @@
1
- # Tutorial: Illuminating Your Data with SHINE in GunDB 🌟
2
-
3
- Hey there, GunDB aficionado! Ready to take your decentralized data game to the next level? Enter SHINE: your ticket to blockchain-verified data integrity. It's not just about storing data anymore; it's about making it cryptographically awesome!
4
-
5
- ## Step 0: Wallet Integration - Your Blockchain Passport
6
-
7
- Before we dive into the SHINE pool, remember: this plugin requires a browser-based wallet provider. Think of it as your blockchain passport. Here's how to check if you're ready to roll:
8
-
9
- ```javascript
10
- async function connectWallet() {
11
- if (typeof window.ethereum !== "undefined") {
12
- console.log("Ethereum object detected");
13
- try {
14
- await window.ethereum.request({ method: "eth_requestAccounts" });
15
- console.log("Wallet connected successfully");
16
- return true;
17
- } catch (error) {
18
- console.error("Wallet connection denied:", error);
19
- return false;
20
- }
21
- } else {
22
- console.log(
23
- "Please install MetaMask or another Ethereum-compatible wallet"
24
- );
25
- return false;
26
- }
27
- }
28
-
29
- // Make sure to call this before using SHINE
30
- await connectWallet();
31
- ```
32
-
33
- Pro tip: Always ensure your wallet is connected before invoking SHINE functions. No wallet, no blockchain magic!
34
-
35
- ## Step 1: Installation - Equipping Your Toolbelt
36
-
37
- Let's add SHINE to your development arsenal:
38
-
39
- ```bash
40
- npm install gun-eth
41
- ```
42
-
43
- If your terminal responds without errors, you're locked and loaded!
44
-
45
- ## Step 2: Import - Assembling the Pieces
46
-
47
- Time to bring Gun and SHINE into your JavaScript playground:
48
-
49
- ```javascript
50
- import Gun from "gun";
51
- import "gun-eth";
52
- const gun = Gun();
53
- ```
54
-
55
- ## Step 3: SHINE in Action - Blockchain Meets Database
56
-
57
- Let's say you've got some mission-critical data to store. Here's how you'd use SHINE to give it that blockchain-grade integrity:
58
-
59
- ```javascript
60
- const criticalData = {
61
- key1: "Encrypted message",
62
- key2: "Top secret algorithm",
63
- key3: "42",
64
- };
65
-
66
- gun.shine("optimismSepolia", null, criticalData, (ack) => {
67
- if (ack.ok) {
68
- console.log("Data successfully anchored to the blockchain");
69
- console.log("Node ID for future reference:", ack.nodeId);
70
- } else {
71
- console.error("Blockchain anchoring failed:", ack.err);
72
- }
73
- });
74
- ```
75
-
76
- Remember, your wallet needs to be ready to sign this transaction. It's like pushing code without commit access - it just won't fly!
77
-
78
- ## Step 4: Verification - Trust the Crypto, Not the Hearsay
79
-
80
- When it's time to verify your data's integrity:
81
-
82
- ```javascript
83
- const nodeId = "your-data-node-id";
84
- gun.shine("optimismSepolia", nodeId, null, (ack) => {
85
- if (ack.ok) {
86
- console.log("Data integrity verified on the blockchain");
87
- console.log("Timestamp:", ack.timestamp);
88
- console.log("Last updater:", ack.updater);
89
- } else {
90
- console.error("Integrity check failed:", ack.err);
91
- }
92
- });
93
- ```
94
-
95
- Again, wallet connection is crucial. No blockchain access, no verification!
96
-
97
- ## Step 5: Reap the Benefits
98
-
99
- Congratulations! You've just leveled up your data management game. Your data is now cryptographically verifiable, tamper-evident, and blockchain-secured.
100
-
101
- Remember: With SHINE, you're not just storing data; you're creating a cryptographic proof of its existence and integrity. Use this power wisely!
102
-
103
- P.S. SHINE responsibly. With great cryptographic power comes great responsibility. Happy coding, and may your data always maintain its integrity! 🚀🔐
@@ -1,163 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <title>💎 Ethereum to 🔫 Gun Key Pair Demo</title>
6
- <!-- Include Gun -->
7
- <script src="https://cdn.jsdelivr.net/npm/gun/gun.js"></script>
8
- <!-- Include SEA (part of Gun) -->
9
- <script src="https://cdn.jsdelivr.net/npm/gun/sea.js"></script>
10
- <!-- Include Ethers.js -->
11
- <script src="https://cdnjs.cloudflare.com/ajax/libs/ethers/6.7.0/ethers.umd.min.js"></script>
12
- <!-- Include the Gun-Eth plugin -->
13
- <script src="https://cdn.jsdelivr.net/npm/gun-eth/src/gun-eth.js""></script>
14
- <style>
15
- body {
16
- font-family: Arial, sans-serif;
17
- margin: 0;
18
- padding: 20px;
19
- background-color: #f0f0f0;
20
- }
21
- .container {
22
- max-width: 400px;
23
- background-color: white;
24
- border: 1px solid #000;
25
- padding: 10px;
26
- }
27
- h1,
28
- h2 {
29
- margin: 0 0 10px 0;
30
- font-size: 16px;
31
- }
32
- form, div {
33
- margin-bottom: 15px;
34
- }
35
- input,
36
- button {
37
- display: inline-block;
38
- margin: 2px 0;
39
- padding: 2px;
40
- font-size: 12px;
41
- }
42
- input {
43
- width: 150px;
44
- }
45
- button {
46
- width: 100px;
47
- }
48
- label {
49
- display: inline-block;
50
- width: 70px;
51
- font-size: 12px;
52
- }
53
- #configStatus,
54
- .result {
55
- font-weight: bold;
56
- margin-bottom: 10px;
57
- }
58
- .result {
59
- color: blue;
60
- }
61
- </style>
62
- </head>
63
- <body>
64
- <div class="container">
65
- <h1>💎 Ethereum to 🔫 Gun Key Pair Demo</h1>
66
-
67
- <form id="configForm">
68
- <h2>🔧 Configuration</h2>
69
- <label for="rpcUrl">🌐 RPC URL:</label>
70
- <br>
71
- <input type="text" id="rpcUrl" name="rpcUrl" required>
72
- <br>
73
- <label for="privateKey">🔑 Private Key:</label>
74
- <br>
75
- <input type="password" id="privateKey" name="privateKey" required>
76
- <br>
77
- <button type="submit">⚙️ Configure</button>
78
- </form>
79
-
80
- <div id="createPairSection">
81
- <h2>🔒 Create and Store Encrypted Pair</h2>
82
- <button id="createPairBtn">🔐 Create Pair</button>
83
- </div>
84
-
85
- <div id="retrievePairSection">
86
- <h2>🔓 Retrieve and Decrypt Pair</h2>
87
- <button id="retrievePairBtn">🔎 Retrieve Pair</button>
88
- </div>
89
-
90
- <div id="resultSection">
91
- <h2>📊 Result</h2>
92
- <p id="resultText"></p>
93
- </div>
94
- </div>
95
-
96
- <script>
97
- let gun;
98
- const MESSAGE_TO_SIGN = "GunDB access with Ethereum";
99
-
100
- document.getElementById('configForm').addEventListener('submit', function(event) {
101
- event.preventDefault();
102
- const rpcUrl = document.getElementById('rpcUrl').value;
103
- const privateKey = document.getElementById('privateKey').value;
104
-
105
- gun = Gun();
106
- gun.setStandaloneConfig(rpcUrl, privateKey);
107
-
108
- console.log('Standalone configuration set');
109
- document.getElementById('resultText').innerText = '✅ Configuration set successfully';
110
- });
111
-
112
- document.getElementById('createPairBtn').addEventListener('click', async function() {
113
- if (!gun) {
114
- alert('⚠️ Please configure Gun first');
115
- return;
116
- }
117
-
118
- try {
119
- const signature = await gun.createSignature(MESSAGE_TO_SIGN);
120
- if (!signature) {
121
- throw new Error('Failed to create signature');
122
- }
123
-
124
- const signer = new ethers.Wallet(document.getElementById('privateKey').value);
125
- const address = await signer.getAddress();
126
-
127
- await gun.createAndStoreEncryptedPair(address, signature);
128
-
129
- document.getElementById('resultText').innerText = '✅ Encrypted pair created and stored successfully';
130
- } catch (error) {
131
- document.getElementById('resultText').innerText = '❌ Error: ' + error.message;
132
- }
133
- });
134
-
135
- document.getElementById('retrievePairBtn').addEventListener('click', async function() {
136
- if (!gun) {
137
- alert('⚠️ Please configure Gun first');
138
- return;
139
- }
140
-
141
- try {
142
- const signature = await gun.createSignature(MESSAGE_TO_SIGN);
143
- if (!signature) {
144
- throw new Error('Failed to create signature');
145
- }
146
-
147
- const signer = new ethers.Wallet(document.getElementById('privateKey').value);
148
- const address = await signer.getAddress();
149
-
150
- const pair = await gun.getAndDecryptPair(address, signature);
151
-
152
- document.getElementById('resultText').innerHTML = `
153
- <strong>🔑 Retrieved pair:</strong>
154
- <br>
155
- ${JSON.stringify(pair, null, 2)}
156
- `;
157
- } catch (error) {
158
- document.getElementById('resultText').innerText = '❌ Error: ' + error.message;
159
- }
160
- });
161
- </script>
162
- </body>
163
- </html>
@@ -1,164 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <title>Gun to Ethereum Address Demo</title>
6
- <!-- Include Gun -->
7
- <script src="https://cdn.jsdelivr.net/npm/gun/gun.js"></script>
8
- <!-- Include SEA (part of Gun) -->
9
- <script src="https://cdn.jsdelivr.net/npm/gun/sea.js"></script>
10
- <!-- Include Ethers.js -->
11
- <script src="https://cdnjs.cloudflare.com/ajax/libs/ethers/6.7.0/ethers.umd.min.js"></script>
12
- <!-- Include the Gun-Eth plugin -->
13
- <script src="https://cdn.jsdelivr.net/npm/gun-eth/src/gun-eth.js""></script>
14
- <style>
15
- body {
16
- font-family: Arial, sans-serif;
17
- margin: 0;
18
- padding: 20px;
19
- background-color: #f0f0f0;
20
- }
21
- .container {
22
- max-width: 400px;
23
- background-color: white;
24
- border: 1px solid #000;
25
- padding: 10px;
26
- }
27
- h1,
28
- h2 {
29
- margin: 0 0 10px 0;
30
- font-size: 16px;
31
- }
32
- form {
33
- margin-bottom: 15px;
34
- }
35
- input,
36
- button {
37
- display: inline-block;
38
- margin: 2px 0;
39
- padding: 2px;
40
- font-size: 12px;
41
- }
42
- input {
43
- width: 150px;
44
- }
45
- button {
46
- width: 100px;
47
- }
48
- label {
49
- display: inline-block;
50
- width: 70px;
51
- font-size: 12px;
52
- }
53
- #configStatus,
54
- .result {
55
- font-weight: bold;
56
- margin-bottom: 10px;
57
- }
58
- .result {
59
- color: blue;
60
- }
61
- .disclaimer {
62
- background-color: #ffffd0;
63
- border: 1px solid #e6e600;
64
- padding: 10px;
65
- margin-bottom: 15px;
66
- font-size: 14px;
67
- }
68
- </style>
69
- </head>
70
- <body>
71
- <div class="container">
72
- <h1>🔫 Gun to 💎 Ethereum Address Demo</h1>
73
-
74
- <form id="gunUserForm">
75
- <h2>👤 User Login/Registration</h2>
76
- <label for="gunAlias">👤 Alias:</label>
77
- <br>
78
- <input type="text" id="gunAlias" name="gunAlias" required>
79
- <br>
80
- <label for="gunPassword">🔑 Password:</label>
81
- <br>
82
- <input type="password" id="gunPassword" name="gunPassword" required>
83
- <br>
84
- <button type="submit">🚀 Create/Login</button>
85
- </form>
86
-
87
- <div id="conversionSection" style="display:none;">
88
- <h2>🔄 Convert Gun User to Ethereum Address</h2>
89
- <button id="convertBtn">🔄 Convert
90
- </div>
91
-
92
- <div id="resultSection">
93
- <h2>Result</h2>
94
- <p id="resultText"></p>
95
- </div>
96
- </div>
97
-
98
- <script>
99
- let gun = Gun();
100
- let currentUser = null;
101
-
102
- document.getElementById('gunUserForm').addEventListener('submit', function(event) {
103
- event.preventDefault();
104
- const alias = document.getElementById('gunAlias').value;
105
- const password = document.getElementById('gunPassword').value;
106
-
107
- console.log('Attempting to create or login user:', alias);
108
-
109
- gun.user().create(alias, password, function(ack) {
110
- if (ack.err) {
111
- console.log('User creation failed, trying to login:', ack.err);
112
- gun.user().auth(alias, password, function(authAck) {
113
- if (authAck.err) {
114
- document.getElementById('resultText').innerText = 'Error logging in: ' + authAck.err;
115
- } else {
116
- currentUser = gun.user();
117
- document.getElementById('resultText').innerText = 'User logged in successfully.';
118
- document.getElementById('conversionSection').style.display = 'block';
119
- }
120
- });
121
- } else {
122
- console.log('User created successfully:', ack);
123
- currentUser = gun.user();
124
- document.getElementById('resultText').innerText = 'User created and logged in successfully.';
125
- document.getElementById('conversionSection').style.display = 'block';
126
- }
127
- });
128
- });
129
-
130
- document.getElementById('convertBtn').addEventListener('click', function() {
131
- if (!currentUser) {
132
- alert('Please login first');
133
- return;
134
- }
135
-
136
- console.log('Current user:', currentUser);
137
- console.log('User pair:', currentUser._.sea);
138
-
139
- try {
140
- const pair = currentUser._.sea;
141
- if (!pair || !pair.priv) {
142
- throw new Error('Unable to retrieve Gun user private key');
143
- }
144
-
145
- const ethAccount = gun.gunToEthAccount(pair.priv);
146
-
147
- document.getElementById('resultText').innerHTML = `
148
- <strong>Gun User</strong>
149
- <br>
150
- ${currentUser.is.alias}
151
- <br>
152
- <br>
153
- <strong>Ethereum Address:</strong>
154
- <br>
155
- ${ethAccount.publicKey}
156
- `;
157
- } catch (error) {
158
- document.getElementById('resultText').innerText = 'Error: ' + error.message;
159
- console.error('Conversion error:', error);
160
- }
161
- });
162
- </script>
163
- </body>
164
- </html>