107 lines
2.5 KiB
JavaScript
107 lines
2.5 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,
|
|
})
|
|
console.log(`Opened wallet "${settings.filename}".`)
|
|
} catch (openErr) {
|
|
|
|
// Create wallet
|
|
delete settings.url
|
|
if (settings.spendKey===undefined)
|
|
delete settings.spendKey
|
|
try {
|
|
await this.rpc('generate_from_keys', settings)
|
|
console.log(`Created wallet "${settings.filename}".`)
|
|
} 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')
|
|
}
|
|
// Get accounts
|
|
async getAccounts(params={}) {
|
|
return await this.rpc('get_accounts', params)
|
|
}
|
|
// Create account
|
|
async createAccount(label) {
|
|
if (!label) return await this.rpc('create_account')
|
|
else return await this.rpc('create_account', {
|
|
label: label,
|
|
})
|
|
}
|
|
// 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)
|
|
}
|
|
|
|
}
|