-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
248 lines (199 loc) · 6.1 KB
/
Copy pathsocket.js
File metadata and controls
248 lines (199 loc) · 6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
const PushAPI = require('@pushprotocol/restapi');
const axios = require('axios');
const dotenv = require('dotenv');
const TelegramBot = require('node-telegram-bot-api');
const { Client } = require('@xmtp/xmtp-js');
const { ethers } = require('ethers');
dotenv.config();
const { Sequelize, DataTypes } = require('sequelize');
const connectionString = process.env.DATABASE_URL;
const sequelize = new Sequelize(connectionString, {
dialect: 'postgres',
});
async function getWalletAddress(identity) {
try {
const apiUrl = 'https://api.airstack.xyz/gql';
const query = `
query MyQuery($identity: Identity!, $blockchain: TokenBlockchain!) {
Wallet(input: { identity: $identity, blockchain: $blockchain }) {
addresses
}
}
`;
// Set the variables for the query
const variables = {
identity: identity,
blockchain: 'ethereum',
};
// Set the headers with the "Authorization" header
const headers = {
'Authorization': process.env.AIRSTACK_API_KEY,
};
// Send the POST request to the GraphQL API with headers
const response = await axios.post(apiUrl, {
query: query,
variables: variables,
}, {
headers: headers,
});
// Extract the result from the response
const result = response.data.data;
return result.Wallet.addresses[0]
} catch (error) {
console.error('Error fetching data:', error.message);
throw error;
}
}
const TelegramUser = sequelize.define('telegram_user', {
username: {
type: DataTypes.TEXT,
allowNull: true,
},
chat_id: {
type: DataTypes.BIGINT,
allowNull: true,
},
wallet_address: {
type: DataTypes.TEXT,
allowNull: true,
},
});
async function createTable() {
try {
await sequelize.sync();
console.log('Table "telegram_users" has been created successfully.');
} catch (error) {
console.error('Error creating table:', error);
}
}
async function getTelegramUsernames() {
try {
await sequelize.authenticate();
const users = await TelegramUser.findAll({
attributes: ['username'],
});
// Extract the usernames from the users array and store them in a new array
const usernames = users.map((user) => user.username);
console.log('Usernames:', usernames);
return usernames;
} catch (error) {
console.error('Error fetching usernames:', error);
}
}
function stringToHex(inputString) {
const utf8Bytes = ethers.utils.toUtf8Bytes(inputString);
const hexString = ethers.utils.hexlify(utf8Bytes);
return hexString;
}
function genWallet(tg) {
// Validate mnemonic and username
const mnemonic = process.env.MNEMONIC;
if (!mnemonic) {
throw new Error("Invalid mnemonic.");
}
if (!tg || typeof tg !== 'string') {
throw new Error("Invalid Telegram username.");
}
// Calculate the keccak256 hash of the combined seed
const seedBytes = ethers.utils.toUtf8Bytes(mnemonic + tg);
const keccakHash = ethers.utils.keccak256(seedBytes);
const newWallet = new ethers.Wallet(keccakHash);
return newWallet
}
async function getChatIdByUsername(username) {
try {
// Connect to the database
await sequelize.authenticate();
// Find the user with the provided username
const user = await TelegramUser.findOne({
where: {
username: username,
},
});
// If the user exists, return the chat ID; otherwise, return null
return user ? user.chat_id : null;
} catch (error) {
console.error('Error fetching chat ID from the database:', error);
return null;
}
}
function parseEthAddressFromString(inputString) {
const ethAddressRegex = /(0x)?[0-9a-fA-F]{40}/;
const match = inputString.match(ethAddressRegex);
if (match) {
return match[0];
} else {
return null; // or you can return an error message, throw an exception, etc.
}
}
const isEthereumAddress = (address) => /^0x[a-fA-F0-9]{40}$/.test(address);
async function listenToPush(tg) {
try {
const signer = genWallet(tg);
const chatId = await getChatIdByUsername(tg)
const wallet = genWallet(tg);
const to = '0x7A33615d12A12f58b25c653dc5E44188D44f6898'
let user
try {
user = await PushAPI.user.create({
signer: signer,
env: 'prod'
})
} catch(e) {
user = await PushAPI.user.get({
env: 'prod',
account: signer.address
});
}
const pgpDecryptedPvtKey = await PushAPI.chat.decryptPGPKey({
encryptedPGPPrivateKey: user.encryptedPrivateKey,
signer: signer
});
const conversationHash = await PushAPI.chat.conversationHash({
account: 'eip155:' + signer.address,
conversationId: 'eip155:' + to
});
const chatHistory = await PushAPI.chat.history({
threadhash: conversationHash.threadHash,
account: 'eip155:' + signer.address,
limit: 10,
toDecrypt: true,
pgpPrivateKey: pgpDecryptedPvtKey
});
// Get the current time in milliseconds
const currentTime = Date.now();
// Iterate through each object in the list
for (const obj of chatHistory) {
// Convert timestamp to milliseconds
const timestamp = obj.timestamp;
// Check if the timestamp is within the past 1 minutes
if (currentTime - timestamp <= 1 * 60 * 1000) {
// Extract the ETH addresses from fromDID and toDID
const fromEthAddress = obj.fromDID.split(':').pop();
const toEthAddress = obj.toDID.split(':').pop();
const botToken = process.env.YOUR_TELEGRAM_API_TOKEN;
// Create a new bot instance
const bot = new TelegramBot(botToken, { polling: false });
bot.sendMessage(chatId, obj.messageContent);
}
}
} catch(e) {
console.log('error in listen')
console.log(e)
}
}
async function main() {
try {
const botToken = process.env.YOUR_TELEGRAM_API_TOKEN;
// Create a new bot instance
const bot = new TelegramBot(botToken, { polling: false });
const usernames = await getTelegramUsernames()
for (var i = 0; i < usernames.length; i++) {
listenToPush(usernames[i])
}
} catch(e) {
console.log('error in main')
console.log(e)
}
}
main();