-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworld.js
353 lines (295 loc) · 8 KB
/
world.js
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
const fs = require("fs");
const { setWorldConstructor } = require("cucumber");
const { CodePromise, ContractPromise } = require("@polkadot/api-contract");
const { ApiPromise, WsProvider, Keyring } = require("@polkadot/api");
const { BN } = require("@polkadot/util");
// require uses the path relative to the file it is called from
const contractAbi = require("../../target/ink/asset_co2_emissions.json");
// fs.readFileSync uses the path relative to the cwd of the calling process (should be root of the project)
const contract = JSON.parse(
fs.readFileSync("./target/ink/asset_co2_emissions.contract")
);
// Max gas limit
const REF_TIME = new BN(300_000_000_000);
const PROOF_SIZE = new BN(1000000);
// Unlimited storage deposit
const STORAGE_DEPOSIT_LIMIT = null;
const INITIAL_BALANCE = 100_000_000_000_000;
// dev mnemonic
const MNENOMIC =
"bottom drive obey lake curtain smoke basket hold race lonely fit walk";
class UserStoryWorld {
constructor() {
this.api = null;
this.contract = null;
this.codeHash = null;
this.sudo = null;
this.result = "";
this.events = [];
this.readOutput = null;
this.accounts = {};
this.keyring = new Keyring({ type: "sr25519" });
this.defaultTxOptions = null;
}
async prepareEnvironment() {
this.sudo = this.keyring.addFromUri("//Alice");
const wsProvider = new WsProvider("ws://127.0.0.1:9944");
this.api = await ApiPromise.create({ provider: wsProvider });
this.defaultTxOptions = {
gasLimit: this.api.registry.createType("WeightV2", {
refTime: REF_TIME,
proofSize: PROOF_SIZE,
}),
STORAGE_DEPOSIT_LIMIT,
};
await this.deploySmartContract(contract);
await this.initiateAccountWithBalance("Seller", INITIAL_BALANCE);
await this.initiateAccountWithBalance("Buyer", INITIAL_BALANCE);
await this.initiateAccountWithBalance("Eve", INITIAL_BALANCE);
}
async deploySmartContract(contract) {
const code = new CodePromise(
this.api,
contractAbi,
contract.source.wasm
);
const tx = code.tx.new(this.defaultTxOptions);
// Wait for the smart contract to deploy, and contract address set
await new Promise((resolve) => {
this.signAndSend(this.sudo, tx, async (result) => {
this.setContractAddress(result);
await this.setCodeHash(this.contract.address);
resolve();
});
});
}
async setCodeHash(contractAddress) {
const { codeHash } = (
await this.api.query.contracts.contractInfoOf(contractAddress)
).toHuman();
this.codeHash = codeHash;
}
async upgradeContract(contract) {
let oldContract = this.contract;
await this.deploySmartContract(contract);
const { gasRequired, storageDeposit, result, output } =
await this.dryRun(
this.sudo,
"setCode",
this.defaultTxOptions,
this.codeHash
);
if (result.isOk) {
this.readOutput = output.toJSON().ok;
return this.readOutput;
}
let txOptions = {
gasLimit: gasRequired,
storageDeposit,
};
let upgradeExtrinsic = oldContract.tx["setCode"](
txOptions,
this.codeHash
);
await this.signAndSend(this.sudo, upgradeExtrinsic, () => {});
}
async setContractOwner(senderName, newOwnerName) {
const newOwner = this.accounts[newOwnerName];
return await this.sendMessage(
senderName,
"setContractOwner",
newOwner.address
);
}
async blastAsset(senderName, metadata, assetParent, assetEmissions) {
const sender = this.accounts[senderName];
return await this.sendMessage(
senderName,
"assetCO2Emissions::blast",
sender.address,
metadata,
assetEmissions,
assetParent
);
}
async transferAsset(senderName, assetId, recipientName, emissions) {
const receiver = this.accounts[recipientName];
return await this.sendMessage(
senderName,
"assetCO2Emissions::transfer",
receiver.address,
assetId,
emissions
);
}
async addEmission(senderName, assetId, emission) {
return await this.sendMessage(
senderName,
"assetCO2Emissions::addEmissions",
assetId,
emission
);
}
async pauseAsset(senderName, assetId) {
return await this.sendMessage(
senderName,
"assetCO2Emissions::pause",
assetId
);
}
async getOwnerOf(senderName, assetId) {
return this.readContract(
senderName,
"assetCO2Emissions::ownerOf",
assetId
);
}
async getAsset(senderName, assetId) {
return this.readContract(
senderName,
"assetCO2Emissions::getAsset",
assetId
);
}
async queryEmissions(senderName, assetId) {
return this.readContract(
senderName,
"assetCO2Emissions::queryEmissions",
assetId
);
}
async initiateAccountWithBalance(accountName, balance) {
const account = this.keyring.addFromUri(MNENOMIC + "//" + accountName);
this.accounts[accountName] = account;
const extrinsic = this.api.tx.sudo.sudo(
this.api.tx.balances.setBalance(account.address, balance, 0)
);
await this.signAndSend(this.sudo, extrinsic, () => {});
}
// Helper to split an asset into the given child assets
async createAssetTree(caller, assets, start = 0) {
for (let [i, asset] of assets.entries()) {
let emissions = [];
for (const emission of asset.emissions) {
emissions.push({
category: emission.emission_category,
dataSource: emission.dataSource,
balanced: true,
date: emission.date,
value: emission.value,
});
}
let assetParent = null;
let parentId = i + start;
if (parentId > 0) {
assetParent = parentId;
// pause the parent asset
await this.pauseAsset(caller, parentId);
}
await this.blastAsset(
caller,
JSON.stringify(asset.metadata),
assetParent,
emissions
);
}
}
getEvents(result) {
if (!result.contractEvents) return [];
let events = [];
for (const event of result.contractEvents) {
const eventItem = {
event: {
name: event.event.identifier,
args: event.args.map((v) => v.toHuman()),
},
};
events.push(eventItem);
}
return events;
}
setContractAddress({ contract }) {
const contractAddress = contract.address.toString();
// Proper way of creating Contract JS Object
this.contract = new ContractPromise(
this.api,
contractAbi,
contractAddress
);
}
async getContractState(sender, message, ...params) {
return await this.dryRun(sender, message, ...params);
}
async dryRun(sender, message, ...params) {
const o = await this.contract.query[message](sender.address, ...params);
if (!o.result.isOk) {
let registryErr = this.api.registry.findMetaError(
o.result.dispatchError.asModule
);
throw new Error(
`Tx failed with error: ${JSON.stringify(registryErr, null, 2)}`
);
}
return o;
}
async readContract(senderName, message, ...params) {
const sender = this.accounts[senderName];
const { result, output } = await this.getContractState(
sender,
message,
this.defaultTxOptions,
...params
);
if (result.isOk) {
this.readOutput = output.toJSON().ok;
return this.readOutput;
}
}
async sendMessage(senderName, message, ...params) {
const sender = this.accounts[senderName];
const { gasRequired, storageDeposit, output } = await this.dryRun(
sender,
message,
this.defaultTxOptions,
...params
);
// Check if contract error exists
if (output.toJSON().ok && output.toJSON().ok.err) {
return output.toJSON().ok.err;
}
let txOptions = {
gasLimit: gasRequired,
storageDeposit,
};
let extrinsic = this.contract.tx[message](txOptions, ...params);
await new Promise((resolve) => {
this.signAndSend(sender, extrinsic, (result) => {
this.events = this.getEvents(result);
resolve();
});
});
}
async signAndSend(wallet, extrinsic, callback) {
await extrinsic.signAndSend(wallet, (result) => {
const status = result.status;
const dispatchError = result.dispatchError;
if (status.isInBlock || status.isFinalized) {
if (dispatchError) {
let registryErr = this.api.registry.findMetaError(
dispatchError.asModule
);
throw new Error(
`Tx failed with error: ${JSON.stringify(
registryErr,
null,
2
)}`
);
} else {
callback(result);
}
}
});
}
}
setWorldConstructor(UserStoryWorld);