Skip to content
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

Anchor IDL generator #89

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,5 @@ build*
.idea
cmake-build-debug
cmake-build-release

node_modules/
120 changes: 120 additions & 0 deletions lib/idl/generator/accounts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { Project } from "ts-morph"
import { CodeBlockWriter } from "ts-morph";
import { tsTypeFromIdl } from "../generator/helper.js";

export function generateAccounts(idl) {
if (idl.accounts === undefined || idl.accounts.length === 0) {
return
}
genAccountFiles(idl)
}

function accountFieldClass(acc, writer) {

writer.write(`class ${acc.name}Fields`).inlineBlock(() => {
writer.writeLine("public:")
for (let i = 0; i < acc.type.fields.length; i++) {
writer.writeLine(`${tsTypeFromIdl(acc.type.fields[i].type)} ${acc.type.fields[i].name};`)
}
}).write(`;`).newLine();

}

function accountClassJson(acc, writer) {

writer.write(`class ${acc.name}JSON`).inlineBlock(() => {
for (let i = 0; i < acc.type.fields.length; i++) {
writer.writeLine(`${tsTypeFromIdl(acc.type.fields[i].type)} ${acc.type.fields[i].name};`)
}
}).write(`;`).newLine();

}

function accountClass(acc, writer) {

writer.write(`class ${acc.name}`).inlineBlock(() => {
for (let i = 0; i < acc.type.fields.length; i++) {
writer.writeLine(`${tsTypeFromIdl(acc.type.fields[i].type)} ${acc.type.fields[i].name};`)
}
writer.blankLine()
writer.write(`${acc.name} ( ${acc.name}Fields field)`).inlineBlock(() => {
for (let i = 0; i < acc.type.fields.length; i++) {
writer.writeLine(`this->${acc.type.fields[i].name} = field.${acc.type.fields[i].name};`)
}
}
).write(`;`).newLine();
writer.blankLine()
writer.write(`${acc.name} fetch (Connection c , PublicKey address)`).inlineBlock(() => {
writer.writeLine(`int info = c.getAccountInfo(address);`)
writer.write(`if (info == NULL)`).inlineBlock(() => {
writer.writeLine(`return NULL;`)
}
).newLine();
writer.writeLine(`return this->decode(info.data);`)
}).newLine();

writer.blankLine()
writer.write(`${acc.name} fetchMultiple (Connection c , PublicKey[] addresses)`).inlineBlock(() => {
writer.writeLine(`int[] infos = c.getMultipleAccountsInfo(addresses);`)
writer.write(`for (auto info : infos)`).inlineBlock(() => {
writer.write(`if (info == NULL)`).inlineBlock(() => {
writer.writeLine(`return NULL;`)
}
).newLine();
writer.writeLine(`return this->decode(info.data);`)
}
).newLine();
}).newLine();

//decode

writer.blankLine()
writer.write(`${acc.name}JSON ToJson`).inlineBlock(() => {
writer.writeLine(`json r = {`)
for (let i = 0; i < acc.type.fields.length; i++) {
writer.writeLine(`${acc.type.fields[i].name} = this.${acc.type.fields[i].name}.toString();`)
}
writer.writeLine(`} \n return r;`)
}).newLine();

writer.blankLine()
writer.write(`${acc.name} FromJson (json ${acc.name}JSON)`).inlineBlock(() => {

writer.writeLine(`${acc.name}Fields fie;`)
writer.writeLine(`${acc.name} obj(fie);`)
for (let i = 0; i < acc.type.fields.length; i++) {
writer.writeLine(`obj.${acc.type.fields[i].name} = ${acc.name}JSON.${acc.type.fields[i].name};`)
}
writer.writeLine(`return obj;`)

}).newLine();

}).write(`;`).newLine();

}


async function genAccountFiles(
idl
) {
const project = new Project()
idl.accounts?.forEach((acc) => {
const src = project.createSourceFile(`accounts/${acc.name}.cpp`, " ", {
overwrite: true,
})
const writers = new CodeBlockWriter({
// optional options
newLine: "\r\n", // default: "\n"
indentNumberOfSpaces: 2, // default: 4
useTabs: false, // default: false
useSingleQuote: true // default: false
});

writers.writeLine(`#include<string>`)
accountFieldClass(acc, writers)
accountClassJson(acc, writers)
accountClass(acc, writers);
src.insertText(0, writer => writer.writeLine(writers.toString()));
})
await project.save()
}
Empty file added lib/idl/generator/errors.js
Empty file.
57 changes: 57 additions & 0 deletions lib/idl/generator/helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@

export function tsTypeFromIdl(ty) {
switch (ty) {
case "bool":
return "bool"
case "u8":
return "uint8_t"
case "i8":
return "int8_t"
case "u16":
return "uint16_t"
case "i16":
return "int16_t"
case "u32":
return "uint32_t"
case "i32":
return "int32_t"
case "f32":
return "float"
case "u64":
return "uint64_t"
case "i64":
return "int64_t"
case "f64":
return "double"
case "u128":
return "uint128_t"
case "i128":
return "int128_t"
case "bytes":
return "std::vector<int> Array"
Copy link
Collaborator

@godmodegalactus godmodegalactus Dec 9, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

std::vector of char

case "string":
return "std::string"
case "publicKey":
return "PublicKey"
default:
if ("vec" in ty) {
return `std::vector<int>`
}
if ("option" in ty) {
return `${tsTypeFromIdl(
ty.option,
)}`
}
if ("coption" in ty) {
return `${tsTypeFromIdl(
ty.coption,
)}`
}
if ("array" in ty) {
return `std::vector<int>`
}
else {
return "std::string"
}
}
}
Empty file.
50 changes: 50 additions & 0 deletions lib/idl/generator/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import * as fileSystem from "fs"
import * as anchor from "@project-serum/anchor"
import * as solana from "@solana/web3.js"

import { generateAccounts } from "./accounts.js"
import { generateTypes } from "./types.js"
import { program } from "commander"


async function main() {
program
.description("generator to interact with anchor IDL")
.argument("address", "address of the deployed program")
.argument("output", " output directory")
.option("-fp, --idlFilePath [value]", "idl file path")
.parse()

const address = program.args[0]
const output = program.args[1]
const filepath = program.opts().idlFilePath || null


//Fetch IDL
const connection = new solana.Connection(solana.clusterApiUrl('mainnet-beta'))
const keypair = anchor.web3.Keypair.generate()
const wallet = new anchor.Wallet(keypair)
const provider = new anchor.AnchorProvider(connection, wallet)
const Program = new solana.PublicKey(address);
const idlFromCluster = await anchor.Program.fetchIdl(Program, provider);

//IDL From File
const idlFromFile = filepath ? JSON.parse(fileSystem.readFileSync(filepath, "utf-8")) : null


//generate classes, methods

//generate accounts
console.log("generating accounts")
generateAccounts(idlFromCluster)
console.log("generating types")
generateTypes(idlFromCluster);




console.log("writing in the files")

}

main();
Empty file added lib/idl/generator/programId.js
Empty file.
123 changes: 123 additions & 0 deletions lib/idl/generator/types.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { Project } from "ts-morph"
import { CodeBlockWriter } from "ts-morph";
import { tsTypeFromIdl } from "../generator/helper.js";

export function generateTypes(idl) {
if (idl.accounts === undefined || idl.accounts.length === 0) {
return
}
genTypesFiles(idl)
}

function typeDatafieldsClass(acc, writer) {

writer.write(`class ${acc.name}DataFields`).inlineBlock(() => {
writer.writeLine("public:")
for (let i = 0; i < acc.type.fields?.length; i++) {
writer.writeLine(`${tsTypeFromIdl(acc.type.fields[i]?.type)} ${acc.type.fields[i]?.name};`)
}

}).write(`;`).newLine();

}

function typeDataClassJson(acc, writer) {

writer.write(`class ${acc.name}DataJSON`).inlineBlock(() => {
writer.writeLine("public:")
for (let i = 0; i < acc.type.fields?.length; i++) {
writer.writeLine(`${tsTypeFromIdl(acc.type.fields[i]?.type)} ${acc.type.fields[i]?.name};`)
}

}).write(`;`).newLine();

}

function typeDataClass(acc, writer) {

writer.write(`class ${acc.name}Data`).inlineBlock(() => {
for (let i = 0; i < acc.type.fields?.length; i++) {
writer.writeLine(`${tsTypeFromIdl(acc.type.fields[i]?.type)} ${acc.type.fields[i]?.name};`)
}
writer.blankLine()
writer.write(`${acc.name} ( ${acc.name}Fields field)`).inlineBlock(() => {
for (let i = 0; i < acc.type.fields?.length; i++) {
writer.writeLine(`this->${acc.type.fields[i]?.name} = field.${acc.type.fields[i]?.name};`)
}
}
).write(`;`).newLine();
writer.blankLine()
writer.write(`${acc.name} fetch (Connection c , PublicKey address)`).inlineBlock(() => {
writer.writeLine(`int info = c.getAccountInfo(address);`)
writer.write(`if (info == NULL)`).inlineBlock(() => {
writer.writeLine(`return NULL;`)
}
).newLine();
writer.writeLine(`return this->decode(info.data);`)
}).newLine();

writer.blankLine()
writer.write(`${acc.name} fetchMultiple (Connection c , PublicKey[] addresses)`).inlineBlock(() => {
writer.writeLine(`int[] infos = c.getMultipleAccountsInfo(addresses);`)
writer.write(`for (auto info : infos)`).inlineBlock(() => {
writer.write(`if (info == NULL)`).inlineBlock(() => {
writer.writeLine(`return NULL;`)
}
).newLine();
writer.writeLine(`return this->decode(info.data);`)
}
).newLine();
}).newLine();

//decode

writer.blankLine()
writer.write(`${acc.name}JSON ToJson`).inlineBlock(() => {
writer.writeLine(`json r = {`)
for (let i = 0; i < acc.type.fields?.length; i++) {
writer.writeLine(`${acc.type.fields[i]?.name} = this.${acc.type.fields[i]?.name}.toString();`)
}
writer.writeLine(`} \n return r;`)
}).newLine();

writer.blankLine()
writer.write(`${acc.name} FromJson (json ${acc.name}JSON)`).inlineBlock(() => {

writer.writeLine(`${acc.name}Fields fie;`)
writer.writeLine(`${acc.name} obj(fie);`)
for (let i = 0; i < acc.type.fields?.length; i++) {
writer.writeLine(`obj.${acc.type.fields[i]?.name} = ${acc.name}JSON.${acc.type.fields[i]?.name};`)
}
writer.writeLine(`return obj;`)

}).newLine();

}).write(`;`).newLine();

}

async function genTypesFiles(
idl
) {

const project = new Project()
idl.types?.forEach((acc) => {
const src = project.createSourceFile(`types/${acc.name}.cpp`, " ", {
overwrite: true,
})
const writers = new CodeBlockWriter({
// optional options
newLine: "\r\n", // default: "\n"
indentNumberOfSpaces: 2, // default: 4
useTabs: false, // default: false
useSingleQuote: true // default: false
});

writers.writeLine(`#include<string>`)
typeDatafieldsClass(acc, writers)
typeDataClassJson(acc, writers)
typeDataClass(acc, writers);
src.insertText(0, writer => writer.writeLine(writers.toString()));
})
await project.save()
}
Loading