-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
164 lines (141 loc) · 5.28 KB
/
index.ts
File metadata and controls
164 lines (141 loc) · 5.28 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
// Full Documentation: https://push.org/docs/chain/build/reading-blockchain-state
import { ethers } from 'ethers';
import { createPublicClient, defineChain, http, webSocket } from 'viem';
// Define Push Testnet chain configuration for Viem
const pushTestnet = defineChain({
id: 42101,
name: 'Push Testnet',
nativeCurrency: {
decimals: 18,
name: 'PC',
symbol: '$PC',
},
rpcUrls: {
default: {
http: ['https://evm.donut.rpc.push.org/'],
},
},
blockExplorers: {
default: {
name: 'Push Testnet Explorer',
url: 'https://explorer.testnet.push.org/',
},
},
});
// Initialize HTTP clients for Ethers
const provider = new ethers.JsonRpcProvider('https://evm.donut.rpc.push.org/');
const viemClient = createPublicClient({
chain: pushTestnet,
transport: http(),
});
// Initialize WebSocket clients
const wsProvider = new ethers.WebSocketProvider('wss://evm.rpc-testnet-donut-node1.push.org/');
const wsViemClient = createPublicClient({
chain: pushTestnet,
transport: webSocket('wss://evm.rpc-testnet-donut-node1.push.org/'),
});
// Initialize WebSocket connection
wsProvider.websocket.close = () => {
console.log('🔴 WebSocket disconnected');
};
wsProvider.websocket.onerror = (error) => {
console.error('❌ WebSocket error:', error);
};
wsProvider.websocket.onopen = () => {
console.log('🟢 WebSocket connected');
};
// Custom replacer function to handle BigInt serialization
function replacer(key: any, value: any) {
if (typeof value === 'bigint') {
return value.toString();
}
return value;
}
// ⭐️ MAIN FUNCTION ⭐️
async function main() {
console.log('🚀 Starting Push Chain state reading examples...');
try {
console.log('\n🔍 Running examples with both ethers.js and viem...');
// Run all examples
await getTransactionByHash();
await getLatestBlock();
await getBlockByHash();
await watchBlocks();
} catch (error) {
console.error('❌ Error:', error);
if (error instanceof Error && error.message?.includes('WebSocket')) {
console.log('ℹ️ Note: Make sure the WebSocket endpoint is available and accessible');
}
}
}
main().catch(console.error);
// 1. Fetch transaction by hash
async function getTransactionByHash() {
console.log('\n1️⃣ Fetching transaction by hash...');
const txHash = '0x750b4d83b2cc3fbab878c2f1b1e9a5413e19d3cdb7db844877d7f7881b8250a0';
// Ethers implementation
const ethersTransaction = await provider.getTransaction(txHash);
console.log('📝 Ethers transaction:', JSON.stringify(ethersTransaction, replacer, 2));
// Viem implementation
const viemTransaction = await viemClient.getTransaction({ hash: txHash });
console.log('📝 Viem transaction:', JSON.stringify(viemTransaction, replacer, 2));
}
// 2. Fetch latest block
async function getLatestBlock() {
console.log('\n2️⃣ Fetching latest block...');
// Ethers implementation
const ethersBlock = await provider.getBlock('latest');
console.log('🔲 Ethers latest block:', JSON.stringify(ethersBlock, replacer, 2));
// Viem implementation
const viemBlock = await viemClient.getBlock();
console.log('🔲 Viem latest block:', JSON.stringify(viemBlock, replacer, 2));
}
// 3. Fetch block by hash
async function getBlockByHash() {
console.log('\n3️⃣ Fetching block by hash...');
const blockHash = '0xa2675c368aa26ac4ebee092a8a6566714de3901cbaa44d30931c064d47d00e5c';
// Ethers implementation
const ethersBlock = await provider.getBlock(blockHash);
console.log('🔲 Ethers block:', JSON.stringify(ethersBlock, replacer, 2));
// Viem implementation
const viemBlock = await viemClient.getBlock({ blockHash });
console.log('🔲 Viem block:', JSON.stringify(viemBlock, replacer, 2));
}
// 4. Watch for new blocks with transaction filtering
async function watchBlocks() {
console.log('\n4️⃣ Watching for new blocks...');
const watchedAddress = '0x0000000000000000000000000000000000042101'.toLowerCase();
// Ethers implementation
console.log('👀 Ethers watching blocks for transactions to:', watchedAddress);
wsProvider.on('block', async (blockNumber) => {
const block = await wsProvider.getBlock(blockNumber, true);
if (block && block.transactions) {
console.log('🆕 New block:', block.number);
const txs = await Promise.all(block.transactions.map((hash) => wsProvider.getTransaction(hash)));
txs
.filter((tx) => tx && tx.to?.toLowerCase() === watchedAddress)
.forEach((tx) => console.log('💸 Transaction detected:', tx?.hash));
}
});
// Viem implementation
console.log('👀 Viem watching blocks for transactions to:', watchedAddress);
const unwatch = wsViemClient.watchBlocks({
onBlock: async (block) => {
console.log('🆕 New block:', block.number);
const fullBlock = await wsViemClient.getBlock({ blockHash: block.hash, includeTransactions: true });
if (fullBlock.transactions) {
fullBlock.transactions
.filter((tx) => tx.to?.toLowerCase() === watchedAddress)
.forEach((tx) => console.log('💸 Transaction detected:', tx.hash));
}
},
onError: console.error,
});
// Stop watching after 30 seconds
setTimeout(() => {
console.log('\n⏹️ Stopping block watchers...');
wsProvider.removeAllListeners();
wsProvider.destroy();
unwatch();
}, 30000);
}