-
Notifications
You must be signed in to change notification settings - Fork 0
/
codegen.js
executable file
·353 lines (284 loc) · 9.56 KB
/
codegen.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
#!/usr/bin/env node
const { compile } = require('json-schema-to-typescript');
const fs = require('fs');
const path = require('path');
const fzstd = require('fzstd');
const nearApi = require('near-api-js');
const { codegenNearReactTs } = require('./codegen-react-ts');
const { codegenNearTs } = require('./codegen-ts');
const networks = {
mainnet: 'https://rpc.mainnet.near.org',
testnet: 'https://rpc.testnet.near.org',
betanet: 'https://rpc.betanet.near.org',
local: 'http://localhost:3030',
};
const pathToConfig = path.resolve('react-near.json');
const config = JSON.parse(fs.readFileSync(pathToConfig, { encoding: 'utf-8' }));
const dist = config.dist || 'dist';
const excludeMethods = [
'new',
'new_with_default_meta',
'migrate',
'ft_on_transfer',
'mt_on_transfer',
'nft_on_transfer',
'nft_on_approve',
];
if (!fs.existsSync(path.resolve(dist))) {
fs.mkdirSync(dist);
}
//
(async () => {
for (const contract of config.contracts) {
const contractId = contract.contractId || contract.testnet || contract.mainnet
if (!contractId) {
throw new Error('Invalid react-near.json config');
}
let schema = contract.abi
? JSON.parse(fs.readFileSync(path.resolve(contract.abi), { encoding: 'utf-8' }))
: await loadAbi(contractId);
if (!schema) {
console.log(`Invalid schema of ${contractId}`);
process.exit(1);
}
const codegenMap = {
default: codegenNearReactTs,
raw: codegenNearTs,
}
const configParse = codegenMap[config.type || 'default'];
if (!configParse) {
throw new Error('Invalid react-near config "type" field.');
}
await generate(
schema,
contract.name,
{ id: contractId, testnet: contract.testnet, mainnet: contract.mainnet },
configParse,
);
}
})();
//
async function generate(abiSchema, contractName, ids, opts) {
const schemaPath = path.resolve(dist, `${camelToSnakeCase(contractName)}.ts`);
const schema = {
...abiSchema.body.root_schema,
title: 'Definitions',
type: 'object',
properties: abiSchema.body.root_schema.definitions,
};
const methods = abiSchema.body.functions.filter((el) => !excludeMethods.includes(el.name));
let code = '// Code is generated by react-near\n\n' + opts.getStartCode({ contractName });
code = (code ? code + '\n\n' : '') + generateConstants(ids, contractName);
code +=
'\n\n' +
generateEnumMethods(
methods.filter((el) => el.is_view),
contractName,
'View',
) +
'\n\n' +
generateEnumMethods(
methods.filter((el) => !el.is_view),
contractName,
'Change',
);
code += '\n\n' + generateContractInterface(methods, contractName);
code += '\n\n' + generateContract({ methods, contractName, getContract: opts.getContract });
code += '\n\n' + opts.getCoreCode({ contractName });
code += '\n\n' + generateMethods({ methods, contractName, getMethod: opts.getMethod });
const ts = await compile(schema, 'MySchema', { additionalProperties: false, bannerComment: '' });
code += `\n\n` + ts;
fs.writeFileSync(schemaPath, prepareCode(code));
console.log(`${contractName} schema generated!`);
}
function generateContractInterface(methods, contractName) {
return [
`export interface I${contractName}Contract {`,
' // view methods',
methods
.filter((el) => el.is_view)
.map((el) => {
const name = formatFunctionName(el.name);
const interfaceName = 'I' + name;
return ` ${el.name}(args: ${interfaceName}Args): ${interfaceName}Result`;
})
.join('\n'),
' // change methods',
methods
.filter((el) => !el.is_view)
.map((el) => {
const name = formatFunctionName(el.name);
const interfaceName = 'I' + name;
return ` ${el.name}(args: ${interfaceName}Args): ${interfaceName}Result`;
})
.join('\n'),
'}',
].join('\n');
}
function generateEnumMethods(methods, contractName, prefix) {
let methodsCode = `export enum ${contractName}${prefix}Methods {\n`;
methods.forEach((func) => {
methodsCode += ` ${func.name} = '${func.name}',${func.is_payable ? ' // payable' : ''}\n`;
});
methodsCode += '}';
return methodsCode;
}
function generateMethods({ methods, contractName, getMethod }) {
return methods.map((el) => getMethodWithTypes({ el, contractName, getMethod })).join('\n\n');
}
function generateContract({ methods, contractName, getContract }) {
return getContract({
contractName,
contractId: contractName,
codegenName: getContractId(contractName),
viewMethods: methods
.filter((el) => el.is_view)
.map((el) => ` ${contractName}ViewMethods.${el.name},`),
changeMethods: methods
.filter((el) => !el.is_view)
.map((el) => ` ${contractName}ChangeMethods.${el.name},`),
interfaceName: `I${contractName}Contract`,
});
}
function generateConstants(ids, contractName) {
const res = [];
res.push(`export const ${getContractId(contractName)}_MAINNET = '${ids.mainnet || ''}';`);
res.push(`export const ${getContractId(contractName)}_TESTNET = '${ids.testnet || ids.id}';`);
return res.join('\n');
}
//
function getMethodWithTypes({ el, contractName, getMethod }) {
const name = formatFunctionName(el.name);
const interfaceName = 'I' + name;
const args = (el.params || []).reduce(
(acc, el2) => ({
...acc,
[el2.name]: formatParam(el2),
}),
{},
);
const isQuery = el.is_view;
const methodArgs = {
functionName: name,
methodName: el.name,
contractName,
isView: !!el.is_view,
isChange: !el.is_view,
isPayable: !!el.is_payable,
raw: el,
argsInterface: `${interfaceName}Args`,
resultInterface: `${interfaceName}Result`,
};
return [
`// ${el.name} ${isQuery ? 'query' : 'mutation'}${el.is_payable ? ' (payable)' : ''}`,
'',
`export type ${interfaceName}Args = {\n${Object.keys(args)
.map((k) => ` ${k}: ${args[k]};`)
.join('\n')}\n};`,
'',
`export type ${interfaceName}Result = ${formatParam(el.result)};`,
'',
getMethod(methodArgs),
].join('\n');
}
function getRefType(refStr) {
if (!refStr) {
return '';
}
return refStr.split('/').slice(-1)[0]
}
function formatParam(el) {
if (!el) {
return 'void';
}
if (el.type_schema.type) {
if (el.type_schema.type === 'array') {
if (el.type_schema.items.type) {
return `${el.type_schema.items.type}[]`;
}
return `${getRefType(el.type_schema.items.$ref)}[]`;
}
if (Array.isArray(el.type_schema.type)) {
if (el.type_schema.type[0] !== 'array') {
return el.type_schema.type.join(' | ');
}
return `[${el.type_schema.items.map(el => getRefType(el.$ref)).join(', ')}] | ${el.type_schema.type[1]}`;
}
if (Array.isArray(el.type_schema.type)) {
return `${el.type_schema.type
.map((el) => {
if (el === 'integer') {
return 'number';
}
return el;
})
.join(' | ')}`;
}
return el.type_schema.type;
}
if (el.type_schema.$ref) {
let res = getRefType(el.type_schema.$ref);
if (res === 'Promise') {
return 'void';
}
return res;
}
if (el.type_schema.anyOf) {
return `${el.type_schema.anyOf
.map((el) => {
if (el.type) {
return el.type;
} else if (el.$ref) {
const res = `${getRefType(el.$ref)}`;
if (res === 'Promise') {
return 'void';
}
return res;
}
})
.join(' | ')}`;
}
return null;
}
function formatFunctionName(str) {
let res = str
.toLowerCase()
.replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace('-', '').replace('_', ''));
return res.slice(0, 1).toUpperCase() + res.slice(1);
}
function getCodegenContractId(contractId) {
return camelToSnakeCase(contractId).toUpperCase() + '_CONTRACT_NAME';
}
function camelToSnakeCase(str) {
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`).slice(1);
}
async function loadAbi(contractId) {
const network = (contractId.includes('.') && contractId.split('.').slice(-1)[0]) || 'testnet';
let near = await nearApi.connect({
keyStore: nearApi.keyStores.InMemoryKeyStore,
nodeUrl: new URL(network in networks ? networks[network] : network),
});
let account = await near.account(contractId);
let response = await account.viewFunction(contractId, '__contract_abi', {}, { parse: (v) => v });
let decompressed_abi = fzstd.decompress(response);
let abi = JSON.parse(Buffer.from(decompressed_abi).toString());
return abi;
}
function prepareCode(ts) {
return (
ts
.replace('export type U128 = number;', 'export type U128 = string;')
.replace('export type U64 = number;', 'export type U64 = string;')
.replace(
'export type PromiseOrValueU128 = number;',
'export type PromiseOrValueU128 = string;',
)
.split('PromiseOrValueArray_of')
.join('PromiseOrValueArrayOf') +
'\n' +
['type integer = number;'].join('\n')
);
}
function getContractId(contractId) {
return camelToSnakeCase(contractId).toUpperCase() + '_CONTRACT_NAME';
}