-
Notifications
You must be signed in to change notification settings - Fork 31
Generate ralph interfaces based on contract artifacts #480
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
/* | ||
Copyright 2018 - 2022 The Alephium Authors | ||
This file is part of the alephium project. | ||
|
||
The library is free software: you can redistribute it and/or modify | ||
it under the terms of the GNU Lesser General Public License as published by | ||
the Free Software Foundation, either version 3 of the License, or | ||
(at your option) any later version. | ||
|
||
The library is distributed in the hope that it will be useful, | ||
but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
GNU Lesser General Public License for more details. | ||
|
||
You should have received a copy of the GNU Lesser General Public License | ||
along with the library. If not, see <http://www.gnu.org/licenses/>. | ||
*/ | ||
|
||
import path from 'path' | ||
import { Contract, decodeArrayType, PrimitiveTypes, Struct } from '@alephium/web3' | ||
import { Project } from './project' | ||
import { promises as fsPromises } from 'fs' | ||
|
||
const header = '// Autogenerated file. Do not edit manually.\n\n' | ||
|
||
export async function genInterfaces(artifactDir: string, outDir: string) { | ||
const structs = await Project.loadStructs(artifactDir) | ||
const contracts = await loadContracts(artifactDir, structs) | ||
const structNames = structs.map((s) => s.name) | ||
const contractNames = contracts.map((c) => c.name) | ||
const interfaceDefs = contracts.map((c) => genInterface(c, structNames, contractNames)) | ||
|
||
const outPath = path.resolve(outDir) | ||
await fsPromises.rm(outPath, { recursive: true, force: true }) | ||
await fsPromises.mkdir(outPath, { recursive: true }) | ||
for (const i of interfaceDefs) { | ||
const filePath = path.join(outPath, `${i.name}.ral`) | ||
await saveToFile(filePath, i.def) | ||
} | ||
if (structs.length > 0) { | ||
const structDefs = genStructs(structs, structNames, contractNames) | ||
await saveToFile(path.join(outPath, '__structs.ral'), structDefs) | ||
} | ||
} | ||
|
||
async function saveToFile(filePath: string, content: string) { | ||
await fsPromises.writeFile(filePath, header + content, 'utf-8') | ||
} | ||
|
||
function genInterface(contract: Contract, structNames: string[], contractNames: string[]) { | ||
const interfaceName = `__I${contract.name}` | ||
const functions: string[] = [] | ||
let publicFuncIndex = 0 | ||
contract.functions.forEach((funcSig, index) => { | ||
const method = contract.decodedContract.methods[`${index}`] | ||
if (!method.isPublic) return | ||
const usingAnnotations: string[] = [] | ||
if (publicFuncIndex !== index) usingAnnotations.push(`methodIndex = ${index}`) | ||
if (method.useContractAssets) usingAnnotations.push('assetsInContract = true') | ||
if (method.usePreapprovedAssets) usingAnnotations.push('preapprovedAssets = true') | ||
if (method.usePayToContractOnly) usingAnnotations.push('payToContractOnly = true') | ||
const annotation = usingAnnotations.length === 0 ? '' : `@using(${usingAnnotations.join(', ')})` | ||
|
||
const params = funcSig.paramNames.map((paramName, index) => { | ||
const type = getType(funcSig.paramTypes[`${index}`], structNames, contractNames) | ||
const isMutable = funcSig.paramIsMutable[`${index}`] | ||
return isMutable ? `mut ${paramName}: ${type}` : `${paramName}: ${type}` | ||
}) | ||
const rets = funcSig.returnTypes.map((type) => getType(type, structNames, contractNames)) | ||
const result = ` | ||
${annotation} | ||
pub fn ${funcSig.name}(${params.join(', ')}) -> (${rets.join(', ')}) | ||
` | ||
functions.push(result.trim()) | ||
publicFuncIndex += 1 | ||
}) | ||
const interfaceDef = format( | ||
`@using(methodSelector = false) | ||
Interface ${interfaceName} { | ||
${functions.join('\n\n')} | ||
}`, | ||
3 | ||
) | ||
return { name: interfaceName, def: interfaceDef } | ||
} | ||
|
||
function getType(typeName: string, structNames: string[], contractNames: string[]): string { | ||
if (PrimitiveTypes.includes(typeName)) return typeName | ||
if (typeName.startsWith('[')) { | ||
const [baseType, size] = decodeArrayType(typeName) | ||
return `[${getType(baseType, structNames, contractNames)}; ${size}]` | ||
} | ||
if (structNames.includes(typeName)) return typeName | ||
if (contractNames.includes(typeName)) return `I${typeName}` | ||
// We currently do not generate artifacts for interface types, so when a function | ||
// param/ret is of an interface type, we use `ByteVec` as the param/ret type | ||
return 'ByteVec' | ||
} | ||
|
||
function genStructs(structs: Struct[], structNames: string[], contractNames: string[]) { | ||
const structDefs = structs.map((s) => { | ||
const fields = s.fieldNames.map((fieldName, index) => { | ||
const fieldType = getType(s.fieldTypes[`${index}`], structNames, contractNames) | ||
const isMutable = s.isMutable[`${index}`] | ||
return isMutable ? `mut ${fieldName}: ${fieldType}` : `${fieldName}: ${fieldType}` | ||
}) | ||
return format( | ||
`struct ${s.name} { | ||
${fields.join(',\n')} | ||
}`, | ||
2 | ||
) | ||
}) | ||
return structDefs.join('\n\n') | ||
} | ||
|
||
function format(str: string, lineToIndentFrom: number): string { | ||
const padding = ' ' // 2 spaces | ||
const lines = str.trim().split('\n') | ||
return lines | ||
.map((line, index) => { | ||
const newLine = line.trim() | ||
if (index < lineToIndentFrom - 1 || index === lines.length - 1) { | ||
return newLine | ||
} else if (newLine.length === 0) { | ||
return line | ||
} else { | ||
return padding + newLine | ||
} | ||
}) | ||
.join('\n') | ||
} | ||
|
||
async function loadContracts(artifactDir: string, structs: Struct[]) { | ||
const contracts: Contract[] = [] | ||
const load = async function (dirPath: string): Promise<void> { | ||
const dirents = await fsPromises.readdir(dirPath, { withFileTypes: true }) | ||
for (const dirent of dirents) { | ||
if (dirent.isFile()) { | ||
const artifactPath = path.join(dirPath, dirent.name) | ||
const contract = await getContractFromArtifact(artifactPath, structs) | ||
if (contract !== undefined) contracts.push(contract) | ||
} else { | ||
const newPath = path.join(dirPath, dirent.name) | ||
await load(newPath) | ||
} | ||
} | ||
} | ||
await load(artifactDir) | ||
return contracts | ||
} | ||
|
||
async function getContractFromArtifact(filePath: string, structs: Struct[]): Promise<Contract | undefined> { | ||
if (!filePath.endsWith('.ral.json')) return undefined | ||
if (filePath.endsWith(Project.structArtifactFileName) || filePath.endsWith(Project.constantArtifactFileName)) { | ||
return undefined | ||
} | ||
const content = await fsPromises.readFile(filePath) | ||
const artifact = JSON.parse(content.toString()) | ||
if ('bytecodeTemplate' in artifact) return undefined | ||
try { | ||
return Contract.fromJson(artifact, '', '', structs) | ||
} catch (error) { | ||
console.error(`Failed to load contract from artifact ${filePath}: `, error) | ||
return undefined | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
__
. E.g.__IFoo.ral
/// Autogenerated file. Do not edit manually.