@alephium/web3 0.5.0-rc.3 → 0.5.0-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,359 +0,0 @@
1
- "use strict";
2
- /*
3
- Copyright 2018 - 2022 The Alephium Authors
4
- This file is part of the alephium project.
5
-
6
- The library is free software: you can redistribute it and/or modify
7
- it under the terms of the GNU Lesser General Public License as published by
8
- the Free Software Foundation, either version 3 of the License, or
9
- (at your option) any later version.
10
-
11
- The library is distributed in the hope that it will be useful,
12
- but WITHOUT ANY WARRANTY; without even the implied warranty of
13
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
- GNU Lesser General Public License for more details.
15
-
16
- You should have received a copy of the GNU Lesser General Public License
17
- along with the library. If not, see <http://www.gnu.org/licenses/>.
18
- */
19
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
20
- if (k2 === undefined) k2 = k;
21
- var desc = Object.getOwnPropertyDescriptor(m, k);
22
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
23
- desc = { enumerable: true, get: function() { return m[k]; } };
24
- }
25
- Object.defineProperty(o, k2, desc);
26
- }) : (function(o, m, k, k2) {
27
- if (k2 === undefined) k2 = k;
28
- o[k2] = m[k];
29
- }));
30
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
31
- Object.defineProperty(o, "default", { enumerable: true, value: v });
32
- }) : function(o, v) {
33
- o["default"] = v;
34
- });
35
- var __importStar = (this && this.__importStar) || function (mod) {
36
- if (mod && mod.__esModule) return mod;
37
- var result = {};
38
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
39
- __setModuleDefault(result, mod);
40
- return result;
41
- };
42
- var __importDefault = (this && this.__importDefault) || function (mod) {
43
- return (mod && mod.__esModule) ? mod : { "default": mod };
44
- };
45
- Object.defineProperty(exports, "__esModule", { value: true });
46
- exports.codegen = void 0;
47
- const prettier = __importStar(require("prettier"));
48
- const path_1 = __importDefault(require("path"));
49
- const fs_1 = __importDefault(require("fs"));
50
- const contract_1 = require("./contract");
51
- const header = `/* Autogenerated file. Do not edit manually. */\n/* tslint:disable */\n/* eslint-disable */\n\n`;
52
- function array(str, size) {
53
- const result = Array(size).fill(str).join(', ');
54
- return `[${result}]`;
55
- }
56
- function parseArrayType(tpe) {
57
- const ignored = '[;]';
58
- const tokens = [];
59
- let acc = '';
60
- for (let index = 0; index < tpe.length; index++) {
61
- if (!ignored.includes(tpe.charAt(index))) {
62
- acc = acc + tpe.charAt(index);
63
- }
64
- else if (acc !== '') {
65
- tokens.push(acc);
66
- acc = '';
67
- }
68
- }
69
- const baseTsType = toTsType(tokens[0]);
70
- const sizes = tokens.slice(1).map((str) => parseInt(str));
71
- return sizes.reduce((acc, size) => array(acc, size), baseTsType);
72
- }
73
- function toTsType(ralphType) {
74
- switch (ralphType) {
75
- case 'U256':
76
- case 'I256':
77
- return 'bigint';
78
- case 'Bool':
79
- return 'boolean';
80
- case 'Address':
81
- case 'ByteVec':
82
- return 'HexString';
83
- default: // array type
84
- return parseArrayType(ralphType);
85
- }
86
- }
87
- function formatParameters(fieldsSig) {
88
- return fieldsSig.names.map((name, idx) => `${name}: ${toTsType(fieldsSig.types[`${idx}`])}`).join(', ');
89
- }
90
- function genCallMethod(contractName, functionSig) {
91
- if (!functionSig.isPublic || functionSig.returnTypes.length === 0) {
92
- return '';
93
- }
94
- const funcName = functionSig.name.charAt(0).toUpperCase() + functionSig.name.slice(1);
95
- const funcHasArgs = functionSig.paramNames.length > 0;
96
- const params = funcHasArgs
97
- ? `params: CallContractParams<{${formatParameters({
98
- names: functionSig.paramNames,
99
- types: functionSig.paramTypes
100
- })}}>`
101
- : `params?: Omit<CallContractParams<{}>, 'args'>`;
102
- const tsReturnTypes = functionSig.returnTypes.map((tpe) => toTsType(tpe));
103
- const retType = tsReturnTypes.length === 0
104
- ? `CallContractResult<null>`
105
- : tsReturnTypes.length === 1
106
- ? `CallContractResult<${tsReturnTypes[0]}>`
107
- : `CallContractResult<[${tsReturnTypes.join(', ')}]>`;
108
- const callParams = funcHasArgs ? 'params' : 'params === undefined ? {} : params';
109
- return `
110
- async call${funcName}Method(${params}): Promise<${retType}> {
111
- return callMethod(${contractName}, this, "${functionSig.name}", ${callParams})
112
- }
113
- `;
114
- }
115
- function getInstanceName(contract) {
116
- return `${contract.name}Instance`;
117
- }
118
- function genAttach(instanceName) {
119
- return `
120
- at(address: string): ${instanceName} {
121
- return new ${instanceName}(address)
122
- }
123
- `;
124
- }
125
- function contractTypes(contractName) {
126
- return `${contractName}Types`;
127
- }
128
- function contractFieldType(contract) {
129
- const hasFields = contract.fieldsSig.names.length > 0;
130
- return hasFields ? `${contractTypes(contract.name)}.Fields` : '{}';
131
- }
132
- function genFetchState(contract) {
133
- return `
134
- async fetchState(): Promise<${contractTypes(contract.name)}.State> {
135
- return fetchContractState(${contract.name}, this)
136
- }
137
- `;
138
- }
139
- function getEventType(event) {
140
- return event.name + 'Event';
141
- }
142
- function genEventType(event) {
143
- if (event.fieldNames.length === 0) {
144
- return `export type ${getEventType(event)} = Omit<ContractEvent, 'fields'>`;
145
- }
146
- const fieldsType = `{${formatParameters({ names: event.fieldNames, types: event.fieldTypes })}}`;
147
- return `export type ${getEventType(event)} = ContractEvent<${fieldsType}>`;
148
- }
149
- function genSubscribeSystemEvent(event) {
150
- return `
151
- subscribe${event.eventSig.name}Event(options: SubscribeOptions<${event.eventType}>, fromCount?: number): EventSubscription {
152
- return subscribe${event.eventSig.name}Event(this, options, fromCount)
153
- }
154
- `;
155
- }
156
- function genSubscribeEvent(contractName, event) {
157
- const eventType = getEventType(event);
158
- const scopedEventType = `${contractTypes(contractName)}.${eventType}`;
159
- return `
160
- subscribe${eventType}(options: SubscribeOptions<${scopedEventType}>, fromCount?: number): EventSubscription {
161
- return subscribeContractEvent(${contractName}.contract, this, options, "${event.name}", fromCount)
162
- }
163
- `;
164
- }
165
- function genSubscribeAllEvents(contract, systemEvents) {
166
- const contractEventTypes = contract.eventsSig.map((e) => `${contractTypes(contract.name)}.${getEventType(e)}`);
167
- const systemEventTypes = systemEvents.map((e) => e.eventType);
168
- const eventTypes = contractEventTypes.concat(systemEventTypes).join(' | ');
169
- return `
170
- subscribeAllEvents(options: SubscribeOptions<${eventTypes}>, fromCount?: number): EventSubscription {
171
- return subscribeAllEvents(${contract.name}.contract, this, options, fromCount)
172
- }
173
- `;
174
- }
175
- function genContractStateType(contract) {
176
- if (contract.fieldsSig.names.length === 0) {
177
- return `export type State = Omit<ContractState<any>, 'fields'>`;
178
- }
179
- return `
180
- export type Fields = {
181
- ${formatParameters(contract.fieldsSig)}
182
- }
183
-
184
- export type State = ContractState<Fields>
185
- `;
186
- }
187
- function genTestMethod(contract, functionSig) {
188
- const funcName = functionSig.name.charAt(0).toUpperCase() + functionSig.name.slice(1);
189
- const funcHasArgs = functionSig.paramNames.length > 0;
190
- const contractHasFields = contract.fieldsSig.names.length > 0;
191
- const argsType = funcHasArgs
192
- ? `{${formatParameters({ names: functionSig.paramNames, types: functionSig.paramTypes })}}`
193
- : 'never';
194
- const fieldsType = contractHasFields ? `${contractFieldType(contract)}` : 'never';
195
- const params = funcHasArgs && contractHasFields
196
- ? `params: TestContractParams<${fieldsType}, ${argsType}>`
197
- : funcHasArgs
198
- ? `params: Omit<TestContractParams<${fieldsType}, ${argsType}>, 'initialFields'>`
199
- : contractHasFields
200
- ? `params: Omit<TestContractParams<${fieldsType}, ${argsType}>, 'testArgs'>`
201
- : `params?: Omit<TestContractParams<${fieldsType}, ${argsType}>, 'testArgs' | 'initialFields'>`;
202
- const tsReturnTypes = functionSig.returnTypes.map((tpe) => toTsType(tpe));
203
- const retType = tsReturnTypes.length === 0
204
- ? `TestContractResult<null>`
205
- : tsReturnTypes.length === 1
206
- ? `TestContractResult<${tsReturnTypes[0]}>`
207
- : `TestContractResult<[${tsReturnTypes.join(', ')}]>`;
208
- const callParams = funcHasArgs || contractHasFields ? 'params' : 'params === undefined ? {} : params';
209
- return `
210
- async test${funcName}Method(${params}): Promise<${retType}> {
211
- return testMethod(this, "${functionSig.name}", ${callParams})
212
- }
213
- `;
214
- }
215
- function genContract(project, contract, artifactRelativePath) {
216
- const contractInfo = project.projectArtifact.infos.get(contract.name);
217
- if (contractInfo === undefined) {
218
- throw new Error(`Contract info does not exist: ${contract.name}`);
219
- }
220
- const systemEvents = [
221
- {
222
- eventSig: contract_1.Contract.ContractCreatedEvent,
223
- eventIndex: contract_1.Contract.ContractCreatedEventIndex,
224
- eventType: 'ContractCreatedEvent'
225
- },
226
- {
227
- eventSig: contract_1.Contract.ContractDestroyedEvent,
228
- eventIndex: contract_1.Contract.ContractDestroyedEventIndex,
229
- eventType: 'ContractDestroyedEvent'
230
- }
231
- ];
232
- const source = `
233
- ${header}
234
-
235
- import {
236
- Address, Contract, ContractState, TestContractResult, HexString, ContractFactory,
237
- SubscribeOptions, EventSubscription, CallContractParams, CallContractResult,
238
- TestContractParams, ContractEvent, subscribeContractCreatedEvent, subscribeContractDestroyedEvent, subscribeContractEvent, subscribeAllEvents, testMethod, callMethod, fetchContractState,
239
- ContractCreatedEvent, ContractDestroyedEvent, ContractInstance
240
- } from '@alephium/web3'
241
- import { default as ${contract.name}ContractJson } from '../${artifactRelativePath}'
242
-
243
- // Custom types for the contract
244
- export namespace ${contract.name}Types {
245
- ${genContractStateType(contract)}
246
- ${contract.eventsSig.map((e) => genEventType(e)).join('\n')}
247
- }
248
-
249
- class Factory extends ContractFactory<${contract.name}Instance, ${contractFieldType(contract)}> {
250
- ${genAttach(getInstanceName(contract))}
251
- ${contract.functions.map((f) => genTestMethod(contract, f)).join('\n')}
252
- }
253
-
254
- // Use this object to test and deploy the contract
255
- export const ${contract.name} = new Factory(Contract.fromJson(
256
- ${contract.name}ContractJson,
257
- '${contractInfo.bytecodeDebugPatch}',
258
- '${contractInfo.codeHashDebug}',
259
- ))
260
-
261
- // Use this class to interact with the blockchain
262
- export class ${contract.name}Instance extends ContractInstance {
263
- constructor(address: Address) {
264
- super(address)
265
- }
266
-
267
- ${genFetchState(contract)}
268
- ${systemEvents.map((e) => genSubscribeSystemEvent(e)).join('\n')}
269
- ${contract.eventsSig.map((e) => genSubscribeEvent(contract.name, e)).join('\n')}
270
- ${genSubscribeAllEvents(contract, systemEvents)}
271
- ${contract.functions.map((f) => genCallMethod(contract.name, f)).join('\n')}
272
- }
273
- `;
274
- return prettier.format(source, { parser: 'typescript' });
275
- }
276
- function genScript(script) {
277
- console.log(`Generating code for script ${script.name}`);
278
- const usePreapprovedAssets = script.functions[0].usePreapprovedAssets;
279
- const fieldsType = script.fieldsSig.names.length > 0 ? `{${formatParameters(script.fieldsSig)}}` : '{}';
280
- const paramsType = usePreapprovedAssets
281
- ? `ExecuteScriptParams<${fieldsType}>`
282
- : `Omit<ExecuteScriptParams<${fieldsType}>, 'attoAlphAmount' | 'tokens'>`;
283
- return `
284
- export namespace ${script.name} {
285
- export async function execute(signer: SignerProvider, params: ${paramsType}): Promise<ExecuteScriptResult> {
286
- const signerParams = await script.txParamsForExecution(signer, params)
287
- return await signer.signAndSubmitExecuteScriptTx(signerParams)
288
- }
289
-
290
- export const script = Script.fromJson(${script.name}ScriptJson)
291
- }
292
- `;
293
- }
294
- function genScripts(project, outDir, exports) {
295
- const artifactDir = project.artifactsRootDir;
296
- exports.push('./scripts');
297
- const scriptPath = path_1.default.join(outDir, 'scripts.ts');
298
- const scripts = Array.from(project.scripts.values());
299
- const importArtifacts = Array.from(scripts)
300
- .map((s) => {
301
- const artifactPath = s.sourceInfo.getArtifactPath(artifactDir);
302
- const artifactRelativePath = path_1.default.relative(artifactDir, artifactPath);
303
- return `import { default as ${s.artifact.name}ScriptJson } from '../${artifactRelativePath}'`;
304
- })
305
- .join('\n');
306
- const scriptsSource = scripts.map((s) => genScript(s.artifact)).join('\n');
307
- const source = `
308
- ${header}
309
-
310
- import {
311
- ExecuteScriptParams,
312
- ExecuteScriptResult,
313
- Script,
314
- SignerProvider,
315
- HexString
316
- } from '@alephium/web3'
317
- ${importArtifacts}
318
-
319
- ${scriptsSource}
320
- `;
321
- const formatted = prettier.format(source, { parser: 'typescript' });
322
- fs_1.default.writeFileSync(scriptPath, formatted, 'utf8');
323
- }
324
- function genIndexTs(outDir, exports) {
325
- const indexPath = path_1.default.join(outDir, 'index.ts');
326
- const exportStatements = exports.map((e) => `export * from "${e}"`).join('\n');
327
- const source = prettier.format(header + exportStatements, { parser: 'typescript' });
328
- fs_1.default.writeFileSync(indexPath, source, 'utf8');
329
- }
330
- function genContracts(project, outDir, exports) {
331
- const artifactDir = project.artifactsRootDir;
332
- Array.from(project.contracts.values()).forEach((c) => {
333
- console.log(`Generating code for contract ${c.artifact.name}`);
334
- exports.push(`./${c.artifact.name}`);
335
- const filename = `${c.artifact.name}.ts`;
336
- const sourcePath = path_1.default.join(outDir, filename);
337
- const artifactPath = c.sourceInfo.getArtifactPath(artifactDir);
338
- const artifactRelativePath = path_1.default.relative(artifactDir, artifactPath);
339
- const sourceCode = genContract(project, c.artifact, artifactRelativePath);
340
- fs_1.default.writeFileSync(sourcePath, sourceCode, 'utf8');
341
- });
342
- }
343
- function codegen(project) {
344
- const outDirTemp = path_1.default.join(project.artifactsRootDir, 'ts');
345
- const outDir = path_1.default.isAbsolute(outDirTemp) ? outDirTemp : path_1.default.resolve(outDirTemp);
346
- if (!fs_1.default.existsSync(outDir)) {
347
- fs_1.default.mkdirSync(outDir, { recursive: true });
348
- }
349
- const exports = [];
350
- try {
351
- genContracts(project, outDir, exports);
352
- genScripts(project, outDir, exports);
353
- genIndexTs(outDir, exports);
354
- }
355
- catch (error) {
356
- console.log(`Failed to generate code: ${error}`);
357
- }
358
- }
359
- exports.codegen = codegen;