Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix : ts errors in backend #2212

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
7 changes: 4 additions & 3 deletions backends/CLightningREST.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,8 @@ export default class CLightningREST extends LND {
getNewAddress = () => this.getRequest('/v1/newaddr?addrType=bech32');
openChannelSync = (data: OpenChannelRequest) => {
let request: any;
const feeRate = `${new BigNumber(data.sat_per_vbyte)
const satPerVbyte = data.satPerVbyte ?? '0'; // Default to '0' if undefined
const feeRate = `${new BigNumber(satPerVbyte)
.times(1000)
.toString()}perkb`;
if (data.utxos && data.utxos.length > 0) {
Expand All @@ -176,7 +177,7 @@ export default class CLightningREST extends LND {
satoshis: data.satoshis,
feeRate,
announce: !data.privateChannel ? 'true' : 'false',
minfConf: data.min_confs,
minfConf: data.minConfs,
utxos: data.utxos
};
} else {
Expand All @@ -185,7 +186,7 @@ export default class CLightningREST extends LND {
satoshis: data.satoshis,
feeRate,
announce: !data.privateChannel ? 'true' : 'false',
minfConf: data.min_confs
minfConf: data.minConfs
};
}

Expand Down
130 changes: 70 additions & 60 deletions backends/Eclair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,73 +6,83 @@ import TransactionRequest from './../models/TransactionRequest';
import OpenChannelRequest from './../models/OpenChannelRequest';
import Base64Utils from './../utils/Base64Utils';
import { Hash as sha256Hash } from 'fast-sha256';

// keep track of all active calls so we can cancel when appropriate
const calls = new Map<string, Promise<any>>();
interface ApiResponse {
[key: string]: any;
}

export default class Eclair {
clearCachedCalls = () => calls.clear();
// keep track of all active calls so we can cancel when appropriate
private calls: Map<string, Promise<ApiResponse>> = new Map();
clearCachedCalls = () => this.calls.clear();
private generateCallId(method: string, params: any): string {
return method + JSON.stringify(params);
}
private createHeaders(): Record<string, string> {
return {
Authorization:
'Basic ' +
Base64Utils.utf8ToBase64(':' + stores.settingsStore.password),
'Content-Type': 'application/x-www-form-urlencoded'
};
}
private normalizeUrl(url: string): string {
return url.endsWith('/') ? url : url + '/';
}
private async makeTorRequest(
url: string,
method: string,
body: string,
headers: Record<string, string>
): Promise<ApiResponse> {
return doTorRequest(url + method, RequestMethod.POST, body, headers);
}
private async makeRegularRequest(
url: string,
method: string,
body: string,
headers: Record<string, string>
): Promise<ApiResponse> {
try {
const response = await ReactNativeBlobUtil.config({
trusty: !stores.settingsStore.certVerification
}).fetch('POST', url + method, headers, body);

const status = response.info().status;
if (status < 300) {
return response.json();
} else {
const errorInfo = await response.json();
throw new Error(errorInfo.error);
}
} catch (error) {
if (error instanceof Error) {
throw error;
}
throw new Error('Unknown error occurred');
}
}
private setCallCleanupTimeout(id: string): void {
setTimeout(() => {
this.calls.delete(id);
}, 9000);
}
api = (method: string, params: any = {}) => {
const { password, certVerification, enableTor } = stores.settingsStore;
let { url } = stores.settingsStore;
const id = this.generateCallId(method, params);

const id: string = method + JSON.stringify(params);
if (calls.has(id)) {
return calls.get(id);
if (this.calls.has(id)) {
return this.calls.get(id)!;
}

url = url.slice(-1) === '/' ? url : url + '/';
const headers = {
Authorization: 'Basic ' + Base64Utils.utf8ToBase64(':' + password),
'Content-Type': 'application/x-www-form-urlencoded'
};
const url = this.normalizeUrl(stores.settingsStore.url);
const headers = this.createHeaders();
const body = querystring.stringify(params);
const apiCall = stores.settingsStore.enableTor
? this.makeTorRequest(url, method, body, headers)
: this.makeRegularRequest(url, method, body, headers);
this.calls.set(id, apiCall);
this.setCallCleanupTimeout(id);

if (enableTor === true) {
calls.set(
id,
doTorRequest(url + method, RequestMethod.POST, body, headers)
);
} else {
calls.set(
id,
ReactNativeBlobUtil.config({
trusty: !certVerification
})
.fetch('POST', url + method, headers, body)
.then((response: any) => {
calls.delete(id);

const status = response.info().status;
if (status < 300) {
return response.json();
} else {
let errorInfo;
try {
errorInfo = response.json();
} catch (err) {
throw new Error(
'response was (' +
status +
')' +
response.text()
);
}
throw new Error(errorInfo.error);
}
})
);
}
setTimeout(
(id: string) => {
calls.delete(id);
},
9000,
id
);

return calls.get(id);
return apiCall;
};

getTransactions = () =>
Expand Down Expand Up @@ -246,9 +256,9 @@ export default class Eclair {
this.api('getnewaddress').then((address: any) => ({ address }));
openChannelSync = (data: OpenChannelRequest) =>
this.api('open', {
nodeId: data.node_pubkey_string,
nodeId: data.nodePubkeyString,
fundingSatoshis: data.satoshis,
fundingFeerateSatByte: data.sat_per_vbyte,
fundingFeerateSatByte: data.satPerVbyte,
channelFlags: data.privateChannel ? 0 : 1
}).then(() => ({}));
connectPeer = (data: any) =>
Expand Down
41 changes: 20 additions & 21 deletions backends/EmbeddedLND.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
checkLndStreamErrorResponse,
LndMobileEventEmitter
} from '../utils/LndMobileUtils';
import Long from 'long';

const {
addInvoice,
Expand All @@ -21,7 +22,6 @@ const {
sendKeysendPaymentV2,
listPayments,
getNetworkInfo,
getRecoveryInfo,
queryRoutes,
lookupInvoice,
fundingStateStep,
Expand Down Expand Up @@ -76,7 +76,6 @@ export default class EmbeddedLND extends LND {
subscribeCustomMessages = async () => await subscribeCustomMessages();
getMyNodeInfo = async () => await getInfo();
getNetworkInfo = async () => await getNetworkInfo();
getRecoveryInfo = async () => await getRecoveryInfo();
getInvoices = async () => await listInvoices();
createInvoice = async (data: any) =>
await addInvoice({
Expand All @@ -94,13 +93,13 @@ export default class EmbeddedLND extends LND {
await newAddress(data.type, data.account);
openChannelSync = async (data: OpenChannelRequest) =>
await openChannelSync(
data.node_pubkey_string,
Number(data.local_funding_amount),
data.nodePubkeyString,
Number(data.localFundingAmount),
data.privateChannel || false,
data.sat_per_vbyte ? Number(data.sat_per_vbyte) : undefined,
data.satPerVbyte ? Number(data.satPerVbyte) : undefined,
data.scidAlias,
data.min_confs,
data.spend_unconfirmed,
data.minConfs,
data.spendUnconfirmed,
data.simpleTaprootChannel,
data.fundMax,
data.utxos
Expand Down Expand Up @@ -128,25 +127,25 @@ export default class EmbeddedLND extends LND {
});

openChannel(
data.node_pubkey_string,
Number(data.local_funding_amount),
data.nodePubkeyString,
Number(data.localFundingAmount),
data.privateChannel || false,
data.sat_per_vbyte && !data.funding_shim
? Number(data.sat_per_vbyte)
data.satPerVbyte && !data.fundingShim
? Number(data.satPerVbyte)
: undefined,
data.scidAlias,
data.min_confs,
data.spend_unconfirmed,
data.minConfs,
data.spendUnconfirmed,
data.simpleTaprootChannel,
data.fundMax,
data.utxos,
data.funding_shim
data.fundingShim
);
});
};
connectPeer = async (data: any) =>
await connectPeer(data.addr.pubkey, data.addr.host, data.perm);
decodePaymentRequest = async (urlParams?: string[]) =>
decodePaymentRequest = async (urlParams: Array<string>) =>
await decodePayReq(urlParams && urlParams[0]);
payLightningInvoice = async (data: any) => {
const sendPaymentReq = {
Expand Down Expand Up @@ -202,9 +201,9 @@ export default class EmbeddedLND extends LND {
);
};

getNodeInfo = async (urlParams?: Array<string>) =>
getNodeInfo = async (urlParams: Array<string>) =>
await getNodeInfo(urlParams[0]);
signMessage = async (msg: Uint8Array) => {
signMessage = async (msg: string) => {
return await signMessageNodePubkey(Base64Utils.stringToUint8Array(msg));
};
verifyMessage = async (data: any) => {
Expand All @@ -217,8 +216,9 @@ export default class EmbeddedLND extends LND {

// getFees = () => N/A;
// setFees = () => N/A;
getRoutes = async (urlParams?: Array<string>) =>
urlParams && (await queryRoutes(urlParams[0], urlParams[1]));
getRoutes = async (urlParams: Array<string | Long>) =>
urlParams &&
(await queryRoutes(urlParams[0] as string, urlParams[1] as Long));
// getForwardingHistory = () => N/A
// // Coin Control
fundPsbt = async (data: any) => await fundPsbt(data);
Expand Down Expand Up @@ -296,8 +296,7 @@ export default class EmbeddedLND extends LND {
supportsSweep = () => true;
supportsOnchainBatching = () => true;
supportsChannelBatching = () => true;
isLNDBased = () => true;
supportsLSPS1customMessage = () => true;
supportsLSPS1rest = () => false;
supportsOffers = () => false;
isLNDBased = () => true;
}
Loading
Loading