-
Notifications
You must be signed in to change notification settings - Fork 8
/
utils.js
448 lines (386 loc) · 13.4 KB
/
utils.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
const { ethers } = require("hardhat");
const {
getAddress,
provider,
keccak256,
encodeRlp,
getSigners,
parseUnits,
getContractAt,
toBeArray,
isHexString,
zeroPadValue,
Interface,
toUtf8Bytes,
} = ethers;
const { getFacets } = require("../../scripts/config/facet-deploy.js");
const { oneWeek, oneMonth, maxPriorityFeePerGas } = require("./constants");
const Role = require("../../scripts/domain/Role");
const { expect } = require("chai");
const Offer = require("../../scripts/domain/Offer");
const { zeroPadBytes } = require("ethers");
function getEvent(receipt, factory, eventName) {
let found = false;
const eventFragment = factory.interface.fragments.filter((e) => e.name == eventName);
const iface = new Interface(eventFragment);
for (const log in receipt.logs) {
const topics = receipt.logs[log].topics;
for (const index in topics) {
const encodedTopic = topics[index];
try {
// CHECK IF TOPIC CORRESPONDS TO THE EVENT GIVEN TO FN
const event = iface.getEvent(encodedTopic);
if (event && event.name == eventName) {
found = true;
const eventArgs = iface.parseLog(receipt.logs[log]).args;
return eventArgs;
}
} catch (e) {
if (e.message.includes("no matching event")) continue;
console.log("event error: ", e);
throw new Error(e);
}
}
}
if (!found) {
throw new Error(`Event with name ${eventName} was not emitted!`);
}
}
function eventEmittedWithArgs(receipt, factory, eventName, args) {
let found = false;
let match = false;
const eventFragment = factory.interface.fragments.filter((e) => e.name == eventName);
const iface = new Interface(eventFragment);
for (const log in receipt.logs) {
const topics = receipt.logs[log].topics;
for (const index in topics) {
const encodedTopic = topics[index];
try {
// CHECK IF TOPIC CORRESPONDS TO THE EVENT GIVEN TO FN
const event = iface.getEvent(encodedTopic);
if (event.name == eventName) {
found = true;
const eventArgs = iface.parseLog(receipt.logs[log]).args;
match = compareArgs(eventArgs, args);
return match;
}
} catch (e) {
if (e.message.includes("no matching event")) continue;
console.log("event error: ", e);
throw new Error(e);
}
}
}
if (!found) {
throw new Error(`Event with name ${eventName} was not emitted!`);
}
}
function compareArgs(eventArgs, args) {
//loop over args because eventArgs always have 2 entries for each argument
let i = args.length;
while (i--) {
if (args[i] != eventArgs[i]) return false;
}
return true;
}
/** Predicate to compare offer structs in emitted events
* Bind expected offer struct to this function and pass it to .withArgs() instead of the expected offer struct
* If returned and expected offer structs are equal, the test will pass, otherwise it raises an error
*
* Example
*
* await expect(
offerHandler.connect(assistant).createOffer(offer, offerDates, offerDurations, disputeResolver.id, agentId)
)
.to.emit(offerHandler, "OfferCreated")
.withArgs(
nextOfferId,
offer.sellerId,
compareOfferStructs.bind(offerStruct), <====== BIND OFFER STRUCT TO THIS FUNCTION
offerDatesStruct,
offerDurationsStruct,
disputeResolutionTermsStruct,
offerFeesStruct,
agentId,
await assistant.getAddress(),
);
*
* @param {*} returnedOffer
* @returns
*/
function compareOfferStructs(returnedOffer) {
expect(Offer.fromStruct(returnedOffer).toStruct()).to.deep.equal(this);
return true;
}
async function setNextBlockTimestamp(timestamp) {
if (typeof timestamp == "string" && timestamp.startsWith("0x0") && timestamp.length > 3)
timestamp = "0x" + timestamp.substring(3);
await provider.send("evm_setNextBlockTimestamp", [timestamp]);
await provider.send("evm_mine", []);
}
function getSignatureParameters(signature) {
if (!isHexString(signature)) {
throw new Error('Given value "'.concat(signature, '" is not a valid hex string.'));
}
signature = signature.substring(2);
const r = "0x" + signature.substring(0, 64);
const s = "0x" + signature.substring(64, 128);
const v = parseInt(signature.substring(128, 130), 16);
return {
r: r,
s: s,
v: v,
};
}
async function prepareDataSignatureParameters(
user,
customTransactionTypes,
primaryType,
message,
forwarderAddress,
domainName = "Boson Protocol",
domainVersion = "V2",
type = "Protocol"
) {
// Initialize data
const domainType =
type == "Protocol"
? [
{ name: "name", type: "string" },
{ name: "version", type: "string" },
{ name: "verifyingContract", type: "address" },
{ name: "salt", type: "bytes32" },
]
: [
{ name: "name", type: "string" },
{ name: "version", type: "string" },
{ name: "chainId", type: "uint256" },
{ name: "verifyingContract", type: "address" },
];
const domainData = {
name: domainName ?? "Boson Protocol",
version: domainVersion ?? "V2",
verifyingContract: forwarderAddress,
};
if (type == "Protocol") {
//hardhat default chain id is 31337
domainData.salt = zeroPadValue("0x" + 31337n.toString(16), 32);
} else {
const { chainId } = await provider.getNetwork();
domainData.chainId = chainId.toString();
}
// Prepare the types
let metaTxTypes = {
EIP712Domain: domainType,
};
metaTxTypes = Object.assign({}, metaTxTypes, customTransactionTypes);
// Prepare the data to sign
let dataToSign = JSON.stringify({
types: metaTxTypes,
domain: domainData,
primaryType: primaryType,
message: message,
});
// Sign the data
const signature = await provider.send("eth_signTypedData_v4", [await user.getAddress(), dataToSign]);
// Collect the Signature components
const { r, s, v } = getSignatureParameters(signature);
return {
r: r,
s: s,
v: v,
signature,
};
}
function calculateVoucherExpiry(block, voucherRedeemableFromDate, voucherValidDuration) {
const startDate =
BigInt(block.timestamp) > BigInt(voucherRedeemableFromDate)
? BigInt(block.timestamp)
: BigInt(voucherRedeemableFromDate);
return (startDate + BigInt(voucherValidDuration)).toString();
}
function applyPercentage(base, percentage) {
return ((BigInt(base) * BigInt(percentage)) / BigInt(10000)).toString();
}
function calculateContractAddress(senderAddress, senderNonce) {
const nonce = BigInt(senderNonce);
const nonceHex = nonce == 0n ? "0x" : toBeArray(nonce);
const input_arr = [senderAddress, nonceHex];
const rlp_encoded = encodeRlp(input_arr);
const contract_address_long = keccak256(rlp_encoded);
const contract_address = "0x" + contract_address_long.substring(26); //Trim the first 24 characters.
return getAddress(contract_address);
}
const paddingType = {
NONE: 0,
START: 1,
END: 2,
};
function getMappingStoragePosition(slot, key, padding = paddingType.NONE) {
let keyBuffer;
switch (padding) {
case paddingType.NONE:
keyBuffer = toUtf8Bytes(key);
break;
case paddingType.START:
keyBuffer = Buffer.from(zeroPadBytes(key, 32).toString().slice(2), "hex");
break;
case paddingType.END:
keyBuffer = Buffer.from(key.slice(2).padEnd(64, "0"), "hex"); // assume key is prefixed with 0x
break;
}
const pBuffer = Buffer.from(slot.toHexString().slice(2), "hex");
return keccak256(Buffer.concat([keyBuffer, pBuffer]));
}
async function getFacetsWithArgs(facetNames, config) {
const facets = await getFacets(config);
const keys = Object.keys(facets).filter((key) => facetNames.includes(key));
return keys.reduce((obj, key) => {
obj[key] = facets[key];
return obj;
}, {});
}
function objectToArray(input) {
// If the input is not an object, return it as-is
if (typeof input !== "object" || input === null) {
return input;
}
// If the input is an array, convert its elements recursively
if (Array.isArray(input)) {
return input.map((element) => objectToArray(element));
}
// If the input is an object, convert its properties recursively
const keys = Object.keys(input);
const result = new Array(keys.length);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = objectToArray(input[key]);
result[i] = value;
}
return result;
}
async function setupTestEnvironment(contracts, { bosonTokenAddress, forwarderAddress } = {}) {
// Load modules only here to avoid the caching issues in upgrade tests
const { deployProtocolDiamond } = require("../../scripts/util/deploy-protocol-diamond.js");
const { deployProtocolClients } = require("../../scripts/util/deploy-protocol-clients");
const { deployAndCutFacets } = require("../../scripts/util/deploy-protocol-handler-facets");
const facetNames = [
"SellerHandlerFacet",
"BuyerHandlerFacet",
"AgentHandlerFacet",
"DisputeResolverHandlerFacet",
"ExchangeHandlerFacet",
"OfferHandlerFacet",
"GroupHandlerFacet",
"TwinHandlerFacet",
"BundleHandlerFacet",
"DisputeHandlerFacet",
"FundsHandlerFacet",
"OrchestrationHandlerFacet1",
"OrchestrationHandlerFacet2",
"PauseHandlerFacet",
"AccountHandlerFacet",
"ProtocolInitializationHandlerFacet",
"ConfigHandlerFacet",
"MetaTransactionsHandlerFacet",
];
const signers = await getSigners();
const [deployer, protocolTreasury, bosonToken, pauser] = signers;
// Deploy the Protocol Diamond
const [protocolDiamond, , , , accessController] = await deployProtocolDiamond(maxPriorityFeePerGas);
// Temporarily grant UPGRADER role to deployer account
await accessController.grantRole(Role.UPGRADER, await deployer.getAddress());
// Grant PROTOCOL role to ProtocolDiamond address and renounces admin
await accessController.grantRole(Role.PROTOCOL, await protocolDiamond.getAddress());
// Grant PAUSER role to pauser account
await accessController.grantRole(Role.PAUSER, await pauser.getAddress());
// Deploy the Protocol client implementation/proxy pairs (currently just the Boson Voucher)
const protocolClientArgs = [await protocolDiamond.getAddress()];
const [implementations, beacons, proxies, clients] = await deployProtocolClients(
protocolClientArgs,
maxPriorityFeePerGas,
forwarderAddress
);
const [beacon] = beacons;
const [proxy] = proxies;
const [bosonVoucher] = clients;
const [voucherImplementation] = implementations;
// set protocolFees
const protocolFeePercentage = "200"; // 2 %
const protocolFeeFlatBoson = parseUnits("0.01", "ether").toString();
const buyerEscalationDepositPercentage = "1000"; // 10%
// Add config Handler, so ids start at 1, and so voucher address can be found
const protocolConfig = [
// Protocol addresses
{
treasury: await protocolTreasury.getAddress(),
token: bosonTokenAddress || (await bosonToken.getAddress()),
voucherBeacon: await beacon.getAddress(),
beaconProxy: await proxy.getAddress(),
},
// Protocol limits
{
maxExchangesPerBatch: 100,
maxOffersPerGroup: 100,
maxTwinsPerBundle: 100,
maxOffersPerBundle: 100,
maxOffersPerBatch: 100,
maxTokensPerWithdrawal: 100,
maxFeesPerDisputeResolver: 100,
maxEscalationResponsePeriod: oneMonth,
maxDisputesPerBatch: 100,
maxAllowedSellers: 100,
maxTotalOfferFeePercentage: 4000, //40%
maxRoyaltyPecentage: 1000, //10%
maxResolutionPeriod: oneMonth,
minDisputePeriod: oneWeek,
maxPremintedVouchers: 10000,
},
// Protocol fees
{
percentage: protocolFeePercentage,
flatBoson: protocolFeeFlatBoson,
buyerEscalationDepositPercentage,
},
];
const facetsToDeploy = await getFacetsWithArgs(facetNames, protocolConfig);
// Cut the protocol handler facets into the Diamond
await deployAndCutFacets(await protocolDiamond.getAddress(), facetsToDeploy, maxPriorityFeePerGas);
let contractInstances = {};
for (const contract of Object.keys(contracts)) {
contractInstances[contract] = await getContractAt(contracts[contract], await protocolDiamond.getAddress());
}
const extraReturnValues = { accessController, bosonVoucher, voucherImplementation, beacon };
return {
signers: signers.slice(3),
contractInstances,
protocolConfig,
diamondAddress: await protocolDiamond.getAddress(),
extraReturnValues,
};
}
async function getSnapshot() {
return await provider.send("evm_snapshot", []);
}
async function revertToSnapshot(snapshotId) {
return await provider.send("evm_revert", [snapshotId]);
}
function deriveTokenId(offerId, exchangeId) {
return (BigInt(offerId) << 128n) + BigInt(exchangeId);
}
exports.setNextBlockTimestamp = setNextBlockTimestamp;
exports.getEvent = getEvent;
exports.eventEmittedWithArgs = eventEmittedWithArgs;
exports.prepareDataSignatureParameters = prepareDataSignatureParameters;
exports.calculateVoucherExpiry = calculateVoucherExpiry;
exports.calculateContractAddress = calculateContractAddress;
exports.applyPercentage = applyPercentage;
exports.getMappingStoragePosition = getMappingStoragePosition;
exports.paddingType = paddingType;
exports.getFacetsWithArgs = getFacetsWithArgs;
exports.compareOfferStructs = compareOfferStructs;
exports.objectToArray = objectToArray;
exports.setupTestEnvironment = setupTestEnvironment;
exports.getSnapshot = getSnapshot;
exports.revertToSnapshot = revertToSnapshot;
exports.deriveTokenId = deriveTokenId;