-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
306 lines (258 loc) · 9.17 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
using Miyabi;
using Miyabi.ClientSdk;
using Miyabi.Common.Models;
using Miyabi.Contract.Client;
using Miyabi.Contract.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using SmartContractSample.ContractFiles;
using Utility;
using Miyabi.Cryptography;
namespace SmartContractSample
{
/// <summary>
/// Program.cs deploys, instantiates, invokes and queries a smart contracts.
/// </summary>
class Program
{
const string ContractFilePath = "ContractFiles\\SampleContract.cs";
static readonly string ContractName =
typeof(SampleContract).FullName;
const string InstanceName = "SampleContractInstance";
static readonly KeyPair TableAdmin =
Utils.GetTableAdminKeyPair();
static readonly KeyPair ContractAdmin =
Utils.GetContractAdminKeyPair();
static readonly KeyPair ContractInstanceOwner = Utils.GetOwnerKeyPair();
static readonly ByteString AssemblyId =
ContractUtils.GetAssemblyId(new[]
{
File.ReadAllText(ContractFilePath)
});
static async Task Main(string[] args)
{
var handler = Utils.GetBypassRemoteCertificateValidationHandler();
var config = new SdkConfig(Utils.ApiUrl);
var client = new Client(config, handler);
var generalApi = new GeneralApi(client);
var contractClient = new ContractClient(client);
// Account aliases
var fromAccount = Utils.GetUser0KeyPair();
var toAccount = Utils.GetUser1KeyPair();
// In order to use miyabi module, registering types is required.
ContractTypesRegisterer.RegisterTypes();
// Deploy the contract files to blockchain
await DeployContract(generalApi);
// Create instance of contract using the deployed binaries
await InstantiateContract(generalApi);
// Call a queryable method. This operation is read only.
// Get the name of the Asset table which stores the digital tokens
await QueryMethod(contractClient,
nameof(SampleContract.GetAssetTableName),
"Check Asset table name in miyabi. Expected: SampleAssetTokenTable_SampleContractInstance",
null);
// Call an invokable method. This operation can be read-write.
// Register an account in the Asset table
await InvokeContract(
generalApi,
nameof(SampleContract.RegisterAccount),
new KeyPair[] { },
new[] { fromAccount.PublicKey.ToString() });
// Call a queryable method. This operation is read only.
// Check whether the account is registered
await QueryMethod(contractClient,
nameof(SampleContract.IsAccountRegistered),
"Check if account registered. Expected: true",
new[] { fromAccount.PublicKey.ToString() });
// Call an invokable method. This operation can be read-write.
// Generate digital tokens
await InvokeContract(
generalApi,
nameof(SampleContract.GenerateAssetToken),
new KeyPair[] { },
new[] { fromAccount.PublicKey.ToString(), "100.0" });
// Call a queryable method. This operation is read only.
// Check the account balance
await QueryMethod(contractClient,
nameof(SampleContract.GetBalanceOf),
"Get balance of account. Expected: 100.0",
new[] { fromAccount.PublicKey.ToString() });
// Call an invokable method. This operation can be read-write.
// Move the digital tokens amongst different accounts
await InvokeContract(
generalApi,
nameof(SampleContract.MoveAssetToken),
new[] { fromAccount },
new[] { fromAccount.PublicKey.ToString(), toAccount.PublicKey.ToString(), "100.0" });
// Call a queryable method. This operation is read only.
// Check whether the account is registered
await QueryMethod(contractClient,
nameof(SampleContract.IsAccountRegistered),
"Check if account registered. Expected: true",
new[] { fromAccount.PublicKey.ToString() });
// Call a queryable method. This operation is read only.
// Check whether the account is registered
await QueryMethod(contractClient,
nameof(SampleContract.IsAccountRegistered),
"Check if account registered. Expected: true",
new[] { toAccount.PublicKey.ToString() });
// Call an invokable method. This operation can be read-write.
// Delete an account
await InvokeContract(
generalApi,
nameof(SampleContract.DeleteAccount),
new[] { fromAccount },
new[] { fromAccount.PublicKey.ToString() });
// Call a queryable method. This operation is read only.
// Check whether the account is registered
await QueryMethod(contractClient,
nameof(SampleContract.IsAccountRegistered),
"Check if account registered. Expected: false",
new[] { fromAccount.PublicKey.ToString() });
// Delete the contract instance.
// This will perform related table and data delete also.
await DeleteContractInstance(generalApi);
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
private static async Task DeployContract(GeneralApi generalApi)
{
Console.WriteLine($"Deploying contract {ContractName}");
// Create entry
var sources = new[]
{
await File.ReadAllTextAsync(ContractFilePath)
};
var instantiators = new[]
{
new PublicKeyAddress(ContractInstanceOwner.PublicKey)
};
var entry =
new ContractDeploy(sources, instantiators: instantiators);
// Create transaction
var tx = TransactionCreator.CreateTransaction(
new[] { entry },
new[]
{
new SignatureCredential(
ContractAdmin.PublicKey)
});
// Sign transaction.
// Deploy contract requires contract admin signature
var txSigned = TransactionCreator.SignTransaction(
tx,
new[] { ContractAdmin.PrivateKey });
// Send transaction
await generalApi.SendTransactionAsync(txSigned);
// Wait until the transaction is stored in a block and get the result
var result = await Utils.WaitTx(generalApi, tx.Id);
Console.WriteLine($"TxId={tx.Id}, Tx Result={result}");
}
private static async Task InstantiateContract(GeneralApi generalApi)
{
Console.WriteLine($"\nCreate new contract instance: {InstanceName}");
// Create gen entry
var instanceOwners = new Address[] { new PublicKeyAddress(ContractInstanceOwner) };
var entry = new ContractInstantiate(
AssemblyId,
ContractName,
InstanceName,
instanceOwners);
// Create signed transaction with builder.
// To generate instantiate contract,
// table admin and contract owner private key is required.
var txSigned = TransactionCreator.CreateTransactionBuilder(
new[] { entry },
new[]
{
new SignatureCredential(
TableAdmin.PublicKey),
new SignatureCredential(ContractInstanceOwner.PublicKey)
})
.Sign(TableAdmin.PrivateKey)
.Sign(ContractInstanceOwner.PrivateKey)
.Build();
await generalApi.SendTransactionAsync(txSigned);
var result = await Utils.WaitTx(generalApi, txSigned.Id);
Console.WriteLine($"TxId={txSigned.Id}, Tx Result={result}");
}
private static async Task InvokeContract(
GeneralApi generalApi,
string methodName,
KeyPair[] signers,
string[] parameters)
{
Console.WriteLine($"\nInvoking contract method {methodName}");
// Create gen entry
var entry =
new ContractInvoke(
AssemblyId,
ContractName,
InstanceName,
methodName,
parameters);
// Create signed transaction with builder.
// Contract invoke requires contract owner's private key
var requiredCredentials = new List<SignatureCredential>();
requiredCredentials
.AddRange(
signers.Select(
keyPair => new SignatureCredential(keyPair.PublicKey)));
var txBuilder = TransactionCreator.CreateTransactionBuilder(
new[] { entry },
requiredCredentials);
foreach (var keyPair in signers)
{
txBuilder.Sign(keyPair.PrivateKey);
}
var txSigned = txBuilder.Build();
await generalApi.SendTransactionAsync(txSigned);
var result = await Utils.WaitTx(generalApi, txSigned.Id);
Console.WriteLine($"TxId={txSigned.Id}, Tx Result={result}");
}
private static async Task QueryMethod(
ContractClient contractClient,
string methodName,
string outputMessage,
string[] arguments)
{
Console.WriteLine($"\nQuerying contract method: {methodName}");
var result = await contractClient.QueryContractAsync(
AssemblyId,
ContractName,
InstanceName,
methodName,
arguments);
Console.WriteLine(outputMessage);
Console.WriteLine($"Query output:={result.Value}");
}
private static async Task DeleteContractInstance(GeneralApi generalApi)
{
Console.WriteLine($"\nDeleting contract instance: {InstanceName}");
// Create delete contract instance entry
var entry = new ContractInstanceDelete(
AssemblyId,
ContractName,
InstanceName);
// Create signed transaction with builder.
// Delete contract instance requires
// signature of the contract instance owners.
var txSigned = TransactionCreator.CreateTransactionBuilder(
new[] { entry },
new[]
{
// Contract Instance Owner
new SignatureCredential(ContractInstanceOwner.PublicKey)
})
.Sign(ContractInstanceOwner.PrivateKey)
.Build();
await generalApi.SendTransactionAsync(txSigned);
var result = await Utils.WaitTx(generalApi, txSigned.Id);
Console.WriteLine($"TxId={txSigned.Id}, Tx Result={result}");
}
}
}