-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
292 lines (244 loc) · 8.05 KB
/
main.go
File metadata and controls
292 lines (244 loc) · 8.05 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// This script is used to test Solana transaction confirmation latency
// Before using, place a private key file generated by Solana CLI (e.g. id.json) in the current directory and specify via -key
// Initialize module: go mod init solana-send-tx && go mod tidy
package main
import (
"context"
"encoding/base64"
"flag"
"fmt"
"os"
"sync"
"time"
"github.com/gagliardetto/solana-go"
"github.com/gagliardetto/solana-go/programs/system"
"github.com/gagliardetto/solana-go/rpc"
"github.com/gagliardetto/solana-go/rpc/ws"
)
func main() {
sendRpcURL := flag.String("send-rpc", "https://api.mainnet-beta.solana.com", "Solana RPC endpoint for sending transactions")
wsURL := flag.String("ws-url", "wss://api.mainnet-beta.solana.com", "WebSocket endpoint for monitoring transaction status")
keyFile := flag.String("key", "id.json", "Private key file path")
toAddr := flag.String("to", "", "Recipient public key (base58)")
amount := flag.Uint64("amount", 1000000, "Transfer amount (lamports)")
pollInterval := flag.Int("poll-interval", 3, "Polling interval in milliseconds for transaction status")
wsWaitTime := flag.Int("ws-wait", 1000, "Time to wait for WebSocket subscription in milliseconds")
flag.Parse()
if *toAddr == "" {
fmt.Println("Recipient public key is required")
flag.Usage()
os.Exit(1)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
fmt.Println("Establishing WebSocket connection...")
wsClient, err := ws.Connect(ctx, *wsURL)
if err != nil {
panic(fmt.Errorf("failed to connect to WebSocket: %w", err))
}
defer wsClient.Close()
fmt.Println("WebSocket connection established")
privKey, err := solana.PrivateKeyFromSolanaKeygenFile(*keyFile)
if err != nil {
panic(fmt.Errorf("failed to load private key: %w", err))
}
sendClient := rpc.New(*sendRpcURL)
blockhashResp, err := sendClient.GetLatestBlockhash(context.Background(), rpc.CommitmentFinalized)
if err != nil {
panic(fmt.Errorf("failed to get blockhash: %w", err))
}
toPub := solana.MustPublicKeyFromBase58(*toAddr)
transferInstr := system.NewTransferInstructionBuilder().
SetFundingAccount(privKey.PublicKey()).
SetRecipientAccount(toPub).
SetLamports(*amount).
Build()
tx, err := solana.NewTransaction([]solana.Instruction{transferInstr}, blockhashResp.Value.Blockhash)
if err != nil {
panic(fmt.Errorf("failed to build transaction: %w", err))
}
tx.Sign(func(key solana.PublicKey) *solana.PrivateKey {
if key.Equals(privKey.PublicKey()) {
return &privKey
}
return nil
})
serializedTx, err := tx.MarshalBinary()
if err != nil {
panic(fmt.Errorf("failed to serialize transaction: %w", err))
}
expectedSig := tx.Signatures[0]
fmt.Printf("Expected signature: %s\n", expectedSig.String())
var processedTime, confirmedTime, finalizedTime time.Time
var receivedTime time.Time
var statusMutex sync.Mutex
var manualProcessedTime time.Time
fmt.Printf("Preparing transaction monitoring...\n")
sub, err := wsClient.SignatureSubscribe(
expectedSig,
rpc.CommitmentProcessed,
)
if err != nil {
panic(fmt.Errorf("failed to subscribe to signature: %w", err))
}
defer sub.Unsubscribe()
statusCh := make(chan struct{})
processedCh := make(chan time.Time, 1)
confirmedCh := make(chan time.Time, 1)
finalizedCh := make(chan time.Time, 1)
receivedCh := make(chan time.Time, 1)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case <-statusCh:
return
default:
notification, err := sub.Recv(ctx)
if err != nil {
time.Sleep(1 * time.Millisecond)
continue
}
now := time.Now()
if notification != nil && notification.Value.Err != nil {
fmt.Printf("Transaction failed: %v\n", notification.Value.Err)
return
}
if notification != nil && notification.Context.Slot > 0 {
processedCh <- now
}
time.Sleep(1 * time.Millisecond)
}
}
}()
fmt.Printf("Subscription activated, waiting %d ms to ensure subscription is fully established...\n", *wsWaitTime)
time.Sleep(time.Duration(*wsWaitTime) * time.Millisecond)
startSend := time.Now()
encodedTx := base64.StdEncoding.EncodeToString(serializedTx)
sig, err := sendClient.SendEncodedTransaction(context.Background(), encodedTx)
if err != nil {
panic(fmt.Errorf("failed to send transaction: %w", err))
}
elapsedSend := time.Since(startSend)
if sig != expectedSig {
panic(fmt.Errorf("signature mismatch: got %s, expected %s", sig.String(), expectedSig.String()))
}
fmt.Printf("Transaction sent, signature: %s, sending time: %v\n", sig.String(), elapsedSend)
manualProcessedTime = time.Now()
wg.Add(1)
var pollProcessedTime time.Time
go func() {
defer wg.Done()
pollCtx, pollCancel := context.WithTimeout(ctx, 5*time.Second)
defer pollCancel()
for i := 0; i < 100; i++ {
select {
case <-pollCtx.Done():
return
case <-statusCh:
return
default:
txStatus, err := sendClient.GetSignatureStatuses(pollCtx, false, sig)
if err == nil && len(txStatus.Value) > 0 && txStatus.Value[0] != nil {
status := txStatus.Value[0].ConfirmationStatus
if status == rpc.ConfirmationStatusProcessed || status == rpc.ConfirmationStatusConfirmed || status == rpc.ConfirmationStatusFinalized {
now := time.Now()
statusMutex.Lock()
if pollProcessedTime.IsZero() {
pollProcessedTime = now
fmt.Printf("PROCESSED status detected via polling: %v after send\n", pollProcessedTime.Sub(startSend))
}
statusMutex.Unlock()
statusMutex.Lock()
if processedTime.IsZero() {
select {
case processedCh <- now:
fmt.Println("Notifying from polling to WebSocket processing channel")
default:
}
}
statusMutex.Unlock()
return
}
}
time.Sleep(time.Duration(*pollInterval) * time.Millisecond)
}
}
}()
fmt.Printf("Monitoring transaction status via WebSocket...\n")
timeout := time.After(30 * time.Second)
for {
allDone := !processedTime.IsZero() && !confirmedTime.IsZero() && !finalizedTime.IsZero()
if allDone {
break
}
select {
case <-timeout:
fmt.Println("Waiting for transaction completion timed out")
goto SUMMARY
case t := <-receivedCh:
statusMutex.Lock()
if receivedTime.IsZero() {
receivedTime = t
fmt.Printf("RECEIVED: %v after send\n", receivedTime.Sub(startSend))
}
statusMutex.Unlock()
case t := <-processedCh:
statusMutex.Lock()
if processedTime.IsZero() {
processedTime = t
fmt.Printf("PROCESSED (WebSocket): %v after send\n", processedTime.Sub(startSend))
}
statusMutex.Unlock()
case t := <-confirmedCh:
statusMutex.Lock()
if confirmedTime.IsZero() {
confirmedTime = t
fmt.Printf("CONFIRMED: %v after send\n", confirmedTime.Sub(startSend))
}
statusMutex.Unlock()
case t := <-finalizedCh:
statusMutex.Lock()
if finalizedTime.IsZero() {
finalizedTime = t
fmt.Printf("FINALIZED: %v after send\n", finalizedTime.Sub(startSend))
}
statusMutex.Unlock()
default:
time.Sleep(1 * time.Millisecond)
}
}
SUMMARY:
close(statusCh)
wg.Wait()
statusMutex.Lock()
defer statusMutex.Unlock()
fmt.Println("\n--- Transaction Processing Time Summary ---")
if !receivedTime.IsZero() {
fmt.Printf("Received time: %v after send\n", receivedTime.Sub(startSend))
}
if processedTime.IsZero() {
if !pollProcessedTime.IsZero() {
processedTime = pollProcessedTime
fmt.Printf("Processing time (via polling): %v after send\n", processedTime.Sub(startSend))
} else {
processedTime = manualProcessedTime
fmt.Printf("Processing time (estimated): %v after send\n", processedTime.Sub(startSend))
}
} else {
fmt.Printf("Processing time (WebSocket): %v after send\n", processedTime.Sub(startSend))
}
if !confirmedTime.IsZero() {
fmt.Printf("Confirmation time: %v after send\n", confirmedTime.Sub(startSend))
}
if !finalizedTime.IsZero() {
fmt.Printf("Finalization time: %v after send\n", finalizedTime.Sub(startSend))
}
if !processedTime.IsZero() && !finalizedTime.IsZero() {
fmt.Printf("Processing to finalization: %v\n", finalizedTime.Sub(processedTime))
}
}