forked from akave-ai/akavelink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb3-utils.js
86 lines (70 loc) · 2.54 KB
/
web3-utils.js
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
const { createPublicClient, http } = require('viem');
const { privateKeyToAccount } = require('viem/accounts');
// Define Akave Fuji chain
const akaveFuji = {
id: 78963,
name: "Akave Fuji",
nativeCurrency: {
decimals: 18,
name: "AKAVE",
symbol: "AKVF",
},
rpcUrls: {
default: {
http: ["https://node1-asia.ava.akave.ai/ext/bc/tLqcnkJkZ1DgyLyWmborZK9d7NmMj6YCzCFmf9d9oQEd2fHon/rpc"],
},
},
};
// Initialize client
const publicClient = createPublicClient({
chain: akaveFuji,
transport: http(),
});
//@note: This function highly depends on Akave Fuji's block time and transaction confirmation time.
//If the transaction is not confirmed in the first block, it will wait for 5 seconds and try again.
//If the transaction is not confirmed in the second block, it will return null.
//@TODO: Find a better way to get the related transaction hash.
async function getLatestTransaction(address, commandId) {
try {
// First attempt
const blockNumber = await publicClient.getBlockNumber();
console.log(`[${commandId}] 🔍 Checking block ${blockNumber} for transactions`);
const block = await publicClient.getBlock({
blockNumber,
includeTransactions: true
});
let transactions = block.transactions.filter(tx =>
tx.from?.toLowerCase() === address.toLowerCase()
);
if (transactions.length > 0) {
const hash = transactions[transactions.length - 1].hash;
console.log(`[${commandId}] ✅ Found transaction hash in first attempt: ${hash}`);
return hash;
}
console.log(`[${commandId}] ⏳ No transaction found, waiting 5 seconds...`);
await new Promise(resolve => setTimeout(resolve, 5000));
// Second attempt
const newBlockNumber = await publicClient.getBlockNumber();
console.log(`[${commandId}] 🔍 Checking block ${newBlockNumber} for transactions`);
const newBlock = await publicClient.getBlock({
blockNumber: newBlockNumber,
includeTransactions: true
});
transactions = newBlock.transactions.filter(tx =>
tx.from?.toLowerCase() === address.toLowerCase()
);
const hash = transactions[transactions.length - 1]?.hash;
if (hash) {
console.log(`[${commandId}] ✅ Found transaction hash in second attempt: ${hash}`);
} else {
console.log(`[${commandId}] ❌ No transaction found after retrying`);
}
return hash || null;
} catch (error) {
console.error(`[${commandId}] 🔴 Error getting latest transaction:`, error);
return null;
}
}
module.exports = {
getLatestTransaction,
};