Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 5737x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 4x 3x 5x 1x 4x 1x 3x 3x 3x 3x 6x 6x 5x 1x 4x 4x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 3x 3x 16x 16x 1x 16x 16x 15x 15x 2x 316x 32x 32x | import * as eslint from 'eslint'
import * as fs from 'fs'
import * as prettier from 'prettier'
import * as ts from 'typescript'
import {ABI} from '@wharfkit/antelope'
import {abiToBlob, ContractKit} from '@wharfkit/contract'
import {log, makeClient} from '../../utils'
import {generateContractClass} from './class'
import {generateImportStatement, getCoreImports} from './helpers'
import {
generateActionNamesInterface,
generateActionReturnValuesInterface,
generateActionsNamespace,
} from './interfaces'
import {generateTableMap, generateTableTypesInterface} from './maps'
import {generateNamespace} from './namespace'
import {generateStructClasses} from './structs'
import {generateActionNamesTypeAlias, generateRowType, generateTableNamesTypeAlias} from './types'
import {generateActionReturnNamesType} from './interfaces'
const printer = ts.createPrinter()
interface CommandOptions {
url?: string
file?: string
json?: string
eslintrc?: string
}
export async function generateContractFromCommand(
contractName: string | undefined,
{url, file, json, eslintrc}: CommandOptions
) {
let abi: ABI | undefined
if (json) {
log(`Loading ABI from ${json}...`)
const abiString = fs.readFileSync(json, 'utf8')
abi = ABI.from(JSON.parse(abiString))
} else {
if (!contractName) {
throw new Error('Contract name is required when json value is not provided.')
}
if (!url) {
throw new Error('URL is required when json value is not provided.')
}
log(`Fetching ABI for ${contractName}...`)
const contractKit = new ContractKit({client: makeClient(url)})
const contract = await contractKit.load(contractName)
abi = contract.abi
}
log(`Generating Contract helpers for ${contractName}...`)
const contractCode = await generateContract(contractName || 'unknown', abi!, eslintrc)
log(`Generated Contract helper class for ${contractName}...`)
if (file) {
fs.writeFileSync(file, contractCode)
log(`Generated Contract helper for ${contractName} saved to ${file}`)
} else {
log(`Generated Contract helper class:\n`)
log(contractCode, 'info')
}
}
export async function generateContract(contractName: string, abi: ABI, eslintrc?: string) {
try {
const {classes, types} = getCoreImports(abi)
const allAntelopeTypeImports = ['Action', ...types]
const importAntelopeTypesStatement = generateImportStatement(
cleanupImports(allAntelopeTypeImports),
'@wharfkit/antelope',
true
)
const allAntelopeClassImports = ['ABI', 'Blob', 'Struct', 'Name', ...classes]
const importAntelopeClassesStatement = generateImportStatement(
cleanupImports(allAntelopeClassImports),
'@wharfkit/antelope'
)
const importContractTypesStatement = generateImportStatement(
['ActionOptions', 'ContractArgs', 'PartialBy', 'Table'],
'@wharfkit/contract',
true
)
const importContractClassStatement = generateImportStatement(
['Contract as BaseContract'],
'@wharfkit/contract'
)
const {classDeclaration} = await generateContractClass(contractName, abi)
const actionNamesInterface = generateActionNamesInterface(abi)
const actionNamesTypeAlias = generateActionNamesTypeAlias()
const actionsNamespace = generateActionsNamespace(abi)
// Iterate through structs and create struct classes with fields
const structDeclarations = generateStructClasses(abi)
// Encode the ABI as a binary hex string
const abiBlob = abiToBlob(abi)
// Generate `abiBlob` field
const abiBlobField = ts.factory.createVariableStatement(
[ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
ts.factory.createVariableDeclarationList(
[
ts.factory.createVariableDeclaration(
'abiBlob',
undefined,
undefined,
ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(
ts.factory.createIdentifier('Blob'),
ts.factory.createIdentifier('from')
),
undefined,
[ts.factory.createStringLiteral(String(abiBlob))]
)
),
],
ts.NodeFlags.Const
)
)
// Generate `abiBlob` field
const abiField = ts.factory.createVariableStatement(
[ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
ts.factory.createVariableDeclarationList(
[
ts.factory.createVariableDeclaration(
'abi',
undefined,
undefined,
ts.factory.createCallExpression(
ts.factory.createPropertyAccessExpression(
ts.factory.createIdentifier('ABI'),
ts.factory.createIdentifier('from')
),
undefined,
[ts.factory.createIdentifier('abiBlob')]
)
),
],
ts.NodeFlags.Const
)
)
const tableMap = generateTableMap(abi)
const tableTypes = generateTableTypesInterface(abi)
const rowTypeAlias = generateRowType()
const tableNamesTypeAlias = generateTableNamesTypeAlias()
let actionResultValuesInterface: ts.InterfaceDeclaration | undefined
let actionResultsNamesType: ts.TypeAliasDeclaration | undefined
if (abi.action_results.length) {
actionResultValuesInterface = generateActionReturnValuesInterface(abi)
actionResultsNamesType = generateActionReturnNamesType()
}
const sourceFile = ts.factory.createSourceFile(
[
importAntelopeTypesStatement,
importAntelopeClassesStatement,
importContractTypesStatement,
importContractClassStatement,
abiBlobField,
abiField,
generateNamespace('Types', structDeclarations),
tableMap,
tableTypes,
rowTypeAlias,
tableNamesTypeAlias,
actionsNamespace,
actionNamesInterface,
actionNamesTypeAlias,
...(actionResultValuesInterface ? [actionResultValuesInterface] : []),
...(actionResultsNamesType ? [actionResultsNamesType] : []),
classDeclaration,
],
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
ts.NodeFlags.None
)
return runPrettier(printer.printFile(sourceFile), eslintrc)
} catch (e) {
// eslint-disable-next-line no-console
console.error(`An error occurred while generating the contract code: ${e}`)
throw e
}
}
async function runPrettier(codeText: string, eslintrc?: string): Promise<string> {
// First prettier and then eslint fix, cause prettier result cann't pass eslint check
const prettiered = prettier.format(codeText, {
arrowParens: 'always',
bracketSpacing: false,
endOfLine: 'lf',
printWidth: 100,
semi: false,
singleQuote: true,
tabWidth: 4,
trailingComma: 'es5',
parser: 'typescript',
})
const linter = new eslint.ESLint({
useEslintrc: false,
fix: true,
baseConfig: {},
overrideConfigFile: eslintrc ? eslintrc : null,
})
const results = await linter.lintText(prettiered)
return results[0].output ? results[0].output : prettiered
}
function cleanupImports(imports: string[]) {
imports = imports.filter((item, index) => imports.indexOf(item) === index)
imports.sort()
return imports
}
|