-
Notifications
You must be signed in to change notification settings - Fork 339
[WIP] Binding gen #1287
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
Draft
Ryang-21
wants to merge
19
commits into
master
Choose a base branch
from
binding-gen
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
[WIP] Binding gen #1287
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
0ac31c1
add contract bindings generation
Ryang-21 a802b40
add cli for binding generation
Ryang-21 b348428
change cli name to avoid naming conflict with stellar-cli
Ryang-21 ee062fe
fix scSymbol type conversion to string
Ryang-21 c03ae81
extract duplicated typedef parsing and create util for generating imp…
Ryang-21 2fcf367
include null in Option union type and Address for scVal Address
Ryang-21 e5ca345
fix parsing of ts type for scVoid
Ryang-21 d4c571e
simplify type generation
Ryang-21 b320cde
set option field for contract methods to be type MethodOptions
Ryang-21 7a0b1f5
sanitize names of functions,interfaces, and enums for js reserved key…
Ryang-21 f065fe7
add js docs to contract method interface
Ryang-21 095f164
replace sh -> js script for fetching sac spec
Ryang-21 33e8b6c
cleanup redundant code
Ryang-21 dcd94cf
Merge branch 'master' into binding-gen
Ryang-21 d38ddeb
fix wasm parser import
Ryang-21 98b0ba0
use --network option for setting passphrase in cli
Ryang-21 c4b6ad3
fix linter errors
Ryang-21 f0497dd
parse scVoid typedef as null
Ryang-21 08974d5
handle nested option types when parsing typedef
Ryang-21 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| // Entry point for the stellar CLI | ||
| require("../lib/cli/index.js").runCli(); | ||
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,82 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| import https from "https"; | ||
| import fs from "fs"; | ||
| import path from "path"; | ||
| import { fileURLToPath } from "url"; | ||
|
|
||
| // Get __dirname equivalent in ESM | ||
| const __filename = fileURLToPath(import.meta.url); | ||
| const __dirname = path.dirname(__filename); | ||
|
|
||
| // Get repo root | ||
| const REPO_ROOT = path.join(__dirname, ".."); | ||
|
|
||
| // URLs and paths | ||
| const REPO_URL = | ||
| "https://raw.githubusercontent.com/stellar/stellar-asset-contract-spec/main/stellar-asset-spec.xdr"; | ||
| const TS_FILE = path.join(REPO_ROOT, "src/bindings/sac-spec.ts"); | ||
|
|
||
| console.log("Downloading Stellar Asset Contract spec from GitHub..."); | ||
|
|
||
| // Download file | ||
| https | ||
| .get(REPO_URL, (response) => { | ||
| if (response.statusCode !== 200) { | ||
| console.error(`✗ Failed to download: HTTP ${response.statusCode}`); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| const chunks = []; | ||
|
|
||
| response.on("data", (chunk) => { | ||
| chunks.push(chunk); | ||
| }); | ||
|
|
||
| response.on("end", () => { | ||
| const buffer = Buffer.concat(chunks); | ||
|
|
||
| // Verify file has content | ||
| if (buffer.length === 0) { | ||
| console.error("✗ Downloaded file is empty"); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| console.log("✓ Successfully downloaded file"); | ||
| console.log(` Size: ${buffer.length} bytes`); | ||
|
|
||
| // Convert to base64 | ||
| console.log("Converting to base64..."); | ||
| const base64Content = buffer.toString("base64"); | ||
|
|
||
| if (!base64Content) { | ||
| console.error("✗ Base64 conversion failed"); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| // Update TypeScript file | ||
| console.log(`Updating ${path.relative(REPO_ROOT, TS_FILE)}...`); | ||
| const tsContent = [ | ||
| "// Auto-generated by scripts/download-sac-spec.sh", | ||
| "// Do not edit manually - run the script to update", | ||
| `export const SAC_SPEC = "${base64Content}";`, | ||
| "", // trailing newline | ||
| ].join("\n"); | ||
|
|
||
| try { | ||
| fs.writeFileSync(TS_FILE, tsContent, "utf8"); | ||
| console.log( | ||
| `✓ Successfully updated ${path.relative(REPO_ROOT, TS_FILE)}`, | ||
| ); | ||
| } catch (error) { | ||
| console.error(`✗ Failed to write file: ${error.message}`); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| console.log("✓ Done"); | ||
| }); | ||
| }) | ||
| .on("error", (error) => { | ||
| console.error(`✗ Error: ${error.message}`); | ||
| process.exit(1); | ||
| }); |
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,213 @@ | ||
| import { xdr } from "@stellar/stellar-base"; | ||
| import { Spec } from "../contract"; | ||
| import { | ||
| parseTypeFromTypeDef, | ||
| generateTypeImports, | ||
| sanitizeName, | ||
| formatJSDocComment, | ||
| } from "./utils"; | ||
|
|
||
| /** | ||
| * Generates TypeScript client class for contract methods | ||
| */ | ||
| export class ClientGenerator { | ||
| private spec: Spec; | ||
|
|
||
| constructor(spec: Spec) { | ||
| this.spec = spec; | ||
| } | ||
|
|
||
| /** | ||
| * Generate client class | ||
| */ | ||
| generate(): string { | ||
| // Generate constructor method if it exists | ||
| let deployMethod = ""; | ||
| try { | ||
| const constructorFunc = this.spec.getFunc("__constructor"); | ||
| deployMethod = this.generateDeployMethod(constructorFunc); | ||
| } catch { | ||
| // For specs without a constructor, generate a deploy method without params | ||
| deployMethod = this.generateDeployMethod(undefined); | ||
| } | ||
| // Generate interface methods | ||
| const interfaceMethods = this.spec | ||
| .funcs() | ||
| .filter((func) => func.name().toString() !== "__constructor") | ||
| .map((func) => this.generateInterfaceMethod(func)) | ||
| .join("\n"); | ||
|
|
||
| const imports = this.generateImports(); | ||
|
|
||
| const specEntries = this.spec.entries.map( | ||
| (entry) => `"${entry.toXDR("base64")}"`, | ||
| ); | ||
|
|
||
| const fromJSON = this.spec | ||
| .funcs() | ||
| .filter((func) => func.name().toString() !== "__constructor") | ||
| .map((func) => this.generateFromJSONMethod(func)) | ||
| .join(","); | ||
|
|
||
| return `${imports} | ||
|
|
||
| export interface Client { | ||
| ${interfaceMethods} | ||
| } | ||
|
|
||
| export class Client extends ContractClient { | ||
| constructor(public readonly options: ContractClientOptions) { | ||
| super( | ||
| new Spec([${specEntries.join(", ")}]), | ||
| options | ||
| ); | ||
| } | ||
|
|
||
| ${deployMethod} | ||
| public readonly fromJSON = { | ||
| ${fromJSON} | ||
| }; | ||
| }`; | ||
| } | ||
|
|
||
| private generateImports(): string { | ||
| const { stellarContractImports, typeFileImports, stellarImports } = | ||
| generateTypeImports( | ||
| this.spec.funcs().flatMap((func) => { | ||
| const inputs = func.inputs(); | ||
| const outputs = func.outputs(); | ||
| const defs = inputs.map((input) => input.type()).concat(outputs); | ||
| return defs; | ||
| }), | ||
| ); | ||
| // Ensure necessary imports for Client class | ||
| stellarContractImports.push( | ||
| "Spec", | ||
| "AssembledTransaction", | ||
| "Client as ContractClient", | ||
| "ClientOptions as ContractClientOptions", | ||
| "MethodOptions", | ||
| ); | ||
| // Build imports | ||
| const importLines: string[] = []; | ||
| if (typeFileImports.length > 0) { | ||
| importLines.push( | ||
| `import {\n${typeFileImports.join(",\n")}\n} from './types.js';`, | ||
| ); | ||
| } | ||
| if (stellarContractImports.length > 0) { | ||
| importLines.push( | ||
| `import {\n${stellarContractImports.join( | ||
| ",\n", | ||
| )}\n} from '@stellar/stellar-sdk/contract';`, | ||
| ); | ||
| } | ||
| if (stellarImports.length > 0) { | ||
| importLines.push( | ||
| `import {\n${stellarImports.join( | ||
| ",\n", | ||
| )}\n} from '@stellar/stellar-sdk';`, | ||
| ); | ||
| } | ||
| importLines.push(`import { Buffer } from 'buffer';`); | ||
| const imports = importLines.join("\n"); | ||
| return imports; | ||
| } | ||
|
|
||
| /** | ||
| * Generate interface method signature | ||
| */ | ||
| private generateInterfaceMethod(func: xdr.ScSpecFunctionV0): string { | ||
| const name = sanitizeName(func.name().toString()); | ||
| const inputs = func.inputs().map((input: any) => ({ | ||
| name: input.name().toString(), | ||
| type: parseTypeFromTypeDef(input.type()), | ||
| })); | ||
| const outputType = | ||
| func.outputs().length > 0 | ||
| ? parseTypeFromTypeDef(func.outputs()[0]) | ||
| : "void"; | ||
| const docs = formatJSDocComment(func.doc().toString(), 2); | ||
| const params = this.formatMethodParameters(inputs); | ||
|
|
||
| return `${docs} ${name}(${params}): Promise<AssembledTransaction<${outputType}>>;`; | ||
| } | ||
|
|
||
| private generateFromJSONMethod(func: xdr.ScSpecFunctionV0): string { | ||
| const name = func.name().toString(); | ||
| const outputType = | ||
| func.outputs().length > 0 | ||
| ? parseTypeFromTypeDef(func.outputs()[0]) | ||
| : "void"; | ||
|
|
||
| return ` ${name} : this.txFromJSON<${outputType}>`; | ||
| } | ||
| /** | ||
| * Generate deploy method | ||
| */ | ||
| private generateDeployMethod( | ||
| constructorFunc: xdr.ScSpecFunctionV0 | undefined, | ||
| ): string { | ||
| // If no constructor, generate deploy with no params | ||
| if (!constructorFunc) { | ||
| const params = this.formatConstructorParameters([]); | ||
| return ` static deploy<T = Client>(${params}): Promise<AssembledTransaction<T>> { | ||
| return ContractClient.deploy(null, options); | ||
| }`; | ||
| } | ||
| const inputs = constructorFunc.inputs().map((input) => ({ | ||
| name: input.name().toString(), | ||
| type: parseTypeFromTypeDef(input.type()), | ||
| })); | ||
|
|
||
| const params = this.formatConstructorParameters(inputs); | ||
| const inputsDestructure = | ||
| inputs.length > 0 ? `{ ${inputs.map((i) => i.name).join(", ")} }, ` : ""; | ||
|
|
||
| return ` static deploy<T = Client>(${params}): Promise<AssembledTransaction<T>> { | ||
| return ContractClient.deploy(${inputsDestructure}options); | ||
| }`; | ||
| } | ||
|
|
||
| /** | ||
| * Format method parameters | ||
| */ | ||
| private formatMethodParameters( | ||
| inputs: Array<{ name: string; type: string }>, | ||
| ): string { | ||
| const params: string[] = []; | ||
|
|
||
| if (inputs.length > 0) { | ||
| const inputsParam = `{ ${inputs.map((i) => `${i.name}: ${i.type}`).join("; ")} }`; | ||
| params.push( | ||
| `{ ${inputs.map((i) => i.name).join(", ")} }: ${inputsParam}`, | ||
| ); | ||
| } | ||
|
|
||
| params.push("options?: MethodOptions"); | ||
|
|
||
| return params.join(", "); | ||
| } | ||
|
|
||
| /** | ||
| * Format constructor parameters | ||
| */ | ||
| private formatConstructorParameters( | ||
| inputs: Array<{ name: string; type: string }>, | ||
| ): string { | ||
| const params: string[] = []; | ||
|
|
||
| if (inputs.length > 0) { | ||
| const inputsParam = `{ ${inputs.map((i) => `${i.name}: ${i.type}`).join("; ")} }`; | ||
| params.push( | ||
| `{ ${inputs.map((i) => i.name).join(", ")} }: ${inputsParam}`, | ||
| ); | ||
| } | ||
|
|
||
| params.push( | ||
| 'options: MethodOptions & Omit<ContractClientOptions, \'contractId\'> & { wasmHash: Buffer | string; salt?: Buffer | Uint8Array; format?: "hex" | "base64"; address?: string; }', | ||
| ); | ||
|
|
||
| return params.join(", "); | ||
| } | ||
| } |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.