monero-wallet-rpc-js/main.js

78 lines
1.7 KiB
JavaScript
Raw Normal View History

2024-04-20 18:47:34 -06:00
const axios = require('axios')
2024-04-20 18:47:34 -06:00
module.exports = class Wallet {
constructor (settings) {
2024-04-20 19:15:17 -06:00
this.url = settings.url
// Open wallet
try {
this.rpc('open_wallet', {
filename: settings.filename,
2024-04-20 18:54:38 -06:00
password: settings.password,
})
} catch (openErr) {
2024-04-21 13:10:22 -06:00
// Create wallet
try {
this.rpc('generate_from_keys', {
2024-04-20 18:54:38 -06:00
restore_height: settings.restoreHeight,
filename: settings.filename,
2024-04-20 18:54:38 -06:00
address: settings.address,
spendKey: settings.spendKey,
viewKey: settings.viewKey,
password: settings.password
})
} catch (createErr) {
console.error(`Failed to open wallet "${settings.filename}": ${openErr}`)
console.error(`Failed to create wallet "${settings.filename}": ${createErr}`)
}
2024-04-21 13:10:22 -06:00
}
// Refresh wallet
try {
this.rpc('refresh', {
start_height: settings.restoreHeight || 0,
})
} catch (err) {
console.error(`Failed to refresh wallet: ${err}`)
}
}
2024-04-21 13:10:22 -06:00
// Arbitrary RPC call
2024-04-21 12:17:12 -06:00
async rpc(method, params=undefined) {
2024-04-21 12:33:09 -06:00
const res = await axios.post(`${this.url}/json_rpc`, {
jsonrpc: '2.0',
id: '0',
method: method,
params: params,
})
if (res.status!==200)
throw new Error(res.statusText)
else if (res.data.error)
throw new Error(res.data.error.message)
else if (!res.data.result)
throw new Error('No result')
else return res.data.result
}
2024-04-21 13:10:22 -06:00
// Get wallet synced height
async getHeight() {
2024-04-21 13:18:25 -06:00
return Number((await this.rpc('get_height')).height)
2024-04-21 13:10:22 -06:00
}
// Get wallet balance
async getBalance() {
2024-04-21 13:46:42 -06:00
return Number((await this.rpc('get_balance')))
2024-04-21 13:10:22 -06:00
}
// Save wallet
async store() {
return await this.rpc('store')
}
// Save and close wallet
async close() {
return await this.rpc('close_wallet')
}
2024-04-20 13:52:41 -06:00
}