diff --git a/src/services/service.ts b/src/services/service.ts index 433884d..73cab33 100755 --- a/src/services/service.ts +++ b/src/services/service.ts @@ -13,7 +13,7 @@ export const U32_MAX = 4294967295; const storageUrl = `https://demo.4nkweb.com/storage`; const BOOTSTRAPURL = [`https://demo.4nkweb.com/ws/`]; - +const DEFAULTAMOUNT = 1000n; export default class Services { private static initializing: Promise | null = null; @@ -195,39 +195,44 @@ export default class Services { const members_str = members.map((member) => JSON.stringify(member)); - const waitForAmount = async (): Promise => { - let attempts = 3; - while (attempts > 0) { - const amount = this.getAmount(); - if (amount !== 0n) { - return amount; - } - attempts--; - if (attempts > 0) { - await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait for 1 second - } - } - throw new Error('Amount is still 0 after 3 attempts'); - }; + try { + // Ensure the amount is available before proceeding + await this.ensureSufficientAmount(); + return this.sdkClient.create_connect_transaction(members_str, 1); + } catch (e) { + console.error('Failed to connect member:', e); + throw e; + } + } + private async ensureSufficientAmount(): Promise { let availableAmt = this.getAmount(); - if (availableAmt === 0n) { + const target: BigInt = DEFAULTAMOUNT * BigInt(2); + + if (availableAmt < target) { const faucetMsg = this.createFaucetMessage(); this.sendFaucetMessage(faucetMsg); - try { - availableAmt = await waitForAmount(); - } catch (e) { - console.error('Failed to retrieve amount:', e); - throw e; // Rethrow the error if needed + await this.waitForAmount(target); + } + } + + private async waitForAmount(target: BigInt): Promise { + let attempts = 3; + + while (attempts > 0) { + const amount = this.getAmount(); + if (amount >= target) { + return amount; + } + + attempts--; + if (attempts > 0) { + await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait for 1 second } } - try { - return this.sdkClient.create_connect_transaction(members_str, 1); - } catch (e) { - throw e; - } + throw new Error('Amount is still 0 after 3 attempts'); } public async createMessagingProcess(otherMembers: Member[],relayAddress: string, feeRate: number): Promise {