-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared.ts
347 lines (329 loc) · 11.2 KB
/
shared.ts
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
import fc from "fast-check";
import {
BaseType,
BaseTypesToArbitrary,
BaseTypesToCV,
ComplexTypesToArbitrary,
ComplexTypesToCV,
ParameterType,
ResponseStatus,
TupleData,
} from "./shared.types";
import { Simnet } from "@hirosystems/clarinet-sdk";
import {
ContractInterfaceFunction,
IContractInterface,
} from "@hirosystems/clarinet-sdk-wasm";
import {
Cl,
ClarityValue,
optionalCVOf,
responseErrorCV,
responseOkCV,
} from "@stacks/transactions";
/**
* Get the interfaces of contracts deployed by the specified deployer from the
* simnet.
* @param simnet The simnet instance.
* @param deployer The deployer address.
* @returns The contracts interfaces.
*/
export const getSimnetDeployerContractsInterfaces = (
simnet: Simnet
): Map<string, IContractInterface> =>
new Map(
Array.from(simnet.getContractsInterfaces()).filter(
([key]) => key.split(".")[0] === simnet.deployer
)
);
/**
* Get the functions from the smart contract interfaces.
* @param contractsInterfaces The smart contract interfaces map.
* @returns A map containing the contracts functions.
*/
export const getFunctionsFromContractInterfaces = (
contractsInterfaces: Map<string, IContractInterface>
): Map<string, ContractInterfaceFunction[]> =>
new Map(
Array.from(contractsInterfaces, ([contractId, contractInterface]) => [
contractId,
contractInterface.functions,
])
);
export const getFunctionsListForContract = (
functionsMap: Map<string, ContractInterfaceFunction[]>,
contractId: string
): ContractInterfaceFunction[] => functionsMap.get(contractId) || [];
/** For a given function, dynamically generate fast-check arbitraries.
* @param fn The function interface.
* @returns Array of fast-check arbitraries.
*/
export const functionToArbitrary = (
fn: ContractInterfaceFunction,
addresses: string[]
): fc.Arbitrary<any>[] =>
fn.args.map((arg) =>
parameterTypeToArbitrary(arg.type as ParameterType, addresses)
);
/**
* For a given type, generate a fast-check arbitrary.
* @param type The parameter type.
* @returns Fast-check arbitrary.
*/
const parameterTypeToArbitrary = (
type: ParameterType,
addresses: string[]
): fc.Arbitrary<any> => {
if (typeof type === "string") {
// The type is a base type.
if (type === "principal") {
if (addresses.length === 0)
throw new Error(
"No addresses could be retrieved from the simnet instance!"
);
return baseTypesToArbitrary.principal(addresses);
} else if (type === "trait_reference") {
throw new Error("Unsupported parameter type: trait_reference");
} else return baseTypesToArbitrary[type];
} else {
// The type is a complex type.
if ("buffer" in type) {
return complexTypesToArbitrary["buffer"](type.buffer.length);
} else if ("string-ascii" in type) {
return complexTypesToArbitrary["string-ascii"](
type["string-ascii"].length
);
} else if ("string-utf8" in type) {
return complexTypesToArbitrary["string-utf8"](type["string-utf8"].length);
} else if ("list" in type) {
return complexTypesToArbitrary["list"](
type.list.type,
type.list.length,
addresses
);
} else if ("tuple" in type) {
return complexTypesToArbitrary["tuple"](type.tuple, addresses);
} else if ("optional" in type) {
return complexTypesToArbitrary["optional"](type.optional, addresses);
} else if ("response" in type) {
return complexTypesToArbitrary.response(
type.response.ok,
type.response.error,
addresses
);
} else {
throw new Error(`Unsupported complex type: ${JSON.stringify(type)}`);
}
}
};
/**
* Base types to fast-check arbitraries mapping.
*/
const baseTypesToArbitrary: BaseTypesToArbitrary = {
int128: fc.integer(),
uint128: fc.nat(),
bool: fc.boolean(),
principal: (addresses: string[]) => fc.constantFrom(...addresses),
trait_reference: undefined,
};
/**
* Custom hexadecimal string generator. The `hexaString` generator from
* fast-check has been deprecated. This generator is implemented to precisely
* match the behavior of the deprecated generator.
*
* @param constraints Fast-check string constraints.
* @returns Fast-check arbitrary for hexadecimal strings.
*
* Reference for the proposed replacement of the deprecated `hexaString`
* generator:
* https://github.com/dubzzz/fast-check/commit/3f4f1203a8863c07d22b45591bf0de1fac02b948
*/
export const hexaString = (
constraints: fc.StringConstraints = {}
): fc.Arbitrary<string> => {
const hexa = (): fc.Arbitrary<string> => {
const hexCharSet = "0123456789abcdef";
return fc.integer({ min: 0, max: 15 }).map((n) => hexCharSet[n]);
};
return fc.string({ ...constraints, unit: hexa() });
};
/**
* Complex types to fast-check arbitraries mapping.
*/
const complexTypesToArbitrary: ComplexTypesToArbitrary = {
// For buffer types, the length must be doubled because they are represented
// in hex. The `argToCV` function expects this format for `buff` ClarityValue
// conversion. The UInt8Array will have half the length of the corresponding
// hex string. Stacks.js reference:
// https://github.com/hirosystems/stacks.js/blob/fd0bf26b5f29fc3c1bf79581d0ad9b89f0d7f15a/packages/common/src/utils.ts#L522
buffer: (length: number) => hexaString({ maxLength: 2 * length }),
"string-ascii": (length: number) =>
fc.string({
unit: fc.constantFrom(...charSet),
maxLength: length,
}),
"string-utf8": (length: number) => fc.string({ maxLength: length }),
list: (type: ParameterType, length: number, addresses: string[]) =>
fc.array(parameterTypeToArbitrary(type, addresses), { maxLength: length }),
tuple: (
items: { name: string; type: ParameterType }[],
addresses: string[]
) => {
const tupleArbitraries: { [key: string]: fc.Arbitrary<any> } = {};
items.forEach((item) => {
tupleArbitraries[item.name] = parameterTypeToArbitrary(
item.type,
addresses
);
});
return fc.record(tupleArbitraries);
},
optional: (type: ParameterType, addresses: string[]) =>
fc.option(parameterTypeToArbitrary(type, addresses)),
response: (
okType: ParameterType,
errType: ParameterType,
addresses: string[]
) =>
fc.oneof(
fc.record({
status: fc.constant("ok"),
value: parameterTypeToArbitrary(okType, addresses),
}),
fc.record({
status: fc.constant("error"),
value: parameterTypeToArbitrary(errType, addresses),
})
),
};
/** The character set used for generating ASCII strings.*/
const charSet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
/**
* Convert function arguments to Clarity values.
* @param fn The function interface.
* @param args Array of arguments.
* @returns Array of Clarity values.
*/
export const argsToCV = (fn: ContractInterfaceFunction, args: any[]) =>
fn.args.map((arg, i) => argToCV(args[i], arg.type as ParameterType));
/**
* Convert a function argument to a Clarity value.
* @param arg Generated argument.
* @param type Argument type (base or complex).
* @returns Clarity value.
*/
const argToCV = (arg: any, type: ParameterType): ClarityValue => {
if (isBaseType(type)) {
// Base type.
switch (type) {
case "int128":
return baseTypesToCV.int128(arg as number);
case "uint128":
return baseTypesToCV.uint128(arg as number);
case "bool":
return baseTypesToCV.bool(arg as boolean);
case "principal":
return baseTypesToCV.principal(arg as string);
default:
throw new Error(`Unsupported base parameter type: ${type}`);
}
} else {
// Complex type.
if ("buffer" in type) {
return complexTypesToCV.buffer(arg);
} else if ("string-ascii" in type) {
return complexTypesToCV["string-ascii"](arg);
} else if ("string-utf8" in type) {
return complexTypesToCV["string-utf8"](arg);
} else if ("list" in type) {
const listItems = arg.map((item: any) => argToCV(item, type.list.type));
return complexTypesToCV.list(listItems);
} else if ("tuple" in type) {
const tupleData: { [key: string]: ClarityValue } = {};
type.tuple.forEach((field) => {
tupleData[field.name] = argToCV(arg[field.name], field.type);
});
return complexTypesToCV.tuple(tupleData);
} else if ("optional" in type) {
return optionalCVOf(arg ? argToCV(arg, type.optional) : undefined);
} else if ("response" in type) {
const status = arg.status as ResponseStatus;
const branchType = type.response[status];
const responseValue = argToCV(arg.value, branchType);
return complexTypesToCV.response(status, responseValue);
} else {
throw new Error(
`Unsupported complex parameter type: ${JSON.stringify(type)}`
);
}
}
};
/**
* Base types to Clarity values mapping.
*/
const baseTypesToCV: BaseTypesToCV = {
int128: (arg: number) => Cl.int(arg),
uint128: (arg: number) => Cl.uint(arg),
bool: (arg: boolean) => Cl.bool(arg),
principal: (arg: string) => Cl.principal(arg),
};
/**
* Complex types to Clarity values mapping.
*/
const complexTypesToCV: ComplexTypesToCV = {
buffer: (arg: string) => Cl.bufferFromHex(arg),
"string-ascii": (arg: string) => Cl.stringAscii(arg),
"string-utf8": (arg: string) => Cl.stringUtf8(arg),
list: (items: ClarityValue[]) => {
return Cl.list(items);
},
tuple: (tupleData: TupleData<ClarityValue>) => {
return Cl.tuple(tupleData);
},
optional: (arg: ClarityValue | null) =>
arg ? optionalCVOf(arg) : optionalCVOf(undefined),
response: (status: ResponseStatus, value: ClarityValue) => {
if (status === "ok") return responseOkCV(value);
else if (status === "error") return responseErrorCV(value);
else throw new Error(`Unsupported response status: ${status}`);
},
};
const isBaseType = (type: ParameterType): type is BaseType => {
return ["int128", "uint128", "bool", "principal"].includes(type as BaseType);
};
/**
* Checks if any parameter of the function contains a `trait_reference` type.
* @param fn The function interface.
* @returns Boolean - true if the function contains a trait reference, false
* otherwise.
*/
export const isTraitReferenceFunction = (
fn: ContractInterfaceFunction
): boolean => {
const hasTraitReference = (type: ParameterType): boolean => {
if (typeof type === "string") {
// The type is a base type.
return type === "trait_reference";
} else {
// The type is a complex type.
if ("buffer" in type) return false;
if ("string-ascii" in type) return false;
if ("string-utf8" in type) return false;
if ("list" in type) return hasTraitReference(type.list.type);
if ("tuple" in type)
return type.tuple.some((item) => hasTraitReference(item.type));
if ("optional" in type) return hasTraitReference(type.optional);
if ("response" in type)
return (
hasTraitReference(type.response.ok) ||
hasTraitReference(type.response.error)
);
// Default to false for unexpected types.
return false;
}
};
return fn.args.some((arg) => hasTraitReference(arg.type as ParameterType));
};
export const getContractNameFromContractId = (contractId: string): string =>
contractId.split(".")[1];