Last active
November 19, 2020 16:40
-
-
Save erukiti/cb6b11d6c2aa9f797426dd6e7155b3a8 to your computer and use it in GitHub Desktop.
Bitcoin Core JSON-RPC client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as rp from 'request-promise' | |
export interface Client { | |
[method: string]: (...args) => Promise<any> | |
} | |
export interface Conf { | |
host: string | |
rpcport: number | |
user: string | |
pass: string | |
} | |
export const createClient = ( | |
{ host, rpcport, user, pass }: Conf, | |
isDebug: boolean = false | |
) => { | |
const client: Client = new Proxy( | |
{}, | |
{ | |
get: (target: any, method: string) => { | |
if (method === 'then' || method === 'catch') { | |
return target[method] | |
} | |
method = method.toLowerCase() | |
return async (...params) => { | |
if (isDebug) { | |
console.log(`\x1b[32mBitcoin\x1b[m:${method}(${params.join(', ')})`) | |
} | |
const { result, error } = JSON.parse( | |
await rp(`http://${host}:${rpcport}`, { | |
method: 'POST', | |
body: JSON.stringify({ method, params }), | |
auth: { user, pass }, | |
}).catch(e => { | |
if (e.statusCode) { | |
return JSON.stringify({ error: JSON.parse(e.error).error }) | |
} else { | |
return JSON.stringify({ error: e.error }) | |
} | |
}) | |
) | |
if (error) { | |
throw error | |
} else { | |
return result | |
} | |
} | |
}, | |
} | |
) | |
return client | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment