-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProgram.cs
307 lines (214 loc) · 10.5 KB
/
Program.cs
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
using Newtonsoft.Json;
// SecretNET
using SecretNET;
using SecretNET.Tx;
using SecretNET.Common;
using SecretNET.Common.Storage;
using System.Reflection.Metadata;
// See https://aka.ms/new-console-template for more information
#region *** Helper functions / Objects ***
Action<string> writeHeadline = (text) =>
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"\r\n**************** {text} ****************\r\n");
Console.ForegroundColor = ConsoleColor.White;
};
Action<string, SecretTx> logSecretTx = (name, tx) =>
{
Console.WriteLine($"{name} Txhash: {tx?.Txhash}");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine($"(Gas used: {tx.GasUsed} - Gas wanted {tx.GasWanted})");
Console.ForegroundColor = ConsoleColor.White;
//Console.WriteLine($"\r\nCodeId: {JsonConvert.SerializeObject(tx.GetResponseJson(), Formatting.Indented)}");
if (tx is SingleSecretTx<Secret.Compute.V1Beta1.MsgStoreCodeResponse>)
{
Console.WriteLine($"\r\nCodeId: {((SingleSecretTx<Secret.Compute.V1Beta1.MsgStoreCodeResponse>)tx).Response.CodeId}");
}
if (tx is SingleSecretTx<Secret.Compute.V1Beta1.MsgInstantiateContractResponse>)
{
Console.WriteLine($"\r\nContractAddress: {((SingleSecretTx<Secret.Compute.V1Beta1.MsgInstantiateContractResponse>)tx)?.Response?.Address}");
}
if (tx != null && (tx.Code > 0 || (tx.Exceptions?.Any()).GetValueOrDefault()))
{
Console.ForegroundColor = ConsoleColor.Red;
if (tx.Code > 0 && !string.IsNullOrWhiteSpace(tx.Codespace))
{
Console.WriteLine($"\r\n!!!!!!!!!!!! Something went wrong => Code: {tx.Code}; Codespace: {tx.Codespace} !!!!!!!!!!!!");
}
if ((tx.Exceptions?.Any()).GetValueOrDefault())
{
foreach (var ex in tx.Exceptions)
{
Console.WriteLine($"\r\n!!!!!!!!!!!! Exception: {ex.Message} !!!!!!!!!!!!");
}
}
Console.WriteLine($"\r\n{tx.RawLog}");
Console.ForegroundColor = ConsoleColor.White;
Console.ReadLine();
}
};
#endregion
writeHeadline("Setup SecretNetworkClient / Wallet");
//var storageProvider = new InMemoryOnlyStorage(); // Temporary and most likely only for DEV
var storageProvider = new AesEncryptedFileStorage("","SuperSecurePassword");
var createWalletOptions = new CreateWalletOptions(storageProvider);
Wallet wallet = null;
if (await storageProvider.HasPrivateKey())
{
var storedMnemonic = await storageProvider.GetFirstMnemonic();
Console.WriteLine("Use stored mnemonic: " + storedMnemonic);
wallet = await Wallet.Create(storedMnemonic, options: createWalletOptions);
Console.WriteLine("wallet.Address: " + wallet.Address);
}
else
{
wallet = await Wallet.Create(options: createWalletOptions);
Console.WriteLine("wallet.Address: " + wallet.Address);
Console.WriteLine("Please first fund the wallet with some SCRT via https://faucet.pulsar.scrttestnet.com/ ");
Console.ReadLine();
}
var gprcUrl = "https://grpc.testnet.secretsaturn.net"; // get from https://github.com/scrtlabs/api-registry
var chainId = "pulsar-2";
var createClientOptions = new CreateClientOptions(gprcUrl, chainId, wallet)
{
AlwaysSimulateTransactions = true, // WARNING: On mainnet it's recommended to not simulate every transaction as this can burden your node provider.
};
var secretClient = new SecretNetworkClient(createClientOptions);
#region *** Get Balance ***
// *** Get Balance (1000000 uscrt == 1 SCRT) ***
//writeHeadline("Get Balance");
//var response = await secretClient.Query.Bank.Balance(wallet.Address);
//Console.WriteLine($"Balance: {(float.Parse(response.Amount) / 1000000f)} SCRT");
#endregion
#region *** Get Subacccount and Send $SCRT ***
//// Send SCRT
//var subaccountWallet = await wallet.GetSubaccount(1);
//Console.WriteLine($"\r\nSubaccount.Address: {subaccountWallet.Address}");
//var sendResponse = await secretClient.Tx.Bank.Send(toAddress: subaccountWallet.Address, amount: 1000000, denom: "uscrt");
//Console.WriteLine($"BroadcastResponse: {(sendResponse.Code == 0 ? "Success" : "Error (see response log)")}");
//var r1 = await secretClient.Query.Bank.Balance(subaccountWallet.Address);
//Console.WriteLine($"Subaccount Balance: {(float.Parse(r1.Amount) / 1000000f)} SCRT\r\n");
//Console.ReadLine();
#endregion
#region *** Simulate and broadcast a complex transaction ***
//var sendToAlice = new Cosmos.Bank.V1Beta1.MsgSend()
//{
// FromAddress = wallet.Address,
// ToAddress = subaccountWallet.Address
//};
//sendToAlice.Amount.Add(new Cosmos.Base.V1Beta1.Coin() { Amount = "1", Denom = "uscrt" });
//var sendToEve = new Cosmos.Bank.V1Beta1.MsgSend()
//{
// FromAddress = wallet.Address,
// ToAddress = subaccountWallet.Address // use the same address for simplicity
//};
//sendToEve.Amount.Add(new Cosmos.Base.V1Beta1.Coin() { Amount = "1", Denom = "uscrt" });
//var messages = new[] { sendToAlice, sendToEve };
//var simulate = await secretClient.Tx.Simulate(messages);
//Console.WriteLine($"Simulate => GasUsed {simulate.GasInfo.GasUsed} uscrt");
//var tx = await secretClient.Tx.Broadcast(messages, new TxOptions
//{
// // Adjust gasLimit up by 10% to account for gas estimation error
// GasLimit = (ulong)Math.Ceiling(simulate.GasInfo.GasUsed * 1.1),
//});
//logSecretTx("Broadcast result", tx);
//Console.ReadLine();
#endregion
#region *** Use of TransactionApprovalCallback ***
//// Skip transaction
//secretClient.TransactionApprovalCallback = async (approvalData) =>
//{
// Console.WriteLine("Approve Transaction:");
// Console.WriteLine("TxData:\r\n" + JsonConvert.SerializeObject(approvalData, Formatting.Indented) + "\r\n");
// Console.WriteLine("Approve? (y/n):");
// var approve = (Console.ReadLine()?.Equals("y", StringComparison.OrdinalIgnoreCase)).GetValueOrDefault();
// return new UserApprovalDecision(approve);
//};
//var sendResponseApprove = await secretClient.Tx.Bank.Send(toAddress: subaccountWallet.Address, amount: 1000000, denom: "uscrt");
//if (sendResponseApprove != null)
//{
// Console.WriteLine("Transaction was approved.");
// Console.WriteLine($"BroadcastResponse: {(sendResponseApprove.Code == 0 ? "Success" : "Error (see response log)")}");
//}
//else
//{
// Console.WriteLine("Transaction was not approved!");
//}
//secretClient.TransactionApprovalCallback = null;
#endregion
#region *** Auth ***
// *** Get Account ***
//writeHeadline("Get Account");
//var accountResponse = await secretClient.Query.Auth.Account(wallet.Address);
//Console.WriteLine("AccountResponse:\r\n" + JsonConvert.SerializeObject(accountResponse, Formatting.Indented) + "\r\n");
////Console.ReadLine();
#endregion
#region *** Codes ***
// *** Get Codes with source ***
//writeHeadline("Get my Codes with source");
//var codesResponse = await secretClient.Query.Compute.Codes();
//var withSource = codesResponse.Where(c => !string.IsNullOrWhiteSpace(c.Source) && c.CreatorAddress == wallet.Address).ToList();
//Console.WriteLine($"My Codes with source (Count: {withSource.Count} ):\r\n" + JsonConvert.SerializeObject(withSource, Formatting.Indented) + "\r\n");
////Console.ReadLine();
#endregion
#region *** Smart Contract (Upload, Init, Query, Execute) ***
// *** Smart Contract (Upload, Init, Query, Execute) ***
writeHeadline("Upload Contract (mysimplecounter.wasm.gz)");
// *** Upload Contract ***
// https://secretjs.scrt.network/#secretjstxcomputestorecode
byte[] wasmByteCode = File.ReadAllBytes(@"..\..\..\..\..\Resources\mysimplecounter.wasm.gz");
// MsgStoreCode
var msgStoreCodeCounter = new MsgStoreCode(wasmByteCode,
source: "https://github.com/scrtlabs/secret-template", // Source is a valid absolute HTTPS URI to the contract's source code, optional
builder: "enigmampc/secret-contract-optimizer:latest" // Builder is a valid docker image name with tag, optional
);
var storeCodeResponse = await secretClient.Tx.Compute.StoreCode(msgStoreCodeCounter);
logSecretTx("StoreCodeResponse", storeCodeResponse);
// *** Init Contract ***
writeHeadline("Init Contract with CodeId " + storeCodeResponse.Response.CodeId);
string? contractAddress = null;
string contractCodeHash = null;
if (storeCodeResponse.Response.CodeId > 0)
{
var codeId = storeCodeResponse.Response.CodeId;
contractCodeHash = await secretClient.Query.Compute.GetCodeHashByCodeId(codeId);
var msgInitContract = new MsgInstantiateContract(
codeId: codeId,
label: $"MySimpleCouter {codeId}",
initMsg: new { count = 100 },
codeHash: contractCodeHash); // optional but way faster
var initContractResponse = await secretClient.Tx.Compute.InstantiateContract(msgInitContract);
logSecretTx("InstantiateContract", initContractResponse);
contractAddress = initContractResponse?.Response?.Address;
Console.WriteLine("Contract CodeHash: " + contractCodeHash);
Console.WriteLine("Contract Address: " + contractAddress);
}
//Console.ReadLine();
#region *** Query Contract ***
//string contractAddress = "Set manual if needed";
//string contractCodeHash = "Set manual if needed";
// *** Query Contract ***
writeHeadline("Query Contract with address " + contractAddress);
var queryMsg = new { get_count = new { } };
Console.WriteLine("Query : " + JsonConvert.SerializeObject(queryMsg, Formatting.Indented) + "\r\n");
var queryContractResult = await secretClient.Query.Compute.QueryContract<object>(contractAddress, queryMsg, contractCodeHash);
Console.WriteLine("QueryContractResult:\r\n " + queryContractResult.Response);
//Console.ReadLine();
#endregion
#region *** Execute Contract ***
// *** Execute Contract ***
writeHeadline("Execute Contract with address " + contractAddress);
var executeMsg = new { increment = new { } };
Console.WriteLine("Execute : " + JsonConvert.SerializeObject(executeMsg, Formatting.Indented) + "\r\n");
var msgExecuteContract = new MsgExecuteContract(
contractAddress: contractAddress,
msg: executeMsg,
codeHash: contractCodeHash);
var executeContractResponse = await secretClient.Tx.Compute.ExecuteContract(msgExecuteContract);
logSecretTx("ExecuteContract", executeContractResponse);
Thread.Sleep(1000); // give some time to let it settle
var queryContractResult2 = await secretClient.Query.Compute.QueryContract<object>(contractAddress, queryMsg, contractCodeHash);
Console.WriteLine("\r\nQueryContractResult (again) :\r\n " + queryContractResult2.Response);
Console.ReadLine();
#endregion
#endregion