-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
231 lines (198 loc) Β· 8.36 KB
/
main.go
File metadata and controls
231 lines (198 loc) Β· 8.36 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
package main
import (
"context"
"fmt"
kwilClientType "github.com/trufnetwork/kwil-db/core/client/types"
kwilTypes "github.com/trufnetwork/kwil-db/core/types"
"log"
"strings"
"time"
"github.com/trufnetwork/kwil-db/core/crypto"
"github.com/trufnetwork/kwil-db/core/crypto/auth"
"github.com/trufnetwork/sdk-go/core/tnclient"
"github.com/trufnetwork/sdk-go/core/types"
"github.com/trufnetwork/sdk-go/core/util"
)
// deployStreamSafely demonstrates the proper way to deploy a stream with WaitForTx
func deployStreamSafely(ctx context.Context, client *tnclient.Client, streamId util.StreamId) error {
fmt.Println("π Deploying stream...")
// Step 1: Submit deployment transaction
deployTx, err := client.DeployStream(ctx, streamId, types.StreamTypePrimitive)
if err != nil {
return fmt.Errorf("failed to submit deployment: %v", err)
}
fmt.Printf(" Deployment submitted: %s\n", deployTx.String())
// Step 2: Wait for deployment to be mined
fmt.Println("β³ Waiting for deployment to be mined...")
txRes, err := client.WaitForTx(ctx, deployTx, time.Second*5)
if err != nil {
return fmt.Errorf("failed to wait for deployment: %v", err)
}
// Step 3: Check if deployment was successful
if txRes.Result.Code != uint32(kwilTypes.CodeOk) {
return fmt.Errorf("deployment failed: %s", txRes.Result.Log)
}
fmt.Println("β
Stream deployed and confirmed on-chain")
return nil
}
// destroyStreamSafely demonstrates the proper way to destroy a stream with WaitForTx
func destroyStreamSafely(ctx context.Context, client *tnclient.Client, streamId util.StreamId) error {
fmt.Println("ποΈ Destroying stream...")
// Step 1: Submit destruction transaction
destroyTx, err := client.DestroyStream(ctx, streamId)
if err != nil {
return fmt.Errorf("failed to submit destruction: %v", err)
}
fmt.Printf(" Destruction submitted: %s\n", destroyTx.String())
// Step 2: Wait for destruction to be mined
fmt.Println("β³ Waiting for destruction to be mined...")
txRes, err := client.WaitForTx(ctx, destroyTx, time.Second*5)
if err != nil {
return fmt.Errorf("failed to wait for destruction: %v", err)
}
// Step 3: Check if destruction was successful
if txRes.Result.Code != uint32(kwilTypes.CodeOk) {
return fmt.Errorf("destruction failed: %s", txRes.Result.Log)
}
fmt.Println("β
Stream destroyed and confirmed on-chain")
return nil
}
func main() {
ctx := context.Background()
// Set up client
pk, err := crypto.Secp256k1PrivateKeyFromHex("<PRIVATE_KEY_HEX>")
if err != nil {
log.Fatalf("Failed to parse private key: %v", err)
}
signer := &auth.EthPersonalSigner{Key: *pk}
endpoint := "https://gateway.mainnet.truf.network"
tnClient, err := tnclient.NewClient(ctx, endpoint, tnclient.WithSigner(signer))
if err != nil {
log.Fatalf("Failed to create TN client: %v", err)
}
streamId := util.GenerateStreamId(fmt.Sprintf("lifecycle-demo-%d", time.Now().Unix()))
fmt.Printf("π Transaction Lifecycle Best Practices Demo\n")
fmt.Printf("===========================================\n")
fmt.Printf("Stream ID: %s\n", streamId)
fmt.Printf("Endpoint: %s\n\n", endpoint)
// Example 1: Proper stream deployment with WaitForTx
fmt.Println("π EXAMPLE 1: Safe Stream Deployment")
fmt.Println("-------------------------------------")
if err := deployStreamSafely(ctx, tnClient, streamId); err != nil {
log.Fatalf("Deployment failed: %v", err)
}
fmt.Println()
// Load primitive actions
primitiveActions, err := tnClient.LoadPrimitiveActions()
if err != nil {
log.Fatalf("Failed to load primitive actions: %v", err)
}
dataProvider := tnClient.Address()
// Example 2: Demonstrate two ways to insert records synchronously
fmt.Println("π EXAMPLE 2: Synchronous Record Insertion")
fmt.Println("------------------------------------------")
// Method A: Using WithSyncBroadcast
fmt.Println("π
°οΈ Method A: Using WithSyncBroadcast(true)")
testValue1 := 123.45
insertTx1, err := primitiveActions.InsertRecord(ctx, types.InsertRecordInput{
DataProvider: dataProvider.Address(),
StreamId: streamId.String(),
EventTime: int(time.Now().Unix()),
Value: testValue1,
}, kwilClientType.WithSyncBroadcast(true))
if err != nil {
log.Fatalf("Failed to insert record with WithSyncBroadcast: %v", err)
}
fmt.Printf(" β
Record inserted and mined: %s\n", insertTx1.String())
// Method B: Manual WaitForTx
fmt.Println("π
±οΈ Method B: Manual WaitForTx")
testValue2 := 456.78
insertTx2, err := primitiveActions.InsertRecord(ctx, types.InsertRecordInput{
DataProvider: dataProvider.Address(),
StreamId: streamId.String(),
EventTime: int(time.Now().Unix()) + 1,
Value: testValue2,
})
if err != nil {
log.Fatalf("Failed to submit record insertion: %v", err)
}
fmt.Printf(" Transaction submitted: %s\n", insertTx2.String())
fmt.Println(" β³ Waiting for insertion to be mined...")
txRes, err := tnClient.WaitForTx(ctx, insertTx2, time.Second*5)
if err != nil {
log.Fatalf("Failed to wait for insertion: %v", err)
}
if txRes.Result.Code != uint32(kwilTypes.CodeOk) {
log.Fatalf("Insertion failed: %s", txRes.Result.Log)
}
fmt.Printf(" β
Record inserted and confirmed: %s\n", insertTx2.String())
fmt.Println()
// Verify both records are accessible
fmt.Println("π EXAMPLE 3: Verify Records After Synchronous Insertion")
fmt.Println("-------------------------------------------------------")
records, err := primitiveActions.GetRecord(ctx, types.GetRecordInput{
DataProvider: dataProvider.Address(),
StreamId: streamId.String(),
})
if err != nil {
log.Fatalf("Failed to retrieve records: %v", err)
}
fmt.Printf("β
Retrieved %d records from stream:\n", len(records.Results))
for i, record := range records.Results {
fmt.Printf(" Record %d: %s (Time: %d)\n", i+1, record.Value.String(), record.EventTime)
}
fmt.Println()
// Example 3: Proper stream destruction with verification
fmt.Println("π EXAMPLE 4: Safe Stream Destruction with Verification")
fmt.Println("------------------------------------------------------")
if err := destroyStreamSafely(ctx, tnClient, streamId); err != nil {
log.Fatalf("Destruction failed: %v", err)
}
// Verify destruction by trying to insert (should fail)
fmt.Println("π§ͺ Testing insertion after destruction...")
insertTx, err := primitiveActions.InsertRecord(ctx, types.InsertRecordInput{
DataProvider: dataProvider.Address(),
StreamId: streamId.String(),
EventTime: int(time.Now().Unix()) + 2,
Value: 789.01,
}, kwilClientType.WithSyncBroadcast(true))
if err != nil {
fmt.Printf("β
PERFECT: Insertion failed immediately (transaction rejected)\n")
fmt.Printf(" Error: %v\n", err)
} else {
// Transaction was submitted, now check if it succeeded or failed on-chain
fmt.Printf(" Transaction submitted: %s\n", insertTx.String())
fmt.Println(" β³ Waiting to see if transaction succeeds or fails...")
txRes, waitErr := tnClient.WaitForTx(ctx, insertTx, time.Second*5)
if waitErr != nil {
fmt.Printf("β
GOOD: Transaction failed to process\n")
fmt.Printf(" Wait Error: %v\n", waitErr)
} else if txRes.Result.Code != uint32(kwilTypes.CodeOk) {
fmt.Printf("β
PERFECT: Transaction was rejected on-chain (Code: %d)\n", txRes.Result.Code)
fmt.Printf(" Transaction Error: %s\n", txRes.Result.Log)
} else {
fmt.Printf("β οΈ WARNING: Insertion succeeded after destruction!\n")
fmt.Printf(" This indicates a race condition - stream destruction wasn't complete\n")
}
}
// Try to retrieve records (should also fail)
fmt.Println("π§ͺ Testing record retrieval after destruction...")
_, err = primitiveActions.GetRecord(ctx, types.GetRecordInput{
DataProvider: dataProvider.Address(),
StreamId: streamId.String(),
})
if err != nil {
fmt.Printf("β
PERFECT: Record retrieval failed as expected\n")
fmt.Printf(" Error: %v\n", err)
} else {
fmt.Printf("β οΈ WARNING: Records still accessible after destruction\n")
}
fmt.Println("\n" + strings.Repeat("=", 60))
fmt.Println("π KEY TAKEAWAYS:")
fmt.Println(strings.Repeat("=", 60))
fmt.Println("β
Use WaitForTx() for DeployStream and DestroyStream")
fmt.Println("β
Use WithSyncBroadcast(true) for record operations when order matters")
fmt.Println("β
Always check transaction result codes")
fmt.Println("β
Verify operations completed before proceeding with dependent actions")
fmt.Println("β οΈ Async operations can cause race conditions in sequential workflows")
}