-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.js
More file actions
262 lines (218 loc) · 7.47 KB
/
index.js
File metadata and controls
262 lines (218 loc) · 7.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Copyright 2024 Tether Operations Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict'
//
// Edit these to your own local instances
const WHISPR = 'http://localhost/whispr/audio/transcriptions'
const OLLAMA = 'http://localhost:11434/api/chat'
// Example address book
const book = {
bob: {
btc: 'bcrt1qrfd2ujntu7la5vjqpjr69u8tc8rl6fxvx6hrzm'
},
alice: {
btc: 'bcrt1q7mm7seyccvf4dyc2je97zumh4aes7xhgetwc6m',
eth: {
usdt: '0x9ede22b627388b5db43c3488f27480b45d22d238'
}
}
}
//
// Seed phrase
// Remove this to generate a new phrase on page refresh
const PHRASE = 'differ current leg erode fog hundred file multiply word inner grain drop'
// Wallet config
const wconfig = {
"network":"regtest",
"electrum_host": "ws://localhost",
"electrum_port": "8001",
"token_contract": "0x959922bE3CAee4b8Cd9a407cc3ac1C251C2007B1",
"web3_indexer_ws": "ws://localhost/eth/hardhat/indexer/ws",
"web3_indexer": "http://localhost/eth/hardhat/indexer/rpc",
"web3": "ws://localhost/eth/hardhat/indexer/web3",
seed : {
mnemonic : PHRASE
}
}
function renderAddressBook (book) {
const container = document.createElement('div')
container.className = 'address-book'
for (const [name, addresses] of Object.entries(book)) {
const personElement = document.createElement('div')
personElement.className = 'person'
const nameElement = document.createElement('h3')
nameElement.textContent = name
personElement.appendChild(nameElement)
const addressList = document.createElement('ul')
renderAddresses(addresses, addressList)
personElement.appendChild(addressList)
container.appendChild(personElement)
}
const node = document.getElementById('addr')
node.appendChild(container)
}
function renderAddresses (addresses, parentElement, prefix = '') {
for (const [key, value] of Object.entries(addresses)) {
const listItem = document.createElement('li')
if (typeof value === 'string') {
listItem.textContent = `${prefix}${key}: ${value}`
} else if (typeof value === 'object') {
listItem.textContent = `${prefix}${key}:`
const nestedList = document.createElement('ul')
renderAddresses(value, nestedList, ' ')
listItem.appendChild(nestedList)
}
parentElement.appendChild(listItem)
}
}
async function initWallet () {
renderAddressBook(book)
const w = await window.wallet(wconfig)
await w.syncHistory({ all: true });
(document.getElementById('seed')).textContent = w.seed.mnemonic
window.demoWallet = w
return w
}
async function walletAction (msg) {
const wallet = window.demoWallet
const asset = wallet.pay[msg.asset.toLowerCase()]
if (!asset) return setStatus(`asset: ${msg.asset} is not supported`)
if (!asset[msg.action]) return setStatus(`action ${msg.action} not supported by wallet`)
if (msg.args) {
msg.args.fee = 10
}
const res = await wallet.pay[msg.asset.toLowerCase()][msg.action]({ token: msg.token?.toLowerCase() }, msg.args)
try {
setStatus(JSON.stringify(res, null, 1))
} catch (err) {
console.log(err)
setStatus('command failed')
}
}
function setStatus (txt) {
const statusDiv = document.getElementById('status')
statusDiv.textContent = txt
}
async function initMic () {
let mediaRecorder
let audioChunks = []
let isRecording = false
const recordButton = document.getElementById('record')
const audioPlayback = document.getElementById('audio')
recordButton.onclick = toggleRecording
async function toggleRecording () {
if (!isRecording) {
await startRecording()
} else {
stopRecording()
}
}
async function startRecording () {
audioChunks = []
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
const mediaRecorder = new window.MediaRecorder(stream, { mimeType: 'audio/ogg; codecs=opus' })
mediaRecorder.ondataavailable = (event) => {
audioChunks.push(event.data)
}
mediaRecorder.onstop = async () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/ogg; codecs=opus' })
const audioUrl = URL.createObjectURL(audioBlob)
audioPlayback.src = audioUrl
await uploadAudio(audioBlob)
}
mediaRecorder.start()
isRecording = true
recordButton.classList.add('recording')
setStatus('Recording.... (Press again to stop recording)')
}
function stopRecording () {
mediaRecorder.stop()
isRecording = false
recordButton.classList.remove('recording')
}
async function uploadAudio (audioBlob) {
const formData = new FormData()
formData.append('file', audioBlob, 'recording.ogg')
formData.append('language', 'en')
setStatus('Uploading...')
const response = await fetch(WHISPR, {
method: 'POST',
body: formData
})
if (response.ok) {
const result = await response.json()
setStatus(`transcribed: ${result.text}. processing ....`)
parseTranscribe(result.text)
} else {
setStatus('Upload failed')
}
}
}
async function parseTranscribe (txt) {
const data = {
model: 'llama3.1',
stream: false,
messages: [
{
role: 'user',
content: `
parse the provided text into a structured JSON format.
the text is about a person interacting with a multi chain cryptocurrency wallet with natural language.
only output JSON string as output in the following format. nothing additional should be provided.
the output will be parsed with Javascript's JSON.parse. Dont wrap JSON in any formatting. provide valid json as output. outpout is used to call a js lib like : lib[asset][action]({token}, args)
Tokens: Tether is a stablecoin that exists on various blockchains. example phrase: New tether on ethereum address: asset: ethereum, token : usdt, action: getNewAddress
My address book of recipients is: JSON ${JSON.stringify(book, null, 2)} parse the sender's address from this JSON.
{ asset: (Required. ticker of the asset, blockchain we are using. example btc, eth. must be 3 letters)
token: (optional. ticker of the token, example usdt, Tether)
action: (required. must be one of: getNewAddress, sendTransaction, get history, syncHistory, getBalance),
args : {
amount: (if action is sending this is required),
unit: ( the unit of the amount getting sent. must be main or base)
address: (optional. this is recipient)
}
}
the text is: ${txt}
`
}
]
}
let msg
try {
const response = await fetch(OLLAMA, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const result = await response.json()
msg = JSON.parse(result.message.content)
} catch (error) {
console.error('Error:', error)
throw error
}
walletAction(msg)
}
// Entry point
async function main () {
await initWallet();
(document.getElementById('record')).textContent = 'Record'
initMic()
}
document.addEventListener('DOMContentLoaded', function () {
main()
})