diff --git a/src/impl/chain/contract.ts b/src/impl/chain/contract.ts index 92f3b83..a0e6fa3 100644 --- a/src/impl/chain/contract.ts +++ b/src/impl/chain/contract.ts @@ -70,11 +70,16 @@ export class ContractHelper { async connect(url: string): Promise { const provider = new Web3.providers.WebsocketProvider(url, { reconnect: { - auto: true, + auto: false, delay: 5000, maxAttempts: 5, - onTimeout: false, + onTimeout: true, }, + clientConfig: { + keepalive: true, + keepaliveInterval: 60000, // ms + }, + timeout: 30000, }); return new Promise((resolve, reject) => { provider.on("connect", () => { @@ -122,22 +127,44 @@ export class ContractHelper { }); const serializedTx = "0x" + tx.sign(key).serialize().toString("hex"); return new Promise((resolve, reject) => { - this.web3.eth - .sendSignedTransaction(serializedTx) - .then((receipt) => { - if (receipt.status) { - resolve(receipt); - } else { - const err = `method ${name} tx hash ${receipt.transactionHash} is reverted`; - reject(err); - } - }) - .catch((err: Error) => { + this.web3.eth.sendSignedTransaction(serializedTx, (err: Error, hash: string) => { + if (err) { reject(err); - }); + } else { + resolve(this.waitForReceipt(hash)); + } + }); }); } + async waitForReceipt(hash: string, retry: number = 3): Promise { + if (retry === 0) { + throw new Error(`unable to get transaction receipt for tx ${hash}`); + } + try { + const receipt = await this.web3.eth.getTransactionReceipt(hash); + if (receipt) { + if (receipt.status == true) { + return receipt; + } else { + throw new Error(`tx ${receipt.transactionHash} is reverted`); + } + } else { + return await this.waitForReceipt(hash); + } + } catch (err) { + if ( + err instanceof Error && + err.message.includes("CONNECTION ERROR") && + err.message.includes("reconnect") + ) { + return await this.waitForReceipt(hash, retry - 1); + } else { + throw err; + } + } + } + decodeLogs(logs: Log[]): Result | undefined { for (const rlog of logs) { const topics = rlog.topics; diff --git a/src/service/server.ts b/src/service/server.ts index b730bc8..55b3c86 100644 --- a/src/service/server.ts +++ b/src/service/server.ts @@ -11,7 +11,12 @@ export function run(host: string, port: number): void { oneofs: true, }); const proto = grpc.loadPackageDefinition(definition) as unknown as ProtoGrpcType; - const server = new grpc.Server(); + const server = new grpc.Server({ + "grpc.keepalive_time_ms": 10000, + "grpc.keepalive_timeout_ms": 5000, + "grpc.keepalive_permit_without_calls": 1, + "grpc.max_pings_without_data": 0, + }); server.addService(proto.chain.Chain.service, chainService); server.bindAsync(`${host}:${port}`, grpc.ServerCredentials.createInsecure(), (err, p) => { if (err) {