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

Payments: add transaction nonce #136

Merged
merged 2 commits into from
Aug 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const bot = new Bot<BotContext>(config.telegramBotAuthToken);
bot.use(
limit({
// Allow only 1 message to be handled every 0.5 seconds.
timeFrame: 100,
timeFrame: 500,
limit: 1,

// This is called when the limit is exceeded.
Expand Down
2 changes: 1 addition & 1 deletion src/modules/open-ai/api/openAi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ export const streamChatCompletion = async (
let completion = "";
let msgId = (
await ctx.reply(
`_${ctx.session.openAi.chatGpt.model.toLocaleUpperCase()}_`,
`...`,
{
parse_mode: "Markdown",
}
Expand Down
84 changes: 56 additions & 28 deletions src/modules/payment/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import bn, { BigNumber } from "bignumber.js";
import config from "../../config";
import {chatService} from "../../database/services";
import { OnMessageContext } from "../types";
import { LRUCache } from 'lru-cache'

interface CoinGeckoResponse {
harmony: {
Expand All @@ -21,6 +22,10 @@ export class BotPayments {
private ONERate: number = 0;
private rpcURL: string = "https://api.harmony.one";
private lastPaymentTimestamp = 0;
private noncePending = new LRUCache<string, number>({
max: 1000,
ttl: 30 * 1000
})

constructor() {
this.web3 = new Web3(this.rpcURL);
Expand Down Expand Up @@ -113,22 +118,41 @@ export class BotPayments {
addressTo: string,
amount: BigNumber
) {
const web3 = new Web3(this.rpcURL);
web3.eth.accounts.wallet.add(accountFrom);

const gasPrice = await web3.eth.getGasPrice();
const txBody = {
from: accountFrom.address,
to: addressTo,
value: web3.utils.toHex(amount.toFixed()),
};
const gasLimit = await web3.eth.estimateGas(txBody);
const tx = await web3.eth.sendTransaction({
...txBody,
gasPrice,
gas: web3.utils.toHex(gasLimit),
});
return tx;
try {
const web3 = new Web3(this.rpcURL);
web3.eth.accounts.wallet.add(accountFrom);

const gasPrice = await web3.eth.getGasPrice();

let nonce = undefined
const nonceCache = this.noncePending.get(accountFrom.address)
if(nonceCache) {
nonce = nonceCache + 1
} else {
nonce = await web3.eth.getTransactionCount(accountFrom.address, 'pending') + 1
}
this.noncePending.set(accountFrom.address, nonce)

const txBody = {
from: accountFrom.address,
to: addressTo,
value: web3.utils.toHex(amount.toFixed()),
nonce
};
const gasLimit = await web3.eth.estimateGas(txBody);
const tx = await web3.eth.sendTransaction({
...txBody,
gasPrice,
gas: web3.utils.toHex(gasLimit),
});
return tx;
} catch (e) {
const message = (e as Error).message || ''
if(message && message.includes('replacement transaction underpriced')) {
} else {
throw new Error(message)
}
}
}

public isUserInWhitelist(userId: number | string, username = "") {
Expand Down Expand Up @@ -198,11 +222,13 @@ export class BotPayments {
userAccount.address,
amountONE.minus(fee)
);
this.logger.info(
`[${userId} @${username}] refund successful, from: ${tx.from}, to: ${
tx.to
}, amount ONE: ${amountONE.toFixed()}, txHash: ${tx.transactionHash}`
);
if(tx) {
this.logger.info(
`[${userId} @${username}] refund successful, from: ${tx.from}, to: ${
tx.to
}, amount ONE: ${amountONE.toFixed()}, txHash: ${tx.transactionHash}`
);
}
return true;
} catch (e) {
this.logger.error(
Expand Down Expand Up @@ -253,13 +279,15 @@ export class BotPayments {
amountToPay
);
this.lastPaymentTimestamp = Date.now();
this.logger.info(
`[${from.id} @${from.username}] withdraw successful, txHash: ${
tx.transactionHash
}, from: ${tx.from}, to: ${
tx.to
}, amount ONE: ${amountToPay.toString()}`
);
if(tx) {
this.logger.info(
`[${from.id} @${from.username}] withdraw successful, txHash: ${
tx.transactionHash
}, from: ${tx.from}, to: ${
tx.to
}, amount ONE: ${amountToPay.toString()}`
);
}
return true;
} catch (e) {
this.logger.error(
Expand Down