@cosmwasm/ts-codegen
Version:
@cosmwasm/ts-codegen converts your CosmWasm smart contracts into dev-friendly TypeScript classes so you can focus on shipping code.
78 lines (77 loc) • 2.41 kB
JavaScript
import { compile } from '@pyramation/json-schema-to-typescript';
import { readFileSync } from 'fs';
import { sync as glob } from 'glob';
import { cleanse } from './cleanse';
import { parser } from './parse';
;
export const readSchemas = async ({ schemaDir, clean = true }) => {
const fn = clean ? cleanse : (schema) => schema;
const files = glob(schemaDir + '/**/*.json')
.filter(file => !file.match(/\/raw\//));
const schemas = files
.map(file => JSON.parse(readFileSync(file, 'utf-8')));
if (schemas.length > 1) {
// legacy
// TODO add console.warn here
return {
schemas: fn(schemas)
};
}
if (schemas.length === 0) {
throw new Error('Error [too few files]: requires one schema file per contract');
}
if (schemas.length !== 1) {
throw new Error('Error [too many files]: CosmWasm v1.1 schemas supports one file');
}
const idlObject = schemas[0];
const {
// contract_name,
// contract_version,
idl_version, responses, instantiate, execute, query, migrate, sudo } = idlObject;
if (typeof idl_version !== 'string') {
// legacy
return {
schemas: fn(schemas)
};
}
// TODO use contract_name, etc.
const idl = {
instantiate,
execute,
query,
migrate,
sudo
};
return {
schemas: [
...Object.values(fn(idl)).filter(Boolean),
...Object.values(fn({ ...responses })).filter(Boolean)
],
responses,
idlObject
};
};
export const findQueryMsg = (schemas) => {
const queryMsg = schemas.find(schema => schema.title === 'QueryMsg');
return queryMsg;
};
export const findExecuteMsg = (schemas) => {
const executeMsg = schemas.find(schema => schema.title.startsWith('ExecuteMsg'));
return executeMsg;
};
export const findAndParseTypes = async (schemas) => {
const Types = schemas;
const allTypes = [];
for (const typ in Types) {
if (Types[typ].definitions) {
for (const key of Object.keys(Types[typ].definitions)) {
// set title
Types[typ].definitions[key].title = key;
}
}
const result = await compile(Types[typ], Types[typ].title);
allTypes.push(result);
}
const typeHash = parser(allTypes);
return typeHash;
};