monero-wallet-rpc-js/main.js

98 lines
2.2 KiB
JavaScript

const axios = require('axios')
module.exports = class Wallet {
// IIAFE https://stackoverflow.com/a/50885340
constructor (settings) { return (async () => {
this.url = settings.url
// Open wallet
try {
await this.rpc('open_wallet', {
filename: settings.filename,
password: settings.password,
})
} catch (openErr) {
// Create wallet
try {
await this.rpc('generate_from_keys', {
restore_height: settings.restoreHeight,
filename: settings.filename,
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}`)
}
}
// Refresh wallet
try {
await this.rpc('refresh', {
start_height: settings.restoreHeight || 0,
})
} catch (err) {
console.error(`Failed to refresh wallet: ${err}`)
}
return this;
})() }
// Arbitrary RPC call
async rpc(method, params=undefined) {
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
}
// Get wallet synced height
async getHeight() {
return Number((await this.rpc('get_height')).height)
}
// Get wallet balance
async getBalance(params) {
return await this.rpc('get_balance', params)
}
// Save wallet
async store() {
return await this.rpc('store')
}
// Save and close wallet
async close() {
return await this.rpc('close_wallet')
}
// Create address
async createAddress(params) {
return await this.rpc('create_address', params)
}
// Get address from its account and index
async getAddress(params) {
return await this.rpc('get_address', params)
}
// Get address index from its address
async getAddressIndex(addr) {
return await this.rpc('get_address_index', {
address: addr,
})
}
// Get transfers
async getTransfers(params) {
return await this.rpc('get_transfers', params)
}
}