prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
import { BattleStats } from "../../value_objects/BattleStats"; import { Item } from "../item/Item"; import { League } from "../league/League"; import { Pokemon } from "../pokemon/Pokemon"; export class Trainer { private _id: string; private _name: string; private _city: string; private _age: number; private _level: number; private _pokemons: Pokemon[]; private _items: Item[]; private _league: League | null; constructor(props: { id: string; name: string; city: string; age: number; level: number; pokemons: Pokemon[]; items: Item[]; league: League | null; }) { this._id = props.id; this._name = props.name; this._city = props.city; this._age = props.age; this._level = props.level; this._pokemons = props.pokemons; this._items = props.items; this._league = props.league; } // Methods addPokemon(pokemon: Pokemon) { this._pokemons.push(pokemon); } removePokemon(pokemon: Pokemon): void { this._pokemons = this._pokemons.filter((p) => p.equals(pokemon)); } addItem(item: Item) { this._items.push(item); } removeItem(item: Item): void { this._items = this._items.filter((i) => i.equals(item)); } applyItem(item: Item, pokemon: Pokemon): void { pokemon.life += item.increaseLife; const newStats = new BattleStats({ attack: pokemon.stats.attack + item.increaseAttack, defense: pokemon.stats.
defense + item.increaseDefense, speed: pokemon.stats.speed + item.increaseSpeed, });
pokemon.stats = newStats; } // Getters and setters get id(): string { return this._id; } set id(id: string) { this._id = id; } get name(): string { return this._name; } set name(name: string) { this._name = name; } get city(): string { return this._city; } set city(city: string) { this._city = city; } get age(): number { return this._age; } set age(age: number) { this._age = age; } get level(): number { return this._level; } set level(level: number) { this._level = level; } get pokemons() { return this._pokemons; } set pokemons(pokemon: Pokemon[]) { this._pokemons = pokemon; } get items() { return this._items; } set items(items: Item[]) { this._items = items; } get league() { return this._league; } set league(league: League | null) { this._league = league; } }
src/app/entities/trainer/Trainer.ts
jnaraujo-poke-battle-manager-e4da436
[ { "filename": "src/app/entities/item/Item.ts", "retrieved_chunk": " equals(item: Item): boolean {\n return this._id === item.id;\n }\n}", "score": 39.744602743431585 }, { "filename": "src/app/entities/item/Item.spec.ts", "retrieved_chunk": " name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n });\n expect(item.equals(item2)).toBeTruthy();\n });\n it(\"should not be equals\", () => {\n const item2 = new Item({", "score": 38.87933388521526 }, { "filename": "src/app/entities/item/Item.spec.ts", "retrieved_chunk": " id: \"2\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n });\n expect(item.equals(item2)).toBeFalsy();\n });\n});", "score": 37.90186111923872 }, { "filename": "src/app/use-cases/pokemon/AddPokemonUseCase.spec.ts", "retrieved_chunk": " for (let i = 0; i < 3; i++) {\n await addPokemonUseCase.execute({\n name: \"Pikachu\",\n level: 25,\n life: 100,\n type: [\"electric\"],\n stats: new BattleStats({\n attack: 10,\n defense: 10,\n speed: 10,", "score": 35.94562760337586 }, { "filename": "src/app/entities/item/Item.spec.ts", "retrieved_chunk": "import { describe, it, expect, beforeEach } from \"vitest\";\nimport { Item } from \"./Item\";\ndescribe(\"Item\", () => {\n let item: Item;\n beforeEach(() => {\n item = new Item({\n id: \"1\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,", "score": 35.90530560109885 } ]
typescript
defense + item.increaseDefense, speed: pokemon.stats.speed + item.increaseSpeed, });
import { BattleStats } from "../../value_objects/BattleStats"; import { Item } from "../item/Item"; import { League } from "../league/League"; import { Pokemon } from "../pokemon/Pokemon"; export class Trainer { private _id: string; private _name: string; private _city: string; private _age: number; private _level: number; private _pokemons: Pokemon[]; private _items: Item[]; private _league: League | null; constructor(props: { id: string; name: string; city: string; age: number; level: number; pokemons: Pokemon[]; items: Item[]; league: League | null; }) { this._id = props.id; this._name = props.name; this._city = props.city; this._age = props.age; this._level = props.level; this._pokemons = props.pokemons; this._items = props.items; this._league = props.league; } // Methods addPokemon(pokemon: Pokemon) { this._pokemons.push(pokemon); } removePokemon(pokemon: Pokemon): void { this._pokemons = this._pokemons.filter((p) => p.equals(pokemon)); } addItem(item: Item) { this._items.push(item); } removeItem(item: Item): void { this._items = this._items.filter((i) => i.equals(item)); } applyItem(item: Item, pokemon: Pokemon): void { pokemon.life += item.increaseLife;
const newStats = new BattleStats({
attack: pokemon.stats.attack + item.increaseAttack, defense: pokemon.stats.defense + item.increaseDefense, speed: pokemon.stats.speed + item.increaseSpeed, }); pokemon.stats = newStats; } // Getters and setters get id(): string { return this._id; } set id(id: string) { this._id = id; } get name(): string { return this._name; } set name(name: string) { this._name = name; } get city(): string { return this._city; } set city(city: string) { this._city = city; } get age(): number { return this._age; } set age(age: number) { this._age = age; } get level(): number { return this._level; } set level(level: number) { this._level = level; } get pokemons() { return this._pokemons; } set pokemons(pokemon: Pokemon[]) { this._pokemons = pokemon; } get items() { return this._items; } set items(items: Item[]) { this._items = items; } get league() { return this._league; } set league(league: League | null) { this._league = league; } }
src/app/entities/trainer/Trainer.ts
jnaraujo-poke-battle-manager-e4da436
[ { "filename": "src/app/entities/item/Item.ts", "retrieved_chunk": " equals(item: Item): boolean {\n return this._id === item.id;\n }\n}", "score": 48.33030011787304 }, { "filename": "src/app/entities/item/Item.spec.ts", "retrieved_chunk": "import { describe, it, expect, beforeEach } from \"vitest\";\nimport { Item } from \"./Item\";\ndescribe(\"Item\", () => {\n let item: Item;\n beforeEach(() => {\n item = new Item({\n id: \"1\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,", "score": 43.30217823091431 }, { "filename": "src/app/repositories/ItemRepository.ts", "retrieved_chunk": "import { Item } from \"../entities/item/Item\";\nimport { Repository } from \"./Repository\";\nexport interface ItemRepository extends Repository<Item> {}", "score": 36.09156559350723 }, { "filename": "src/app/entities/item/Item.spec.ts", "retrieved_chunk": " name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n });\n expect(item.equals(item2)).toBeTruthy();\n });\n it(\"should not be equals\", () => {\n const item2 = new Item({", "score": 34.80486620356764 }, { "filename": "src/app/entities/trainer/Trainer.spec.ts", "retrieved_chunk": "import { beforeEach, describe, it, expect } from \"vitest\";\nimport { Trainer } from \"./Trainer\";\nimport { Item } from \"../item/Item\";\nimport { BattleStats } from \"../../value_objects/BattleStats\";\nimport { Pokemon } from \"../pokemon/Pokemon\";\ndescribe(\"Trainer\", () => {\n let trainer: Trainer;\n beforeEach(() => {\n trainer = new Trainer({\n id: \"1\",", "score": 33.28131734925643 } ]
typescript
const newStats = new BattleStats({
import { Pokemon } from "../../entities/pokemon/Pokemon"; import { PokemonRepository } from "../../repositories/PokemonRepository"; import crypto from "node:crypto"; import { BattleStats } from "../../value_objects/BattleStats"; import { PokemonMove } from "../../value_objects/PokemonMove"; interface AddPokemonRequest { trainerID: string; name: string; level: number; life: number; type: string[]; stats: BattleStats; moves: PokemonMove[]; } export class AddPokemonUseCase { constructor(private pokemonRepository: PokemonRepository) {} async execute({ trainerID, name, level, life, type, stats, moves, }: AddPokemonRequest): Promise<Pokemon> { const pokemon = new Pokemon({ id: crypto.randomUUID(), trainerID: trainerID, name: name, level: level, life: life, type: type, stats: stats, moves: moves, });
const trainerPokemons = await this.pokemonRepository.findByTrainerId( pokemon.trainerID );
if (trainerPokemons.length >= 3) { throw new Error("Trainer already has 3 pokemons"); } await this.pokemonRepository.save(pokemon); return pokemon; } }
src/app/use-cases/pokemon/AddPokemonUseCase.ts
jnaraujo-poke-battle-manager-e4da436
[ { "filename": "src/app/use-cases/battle/CreateBattleUseCase.spec.ts", "retrieved_chunk": " name: `Pikachu ${i}`,\n type: [\"Electric\"],\n level: 1,\n trainerID: trainer2.id,\n life: 100,\n moves: [],\n stats: new BattleStats({\n attack: 100,\n defense: 100,\n speed: 100,", "score": 25.594648862179465 }, { "filename": "src/app/entities/pokemon/Pokemon.ts", "retrieved_chunk": " this.trainerID === other.trainerID &&\n this.stats.equals(other.stats) &&\n isEqual(this.type, other.type) &&\n isEqual(this.moves, other.moves)\n );\n }\n}", "score": 24.82352935874795 }, { "filename": "src/app/entities/pokemon/Pokemon.ts", "retrieved_chunk": " moves: PokemonMove[];\n }) {\n this._id = props.id;\n this._name = props.name;\n this._level = props.level;\n this._life = props.life;\n this._type = props.type;\n this._trainerID = props.trainerID;\n this._stats = props.stats;\n this._moves = props.moves;", "score": 23.718596180011644 }, { "filename": "src/app/entities/trainer/Trainer.spec.ts", "retrieved_chunk": " defense: 100,\n speed: 100,\n }),\n level: 25,\n life: 100,\n moves: [],\n trainerID: \"1\",\n type: [\"Electric\"],\n }),\n ],", "score": 23.461341190610217 }, { "filename": "src/app/use-cases/pokemon/AddPokemonUseCase.spec.ts", "retrieved_chunk": " }),\n moves: [],\n trainerID: \"123\",\n });\n }\n await expect(\n addPokemonUseCase.execute({\n name: \"Pikachu\",\n level: 25,\n life: 100,", "score": 22.502595366582952 } ]
typescript
const trainerPokemons = await this.pokemonRepository.findByTrainerId( pokemon.trainerID );
import { isEqual } from "lodash"; import { PokemonMove } from "../../value_objects/PokemonMove"; import { BattleStats } from "../../value_objects/BattleStats"; export class Pokemon { private _id: string; private _name: string; private _level: number; private _life: number; private _type: string[]; private _trainerID: string; private _stats: BattleStats; private _moves: PokemonMove[]; constructor(props: { id: string; name: string; level: number; life: number; type: string[]; trainerID: string; stats: BattleStats; moves: PokemonMove[]; }) { this._id = props.id; this._name = props.name; this._level = props.level; this._life = props.life; this._type = props.type; this._trainerID = props.trainerID; this._stats = props.stats; this._moves = props.moves; } // Predicates isAwake(): boolean { return this.life > 0; } // Actions attack(target: Pokemon): void { const damage = this._stats
.attack - target.stats.defense;
if (damage > 0) { target.life -= damage; } if (target.life < 0) { target.life = 0; } } // Getters and setters get id(): string { return this._id; } set id(id: string) { this._id = id; } get name(): string { return this._name; } set name(name: string) { this._name = name; } get level(): number { return this._level; } set level(level: number) { this._level = level; } get life(): number { return this._life; } set life(life: number) { this._life = life; } get type(): string[] { return this._type; } set type(type: string[]) { this._type = type; } get trainerID(): string { return this._trainerID; } set trainerID(trainerID: string) { this._trainerID = trainerID; } get stats(): BattleStats { return this._stats; } set stats(stats: BattleStats) { this._stats = stats; } get moves(): PokemonMove[] { return this._moves; } set moves(moves: PokemonMove[]) { this._moves = moves; } // Equals equals(other: Pokemon): boolean { return ( this.id === other.id && this.name === other.name && this.level === other.level && this.trainerID === other.trainerID && this.stats.equals(other.stats) && isEqual(this.type, other.type) && isEqual(this.moves, other.moves) ); } }
src/app/entities/pokemon/Pokemon.ts
jnaraujo-poke-battle-manager-e4da436
[ { "filename": "src/app/entities/trainer/Trainer.ts", "retrieved_chunk": " this._items.push(item);\n }\n removeItem(item: Item): void {\n this._items = this._items.filter((i) => i.equals(item));\n }\n applyItem(item: Item, pokemon: Pokemon): void {\n pokemon.life += item.increaseLife;\n const newStats = new BattleStats({\n attack: pokemon.stats.attack + item.increaseAttack,\n defense: pokemon.stats.defense + item.increaseDefense,", "score": 20.702381947449208 }, { "filename": "src/app/entities/pokemon/Pokemon.spec.ts", "retrieved_chunk": " });\n it(\"should attack\", () => {\n pikachu.attack(charmander);\n const expectedDamage = pikachu.stats.attack - charmander.stats.defense;\n expect(charmander.life).toBe(100 - expectedDamage);\n });\n it(\"should be awake\", () => {\n expect(pikachu.isAwake()).toBeTruthy();\n });\n it(\"should be asleep\", () => {", "score": 19.47716480053223 }, { "filename": "src/app/use-cases/battle/CreateBattleUseCase.spec.ts", "retrieved_chunk": " trainerID: trainer1.id,\n life: 100,\n moves: [],\n stats: new BattleStats({\n attack: 100,\n defense: 100,\n speed: 100,\n }),\n })\n );", "score": 16.98363452616504 }, { "filename": "src/app/value_objects/BattleStats.ts", "retrieved_chunk": "export class BattleStats {\n private _attack: number;\n private _defense: number;\n private _speed: number;\n constructor(props: { attack: number; defense: number; speed: number }) {\n this._attack = props.attack;\n this._defense = props.defense;\n this._speed = props.speed;\n }\n get attack() {", "score": 16.664109123956038 }, { "filename": "src/app/entities/pokemon/Pokemon.spec.ts", "retrieved_chunk": " stats: new BattleStats({\n attack: 100,\n defense: 100,\n speed: 100,\n }),\n level: 25,\n life: 100,\n moves: [\n new PokemonMove({\n name: \"Thunderbolt\",", "score": 15.93517726798422 } ]
typescript
.attack - target.stats.defense;
import { BattleStats } from "../../value_objects/BattleStats"; import { Item } from "../item/Item"; import { League } from "../league/League"; import { Pokemon } from "../pokemon/Pokemon"; export class Trainer { private _id: string; private _name: string; private _city: string; private _age: number; private _level: number; private _pokemons: Pokemon[]; private _items: Item[]; private _league: League | null; constructor(props: { id: string; name: string; city: string; age: number; level: number; pokemons: Pokemon[]; items: Item[]; league: League | null; }) { this._id = props.id; this._name = props.name; this._city = props.city; this._age = props.age; this._level = props.level; this._pokemons = props.pokemons; this._items = props.items; this._league = props.league; } // Methods addPokemon(pokemon: Pokemon) { this._pokemons.push(pokemon); } removePokemon(pokemon: Pokemon): void {
this._pokemons = this._pokemons.filter((p) => p.equals(pokemon));
} addItem(item: Item) { this._items.push(item); } removeItem(item: Item): void { this._items = this._items.filter((i) => i.equals(item)); } applyItem(item: Item, pokemon: Pokemon): void { pokemon.life += item.increaseLife; const newStats = new BattleStats({ attack: pokemon.stats.attack + item.increaseAttack, defense: pokemon.stats.defense + item.increaseDefense, speed: pokemon.stats.speed + item.increaseSpeed, }); pokemon.stats = newStats; } // Getters and setters get id(): string { return this._id; } set id(id: string) { this._id = id; } get name(): string { return this._name; } set name(name: string) { this._name = name; } get city(): string { return this._city; } set city(city: string) { this._city = city; } get age(): number { return this._age; } set age(age: number) { this._age = age; } get level(): number { return this._level; } set level(level: number) { this._level = level; } get pokemons() { return this._pokemons; } set pokemons(pokemon: Pokemon[]) { this._pokemons = pokemon; } get items() { return this._items; } set items(items: Item[]) { this._items = items; } get league() { return this._league; } set league(league: League | null) { this._league = league; } }
src/app/entities/trainer/Trainer.ts
jnaraujo-poke-battle-manager-e4da436
[ { "filename": "src/app/__tests__/repositories/InMemoryPokemonRepository.ts", "retrieved_chunk": " async findById(id: string): Promise<Pokemon | null> {\n return this.pokemons.find((pokemon) => pokemon.id === id) || null;\n }\n async save(entity: Pokemon): Promise<void> {\n this.pokemons.push(entity);\n }\n async delete(entity: Pokemon): Promise<void> {\n this.pokemons = this.pokemons.filter((pokemon) => pokemon.id !== entity.id);\n }\n async update(entity: Pokemon): Promise<void> {", "score": 34.93257364582203 }, { "filename": "src/app/entities/battle/Battle.ts", "retrieved_chunk": " this._trainer2 = props.trainer2;\n this._league = props.league;\n this._winner = null;\n this._loser = null;\n this._createdAt = null;\n this._startedAt = null;\n this._finishedAt = null;\n }\n // Methods\n start(): void {", "score": 28.311051082482308 }, { "filename": "src/app/__tests__/repositories/InMemoryPokemonRepository.ts", "retrieved_chunk": "import { Pokemon } from \"../../entities/pokemon/Pokemon\";\nimport { PokemonRepository } from \"../../repositories/PokemonRepository\";\nexport class InMemoryPokemonRepository implements PokemonRepository {\n private pokemons: Pokemon[] = [];\n async findByTrainerId(trainerId: string): Promise<Pokemon[]> {\n return this.pokemons.filter((pokemon) => pokemon.trainerID === trainerId);\n }\n async findAll(): Promise<Pokemon[]> {\n return this.pokemons;\n }", "score": 27.950773129725285 }, { "filename": "src/app/entities/league/League.ts", "retrieved_chunk": " this._prize = props.prize;\n this._name = props.name;\n this._trainers = [];\n this._battles = [];\n this._createdAt = null;\n this._startedAt = null;\n this._finishedAt = null;\n }\n // Methods\n start(): void {", "score": 24.123021859991397 }, { "filename": "src/app/use-cases/pokemon/UpdatePokemonUseCase.ts", "retrieved_chunk": "import { Pokemon } from \"../../entities/pokemon/Pokemon\";\nimport { PokemonRepository } from \"../../repositories/PokemonRepository\";\ninterface UpdatePokemonRequest {\n pokemon: Pokemon;\n}\nexport class UpdatePokemonUseCase {\n constructor(private pokemonRepository: PokemonRepository) {}\n async execute({ pokemon }: UpdatePokemonRequest) {\n const doesPokemonExist = await this.pokemonRepository.findById(pokemon.id);\n if (!doesPokemonExist) {", "score": 22.516080555547198 } ]
typescript
this._pokemons = this._pokemons.filter((p) => p.equals(pokemon));
import { BattleStats } from "../../value_objects/BattleStats"; import { Item } from "../item/Item"; import { League } from "../league/League"; import { Pokemon } from "../pokemon/Pokemon"; export class Trainer { private _id: string; private _name: string; private _city: string; private _age: number; private _level: number; private _pokemons: Pokemon[]; private _items: Item[]; private _league: League | null; constructor(props: { id: string; name: string; city: string; age: number; level: number; pokemons: Pokemon[]; items: Item[]; league: League | null; }) { this._id = props.id; this._name = props.name; this._city = props.city; this._age = props.age; this._level = props.level; this._pokemons = props.pokemons; this._items = props.items; this._league = props.league; } // Methods addPokemon(pokemon: Pokemon) { this._pokemons.push(pokemon); } removePokemon(pokemon: Pokemon): void { this._pokemons = this._pokemons.filter((p) => p.equals(pokemon)); } addItem(item: Item) { this._items.push(item); } removeItem(item: Item): void { this._items = this._items.filter((i) => i.equals(item)); } applyItem(item: Item, pokemon: Pokemon): void { pokemon.life += item.increaseLife; const newStats = new BattleStats({ attack: pokemon.stats.attack + item.increaseAttack, defense: pokemon.stats.defense + item.increaseDefense, speed: pokemon.stats
.speed + item.increaseSpeed, });
pokemon.stats = newStats; } // Getters and setters get id(): string { return this._id; } set id(id: string) { this._id = id; } get name(): string { return this._name; } set name(name: string) { this._name = name; } get city(): string { return this._city; } set city(city: string) { this._city = city; } get age(): number { return this._age; } set age(age: number) { this._age = age; } get level(): number { return this._level; } set level(level: number) { this._level = level; } get pokemons() { return this._pokemons; } set pokemons(pokemon: Pokemon[]) { this._pokemons = pokemon; } get items() { return this._items; } set items(items: Item[]) { this._items = items; } get league() { return this._league; } set league(league: League | null) { this._league = league; } }
src/app/entities/trainer/Trainer.ts
jnaraujo-poke-battle-manager-e4da436
[ { "filename": "src/app/entities/item/Item.ts", "retrieved_chunk": " equals(item: Item): boolean {\n return this._id === item.id;\n }\n}", "score": 39.744602743431585 }, { "filename": "src/app/entities/item/Item.spec.ts", "retrieved_chunk": " name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n });\n expect(item.equals(item2)).toBeTruthy();\n });\n it(\"should not be equals\", () => {\n const item2 = new Item({", "score": 38.87933388521526 }, { "filename": "src/app/entities/item/Item.spec.ts", "retrieved_chunk": " id: \"2\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n });\n expect(item.equals(item2)).toBeFalsy();\n });\n});", "score": 37.90186111923872 }, { "filename": "src/app/use-cases/pokemon/AddPokemonUseCase.spec.ts", "retrieved_chunk": " for (let i = 0; i < 3; i++) {\n await addPokemonUseCase.execute({\n name: \"Pikachu\",\n level: 25,\n life: 100,\n type: [\"electric\"],\n stats: new BattleStats({\n attack: 10,\n defense: 10,\n speed: 10,", "score": 35.94562760337586 }, { "filename": "src/app/entities/item/Item.spec.ts", "retrieved_chunk": "import { describe, it, expect, beforeEach } from \"vitest\";\nimport { Item } from \"./Item\";\ndescribe(\"Item\", () => {\n let item: Item;\n beforeEach(() => {\n item = new Item({\n id: \"1\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,", "score": 35.90530560109885 } ]
typescript
.speed + item.increaseSpeed, });
import { BattleStats } from "../../value_objects/BattleStats"; import { Item } from "../item/Item"; import { League } from "../league/League"; import { Pokemon } from "../pokemon/Pokemon"; export class Trainer { private _id: string; private _name: string; private _city: string; private _age: number; private _level: number; private _pokemons: Pokemon[]; private _items: Item[]; private _league: League | null; constructor(props: { id: string; name: string; city: string; age: number; level: number; pokemons: Pokemon[]; items: Item[]; league: League | null; }) { this._id = props.id; this._name = props.name; this._city = props.city; this._age = props.age; this._level = props.level; this._pokemons = props.pokemons; this._items = props.items; this._league = props.league; } // Methods addPokemon(pokemon: Pokemon) { this._pokemons.push(pokemon); } removePokemon(pokemon: Pokemon): void { this._pokemons = this._pokemons.filter((p) => p.equals(pokemon)); } addItem(item: Item) { this._items.push(item); } removeItem(item: Item): void { this._items = this._items.filter((i) => i.equals(item)); } applyItem(item: Item, pokemon: Pokemon): void {
pokemon.life += item.increaseLife;
const newStats = new BattleStats({ attack: pokemon.stats.attack + item.increaseAttack, defense: pokemon.stats.defense + item.increaseDefense, speed: pokemon.stats.speed + item.increaseSpeed, }); pokemon.stats = newStats; } // Getters and setters get id(): string { return this._id; } set id(id: string) { this._id = id; } get name(): string { return this._name; } set name(name: string) { this._name = name; } get city(): string { return this._city; } set city(city: string) { this._city = city; } get age(): number { return this._age; } set age(age: number) { this._age = age; } get level(): number { return this._level; } set level(level: number) { this._level = level; } get pokemons() { return this._pokemons; } set pokemons(pokemon: Pokemon[]) { this._pokemons = pokemon; } get items() { return this._items; } set items(items: Item[]) { this._items = items; } get league() { return this._league; } set league(league: League | null) { this._league = league; } }
src/app/entities/trainer/Trainer.ts
jnaraujo-poke-battle-manager-e4da436
[ { "filename": "src/app/entities/item/Item.ts", "retrieved_chunk": " equals(item: Item): boolean {\n return this._id === item.id;\n }\n}", "score": 52.87378248097452 }, { "filename": "src/app/entities/item/Item.spec.ts", "retrieved_chunk": "import { describe, it, expect, beforeEach } from \"vitest\";\nimport { Item } from \"./Item\";\ndescribe(\"Item\", () => {\n let item: Item;\n beforeEach(() => {\n item = new Item({\n id: \"1\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,", "score": 42.823384402653765 }, { "filename": "src/app/repositories/ItemRepository.ts", "retrieved_chunk": "import { Item } from \"../entities/item/Item\";\nimport { Repository } from \"./Repository\";\nexport interface ItemRepository extends Repository<Item> {}", "score": 36.09156559350723 }, { "filename": "src/app/entities/item/Item.spec.ts", "retrieved_chunk": " name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n });\n expect(item.equals(item2)).toBeTruthy();\n });\n it(\"should not be equals\", () => {\n const item2 = new Item({", "score": 35.88997335187807 }, { "filename": "src/app/entities/item/Item.spec.ts", "retrieved_chunk": " increaseDefense: 0,\n increaseSpeed: 0,\n });\n });\n it(\"should be created\", () => {\n expect(item).toBeDefined();\n });\n it(\"should be equals\", () => {\n const item2 = new Item({\n id: \"1\",", "score": 32.45264418989311 } ]
typescript
pokemon.life += item.increaseLife;
import { FC, useCallback, useRef, useState } from 'react'; import { useDecryptFile, useDownloadFile } from '@app/hooks'; import { saveFile } from '@app/lib/files'; import { IconButton, Spinner, useToast } from '@chakra-ui/react'; import { DownloadIcon, ShieldLockIcon } from './Icons'; interface props { fileId: string; } const DownloadButton: FC<props> = (props: props) => { const { fileId } = props; const toast = useToast(); const [downloading, setDownloading] = useState(false); const [decrypting, setDecrypting] = useState(false); const downloadFile = useDownloadFile(); const decryptFile = useDecryptFile(); const ref = useRef<HTMLAnchorElement>(null); const handleClick = useCallback(async () => { setDownloading(true); const { data, metadata } = await downloadFile(fileId); setDownloading(false); setDecrypting(true); try { const fileData = await decryptFile(data); saveFile([fileData], metadata.name, metadata.mimeType, ref); } catch (err) { toast.closeAll(); toast({ position: 'bottom-right', duration: 5000, isClosable: true, title: 'Error decrypting file', description: (err as Error).message, status: 'error', }); } finally { setDecrypting(false); } }, [decryptFile, downloadFile, fileId]); return ( <> <IconButton id={`download-${fileId}`} visibility={downloading || decrypting ? 'visible' : 'hidden'} variant="none" color="purple.600" aria-label="download" icon={ downloading ? ( <Spinner /> ) : decrypting ? (
<ShieldLockIcon boxSize="1.5rem" /> ) : ( <DownloadIcon boxSize="1.5rem" /> ) }
onClick={handleClick} isDisabled={downloading || decrypting} /> <a hidden ref={ref} /> </> ); }; export default DownloadButton;
src/components/DownloadButton.tsx
9OP-Encryptly-ef8661c
[ { "filename": "src/components/Pagination.tsx", "retrieved_chunk": " alignItems=\"center\"\n marginTop=\"1rem\"\n color=\"gray.700\"\n >\n <HStack padding=\"0\" margin=\"0\" spacing=\"0.1rem\">\n <IconButton\n aria-label=\"previous\"\n icon={<ChevronLeftIcon boxSize=\"1.3rem\" />}\n onClick={onPrevious}\n size=\"xs\"", "score": 22.287235546567235 }, { "filename": "src/components/UserCard.tsx", "retrieved_chunk": " size=\"md\"\n leftIcon={<SecretIcon boxSize=\"1.5rem\" />}\n variant=\"link\"\n onClick={onOpen}\n >\n key\n </Button>\n <InfoModal onDownload={onDownload} onClose={onClose} isOpen={isOpen} />\n <a hidden ref={ref} />\n <LogoutButton />", "score": 18.934902949193557 }, { "filename": "src/components/Pagination.tsx", "retrieved_chunk": " icon={<ChevronRightIcon boxSize=\"1.3rem\" />}\n onClick={onNext}\n size=\"xs\"\n variant=\"ghost\"\n disabled={selected === range}\n />\n </HStack>\n </Flex>\n );\n};", "score": 18.430473271301995 }, { "filename": "src/components/LogoutButton.tsx", "retrieved_chunk": "import { useLogout } from '@app/hooks';\nimport { Button } from '@chakra-ui/react';\nimport { LogoutIcon } from './Icons';\nconst LogoutButton = () => {\n const logout = useLogout();\n return (\n <Button\n size=\"md\"\n aria-label=\"logout\"\n leftIcon={<LogoutIcon boxSize=\"1.2rem\" />}", "score": 17.314647987736407 }, { "filename": "src/theme.ts", "retrieved_chunk": " },\n sizes: {},\n variants: {},\n defaultProps: {},\n};\nconst CardStyle: ComponentStyleConfig = {\n baseStyle: {\n padding: '1.5rem',\n borderWidth: '3px',\n borderRadius: '10px',", "score": 15.124069729769204 } ]
typescript
<ShieldLockIcon boxSize="1.5rem" /> ) : ( <DownloadIcon boxSize="1.5rem" /> ) }
import { forwardRef, ReactNode, RefObject, useEffect, useImperativeHandle, useState, } from 'react'; import { revalidateListFiles, useEncryptFile, useUploadFile } from '@app/hooks'; import { ToastId, useToast } from '@chakra-ui/react'; import UploadFeedback from './UploadToast'; interface UploadProps { ref: RefObject<any>; children: ReactNode; } export interface UploadHandle { onSubmit: (file: File[]) => Promise<void>; } const Upload = forwardRef<UploadHandle, UploadProps>((props: UploadProps, ref: any) => { const { children } = props; const toast = useToast(); const [submitCount, setSubmitCount] = useState(0); const [steps, setSteps] = useState<{ [name: string]: 'ENCRYPTING' | 'UPLOADING'; }>({}); const [progress, setProgress] = useState<{ [name: string]: number }>({}); const [toastId, setToastId] = useState<ToastId>(''); const [files, setFiles] = useState<File[]>([]); const uploadFile = useUploadFile(); const encryptFile = useEncryptFile(); useImperativeHandle<UploadHandle, any>(ref, () => ({ async onSubmit(files: File[]) { await onSubmit(files); }, })); useEffect(() => { if (toastId) { toast.update(toastId, {
render: () => <UploadFeedback files={files} steps={steps} progress={progress} />, });
} }, [steps, progress, files]); useEffect(() => { if (submitCount === 0 && toastId) { toast.close(toastId); toast({ position: 'bottom-right', duration: 5000, isClosable: true, title: `Uploaded`, description: `${files.length} file(s)`, status: 'success', }); setToastId(''); setProgress({}); setSteps({}); setFiles([]); } }, [submitCount]); const onSubmit = async (fls: File[]) => { if (!fls.length) { return; } setSubmitCount((count) => count + 1); setFiles((prev) => [...prev, ...fls]); if (!toastId) { setToastId( toast({ position: 'bottom-right', duration: null, isClosable: true, render: () => ( <UploadFeedback files={files} steps={steps} progress={progress} /> ), }), ); } await Promise.all( fls.map(async (file) => { setSteps((prev) => ({ ...prev, [file.name]: 'ENCRYPTING' })); const data = await encryptFile(file); setSteps((prev) => ({ ...prev, [file.name]: 'UPLOADING' })); const gen = await uploadFile({ name: file.name, data }); for await (const value of gen) { setProgress((prev) => ({ ...prev, [file.name]: value })); } }), ); await revalidateListFiles(); setSubmitCount((count) => count - 1); }; return <>{children}</>; }); export default Upload;
src/components/Upload.tsx
9OP-Encryptly-ef8661c
[ { "filename": "src/components/UploadToast.tsx", "retrieved_chunk": " VStack,\n} from '@chakra-ui/react';\nimport { CheckIcon, ShieldLockIcon } from './Icons';\ninterface props {\n files: File[];\n steps: { [name: string]: 'ENCRYPTING' | 'UPLOADING' };\n progress: { [name: string]: number };\n}\nconst UploadFeedback: FC<props> = (props: props) => {\n const { files, progress, steps } = props;", "score": 42.054338525004695 }, { "filename": "src/pages/home.tsx", "retrieved_chunk": "const Home: FC = () => {\n const [search, setSearch] = useState('');\n const [filesCount, setFilesCount] = useState(0);\n const [storageCount, setStorageCount] = useState(0);\n const ref = useRef<UploadHandle>(null);\n const handleUpload = async (files: File[]) => {\n await ref?.current?.onSubmit(files);\n };\n return (\n <Upload ref={ref}>", "score": 33.901609143739364 }, { "filename": "src/components/DropZone.tsx", "retrieved_chunk": " const toast = useToast();\n const handleDrop = async (event: React.DragEvent<HTMLInputElement>) => {\n event.preventDefault();\n setDragOver(false);\n const items = [...event.dataTransfer.items];\n const files = await handleDataItem(items);\n try {\n if ([...files].length) {\n await onUpload([...files]);\n }", "score": 21.806596148052556 }, { "filename": "src/components/DeleteButton.tsx", "retrieved_chunk": " const { onOpen, onClose, isOpen } = useDisclosure();\n const { fileId } = props;\n const { data: files } = useListFiles();\n const deleteFile = useDeleteFile();\n const toast = useToast();\n const file = useMemo(() => files?.find(({ id }) => id === fileId), [files]);\n const onDelete = async () => {\n await deleteFile(fileId);\n toast({\n status: 'info',", "score": 19.69815133284878 }, { "filename": "src/lib/files.ts", "retrieved_chunk": " if (ref.current) {\n ref.current.href = objectUrl;\n ref.current.download = name;\n ref.current.click();\n }\n};\nexport const handleDataItem = async (items: DataTransferItem[]) => {\n const files: File[] = [];\n for (let i = 0; i < items.length; i++) {\n const item = items[0].webkitGetAsEntry();", "score": 18.394253979797867 } ]
typescript
render: () => <UploadFeedback files={files} steps={steps} progress={progress} />, });
import { FC, useCallback, useRef, useState } from 'react'; import { useDecryptFile, useDownloadFile } from '@app/hooks'; import { saveFile } from '@app/lib/files'; import { IconButton, Spinner, useToast } from '@chakra-ui/react'; import { DownloadIcon, ShieldLockIcon } from './Icons'; interface props { fileId: string; } const DownloadButton: FC<props> = (props: props) => { const { fileId } = props; const toast = useToast(); const [downloading, setDownloading] = useState(false); const [decrypting, setDecrypting] = useState(false); const downloadFile = useDownloadFile(); const decryptFile = useDecryptFile(); const ref = useRef<HTMLAnchorElement>(null); const handleClick = useCallback(async () => { setDownloading(true); const { data, metadata } = await downloadFile(fileId); setDownloading(false); setDecrypting(true); try { const fileData = await decryptFile(data); saveFile([fileData], metadata.name, metadata.mimeType, ref); } catch (err) { toast.closeAll(); toast({ position: 'bottom-right', duration: 5000, isClosable: true, title: 'Error decrypting file', description: (err as Error).message, status: 'error', }); } finally { setDecrypting(false); } }, [decryptFile, downloadFile, fileId]); return ( <> <IconButton id={`download-${fileId}`} visibility={downloading || decrypting ? 'visible' : 'hidden'} variant="none" color="purple.600" aria-label="download" icon={ downloading ? ( <Spinner /> ) : decrypting ? ( <
ShieldLockIcon boxSize="1.5rem" /> ) : ( <DownloadIcon boxSize="1.5rem" /> ) }
onClick={handleClick} isDisabled={downloading || decrypting} /> <a hidden ref={ref} /> </> ); }; export default DownloadButton;
src/components/DownloadButton.tsx
9OP-Encryptly-ef8661c
[ { "filename": "src/components/UserCard.tsx", "retrieved_chunk": " size=\"md\"\n leftIcon={<SecretIcon boxSize=\"1.5rem\" />}\n variant=\"link\"\n onClick={onOpen}\n >\n key\n </Button>\n <InfoModal onDownload={onDownload} onClose={onClose} isOpen={isOpen} />\n <a hidden ref={ref} />\n <LogoutButton />", "score": 18.934902949193557 }, { "filename": "src/components/Pagination.tsx", "retrieved_chunk": " icon={<ChevronRightIcon boxSize=\"1.3rem\" />}\n onClick={onNext}\n size=\"xs\"\n variant=\"ghost\"\n disabled={selected === range}\n />\n </HStack>\n </Flex>\n );\n};", "score": 18.430473271301995 }, { "filename": "src/theme.ts", "retrieved_chunk": " },\n sizes: {},\n variants: {},\n defaultProps: {},\n};\nconst CardStyle: ComponentStyleConfig = {\n baseStyle: {\n padding: '1.5rem',\n borderWidth: '3px',\n borderRadius: '10px',", "score": 15.124069729769204 }, { "filename": "src/components/Pagination.tsx", "retrieved_chunk": " alignItems=\"center\"\n marginTop=\"1rem\"\n color=\"gray.700\"\n >\n <HStack padding=\"0\" margin=\"0\" spacing=\"0.1rem\">\n <IconButton\n aria-label=\"previous\"\n icon={<ChevronLeftIcon boxSize=\"1.3rem\" />}\n onClick={onPrevious}\n size=\"xs\"", "score": 14.78964131617837 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " <ArrowUpIcon boxSize=\"1rem\" />\n ) : (\n <ArrowDownIcon boxSize=\"1rem\" />\n )\n }\n />\n </HStack>\n </Th>\n );\n const handleSorting = useCallback(", "score": 11.439264666688125 } ]
typescript
ShieldLockIcon boxSize="1.5rem" /> ) : ( <DownloadIcon boxSize="1.5rem" /> ) }
import { FC, useMemo, useState } from 'react'; import { useDeleteFile, useListFiles } from '@app/hooks'; import { FileMetadata } from '@app/models'; import { Button, IconButton, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, ModalOverlay, Spinner, Tag, useDisclosure, useToast, } from '@chakra-ui/react'; import { TrashIcon } from './Icons'; interface PropsModal { onDelete: () => Promise<void>; file: FileMetadata; onClose: () => void; isOpen: boolean; } const DeleteModal: FC<PropsModal> = (props: PropsModal) => { const { file, onDelete, onClose, isOpen } = props; const [deleting, setDeleting] = useState(false); const handleDelete = async () => { setDeleting(true); try { await onDelete(); onClose(); } finally { setDeleting(false); } }; return ( <Modal closeOnOverlayClick={!deleting} isOpen={isOpen} onClose={onClose}> <ModalOverlay /> <ModalContent backgroundColor="red.500"> <ModalHeader>Delete</ModalHeader> <ModalBody> Are your sure to delete <Tag colorScheme="red">{file.name}</Tag> ? </ModalBody> <ModalFooter> <Button autoFocus mr={3} onClick={onClose} color="black" isDisabled={deleting}> Cancel </Button> <Button onClick={handleDelete} isDisabled={deleting} colorScheme="red"> {deleting ? <Spinner /> : 'Delete'} </Button> </ModalFooter> </ModalContent> </Modal> ); }; interface PropsButton { fileId: string; } const DeleteButton: FC<PropsButton> = (props: PropsButton) => { const { onOpen, onClose, isOpen } = useDisclosure(); const { fileId } = props; const { data: files } = useListFiles(); const deleteFile = useDeleteFile(); const toast = useToast(); const file = useMemo(() => files?.find(({ id }) => id === fileId), [files]); const onDelete = async () => { await deleteFile(fileId); toast({ status: 'info', duration: 3000, position: 'bottom-right', isClosable: true, title: 'File deleted', description: file?.name, }); }; return ( <> <IconButton id={`delete-${fileId}`} visibility="hidden" variant="none" color="purple.400" aria-label="delete"
icon={<TrashIcon />}
onClick={onOpen} /> {file && ( <DeleteModal file={file} onDelete={onDelete} onClose={onClose} isOpen={isOpen} /> )} </> ); }; export default DeleteButton;
src/components/DeleteButton.tsx
9OP-Encryptly-ef8661c
[ { "filename": "src/components/DownloadButton.tsx", "retrieved_chunk": " <IconButton\n id={`download-${fileId}`}\n visibility={downloading || decrypting ? 'visible' : 'hidden'}\n variant=\"none\"\n color=\"purple.600\"\n aria-label=\"download\"\n icon={\n downloading ? (\n <Spinner />\n ) : decrypting ? (", "score": 46.98145600446777 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " {sortedFiles.map((file) => (\n <Tr\n key={file.id}\n sx={{\n [`&:hover #download-${file.id}`]: {\n visibility: 'visible!important',\n },\n [`&:hover #delete-${file.id}`]: {\n visibility: 'visible!important',\n },", "score": 24.30982097906319 }, { "filename": "src/components/Pagination.tsx", "retrieved_chunk": " onClick={() => setSelected(range)}\n size=\"xs\"\n variant=\"ghost\"\n color={selected === range ? 'red.600' : ''}\n >\n {range}\n </Button>\n )}\n <IconButton\n aria-label=\"next\"", "score": 19.505515756583495 }, { "filename": "src/components/Pagination.tsx", "retrieved_chunk": " alignItems=\"center\"\n marginTop=\"1rem\"\n color=\"gray.700\"\n >\n <HStack padding=\"0\" margin=\"0\" spacing=\"0.1rem\">\n <IconButton\n aria-label=\"previous\"\n icon={<ChevronLeftIcon boxSize=\"1.3rem\" />}\n onClick={onPrevious}\n size=\"xs\"", "score": 17.53908107488008 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " setOrder: Dispatch<SetStateAction<SortOrder>>;\n }) => (\n <Th padding={0} textTransform=\"capitalize\">\n <HStack spacing={1} marginBottom=\"0.6rem\">\n <Text fontSize=\"md\" color=\"black\">\n {title}\n </Text>\n <IconButton\n color=\"black\"\n variant=\"none\"", "score": 13.588402316602009 } ]
typescript
icon={<TrashIcon />}
import { FC, useContext, useRef } from 'react'; import { AppContext } from '@app/context'; import { useUserInfo } from '@app/hooks'; import { saveFile } from '@app/lib/files'; import { Button, HStack, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, ModalOverlay, Tag, Text, useDisclosure, VStack, } from '@chakra-ui/react'; import Card from './Card'; import { SecretIcon } from './Icons'; import LogoutButton from './LogoutButton'; interface PropsModal { onDownload: () => void; onClose: () => void; isOpen: boolean; } const InfoModal: FC<PropsModal> = (props: PropsModal) => { const { onDownload, onClose, isOpen } = props; const handleDownload = () => { onDownload(); onClose(); }; return ( <Modal isOpen={isOpen} onClose={onClose}> <ModalOverlay /> <ModalContent backgroundColor="blue.500"> <ModalHeader>Info</ModalHeader> <ModalBody> Backup your encryption key securely. Anyone with access to your key is able to decrypt your files. <br /> <br /> <Tag colorScheme="blue">Do not store your key on Google Drive !</Tag> </ModalBody> <ModalFooter> <Button onClick={handleDownload} colorScheme="blue"> Download my key </Button> </ModalFooter> </ModalContent> </Modal> ); }; const UserCard: FC = () => { const { onOpen, onClose, isOpen } = useDisclosure(); const { data: user } = useUserInfo(); const { encryptionKey } = useContext(AppContext); const ref = useRef<HTMLAnchorElement>(null); const onDownload = () => { saveFile([encryptionKey.value], `${user?.email}_key.txt`, 'text/plain', ref); }; return ( <Card backgroundColor="teal.200"> <VStack spacing="1.5rem" align="flex-end" justifyContent="flex-end" height="100%"> <Text fontSize="md" fontWeight="semibold"> [{user?.email}] </Text> <HStack justifyContent="space-between" w="100%"> <Button colorScheme="black" size="md"
leftIcon={<SecretIcon boxSize="1.5rem" />}
variant="link" onClick={onOpen} > key </Button> <InfoModal onDownload={onDownload} onClose={onClose} isOpen={isOpen} /> <a hidden ref={ref} /> <LogoutButton /> </HStack> </VStack> </Card> ); }; export default UserCard;
src/components/UserCard.tsx
9OP-Encryptly-ef8661c
[ { "filename": "src/components/SearchBar.tsx", "retrieved_chunk": " return (\n <Card\n display=\"flex\"\n flex={1}\n width=\"100%\"\n height=\"100%\"\n flexDirection=\"column\"\n backgroundColor=\"yellow.200\"\n justifyContent=\"space-between\"\n >", "score": 54.31437885502346 }, { "filename": "src/components/PassphraseInput.tsx", "retrieved_chunk": " if (data) {\n await setEncryptionKey(passphrase, data.encryptionKey);\n }\n };\n return (\n <VStack spacing=\"1rem\">\n <FormControl>\n <FormLabel fontSize=\"md\" fontWeight=\"semibold\" margin={0}>\n <HStack justifyContent=\"space-between\">\n <Text>Passphrase</Text>", "score": 45.57228536862077 }, { "filename": "src/components/StorageQuota.tsx", "retrieved_chunk": " <CloudIcon boxSize=\"1.2rem\" />\n <Text fontWeight=\"semibold\">Storage quota</Text>\n </HStack>\n <Flex justifyContent=\"center\">\n {data ? (\n <Flex flexDirection=\"column\" width=\"100%\" alignItems=\"center\">\n <Progress\n backgroundColor=\"white\"\n colorScheme=\"blue\"\n width=\"100%\"", "score": 41.52590604002053 }, { "filename": "src/pages/login.tsx", "retrieved_chunk": " </VStack>\n <VStack w=\"100%\" alignItems=\"flex-start\">\n <Link href=\"https://www.linkedin.com/in/martin-g-105b74150/\">\n <Button leftIcon={<LinkedinIcon />} variant=\"link\">\n Martin\n </Button>\n </Link>\n <HStack w=\"100%\" justifyContent=\"space-between\">\n <Link href=\"https://github.com/9OP/Encryptly/\">\n <Button leftIcon={<GithubIcon />} variant=\"link\">", "score": 38.223638582982936 }, { "filename": "src/components/SearchBar.tsx", "retrieved_chunk": " <HStack w=\"100%\" marginBottom=\"1rem\">\n <Tag size=\"md\" colorScheme=\"purple\" fontWeight=\"semibold\">\n Files: {filesCount}\n </Tag>\n <Tag size=\"md\" colorScheme=\"blue\" fontWeight=\"semibold\">\n Content: {formatBytes(storageCount)}\n </Tag>\n </HStack>\n <InputGroup width=\"18rem\" size=\"sm\" w=\"100%\">\n <InputLeftElement pointerEvents=\"none\" paddingLeft=\".4rem\">", "score": 34.43961280913601 } ]
typescript
leftIcon={<SecretIcon boxSize="1.5rem" />}
import { Dispatch, FC, SetStateAction, useCallback, useEffect, useMemo, useState, } from 'react'; import DownloadButton from '@app/components/DownloadButton'; import { ArrowDownIcon, ArrowUpIcon } from '@app/components/Icons'; import Pagination from '@app/components/Pagination'; import { useListFiles } from '@app/hooks'; import formatBytes from '@app/lib/formatBytes'; import { FileMetadata } from '@app/models'; import { Box, HStack, IconButton, Spinner, Table, TableContainer, Tbody, Td, Text, Th, Thead, Tooltip, Tr, } from '@chakra-ui/react'; import DeleteButton from './DeleteButton'; interface props { files: FileMetadata[]; isFetching: boolean; } type SortOrder = 'ASC' | 'DESC'; const FileTable: FC<props> = (props: props) => { const { files, isFetching } = props; const [sortedFiles, setSortedFiles] = useState<FileMetadata[]>(files); const [nameOrder, setNameOrder] = useState<SortOrder>('DESC'); const [dateOrder, setDateOrder] = useState<SortOrder>('DESC'); const [sizeOrder, setSizeOrder] = useState<SortOrder>('DESC'); const [sort, setSort] = useState<'name' | 'date' | 'size'>('name'); const ColHeader = ({ title, order, setOrder, }: { title: 'name' | 'date' | 'size'; order: SortOrder; setOrder: Dispatch<SetStateAction<SortOrder>>; }) => ( <Th padding={0} textTransform="capitalize"> <HStack spacing={1} marginBottom="0.6rem"> <Text fontSize="md" color="black"> {title} </Text> <IconButton color="black" variant="none" backgroundColor="transparent" size="xs" aria-label="sort" onClick={() => { setOrder((prev) => (prev === 'ASC' ? 'DESC' : 'ASC')); handleSorting(title); setSort(title); }} icon={ order === 'DESC' ? ( <ArrowUpIcon boxSize="1rem" /> ) : ( <ArrowDownIcon boxSize="1rem" /> ) } /> </HStack> </Th> ); const handleSorting = useCallback( (sortField: 'name' | 'date' | 'size') => { const sorted = [...files].sort((a, b) => { switch (sortField) { case 'name': return nameOrder === 'DESC' ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name); case 'date': return dateOrder === 'DESC' ? a.createdTime.getTime() - b.createdTime.getTime() : b.createdTime.getTime() - a.createdTime.getTime(); case 'size': return sizeOrder === 'DESC' ? a.size - b.size : b.size - a.size; default: return 0; } }); setSortedFiles(sorted); }, [dateOrder, files, nameOrder, sizeOrder], ); useEffect(() => { handleSorting(sort); }, [files, handleSorting, sort]); return ( <TableContainer overflow="auto"> <Table variant="simple" size="sm"> <Thead borderColor="black" borderBottomWidth="2px"> <Tr padding={0}> <ColHeader title="name" order={nameOrder} setOrder={setNameOrder} /> <ColHeader title="date" order={dateOrder} setOrder={setDateOrder} /> <ColHeader title="size" order={sizeOrder} setOrder={setSizeOrder} /> <Td padding={0}> <HStack justifyContent="flex-end" alignItems="center" marginBottom="0.6rem"> {isFetching ? <Spinner size="md" /> : <></>} </HStack> </Td> </Tr> </Thead> <Tbody> {sortedFiles.map((file) => ( <Tr key={file.id} sx={{ [`&:hover #download-${file.id}`]: { visibility: 'visible!important', }, [`&:hover #delete-${file.id}`]: { visibility: 'visible!important', }, }} cursor="pointer" > <Td paddingX={0} paddingY="0.8rem" border="0"> <HStack draggable={true} onDragStart={(e) => { e.dataTransfer.setData('text/plain', file.id); }} > <Tooltip label={file.name} hasArrow> <Text maxW="15rem" color="black" fontWeight="semibold" whiteSpace="nowrap" overflow="hidden" textOverflow="ellipsis" className="txt" > {file.name} </Text> </Tooltip> </HStack> </Td> <Td fontSize="sm" fontWeight="medium" paddingX={0} border="0"> {file?.createdTime?.toLocaleString()} </Td> <Td fontSize="sm" fontWeight="medium" paddingX={0} border="0"> {formatBytes(file?.size || 0)} </Td> <Td border="0"> <HStack justifyContent="flex-end"> <DownloadButton fileId={file.id} /> <
DeleteButton fileId={file.id} /> </HStack> </Td> </Tr> ))}
</Tbody> </Table> </TableContainer> ); }; interface PropsTable { search: string; setFilesCount: React.Dispatch<React.SetStateAction<number>>; setStorageCount: React.Dispatch<React.SetStateAction<number>>; } const PaginatedFileTable: FC<PropsTable> = (props: PropsTable): JSX.Element => { const { search, setFilesCount, setStorageCount } = props; const [selected, setSelected] = useState(1); const { data, isLoading, isValidating } = useListFiles(); const pagination = 8; const isFetching = useMemo(() => isLoading || isValidating, [isLoading, isValidating]); const filteredFiles = useMemo(() => { let filtered = data || []; if (search) { filtered = filtered.filter((f) => f.name.toLowerCase().includes(search.toLowerCase())) || []; } return filtered; }, [data, search]); const pages = useMemo(() => { return Math.ceil((filteredFiles?.length || 0) / pagination); }, [filteredFiles]); const rangeFiles = useMemo(() => { const startIndex = (selected - 1) * pagination + 1; const endIndex = selected * pagination + 1; return filteredFiles?.slice(startIndex - 1, endIndex - 1); }, [filteredFiles, selected, pagination]); useEffect(() => { setFilesCount(filteredFiles?.length || 0); setStorageCount(filteredFiles?.reduce((acc, { size }) => acc + size, 0)); }, [filteredFiles]); useEffect(() => { if (selected > pages && pages != 0) { setSelected(pages); } }, [pages]); return ( <Box width="100%"> <FileTable files={rangeFiles} isFetching={isFetching} /> {pages > 1 && ( <Pagination range={pages} selected={selected} setSelected={setSelected} /> )} </Box> ); }; export default PaginatedFileTable;
src/components/FileTable.tsx
9OP-Encryptly-ef8661c
[ { "filename": "src/components/DeleteButton.tsx", "retrieved_chunk": " const { onOpen, onClose, isOpen } = useDisclosure();\n const { fileId } = props;\n const { data: files } = useListFiles();\n const deleteFile = useDeleteFile();\n const toast = useToast();\n const file = useMemo(() => files?.find(({ id }) => id === fileId), [files]);\n const onDelete = async () => {\n await deleteFile(fileId);\n toast({\n status: 'info',", "score": 21.089960025197698 }, { "filename": "src/components/DeleteButton.tsx", "retrieved_chunk": " id={`delete-${fileId}`}\n visibility=\"hidden\"\n variant=\"none\"\n color=\"purple.400\"\n aria-label=\"delete\"\n icon={<TrashIcon />}\n onClick={onOpen}\n />\n {file && (\n <DeleteModal file={file} onDelete={onDelete} onClose={onClose} isOpen={isOpen} />", "score": 19.36128904154461 }, { "filename": "src/components/UserCard.tsx", "retrieved_chunk": " };\n return (\n <Card backgroundColor=\"teal.200\">\n <VStack spacing=\"1.5rem\" align=\"flex-end\" justifyContent=\"flex-end\" height=\"100%\">\n <Text fontSize=\"md\" fontWeight=\"semibold\">\n [{user?.email}]\n </Text>\n <HStack justifyContent=\"space-between\" w=\"100%\">\n <Button\n colorScheme=\"black\"", "score": 17.90287216271485 }, { "filename": "src/components/UploadToast.tsx", "retrieved_chunk": " return (\n <Alert status=\"info\" width=\"100%\">\n <AlertIcon />\n <VStack spacing={0} alignItems=\"flex-start\" justifyContent=\"center\">\n <AlertTitle>Uploading ...</AlertTitle>\n <AlertDescription>\n {files.map((f, i) => {\n const value = progress[f.name] || 0;\n return (\n <HStack key={i} alignItems=\"center\" justifyContent=\"flex-start\">", "score": 14.997354320371947 }, { "filename": "src/hooks/http.ts", "retrieved_chunk": " return await loadConfigFile(token, configFile.id);\n};\n// only for debug\nexport const deleteAppFolder = async (token: string): Promise<void> => {\n const files = await getAppFiles(token);\n const promises = files.map(({ id: fileId }) => {\n return fetch(`https://www.googleapis.com/drive/v3/files/${fileId}`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${token}` },\n });", "score": 14.799914466454805 } ]
typescript
DeleteButton fileId={file.id} /> </HStack> </Td> </Tr> ))}
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { CompilerBuffer } from './buffer.js' import { TupleNodeCompiler } from './nodes/tuple.js' import { ArrayNodeCompiler } from './nodes/array.js' import { UnionNodeCompiler } from './nodes/union.js' import { RecordNodeCompiler } from './nodes/record.js' import { ObjectNodeCompiler } from './nodes/object.js' import { createRootField } from './fields/root_field.js' import { LiteralNodeCompiler } from './nodes/literal.js' import { createArrayField } from './fields/array_field.js' import { createTupleField } from './fields/tuple_field.js' import { reportErrors } from '../scripts/report_errors.js' import { createObjectField } from './fields/object_field.js' import { createRecordField } from './fields/record_field.js' import { defineInlineFunctions } from '../scripts/define_inline_functions.js' import { defineInlineErrorMessages } from '../scripts/define_error_messages.js' import type { Refs, RootNode, CompilerField, CompilerNodes, CompilerParent, CompilerOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' /** * Representation of an async function */ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor /** * Compiler is used to compile an array of schema nodes into a re-usable * JavaScript. */ export class Compiler { /** * Variables counter is used to generate unique variable * names with a counter suffix. */ variablesCounter: number = 0 /** * An array of nodes to process */ #rootNode: RootNode /** * Options to configure the compiler behavior */ #options: CompilerOptions /** * Buffer for collection the JS output string */ #buffer: CompilerBuffer = new CompilerBuffer() constructor(rootNode: RootNode, options?: CompilerOptions) { this.#rootNode = rootNode this.#options = options || { convertEmptyStringsToNull: false } } /** * Initiates the JS output */ #initiateJSOutput() { this.#buffer.writeStatement( defineInlineErrorMessages({ required: 'value is required', object: 'value is not a valid object', array: 'value is not a valid array', ...this.#options.messages, }) )
this.#buffer.writeStatement(defineInlineFunctions(this.#options)) this.#buffer.writeStatement('let out;') }
/** * Finished the JS output */ #finishJSOutput() { this.#buffer.writeStatement(reportErrors()) this.#buffer.writeStatement('return out;') } /** * Compiles all the nodes */ #compileNodes() { this.compileNode(this.#rootNode.schema, this.#buffer, { type: 'root', variableName: 'root', outputExpression: 'out', fieldPathExpression: 'out', wildCardPath: '', }) } /** * Returns compiled output as a function */ #toAsyncFunction<T extends Record<string, any>>(): ( data: any, meta: Record<string, any>, refs: Refs, messagesProvider: MessagesProviderContact, errorReporter: ErrorReporterContract ) => Promise<T> { return new AsyncFunction( 'root', 'meta', 'refs', 'messagesProvider', 'errorReporter', this.#buffer.toString() ) } /** * Converts a node to a field. Optionally accepts a parent node to create * a field for a specific parent type. */ createFieldFor(node: CompilerNodes, parent: CompilerParent) { switch (parent.type) { case 'array': return createArrayField(parent) case 'root': return createRootField(parent) case 'object': return createObjectField(node, this.variablesCounter, parent) case 'tuple': return createTupleField(node, parent) case 'record': return createRecordField(parent) } } /** * Compiles a given compiler node */ compileNode( node: CompilerNodes, buffer: CompilerBuffer, parent: CompilerParent, parentField?: CompilerField ) { switch (node.type) { case 'literal': return new LiteralNodeCompiler(node, buffer, this, parent, parentField).compile() case 'array': return new ArrayNodeCompiler(node, buffer, this, parent, parentField).compile() case 'record': return new RecordNodeCompiler(node, buffer, this, parent, parentField).compile() case 'object': return new ObjectNodeCompiler(node, buffer, this, parent, parentField).compile() case 'tuple': return new TupleNodeCompiler(node, buffer, this, parent, parentField).compile() case 'union': return new UnionNodeCompiler(node, buffer, this, parent, parentField).compile() } } /** * Compile schema nodes to an async function */ compile() { this.#initiateJSOutput() this.#compileNodes() this.#finishJSOutput() const outputFunction = this.#toAsyncFunction() this.variablesCounter = 0 this.#buffer.flush() return outputFunction } }
src/compiler/main.ts
vinejs-compiler-8909bb5
[ { "filename": "src/types.ts", "retrieved_chunk": " * normalization\n */\n convertEmptyStringsToNull: boolean\n /**\n * Provide messages to use for required, object and\n * array validations.\n */\n messages?: Partial<{\n required: string\n object: string", "score": 28.61281786459999 }, { "filename": "src/scripts/define_error_messages.ts", "retrieved_chunk": " * Returns JS fragment for inline error messages for errors raised\n * by the compiler.\n */\nexport function defineInlineErrorMessages(\n messages: Required<Exclude<CompilerOptions['messages'], undefined>>\n) {\n return `const REQUIRED = '${messages.required}';\nconst NOT_AN_OBJECT = '${messages.object}';\nconst NOT_AN_ARRAY = '${messages.array}';`\n}", "score": 25.51023856014694 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isObjectValidBlock}`,\n })\n /**\n * Step 3: Define `if value is an object` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(", "score": 21.95077511196984 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " })\n /**\n * Step 3: Define `if value is an array` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(\n `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,", "score": 21.475748812674873 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " /**\n * Step 3: Define `if value is an object` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(\n `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({\n variableName: this.field.variableName,\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n conditional: 'else if',", "score": 20.47498921277934 } ]
typescript
this.#buffer.writeStatement(defineInlineFunctions(this.#options)) this.#buffer.writeStatement('let out;') }
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValueOutput } from '../../scripts/field/value_output.js' import type { LiteralNode, CompilerParent, CompilerField } from '../../types.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles a literal schema node to JS string output. */ export class LiteralNodeCompiler extends BaseNode { #node: LiteralNode #buffer: CompilerBuffer constructor( node: LiteralNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define block to validate the existence of field */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Step 3: Define code to run validations on field */ this.#buffer.writeStatement( defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: false, }) ) /** * Step 4: Define block to save the output value or the null value */ this.#buffer.writeStatement( `${defineFieldValueOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, transformFnRefId: this.#node.transformFnId,
})}${this.#buffer.newLine}${defineFieldNullOutput({
variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, transformFnRefId: this.#node.transformFnId, conditional: 'else if', })}` ) } }
src/compiler/nodes/literal.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " })\n /**\n * Step 3: Define `if value is an array` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(\n `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,", "score": 33.710300047044186 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " /**\n * Step 3: Define `if value is an object` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(\n `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({\n variableName: this.field.variableName,\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n conditional: 'else if',", "score": 32.50816736637013 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isObjectValidBlock}`,\n })\n /**\n * Step 3: Define `if value is an object` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(", "score": 24.360212638257835 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " variableName: this.field.variableName,\n validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isArrayValidBlock}`,\n })\n /**\n * Step 3: Define `if value is an array` block and `else if value is null`\n * block.\n */", "score": 23.75325678529178 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " this.#buffer.writeStatement(\n `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n conditional: 'else if',\n })}`\n )\n }\n}", "score": 23.37280288857864 } ]
typescript
})}${this.#buffer.newLine}${defineFieldNullOutput({
import { FC, useCallback, useRef, useState } from 'react'; import { useDecryptFile, useDownloadFile } from '@app/hooks'; import { saveFile } from '@app/lib/files'; import { IconButton, Spinner, useToast } from '@chakra-ui/react'; import { DownloadIcon, ShieldLockIcon } from './Icons'; interface props { fileId: string; } const DownloadButton: FC<props> = (props: props) => { const { fileId } = props; const toast = useToast(); const [downloading, setDownloading] = useState(false); const [decrypting, setDecrypting] = useState(false); const downloadFile = useDownloadFile(); const decryptFile = useDecryptFile(); const ref = useRef<HTMLAnchorElement>(null); const handleClick = useCallback(async () => { setDownloading(true); const { data, metadata } = await downloadFile(fileId); setDownloading(false); setDecrypting(true); try { const fileData = await decryptFile(data); saveFile([fileData], metadata.name, metadata.mimeType, ref); } catch (err) { toast.closeAll(); toast({ position: 'bottom-right', duration: 5000, isClosable: true, title: 'Error decrypting file', description: (err as Error).message, status: 'error', }); } finally { setDecrypting(false); } }, [decryptFile, downloadFile, fileId]); return ( <> <IconButton id={`download-${fileId}`} visibility={downloading || decrypting ? 'visible' : 'hidden'} variant="none" color="purple.600" aria-label="download" icon={ downloading ? ( <Spinner /> ) : decrypting ? ( <ShieldLockIcon boxSize="1.5rem" /> ) : (
<DownloadIcon boxSize="1.5rem" /> ) }
onClick={handleClick} isDisabled={downloading || decrypting} /> <a hidden ref={ref} /> </> ); }; export default DownloadButton;
src/components/DownloadButton.tsx
9OP-Encryptly-ef8661c
[ { "filename": "src/components/Pagination.tsx", "retrieved_chunk": " alignItems=\"center\"\n marginTop=\"1rem\"\n color=\"gray.700\"\n >\n <HStack padding=\"0\" margin=\"0\" spacing=\"0.1rem\">\n <IconButton\n aria-label=\"previous\"\n icon={<ChevronLeftIcon boxSize=\"1.3rem\" />}\n onClick={onPrevious}\n size=\"xs\"", "score": 22.287235546567235 }, { "filename": "src/components/UserCard.tsx", "retrieved_chunk": " size=\"md\"\n leftIcon={<SecretIcon boxSize=\"1.5rem\" />}\n variant=\"link\"\n onClick={onOpen}\n >\n key\n </Button>\n <InfoModal onDownload={onDownload} onClose={onClose} isOpen={isOpen} />\n <a hidden ref={ref} />\n <LogoutButton />", "score": 18.934902949193557 }, { "filename": "src/components/Pagination.tsx", "retrieved_chunk": " icon={<ChevronRightIcon boxSize=\"1.3rem\" />}\n onClick={onNext}\n size=\"xs\"\n variant=\"ghost\"\n disabled={selected === range}\n />\n </HStack>\n </Flex>\n );\n};", "score": 18.430473271301995 }, { "filename": "src/components/LogoutButton.tsx", "retrieved_chunk": "import { useLogout } from '@app/hooks';\nimport { Button } from '@chakra-ui/react';\nimport { LogoutIcon } from './Icons';\nconst LogoutButton = () => {\n const logout = useLogout();\n return (\n <Button\n size=\"md\"\n aria-label=\"logout\"\n leftIcon={<LogoutIcon boxSize=\"1.2rem\" />}", "score": 17.314647987736407 }, { "filename": "src/theme.ts", "retrieved_chunk": " },\n sizes: {},\n variants: {},\n defaultProps: {},\n};\nconst CardStyle: ComponentStyleConfig = {\n baseStyle: {\n padding: '1.5rem',\n borderWidth: '3px',\n borderRadius: '10px',", "score": 15.124069729769204 } ]
typescript
<DownloadIcon boxSize="1.5rem" /> ) }
import { AppData, FileMetadata, StorageQuota, UserInfo } from '../models'; const JSONtoUserInfo = (json: any): UserInfo => { const userInfo: UserInfo = { email: json['emailAddress'], }; return userInfo; }; const JSONtoFileMetadata = (json: any): FileMetadata => { const fileMetadata: FileMetadata = { id: json['id'], name: json['name'], size: parseInt(json['size'] || 0), createdTime: new Date(json['createdTime']), mimeType: json['mimeType'], }; return fileMetadata; }; const JSONtoFilesMetadata = (json: any): FileMetadata[] => { return json .map((file: any): FileMetadata | undefined => { if (file['trashed'] === true) { return; } return JSONtoFileMetadata(file); }) .filter((e: any) => e != null) .sort((a: FileMetadata, b: FileMetadata) => a.createdTime && b.createdTime ? a.createdTime > b.createdTime : 0, ); }; const JSONtoAppData = (json: any)
: AppData => {
const appData: AppData = { encryptionKey: { enc: json['encryptionKey']['enc'], salt: json['encryptionKey']['salt'], }, }; return appData; }; const JSONtoStorageQuota = (json: any): StorageQuota => { const storageQuota: StorageQuota = { limit: parseInt(json['limit']), usage: parseInt(json['usage']), usageInDrive: parseInt(json['usageInDrive']), }; return storageQuota; }; export const getUserInfo = async (token: string): Promise<UserInfo> => { const res = await fetch('https://www.googleapis.com/drive/v3/about?fields=user', { method: 'GET', headers: { Authorization: `Bearer ${token}` }, }); const json = await res.json(); if (!res.ok) { const error = new Error('Failed fetching user.'); error.info = json; error.status = res.status; throw error; } return JSONtoUserInfo(json['user']); }; export const revokeToken = async (token: string): Promise<void> => { fetch(`https://oauth2.googleapis.com/revoke?token=${token}type=accesstoken`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, }); }; export const revokeApp = async (token: string): Promise<void> => { fetch(`https://oauth2.googleapis.com/revoke`, { method: 'POST', headers: { Authorization: `Bearer ${token}` }, }); }; const CONFIG_FILE_NAME = 'config.json'; const APP_DATA_FOLDER = 'appDataFolder'; const createConfigFile = async (token: string): Promise<string> => { const res = await fetch('https://www.googleapis.com/drive/v3/files?fields=id', { method: 'POST', body: JSON.stringify({ mimeType: 'application/json', parents: [APP_DATA_FOLDER], name: CONFIG_FILE_NAME, }), headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, }); const json = await res.json(); return json['id']; }; const uploadConfigFile = async ( token: string, configFileId: string, data: AppData, ): Promise<void> => { const bytes = new TextEncoder().encode(JSON.stringify(data)); const file = new File([bytes], 'config.json', { type: 'application/json' }); await fetch( `https://www.googleapis.com/upload/drive/v3/files/${configFileId}?uploadType=media`, { method: 'PATCH', body: file, headers: { Authorization: `Bearer ${token}` }, }, ); }; export const saveAppData = async (token: string, data: AppData): Promise<void> => { const configFileId = await createConfigFile(token); await uploadConfigFile(token, configFileId, data); }; const getAppFiles = async (token: string) => { const res = await fetch( 'https://www.googleapis.com/drive/v3/files?spaces=appDataFolder&fields=files(*)', { method: 'GET', headers: { Authorization: `Bearer ${token}` }, }, ); const json = await res.json(); return JSONtoFilesMetadata(json['files']); }; const loadConfigFile = async (token: string, configFileId: string): Promise<AppData> => { const res = await fetch( `https://www.googleapis.com/drive/v3/files/${configFileId}?spaces=appDataFolder&alt=media`, { method: 'GET', headers: { Authorization: `Bearer ${token}` }, }, ); const json = await res.json(); return JSONtoAppData(json); }; export const loadAppData = async (token: string): Promise<AppData | undefined> => { const files = await getAppFiles(token); const configFile = files.find((f) => f.name == CONFIG_FILE_NAME); if (!configFile) { // throw new Error(`Config file <${CONFIG_FILE_NAME}> not found`); return; } return await loadConfigFile(token, configFile.id); }; // only for debug export const deleteAppFolder = async (token: string): Promise<void> => { const files = await getAppFiles(token); const promises = files.map(({ id: fileId }) => { return fetch(`https://www.googleapis.com/drive/v3/files/${fileId}`, { method: 'DELETE', headers: { Authorization: `Bearer ${token}` }, }); }); await Promise.all(promises); }; export const getStorageQuota = async (token: string): Promise<StorageQuota> => { const res = await fetch( 'https://www.googleapis.com/drive/v3/about?fields=storageQuota', { method: 'GET', headers: { Authorization: `Bearer ${token}` }, }, ); const json = await res.json(); return JSONtoStorageQuota(json['storageQuota']); }; export const getUserFiles = async (token: string): Promise<FileMetadata[]> => { const res = await fetch('https://www.googleapis.com/drive/v3/files?fields=*', { method: 'GET', headers: { Authorization: `Bearer ${token}` }, }); const json = await res.json(); return JSONtoFilesMetadata(json['files']); }; const uploadFileMetadata = async (token: string, name: string): Promise<string> => { // https://developers.google.com/drive/api/guides/manage-uploads#http_2 const res = await fetch( 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable', { method: 'POST', body: JSON.stringify({ name: name, originalFilename: name, mimeType: 'application/octet-stream', // "text/plain" description: 'From encryptly', }), headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json; charset=UTF-8', 'X-Upload-Content-Type': 'application/octet-stream', }, }, ); const location = res.headers.get('location'); if (!res.ok || !location) { const error = new Error('Failed upload session resume.'); error.info = await res.json(); error.status = res.status; throw error; } return location; }; interface Chunk { data: Blob; ratio: number; contentLength: string; contentRange: string; } const generateChunks = (data: Blob): Chunk[] => { /** * Create chunks in multiples of 256 KB (256 x 1024 bytes) in size, * except for the final chunk that completes the upload. * Keep the chunk size as large as possible so that the upload is efficient. * * Add headers: * - Content-Length. Set to the number of bytes in the current chunk. * - Content-Range. Set to show which bytes in the file you upload. * For example, Content-Range: bytes 0-524287/2000000 shows that you * upload the first 524,288 bytes (256 x 1024 x 2) in a 2,000,000 byte file. */ const chunkSize = 256 * 1024 * 16; const dataSize = data.size; const chunks: Chunk[] = []; let chunkCount = 0; for (; (chunkCount + 1) * chunkSize < dataSize; chunkCount += 1) { const start = chunkSize * chunkCount; const end = chunkSize * (chunkCount + 1); const chunk: Chunk = { data: data.slice(start, end), ratio: (end / dataSize) * 100, contentLength: (end - start).toString(), contentRange: `bytes ${start}-${end - 1}/${dataSize}`, }; chunks.push(chunk); } const start = chunkSize * chunkCount; const end = dataSize; const lastChunk: Chunk = { data: data.slice(start, end), ratio: 100, contentLength: (end - start).toString(), contentRange: `bytes ${start}-${end - 1}/${dataSize}`, }; chunks.push(lastChunk); return chunks; }; async function* uploadFileMedia( token: string, file: Blob, session: string, ): AsyncGenerator<number, string, void> { // https://developers.google.com/drive/api/guides/manage-uploads#http---multiple-requests const chunks = generateChunks(file); for (const { data, ratio, contentLength, contentRange } of chunks) { await fetch(session, { method: 'PUT', body: data, headers: { Authorization: `Bearer ${token}`, 'Content-Length': contentLength, 'Content-Range': contentRange, }, }); yield ratio; } return 'ok'; } export const uploadFile = async ( token: string, name: string, data: Blob, ): Promise<AsyncGenerator<number, string, void>> => { const uploadSession = await uploadFileMetadata(token, name); return uploadFileMedia(token, data, uploadSession); }; const downloadFileMedia = async (token: string, fileId: string): Promise<Blob> => { const res = await fetch( `https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`, { method: 'GET', headers: { Authorization: `Bearer ${token}` }, }, ); const data = await res.blob(); return data; }; const downloadFileMetadata = async ( token: string, fileId: string, ): Promise<FileMetadata> => { const res = await fetch( `https://www.googleapis.com/drive/v3/files/${fileId}?fields=*`, { method: 'GET', headers: { Authorization: `Bearer ${token}` }, }, ); const json = await res.json(); const metadata = JSONtoFileMetadata(json); return metadata; }; export const downloadFile = async ( token: string, fileId: string, ): Promise<{ metadata: FileMetadata; data: Blob; }> => { const data = await downloadFileMedia(token, fileId); const metadata = await downloadFileMetadata(token, fileId); return { metadata, data }; }; export const deleteFile = async (token: string, fileId: string): Promise<void> => { await fetch(`https://www.googleapis.com/drive/v2/files/${fileId}`, { method: 'DELETE', headers: { Authorization: `Bearer ${token}` }, }); };
src/hooks/http.ts
9OP-Encryptly-ef8661c
[ { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " : b.createdTime.getTime() - a.createdTime.getTime();\n case 'size':\n return sizeOrder === 'DESC' ? a.size - b.size : b.size - a.size;\n default:\n return 0;\n }\n });\n setSortedFiles(sorted);\n },\n [dateOrder, files, nameOrder, sizeOrder],", "score": 63.53275478522608 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " (sortField: 'name' | 'date' | 'size') => {\n const sorted = [...files].sort((a, b) => {\n switch (sortField) {\n case 'name':\n return nameOrder === 'DESC'\n ? a.name.localeCompare(b.name)\n : b.name.localeCompare(a.name);\n case 'date':\n return dateOrder === 'DESC'\n ? a.createdTime.getTime() - b.createdTime.getTime()", "score": 63.189917938049305 }, { "filename": "src/models/index.ts", "retrieved_chunk": " name: string;\n size: number;\n createdTime: Date;\n mimeType: string;\n}\nexport interface WrappedKey {\n enc: string;\n salt: number[];\n}\nexport interface AppData {", "score": 24.548040868970933 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " {file.name}\n </Text>\n </Tooltip>\n </HStack>\n </Td>\n <Td fontSize=\"sm\" fontWeight=\"medium\" paddingX={0} border=\"0\">\n {file?.createdTime?.toLocaleString()}\n </Td>\n <Td fontSize=\"sm\" fontWeight=\"medium\" paddingX={0} border=\"0\">\n {formatBytes(file?.size || 0)}", "score": 21.514496530007737 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " }}\n cursor=\"pointer\"\n >\n <Td paddingX={0} paddingY=\"0.8rem\" border=\"0\">\n <HStack\n draggable={true}\n onDragStart={(e) => {\n e.dataTransfer.setData('text/plain', file.id);\n }}\n >", "score": 15.13918541028766 } ]
typescript
: AppData => {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js' /** * Compiles an object schema node to JS string output. */ export class ObjectNodeCompiler extends BaseNode { #node: ObjectNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ObjectNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Returns known field names for the object */ #getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] { let fieldNames = node.properties.map((child) => child.fieldName) const groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) } /** * Returns field names of a group. */ #getGroupFieldNames(group: ObjectGroupNode): string[] { return group.conditions.flatMap((condition) => { return this.#getFieldNames(condition.schema) }) } /** * Compiles object children to JS output */ #compileObjectChildren() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent)) return buffer.toString() } /** * Compiles object groups with conditions to JS output. */ #compileObjectGroups() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent)) return buffer.toString() } /** * Compiles an object groups recursively */ #compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) { group
.conditions.forEach((condition, index) => {
const guardBuffer = buffer.child() condition.schema.properties.forEach((child) => { this.#compiler.compileNode(child, guardBuffer, parent) }) condition.schema.groups.forEach((child) => { this.#compileObjectGroup(child, guardBuffer, parent) }) buffer.writeStatement( defineConditionalGuard({ variableName: this.field.variableName, conditional: index === 0 ? 'if' : 'else if', conditionalFnRefId: condition.conditionalFnRefId, guardedCodeSnippet: guardBuffer.toString(), }) ) }) /** * Define else block */ if (group.elseConditionalFnRefId && group.conditions.length) { buffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: group.elseConditionalFnRefId, }) ) } } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + object children validations * validation inside `if object field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: '{}', })}${this.#buffer.newLine}${this.#compileObjectChildren()}${ this.#buffer.newLine }${this.#compileObjectGroups()}${this.#buffer.newLine}${defineMoveProperties({ variableName: this.field.variableName, allowUnknownProperties: this.#node.allowUnknownProperties, fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [], })}`, }) /** * Wrapping field validations + "isObjectValidBlock" inside * `if value is object` check. * * Pre step: 3 */ const isValueAnObject = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({ variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, conditional: 'else if', })}` ) } }
src/compiler/nodes/object.ts
vinejs-compiler-8909bb5
[ { "filename": "src/types.ts", "retrieved_chunk": " /**\n * Object known properties\n */\n properties: CompilerNodes[]\n /**\n * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]", "score": 34.38788820583946 }, { "filename": "src/types.ts", "retrieved_chunk": "}\n/**\n * A compiler object group produces a single sub object based upon\n * the defined conditions.\n */\nexport type ObjectGroupNode = {\n type: 'group'\n /**\n * An optional function to call when all of the conditions\n * are false.", "score": 33.52246399331587 }, { "filename": "src/types.ts", "retrieved_chunk": " * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]\n }\n }[]\n}\n/**\n * Shape of the tuple node accepted by the compiler", "score": 33.51973366129072 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " #compileUnionChildren() {\n const childrenBuffer = this.#buffer.child()\n this.#node.conditions.forEach((child, index) => {\n const conditionalBuffer = this.#buffer.child()\n /**\n * Parse the value once the condition is true\n */\n if ('parseFnId' in child.schema) {\n conditionalBuffer.writeStatement(\n callParseFunction({", "score": 26.837240779334774 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " #compileTupleChildren() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'tuple',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => {", "score": 22.890266614490105 } ]
typescript
.conditions.forEach((condition, index) => {
import { FC, useMemo, useState } from 'react'; import { useDeleteFile, useListFiles } from '@app/hooks'; import { FileMetadata } from '@app/models'; import { Button, IconButton, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, ModalOverlay, Spinner, Tag, useDisclosure, useToast, } from '@chakra-ui/react'; import { TrashIcon } from './Icons'; interface PropsModal { onDelete: () => Promise<void>; file: FileMetadata; onClose: () => void; isOpen: boolean; } const DeleteModal: FC<PropsModal> = (props: PropsModal) => { const { file, onDelete, onClose, isOpen } = props; const [deleting, setDeleting] = useState(false); const handleDelete = async () => { setDeleting(true); try { await onDelete(); onClose(); } finally { setDeleting(false); } }; return ( <Modal closeOnOverlayClick={!deleting} isOpen={isOpen} onClose={onClose}> <ModalOverlay /> <ModalContent backgroundColor="red.500"> <ModalHeader>Delete</ModalHeader> <ModalBody> Are your sure to delete <Tag colorScheme="red">{file.name}</Tag> ? </ModalBody> <ModalFooter> <Button autoFocus mr={3} onClick={onClose} color="black" isDisabled={deleting}> Cancel </Button> <Button onClick={handleDelete} isDisabled={deleting} colorScheme="red"> {deleting ? <Spinner /> : 'Delete'} </Button> </ModalFooter> </ModalContent> </Modal> ); }; interface PropsButton { fileId: string; } const DeleteButton: FC<PropsButton> = (props: PropsButton) => { const { onOpen, onClose, isOpen } = useDisclosure(); const { fileId } = props; const { data: files } = useListFiles(); const deleteFile = useDeleteFile(); const toast = useToast(); const file = useMemo(() => files?.find(({ id }) => id === fileId), [files]); const onDelete = async () => { await deleteFile(fileId); toast({ status: 'info', duration: 3000, position: 'bottom-right', isClosable: true, title: 'File deleted', description: file?.name, }); }; return ( <> <IconButton id={`delete-${fileId}`} visibility="hidden" variant="none" color="purple.400" aria-label="delete" icon={
<TrashIcon />}
onClick={onOpen} /> {file && ( <DeleteModal file={file} onDelete={onDelete} onClose={onClose} isOpen={isOpen} /> )} </> ); }; export default DeleteButton;
src/components/DeleteButton.tsx
9OP-Encryptly-ef8661c
[ { "filename": "src/components/DownloadButton.tsx", "retrieved_chunk": " <IconButton\n id={`download-${fileId}`}\n visibility={downloading || decrypting ? 'visible' : 'hidden'}\n variant=\"none\"\n color=\"purple.600\"\n aria-label=\"download\"\n icon={\n downloading ? (\n <Spinner />\n ) : decrypting ? (", "score": 46.98145600446777 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " {sortedFiles.map((file) => (\n <Tr\n key={file.id}\n sx={{\n [`&:hover #download-${file.id}`]: {\n visibility: 'visible!important',\n },\n [`&:hover #delete-${file.id}`]: {\n visibility: 'visible!important',\n },", "score": 24.30982097906319 }, { "filename": "src/components/Pagination.tsx", "retrieved_chunk": " onClick={() => setSelected(range)}\n size=\"xs\"\n variant=\"ghost\"\n color={selected === range ? 'red.600' : ''}\n >\n {range}\n </Button>\n )}\n <IconButton\n aria-label=\"next\"", "score": 19.505515756583495 }, { "filename": "src/components/Pagination.tsx", "retrieved_chunk": " alignItems=\"center\"\n marginTop=\"1rem\"\n color=\"gray.700\"\n >\n <HStack padding=\"0\" margin=\"0\" spacing=\"0.1rem\">\n <IconButton\n aria-label=\"previous\"\n icon={<ChevronLeftIcon boxSize=\"1.3rem\" />}\n onClick={onPrevious}\n size=\"xs\"", "score": 17.53908107488008 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " setOrder: Dispatch<SetStateAction<SortOrder>>;\n }) => (\n <Th padding={0} textTransform=\"capitalize\">\n <HStack spacing={1} marginBottom=\"0.6rem\">\n <Text fontSize=\"md\" color=\"black\">\n {title}\n </Text>\n <IconButton\n color=\"black\"\n variant=\"none\"", "score": 13.588402316602009 } ]
typescript
<TrashIcon />}
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { CompilerBuffer } from './buffer.js' import { TupleNodeCompiler } from './nodes/tuple.js' import { ArrayNodeCompiler } from './nodes/array.js' import { UnionNodeCompiler } from './nodes/union.js' import { RecordNodeCompiler } from './nodes/record.js' import { ObjectNodeCompiler } from './nodes/object.js' import { createRootField } from './fields/root_field.js' import { LiteralNodeCompiler } from './nodes/literal.js' import { createArrayField } from './fields/array_field.js' import { createTupleField } from './fields/tuple_field.js' import { reportErrors } from '../scripts/report_errors.js' import { createObjectField } from './fields/object_field.js' import { createRecordField } from './fields/record_field.js' import { defineInlineFunctions } from '../scripts/define_inline_functions.js' import { defineInlineErrorMessages } from '../scripts/define_error_messages.js' import type { Refs, RootNode, CompilerField, CompilerNodes, CompilerParent, CompilerOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' /** * Representation of an async function */ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor /** * Compiler is used to compile an array of schema nodes into a re-usable * JavaScript. */ export class Compiler { /** * Variables counter is used to generate unique variable * names with a counter suffix. */ variablesCounter: number = 0 /** * An array of nodes to process */ #rootNode: RootNode /** * Options to configure the compiler behavior */ #options: CompilerOptions /** * Buffer for collection the JS output string */
#buffer: CompilerBuffer = new CompilerBuffer() constructor(rootNode: RootNode, options?: CompilerOptions) {
this.#rootNode = rootNode this.#options = options || { convertEmptyStringsToNull: false } } /** * Initiates the JS output */ #initiateJSOutput() { this.#buffer.writeStatement( defineInlineErrorMessages({ required: 'value is required', object: 'value is not a valid object', array: 'value is not a valid array', ...this.#options.messages, }) ) this.#buffer.writeStatement(defineInlineFunctions(this.#options)) this.#buffer.writeStatement('let out;') } /** * Finished the JS output */ #finishJSOutput() { this.#buffer.writeStatement(reportErrors()) this.#buffer.writeStatement('return out;') } /** * Compiles all the nodes */ #compileNodes() { this.compileNode(this.#rootNode.schema, this.#buffer, { type: 'root', variableName: 'root', outputExpression: 'out', fieldPathExpression: 'out', wildCardPath: '', }) } /** * Returns compiled output as a function */ #toAsyncFunction<T extends Record<string, any>>(): ( data: any, meta: Record<string, any>, refs: Refs, messagesProvider: MessagesProviderContact, errorReporter: ErrorReporterContract ) => Promise<T> { return new AsyncFunction( 'root', 'meta', 'refs', 'messagesProvider', 'errorReporter', this.#buffer.toString() ) } /** * Converts a node to a field. Optionally accepts a parent node to create * a field for a specific parent type. */ createFieldFor(node: CompilerNodes, parent: CompilerParent) { switch (parent.type) { case 'array': return createArrayField(parent) case 'root': return createRootField(parent) case 'object': return createObjectField(node, this.variablesCounter, parent) case 'tuple': return createTupleField(node, parent) case 'record': return createRecordField(parent) } } /** * Compiles a given compiler node */ compileNode( node: CompilerNodes, buffer: CompilerBuffer, parent: CompilerParent, parentField?: CompilerField ) { switch (node.type) { case 'literal': return new LiteralNodeCompiler(node, buffer, this, parent, parentField).compile() case 'array': return new ArrayNodeCompiler(node, buffer, this, parent, parentField).compile() case 'record': return new RecordNodeCompiler(node, buffer, this, parent, parentField).compile() case 'object': return new ObjectNodeCompiler(node, buffer, this, parent, parentField).compile() case 'tuple': return new TupleNodeCompiler(node, buffer, this, parent, parentField).compile() case 'union': return new UnionNodeCompiler(node, buffer, this, parent, parentField).compile() } } /** * Compile schema nodes to an async function */ compile() { this.#initiateJSOutput() this.#compileNodes() this.#finishJSOutput() const outputFunction = this.#toAsyncFunction() this.variablesCounter = 0 this.#buffer.flush() return outputFunction } }
src/compiler/main.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " * Compiles an array schema node to JS string output.\n */\nexport class ArrayNodeCompiler extends BaseNode {\n #node: ArrayNode\n #buffer: CompilerBuffer\n #compiler: Compiler\n constructor(\n node: ArrayNode,\n buffer: CompilerBuffer,\n compiler: Compiler,", "score": 18.286383757073207 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " * Compiles a record schema node to JS string output.\n */\nexport class RecordNodeCompiler extends BaseNode {\n #node: RecordNode\n #buffer: CompilerBuffer\n #compiler: Compiler\n constructor(\n node: RecordNode,\n buffer: CompilerBuffer,\n compiler: Compiler,", "score": 18.286383757073207 }, { "filename": "src/types.ts", "retrieved_chunk": " field: FieldContext,\n args?: Record<string, any>\n ): string\n}\n/**\n * Options accepted by the compiler\n */\nexport type CompilerOptions = {\n /**\n * Convert empty string values to null for sake of", "score": 17.770193185185022 }, { "filename": "src/compiler/buffer.ts", "retrieved_chunk": " */\nexport class CompilerBuffer {\n #content: string = ''\n /**\n * The character used to create a new line\n */\n newLine = '\\n'\n /**\n * Write statement ot the output\n */", "score": 15.233453774948712 }, { "filename": "src/types.ts", "retrieved_chunk": " validator(value: unknown, options: any, field: FieldContext): any\n /**\n * Options to pass\n */\n options?: any\n}\n/**\n * The shape of parse function picked from the refs\n */\nexport type ParseFn = (value: unknown, ctx: Pick<FieldContext, 'data' | 'parent' | 'meta'>) => any", "score": 14.702923765401017 } ]
typescript
#buffer: CompilerBuffer = new CompilerBuffer() constructor(rootNode: RootNode, options?: CompilerOptions) {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineRecordLoop } from '../../scripts/record/loop.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import type { CompilerField, CompilerParent, RecordNode } from '../../types.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles a record schema node to JS string output. */ export class RecordNodeCompiler extends BaseNode { #node: RecordNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: RecordNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Compiles the record elements to a JS fragment */ #compileRecordElements() { const buffer = this.#buffer.child() const recordElementsBuffer = this.#buffer.child() this.#compiler.compileNode(this.#node.each, recordElementsBuffer, { type: 'record', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, }) buffer.writeStatement( defineRecordLoop({ variableName: this.field.variableName, loopCodeSnippet: recordElementsBuffer.toString(), }) ) recordElementsBuffer.flush() return buffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + tuple validation + array elements * validation inside `if array field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: `{}`, })}${this.#compileRecordElements()}`, }) /** * Wrapping field validations + "isArrayValidBlock" inside * `if value is array` check. * * Pre step: 3 */ const isValueAnObjectBlock = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${this.#buffer.newLine}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `
${isValueAnObjectBlock}${this.#buffer.newLine}${defineFieldNullOutput({
allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, variableName: this.field.variableName, conditional: 'else if', })}` ) } }
src/compiler/nodes/record.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " /**\n * Step 3: Define `if value is an object` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(\n `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({\n variableName: this.field.variableName,\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n conditional: 'else if',", "score": 49.53184310416979 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " variableName: this.field.variableName,\n validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isArrayValidBlock}`,\n })\n /**\n * Step 3: Define `if value is an array` block and `else if value is null`\n * block.\n */", "score": 48.17618141544696 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " })\n /**\n * Step 3: Define `if value is an array` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(\n `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,", "score": 48.12360761723589 }, { "filename": "src/compiler/nodes/literal.ts", "retrieved_chunk": " * Step 4: Define block to save the output value or the null value\n */\n this.#buffer.writeStatement(\n `${defineFieldValueOutput({\n variableName: this.field.variableName,\n outputExpression: this.field.outputExpression,\n transformFnRefId: this.#node.transformFnId,\n })}${this.#buffer.newLine}${defineFieldNullOutput({\n variableName: this.field.variableName,\n allowNull: this.#node.allowNull,", "score": 28.090321244898618 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " this.#buffer.writeStatement(\n `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n conditional: 'else if',\n })}`\n )\n }\n}", "score": 23.462142197184825 } ]
typescript
${isValueAnObjectBlock}${this.#buffer.newLine}${defineFieldNullOutput({
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { CompilerBuffer } from './buffer.js' import { TupleNodeCompiler } from './nodes/tuple.js' import { ArrayNodeCompiler } from './nodes/array.js' import { UnionNodeCompiler } from './nodes/union.js' import { RecordNodeCompiler } from './nodes/record.js' import { ObjectNodeCompiler } from './nodes/object.js' import { createRootField } from './fields/root_field.js' import { LiteralNodeCompiler } from './nodes/literal.js' import { createArrayField } from './fields/array_field.js' import { createTupleField } from './fields/tuple_field.js' import { reportErrors } from '../scripts/report_errors.js' import { createObjectField } from './fields/object_field.js' import { createRecordField } from './fields/record_field.js' import { defineInlineFunctions } from '../scripts/define_inline_functions.js' import { defineInlineErrorMessages } from '../scripts/define_error_messages.js' import type { Refs, RootNode, CompilerField, CompilerNodes, CompilerParent, CompilerOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' /** * Representation of an async function */ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor /** * Compiler is used to compile an array of schema nodes into a re-usable * JavaScript. */ export class Compiler { /** * Variables counter is used to generate unique variable * names with a counter suffix. */ variablesCounter: number = 0 /** * An array of nodes to process */ #rootNode: RootNode /** * Options to configure the compiler behavior */ #options: CompilerOptions /** * Buffer for collection the JS output string */ #buffer: CompilerBuffer = new CompilerBuffer() constructor(rootNode: RootNode, options?: CompilerOptions) { this.#rootNode = rootNode this.#options = options || { convertEmptyStringsToNull: false } } /** * Initiates the JS output */ #initiateJSOutput() { this.#buffer.writeStatement( defineInlineErrorMessages({ required: 'value is required', object: 'value is not a valid object', array: 'value is not a valid array', ...this.#options.messages, }) ) this.#buffer.writeStatement(defineInlineFunctions(this.#options)) this.#buffer.writeStatement('let out;') } /** * Finished the JS output */ #finishJSOutput() { this.#buffer.writeStatement(reportErrors()) this.#buffer.writeStatement('return out;') } /** * Compiles all the nodes */ #compileNodes() { this.compileNode(this.#rootNode.schema, this.#buffer, { type: 'root', variableName: 'root', outputExpression: 'out', fieldPathExpression: 'out', wildCardPath: '', }) } /** * Returns compiled output as a function */ #toAsyncFunction<T extends Record<string, any>>(): ( data: any, meta: Record<string, any>, refs: Refs, messagesProvider: MessagesProviderContact, errorReporter: ErrorReporterContract ) => Promise<T> { return new AsyncFunction( 'root', 'meta', 'refs', 'messagesProvider', 'errorReporter', this.#buffer.toString() ) } /** * Converts a node to a field. Optionally accepts a parent node to create * a field for a specific parent type. */ createFieldFor(node: CompilerNodes, parent: CompilerParent) { switch (parent.type) { case 'array': return createArrayField(parent) case 'root': return createRootField(parent) case 'object': return createObjectField(node, this.variablesCounter, parent) case 'tuple': return createTupleField(node, parent) case 'record': return createRecordField(parent) } } /** * Compiles a given compiler node */ compileNode( node: CompilerNodes,
buffer: CompilerBuffer, parent: CompilerParent, parentField?: CompilerField ) {
switch (node.type) { case 'literal': return new LiteralNodeCompiler(node, buffer, this, parent, parentField).compile() case 'array': return new ArrayNodeCompiler(node, buffer, this, parent, parentField).compile() case 'record': return new RecordNodeCompiler(node, buffer, this, parent, parentField).compile() case 'object': return new ObjectNodeCompiler(node, buffer, this, parent, parentField).compile() case 'tuple': return new TupleNodeCompiler(node, buffer, this, parent, parentField).compile() case 'union': return new UnionNodeCompiler(node, buffer, this, parent, parentField).compile() } } /** * Compile schema nodes to an async function */ compile() { this.#initiateJSOutput() this.#compileNodes() this.#finishJSOutput() const outputFunction = this.#toAsyncFunction() this.variablesCounter = 0 this.#buffer.flush() return outputFunction } }
src/compiler/main.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/literal.ts", "retrieved_chunk": " #node: LiteralNode\n #buffer: CompilerBuffer\n constructor(\n node: LiteralNode,\n buffer: CompilerBuffer,\n compiler: Compiler,\n parent: CompilerParent,\n parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)", "score": 21.783932813315204 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " #node: UnionNode\n #buffer: CompilerBuffer\n #parent: CompilerParent\n constructor(\n node: UnionNode,\n buffer: CompilerBuffer,\n compiler: Compiler,\n parent: CompilerParent,\n parentField?: CompilerField\n ) {", "score": 21.660850074922003 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " parent: CompilerParent,\n parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }\n /**\n * Compiles the record elements to a JS fragment", "score": 20.94948441028121 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " parent: CompilerParent,\n parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }\n /**\n * Compiles the array elements to a JS fragment", "score": 20.94948441028121 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " buffer: CompilerBuffer,\n compiler: Compiler,\n parent: CompilerParent,\n parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }", "score": 20.742098585995464 } ]
typescript
buffer: CompilerBuffer, parent: CompilerParent, parentField?: CompilerField ) {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { CompilerBuffer } from './buffer.js' import { TupleNodeCompiler } from './nodes/tuple.js' import { ArrayNodeCompiler } from './nodes/array.js' import { UnionNodeCompiler } from './nodes/union.js' import { RecordNodeCompiler } from './nodes/record.js' import { ObjectNodeCompiler } from './nodes/object.js' import { createRootField } from './fields/root_field.js' import { LiteralNodeCompiler } from './nodes/literal.js' import { createArrayField } from './fields/array_field.js' import { createTupleField } from './fields/tuple_field.js' import { reportErrors } from '../scripts/report_errors.js' import { createObjectField } from './fields/object_field.js' import { createRecordField } from './fields/record_field.js' import { defineInlineFunctions } from '../scripts/define_inline_functions.js' import { defineInlineErrorMessages } from '../scripts/define_error_messages.js' import type { Refs, RootNode, CompilerField, CompilerNodes, CompilerParent, CompilerOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' /** * Representation of an async function */ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor /** * Compiler is used to compile an array of schema nodes into a re-usable * JavaScript. */ export class Compiler { /** * Variables counter is used to generate unique variable * names with a counter suffix. */ variablesCounter: number = 0 /** * An array of nodes to process */ #rootNode: RootNode /** * Options to configure the compiler behavior */ #options: CompilerOptions /** * Buffer for collection the JS output string */ #buffer: CompilerBuffer = new CompilerBuffer() constructor(rootNode: RootNode, options?: CompilerOptions) { this.#rootNode = rootNode this.#options = options || { convertEmptyStringsToNull: false } } /** * Initiates the JS output */ #initiateJSOutput() { this.#buffer.writeStatement( defineInlineErrorMessages({ required: 'value is required', object: 'value is not a valid object', array: 'value is not a valid array', ...this.#options.messages, }) ) this.#buffer.writeStatement(defineInlineFunctions(this.#options)) this.#buffer.writeStatement('let out;') } /** * Finished the JS output */ #finishJSOutput() { this.#buffer.
writeStatement(reportErrors()) this.#buffer.writeStatement('return out;') }
/** * Compiles all the nodes */ #compileNodes() { this.compileNode(this.#rootNode.schema, this.#buffer, { type: 'root', variableName: 'root', outputExpression: 'out', fieldPathExpression: 'out', wildCardPath: '', }) } /** * Returns compiled output as a function */ #toAsyncFunction<T extends Record<string, any>>(): ( data: any, meta: Record<string, any>, refs: Refs, messagesProvider: MessagesProviderContact, errorReporter: ErrorReporterContract ) => Promise<T> { return new AsyncFunction( 'root', 'meta', 'refs', 'messagesProvider', 'errorReporter', this.#buffer.toString() ) } /** * Converts a node to a field. Optionally accepts a parent node to create * a field for a specific parent type. */ createFieldFor(node: CompilerNodes, parent: CompilerParent) { switch (parent.type) { case 'array': return createArrayField(parent) case 'root': return createRootField(parent) case 'object': return createObjectField(node, this.variablesCounter, parent) case 'tuple': return createTupleField(node, parent) case 'record': return createRecordField(parent) } } /** * Compiles a given compiler node */ compileNode( node: CompilerNodes, buffer: CompilerBuffer, parent: CompilerParent, parentField?: CompilerField ) { switch (node.type) { case 'literal': return new LiteralNodeCompiler(node, buffer, this, parent, parentField).compile() case 'array': return new ArrayNodeCompiler(node, buffer, this, parent, parentField).compile() case 'record': return new RecordNodeCompiler(node, buffer, this, parent, parentField).compile() case 'object': return new ObjectNodeCompiler(node, buffer, this, parent, parentField).compile() case 'tuple': return new TupleNodeCompiler(node, buffer, this, parent, parentField).compile() case 'union': return new UnionNodeCompiler(node, buffer, this, parent, parentField).compile() } } /** * Compile schema nodes to an async function */ compile() { this.#initiateJSOutput() this.#compileNodes() this.#finishJSOutput() const outputFunction = this.#toAsyncFunction() this.variablesCounter = 0 this.#buffer.flush() return outputFunction } }
src/compiler/main.ts
vinejs-compiler-8909bb5
[ { "filename": "src/scripts/define_inline_functions.ts", "retrieved_chunk": " out = Array((k = val.length))\n while (k--) out[k] = (tmp = val[k]) && typeof tmp == 'object' ? copyProperties(tmp) : tmp\n return out\n }\n if (Object.prototype.toString.call(val) === '[object Object]') {\n out = {} // null\n for (k in val) {\n out[k] = (tmp = val[k]) && typeof tmp == 'object' ? copyProperties(tmp) : tmp\n }\n return out", "score": 17.35540725420801 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " })\n buffer.writeStatement(\n defineRecordLoop({\n variableName: this.field.variableName,\n loopCodeSnippet: recordElementsBuffer.toString(),\n })\n )\n recordElementsBuffer.flush()\n return buffer.toString()\n }", "score": 15.643542178382887 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n buffer.writeStatement(\n defineArrayLoop({\n variableName: this.field.variableName,\n startingIndex: 0,\n loopCodeSnippet: arrayElementsBuffer.toString(),\n })\n )\n arrayElementsBuffer.flush()\n return buffer.toString()", "score": 15.223228779284616 }, { "filename": "src/scripts/define_inline_functions.ts", "retrieved_chunk": " }\n if (Array.isArray(field.value)) {\n return true;\n }\n field.report(NOT_AN_ARRAY, 'array', field);\n return false;\n};\nfunction copyProperties(val) {\n let k, out, tmp;\n if (Array.isArray(val)) {", "score": 14.506576246511642 }, { "filename": "src/compiler/buffer.ts", "retrieved_chunk": " writeStatement(statement: string) {\n this.#content = `${this.#content}${this.newLine}${statement}`\n }\n /**\n * Creates a child buffer\n */\n child() {\n return new CompilerBuffer()\n }\n /**", "score": 13.537298558910258 } ]
typescript
writeStatement(reportErrors()) this.#buffer.writeStatement('return out;') }
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js' /** * Compiles an object schema node to JS string output. */ export class ObjectNodeCompiler extends BaseNode { #node: ObjectNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ObjectNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Returns known field names for the object */ #getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] { let fieldNames = node.properties.map((child) => child.fieldName) const
groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) }
/** * Returns field names of a group. */ #getGroupFieldNames(group: ObjectGroupNode): string[] { return group.conditions.flatMap((condition) => { return this.#getFieldNames(condition.schema) }) } /** * Compiles object children to JS output */ #compileObjectChildren() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent)) return buffer.toString() } /** * Compiles object groups with conditions to JS output. */ #compileObjectGroups() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent)) return buffer.toString() } /** * Compiles an object groups recursively */ #compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) { group.conditions.forEach((condition, index) => { const guardBuffer = buffer.child() condition.schema.properties.forEach((child) => { this.#compiler.compileNode(child, guardBuffer, parent) }) condition.schema.groups.forEach((child) => { this.#compileObjectGroup(child, guardBuffer, parent) }) buffer.writeStatement( defineConditionalGuard({ variableName: this.field.variableName, conditional: index === 0 ? 'if' : 'else if', conditionalFnRefId: condition.conditionalFnRefId, guardedCodeSnippet: guardBuffer.toString(), }) ) }) /** * Define else block */ if (group.elseConditionalFnRefId && group.conditions.length) { buffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: group.elseConditionalFnRefId, }) ) } } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + object children validations * validation inside `if object field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: '{}', })}${this.#buffer.newLine}${this.#compileObjectChildren()}${ this.#buffer.newLine }${this.#compileObjectGroups()}${this.#buffer.newLine}${defineMoveProperties({ variableName: this.field.variableName, allowUnknownProperties: this.#node.allowUnknownProperties, fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [], })}`, }) /** * Wrapping field validations + "isObjectValidBlock" inside * `if value is object` check. * * Pre step: 3 */ const isValueAnObject = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({ variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, conditional: 'else if', })}` ) } }
src/compiler/nodes/object.ts
vinejs-compiler-8909bb5
[ { "filename": "src/types.ts", "retrieved_chunk": " /**\n * Object known properties\n */\n properties: CompilerNodes[]\n /**\n * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]", "score": 35.71584559543323 }, { "filename": "src/types.ts", "retrieved_chunk": " * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]\n }\n }[]\n}\n/**\n * Shape of the tuple node accepted by the compiler", "score": 24.861571657428954 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " #compileTupleChildren() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'tuple',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => {", "score": 21.27983454995614 }, { "filename": "src/types.ts", "retrieved_chunk": " /**\n * Tuple known properties\n */\n properties: CompilerNodes[]\n}\n/**\n * Shape of the record node accepted by the compiler\n */\nexport type RecordNode = FieldNode & {\n type: 'record'", "score": 18.446556078948163 }, { "filename": "src/compiler/fields/tuple_field.ts", "retrieved_chunk": " node: Pick<FieldNode, 'fieldName' | 'propertyName'>,\n parent: CompilerParent\n): CompilerField {\n /**\n * Commented to see if a use case arrives for using this.\n */\n // const fieldPathExpression =\n // parent.fieldPathExpression !== `''`\n // ? `${parent.fieldPathExpression} + '.' + '${node.fieldName}'`\n // : `'${node.fieldName}'`", "score": 17.989914995965766 } ]
typescript
groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) }
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { CompilerBuffer } from './buffer.js' import { TupleNodeCompiler } from './nodes/tuple.js' import { ArrayNodeCompiler } from './nodes/array.js' import { UnionNodeCompiler } from './nodes/union.js' import { RecordNodeCompiler } from './nodes/record.js' import { ObjectNodeCompiler } from './nodes/object.js' import { createRootField } from './fields/root_field.js' import { LiteralNodeCompiler } from './nodes/literal.js' import { createArrayField } from './fields/array_field.js' import { createTupleField } from './fields/tuple_field.js' import { reportErrors } from '../scripts/report_errors.js' import { createObjectField } from './fields/object_field.js' import { createRecordField } from './fields/record_field.js' import { defineInlineFunctions } from '../scripts/define_inline_functions.js' import { defineInlineErrorMessages } from '../scripts/define_error_messages.js' import type { Refs, RootNode, CompilerField, CompilerNodes, CompilerParent, CompilerOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' /** * Representation of an async function */ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor /** * Compiler is used to compile an array of schema nodes into a re-usable * JavaScript. */ export class Compiler { /** * Variables counter is used to generate unique variable * names with a counter suffix. */ variablesCounter: number = 0 /** * An array of nodes to process */ #rootNode: RootNode /** * Options to configure the compiler behavior */ #options: CompilerOptions /** * Buffer for collection the JS output string */ #buffer: CompilerBuffer = new CompilerBuffer() constructor(rootNode: RootNode, options?: CompilerOptions) { this.#rootNode = rootNode this.#options = options || { convertEmptyStringsToNull: false } } /** * Initiates the JS output */ #initiateJSOutput() { this.#buffer.writeStatement( defineInlineErrorMessages({ required: 'value is required', object: 'value is not a valid object', array: 'value is not a valid array', ...this.#options.messages, }) ) this.#buffer.writeStatement(defineInlineFunctions(this.#options)) this.#buffer.writeStatement('let out;') } /** * Finished the JS output */ #finishJSOutput() { this.#buffer.writeStatement(reportErrors()) this.#buffer.writeStatement('return out;') } /** * Compiles all the nodes */ #compileNodes() { this.compileNode(this.#rootNode.schema, this.#buffer, { type: 'root', variableName: 'root', outputExpression: 'out', fieldPathExpression: 'out', wildCardPath: '', }) } /** * Returns compiled output as a function */ #toAsyncFunction<T extends Record<string, any>>(): ( data: any, meta: Record<string, any>, refs: Refs, messagesProvider: MessagesProviderContact, errorReporter: ErrorReporterContract ) => Promise<T> { return new AsyncFunction( 'root', 'meta', 'refs', 'messagesProvider', 'errorReporter', this.#buffer.toString() ) } /** * Converts a node to a field. Optionally accepts a parent node to create * a field for a specific parent type. */ createFieldFor(node: CompilerNodes, parent: CompilerParent) { switch (parent.type) { case 'array': return createArrayField(parent) case 'root': return createRootField(parent) case 'object': return createObjectField(node, this.variablesCounter, parent) case 'tuple': return createTupleField(node, parent) case 'record':
return createRecordField(parent) }
} /** * Compiles a given compiler node */ compileNode( node: CompilerNodes, buffer: CompilerBuffer, parent: CompilerParent, parentField?: CompilerField ) { switch (node.type) { case 'literal': return new LiteralNodeCompiler(node, buffer, this, parent, parentField).compile() case 'array': return new ArrayNodeCompiler(node, buffer, this, parent, parentField).compile() case 'record': return new RecordNodeCompiler(node, buffer, this, parent, parentField).compile() case 'object': return new ObjectNodeCompiler(node, buffer, this, parent, parentField).compile() case 'tuple': return new TupleNodeCompiler(node, buffer, this, parent, parentField).compile() case 'union': return new UnionNodeCompiler(node, buffer, this, parent, parentField).compile() } } /** * Compile schema nodes to an async function */ compile() { this.#initiateJSOutput() this.#compileNodes() this.#finishJSOutput() const outputFunction = this.#toAsyncFunction() this.variablesCounter = 0 this.#buffer.flush() return outputFunction } }
src/compiler/main.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/fields/record_field.ts", "retrieved_chunk": " /**\n * Commented to see if a use case arrives for using this.\n */\n // const fieldPathExpression =\n // parent.fieldPathExpression !== `''`\n // ? `${parent.fieldPathExpression} + '.' + ${parent.variableName}_i`\n // : `${parent.variableName}_i`\n const wildCardPath = parent.wildCardPath !== '' ? `${parent.wildCardPath}.*` : `*`\n return {\n parentValueExpression: `${parent.variableName}.value`,", "score": 33.24825437523101 }, { "filename": "src/compiler/fields/array_field.ts", "retrieved_chunk": " /**\n * Commented to see if a use case arrives for using this.\n */\n // const fieldPathExpression =\n // parent.fieldPathExpression !== `''`\n // ? `${parent.fieldPathExpression} + '.' + ${parent.variableName}_i`\n // : `${parent.variableName}_i`\n const wildCardPath = parent.wildCardPath !== '' ? `${parent.wildCardPath}.*` : `*`\n return {\n parentValueExpression: `${parent.variableName}.value`,", "score": 33.24825437523101 }, { "filename": "src/compiler/fields/object_field.ts", "retrieved_chunk": " node: Pick<FieldNode, 'fieldName' | 'propertyName'>,\n variablesCounter: number,\n parent: CompilerParent\n): CompilerField {\n /**\n * Commented to see if a use case arrives for using this.\n */\n // const fieldPathExpression =\n // parent.fieldPathExpression !== `''`\n // ? `${parent.fieldPathExpression} + '.' + '${node.fieldName}'`", "score": 32.673108401333046 }, { "filename": "src/compiler/fields/tuple_field.ts", "retrieved_chunk": " node: Pick<FieldNode, 'fieldName' | 'propertyName'>,\n parent: CompilerParent\n): CompilerField {\n /**\n * Commented to see if a use case arrives for using this.\n */\n // const fieldPathExpression =\n // parent.fieldPathExpression !== `''`\n // ? `${parent.fieldPathExpression} + '.' + '${node.fieldName}'`\n // : `'${node.fieldName}'`", "score": 29.134254474498263 }, { "filename": "src/compiler/fields/object_field.ts", "retrieved_chunk": " // : `'${node.fieldName}'`\n const wildCardPath =\n parent.wildCardPath !== '' ? `${parent.wildCardPath}.${node.fieldName}` : node.fieldName\n return {\n parentValueExpression: `${parent.variableName}.value`,\n fieldNameExpression: `'${node.fieldName}'`,\n fieldPathExpression: wildCardPath,\n wildCardPath: wildCardPath,\n variableName: `${node.propertyName}_${variablesCounter}`,\n valueExpression: `${parent.variableName}.value['${node.fieldName}']`,", "score": 25.56904094957777 } ]
typescript
return createRecordField(parent) }
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValueOutput } from '../../scripts/field/value_output.js' import type { LiteralNode, CompilerParent, CompilerField } from '../../types.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles a literal schema node to JS string output. */ export class LiteralNodeCompiler extends BaseNode { #node: LiteralNode #buffer: CompilerBuffer constructor( node: LiteralNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define block to validate the existence of field */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Step 3: Define code to run validations on field */ this.#buffer.writeStatement( defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: false, }) ) /** * Step 4: Define block to save the output value or the null value */ this.#buffer.writeStatement(
`${defineFieldValueOutput({
variableName: this.field.variableName, outputExpression: this.field.outputExpression, transformFnRefId: this.#node.transformFnId, })}${this.#buffer.newLine}${defineFieldNullOutput({ variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, transformFnRefId: this.#node.transformFnId, conditional: 'else if', })}` ) } }
src/compiler/nodes/literal.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isObjectValidBlock}`,\n })\n /**\n * Step 3: Define `if value is an object` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(", "score": 37.63135723661357 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " variableName: this.field.variableName,\n validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isArrayValidBlock}`,\n })\n /**\n * Step 3: Define `if value is an array` block and `else if value is null`\n * block.\n */", "score": 34.699475478740766 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " */\n const isValueAnObject = defineObjectGuard({\n variableName: this.field.variableName,\n guardedCodeSnippet: `${defineFieldValidations({\n variableName: this.field.variableName,\n validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${isObjectValidBlock}`,\n })", "score": 21.838989624706862 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " * Pre step: 3\n */\n const isValueAnArrayBlock = defineArrayGuard({\n variableName: this.field.variableName,\n guardedCodeSnippet: `${defineFieldValidations({\n variableName: this.field.variableName,\n validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isArrayValidBlock}`,", "score": 21.330834002065846 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " })\n /**\n * Step 3: Define `if value is an array` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(\n `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,", "score": 19.64783253224434 } ]
typescript
`${defineFieldValueOutput({
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { CompilerBuffer } from './buffer.js' import { TupleNodeCompiler } from './nodes/tuple.js' import { ArrayNodeCompiler } from './nodes/array.js' import { UnionNodeCompiler } from './nodes/union.js' import { RecordNodeCompiler } from './nodes/record.js' import { ObjectNodeCompiler } from './nodes/object.js' import { createRootField } from './fields/root_field.js' import { LiteralNodeCompiler } from './nodes/literal.js' import { createArrayField } from './fields/array_field.js' import { createTupleField } from './fields/tuple_field.js' import { reportErrors } from '../scripts/report_errors.js' import { createObjectField } from './fields/object_field.js' import { createRecordField } from './fields/record_field.js' import { defineInlineFunctions } from '../scripts/define_inline_functions.js' import { defineInlineErrorMessages } from '../scripts/define_error_messages.js' import type { Refs, RootNode, CompilerField, CompilerNodes, CompilerParent, CompilerOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' /** * Representation of an async function */ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor /** * Compiler is used to compile an array of schema nodes into a re-usable * JavaScript. */ export class Compiler { /** * Variables counter is used to generate unique variable * names with a counter suffix. */ variablesCounter: number = 0 /** * An array of nodes to process */ #rootNode: RootNode /** * Options to configure the compiler behavior */ #options: CompilerOptions /** * Buffer for collection the JS output string */ #buffer: CompilerBuffer = new CompilerBuffer() constructor(rootNode: RootNode, options?: CompilerOptions) { this.#rootNode = rootNode this.#options = options || { convertEmptyStringsToNull: false } } /** * Initiates the JS output */ #initiateJSOutput() { this.#buffer.writeStatement( defineInlineErrorMessages({ required: 'value is required', object: 'value is not a valid object', array: 'value is not a valid array', ...this.#options.messages, }) ) this.#buffer.writeStatement(defineInlineFunctions(this.#options)) this.#buffer.writeStatement('let out;') } /** * Finished the JS output */ #finishJSOutput() { this.#buffer.writeStatement(reportErrors()) this.#buffer.writeStatement('return out;') } /** * Compiles all the nodes */ #compileNodes() { this.compileNode(this.#rootNode.schema, this.#buffer, { type: 'root', variableName: 'root', outputExpression: 'out', fieldPathExpression: 'out', wildCardPath: '', }) } /** * Returns compiled output as a function */ #toAsyncFunction<T extends Record<string, any>>(): ( data: any, meta: Record<string, any>, refs: Refs, messagesProvider: MessagesProviderContact, errorReporter: ErrorReporterContract ) => Promise<T> { return new AsyncFunction( 'root', 'meta', 'refs', 'messagesProvider', 'errorReporter', this.#buffer.toString() ) } /** * Converts a node to a field. Optionally accepts a parent node to create * a field for a specific parent type. */ createFieldFor(node: CompilerNodes, parent: CompilerParent) { switch (parent.type) { case 'array': return createArrayField(parent) case 'root': return createRootField(parent) case 'object': return createObjectField(node, this.variablesCounter, parent) case 'tuple':
return createTupleField(node, parent) case 'record': return createRecordField(parent) }
} /** * Compiles a given compiler node */ compileNode( node: CompilerNodes, buffer: CompilerBuffer, parent: CompilerParent, parentField?: CompilerField ) { switch (node.type) { case 'literal': return new LiteralNodeCompiler(node, buffer, this, parent, parentField).compile() case 'array': return new ArrayNodeCompiler(node, buffer, this, parent, parentField).compile() case 'record': return new RecordNodeCompiler(node, buffer, this, parent, parentField).compile() case 'object': return new ObjectNodeCompiler(node, buffer, this, parent, parentField).compile() case 'tuple': return new TupleNodeCompiler(node, buffer, this, parent, parentField).compile() case 'union': return new UnionNodeCompiler(node, buffer, this, parent, parentField).compile() } } /** * Compile schema nodes to an async function */ compile() { this.#initiateJSOutput() this.#compileNodes() this.#finishJSOutput() const outputFunction = this.#toAsyncFunction() this.variablesCounter = 0 this.#buffer.flush() return outputFunction } }
src/compiler/main.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/fields/record_field.ts", "retrieved_chunk": " /**\n * Commented to see if a use case arrives for using this.\n */\n // const fieldPathExpression =\n // parent.fieldPathExpression !== `''`\n // ? `${parent.fieldPathExpression} + '.' + ${parent.variableName}_i`\n // : `${parent.variableName}_i`\n const wildCardPath = parent.wildCardPath !== '' ? `${parent.wildCardPath}.*` : `*`\n return {\n parentValueExpression: `${parent.variableName}.value`,", "score": 33.24825437523101 }, { "filename": "src/compiler/fields/array_field.ts", "retrieved_chunk": " /**\n * Commented to see if a use case arrives for using this.\n */\n // const fieldPathExpression =\n // parent.fieldPathExpression !== `''`\n // ? `${parent.fieldPathExpression} + '.' + ${parent.variableName}_i`\n // : `${parent.variableName}_i`\n const wildCardPath = parent.wildCardPath !== '' ? `${parent.wildCardPath}.*` : `*`\n return {\n parentValueExpression: `${parent.variableName}.value`,", "score": 33.24825437523101 }, { "filename": "src/compiler/fields/object_field.ts", "retrieved_chunk": " node: Pick<FieldNode, 'fieldName' | 'propertyName'>,\n variablesCounter: number,\n parent: CompilerParent\n): CompilerField {\n /**\n * Commented to see if a use case arrives for using this.\n */\n // const fieldPathExpression =\n // parent.fieldPathExpression !== `''`\n // ? `${parent.fieldPathExpression} + '.' + '${node.fieldName}'`", "score": 32.673108401333046 }, { "filename": "src/compiler/fields/tuple_field.ts", "retrieved_chunk": " node: Pick<FieldNode, 'fieldName' | 'propertyName'>,\n parent: CompilerParent\n): CompilerField {\n /**\n * Commented to see if a use case arrives for using this.\n */\n // const fieldPathExpression =\n // parent.fieldPathExpression !== `''`\n // ? `${parent.fieldPathExpression} + '.' + '${node.fieldName}'`\n // : `'${node.fieldName}'`", "score": 29.134254474498263 }, { "filename": "src/compiler/fields/object_field.ts", "retrieved_chunk": " // : `'${node.fieldName}'`\n const wildCardPath =\n parent.wildCardPath !== '' ? `${parent.wildCardPath}.${node.fieldName}` : node.fieldName\n return {\n parentValueExpression: `${parent.variableName}.value`,\n fieldNameExpression: `'${node.fieldName}'`,\n fieldPathExpression: wildCardPath,\n wildCardPath: wildCardPath,\n variableName: `${node.propertyName}_${variablesCounter}`,\n valueExpression: `${parent.variableName}.value['${node.fieldName}']`,", "score": 25.56904094957777 } ]
typescript
return createTupleField(node, parent) case 'record': return createRecordField(parent) }
import { FC } from 'react'; import formatBytes from '@app/lib/formatBytes'; import { Alert, AlertDescription, AlertIcon, AlertTitle, CircularProgress, HStack, Text, VStack, } from '@chakra-ui/react'; import { CheckIcon, ShieldLockIcon } from './Icons'; interface props { files: File[]; steps: { [name: string]: 'ENCRYPTING' | 'UPLOADING' }; progress: { [name: string]: number }; } const UploadFeedback: FC<props> = (props: props) => { const { files, progress, steps } = props; return ( <Alert status="info" width="100%"> <AlertIcon /> <VStack spacing={0} alignItems="flex-start" justifyContent="center"> <AlertTitle>Uploading ...</AlertTitle> <AlertDescription> {files.map((f, i) => { const value = progress[f.name] || 0; return ( <HStack key={i} alignItems="center" justifyContent="flex-start"> {steps[f.name] === 'ENCRYPTING' && ( <ShieldLockIcon boxSize="1rem" color="white" /> )} {steps[f.name] === 'UPLOADING' && (value < 100 ? ( <CircularProgress value={value} color="blue.700" trackColor="white" size="16px" thickness="20px" /> ) : (
<CheckIcon boxSize="1rem" color="white" /> ))}
<Text fontWeight="medium" maxWidth="15rem" whiteSpace="nowrap" overflow="hidden" textOverflow="ellipsis" > {f.name} </Text> <Text fontWeight="semibold">{formatBytes(f.size)}</Text> </HStack> ); })} </AlertDescription> </VStack> </Alert> ); }; export default UploadFeedback;
src/components/UploadToast.tsx
9OP-Encryptly-ef8661c
[ { "filename": "src/components/LoginButton.tsx", "retrieved_chunk": " padding=\"0.1rem\"\n />\n }\n onClick={handleClick}\n backgroundColor=\"white\"\n _active={{\n backgroundColor: '#4285F4',\n color: 'white',\n }}\n >", "score": 25.161533741722536 }, { "filename": "src/components/SearchBar.tsx", "retrieved_chunk": " <SearchIcon color=\"gray.400\" boxSize=\"1.2rem\" />\n </InputLeftElement>\n <Input\n bg=\"white\"\n placeholder=\"search...\"\n value={search}\n onChange={(e) => setSearch(e.target.value)}\n //\n _hover={{ boxShadow: 'none' }}\n borderRadius=\"10px\"", "score": 23.59669669185061 }, { "filename": "src/components/Pagination.tsx", "retrieved_chunk": " alignItems=\"center\"\n marginTop=\"1rem\"\n color=\"gray.700\"\n >\n <HStack padding=\"0\" margin=\"0\" spacing=\"0.1rem\">\n <IconButton\n aria-label=\"previous\"\n icon={<ChevronLeftIcon boxSize=\"1.3rem\" />}\n onClick={onPrevious}\n size=\"xs\"", "score": 19.74364704816692 }, { "filename": "src/components/PassphraseInput.tsx", "retrieved_chunk": " return (\n <>\n {isLoading ? (\n <Box display=\"flex\" alignItems=\"center\" justifyContent=\"center\">\n <Spinner\n emptyColor=\"gray.200\"\n thickness=\"3px\"\n size=\"lg\"\n color=\"blue.500\"\n speed=\"0.4s\"", "score": 17.34690600566418 }, { "filename": "src/theme.ts", "retrieved_chunk": " color: 'white',\n borderWidth: '3px',\n borderRadius: '10px',\n borderColor: 'black',\n boxShadow: '-4px 4px 0px 0px #000',\n },\n },\n sizes: {},\n variants: {},\n defaultProps: {},", "score": 16.0058298100113 } ]
typescript
<CheckIcon boxSize="1rem" color="white" /> ))}
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js' /** * Compiles an object schema node to JS string output. */ export class ObjectNodeCompiler extends BaseNode { #node: ObjectNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ObjectNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Returns known field names for the object */ #getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] { let fieldNames = node.properties.map((child) => child.fieldName) const groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) } /** * Returns field names of a group. */ #getGroupFieldNames(group: ObjectGroupNode): string[] { return group.conditions.flatMap((condition) => { return this.#getFieldNames(condition.schema) }) } /** * Compiles object children to JS output */ #compileObjectChildren() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent)) return buffer.toString() } /** * Compiles object groups with conditions to JS output. */ #compileObjectGroups() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent)) return buffer.toString() } /** * Compiles an object groups recursively */ #compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) { group.conditions.forEach((condition, index) => { const guardBuffer = buffer.child() condition.schema.properties.forEach((child) => { this.#compiler.compileNode(child, guardBuffer, parent) }) condition.schema.groups.forEach((child) => { this.#compileObjectGroup(child, guardBuffer, parent) }) buffer.writeStatement( defineConditionalGuard({ variableName: this.field.variableName, conditional: index === 0 ? 'if' : 'else if', conditionalFnRefId: condition.conditionalFnRefId, guardedCodeSnippet: guardBuffer.toString(), }) ) }) /** * Define else block */ if (group.elseConditionalFnRefId && group.conditions.length) { buffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: group.elseConditionalFnRefId, }) ) } } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + object children validations * validation inside `if object field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: '{}', })}${this.#buffer.newLine}${this.#compileObjectChildren()}${ this.#buffer.newLine }${this.#compileObjectGroups()}${this.#buffer.newLine}${defineMoveProperties({ variableName: this.field.variableName, allowUnknownProperties: this.#node.allowUnknownProperties, fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [], })}`, }) /** * Wrapping field validations + "isObjectValidBlock" inside * `if value is object` check. * * Pre step: 3 */
const isValueAnObject = defineObjectGuard({
variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({ variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, conditional: 'else if', })}` ) } }
src/compiler/nodes/object.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " /**\n * Wrapping field validations + \"isArrayValidBlock\" inside\n * `if value is array` check.\n *\n * Pre step: 3\n */\n const isValueAnObjectBlock = defineObjectGuard({\n variableName: this.field.variableName,\n guardedCodeSnippet: `${defineFieldValidations({\n variableName: this.field.variableName,", "score": 33.68781370587865 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " })\n /**\n * Wrapping field validations + \"isArrayValidBlock\" inside\n * `if value is array` check.\n *\n * Pre step: 3\n */\n const isValueAnArrayBlock = defineArrayGuard({\n variableName: this.field.variableName,\n guardedCodeSnippet: `${defineFieldValidations({", "score": 31.21151650425185 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " outputExpression: this.field.outputExpression,\n outputValueExpression: this.#node.allowUnknownProperties\n ? `copyProperties(${this.field.variableName}.value)`\n : `[]`,\n })}${this.#compileTupleChildren()}`,\n })\n /**\n * Wrapping field validations + \"isArrayValidBlock\" inside\n * `if value is array` check.\n *", "score": 24.655264982131502 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " allowNull: this.#node.allowNull,\n isOptional: this.#node.isOptional,\n variableName: this.field.variableName,\n })\n )\n /**\n * Wrapping initialization of output + tuple validation + array elements\n * validation inside `if array field is valid` block.\n *\n * Pre step: 3", "score": 21.612052280639183 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " * Wrapping initialization of output + tuple validation\n * validation inside `if array field is valid` block.\n *\n * Pre step: 3\n */\n const isArrayValidBlock = defineIsValidGuard({\n variableName: this.field.variableName,\n bail: this.#node.bail,\n guardedCodeSnippet: `${defineArrayInitialOutput({\n variableName: this.field.variableName,", "score": 21.522892636190676 } ]
typescript
const isValueAnObject = defineObjectGuard({
import { FC, useMemo, useState } from 'react'; import { SecretIcon, ShieldLockIcon } from '@app/components/Icons'; import { useAppData, useSaveAppData, useUserInfo } from '@app/hooks'; import { sha256 } from '@app/lib/crypto'; import { WrappedKey } from '@app/models'; import { Box, Button, FormControl, FormErrorMessage, FormLabel, HStack, Input, Spinner, Text, VStack, } from '@chakra-ui/react'; const SetPassphrase = () => { const [loading, setLoading] = useState(false); const [passphrase, setPassphrase] = useState(''); const [confirm, setConfirm] = useState(''); const saveAppData = useSaveAppData(); const onSetPassphrase = async () => { setLoading(true); if (isValid) { const digest = await sha256(passphrase); console.log('set passphrase', digest); await saveAppData(digest); } setLoading(false); }; const isValid = useMemo( () => passphrase != '' && passphrase === confirm, [passphrase, confirm], ); return ( <VStack spacing="1rem"> <FormControl isInvalid={passphrase === ''} isRequired> <FormLabel>Passphrase</FormLabel> <Input autoFocus size="sm" placeholder="passphrase..." type="password" value={passphrase} onChange={(e) => setPassphrase(e.target.value.trim())} /> </FormControl> <FormControl isInvalid={passphrase !== confirm} isRequired> <FormLabel>Confirm passphrase</FormLabel> <Input size="sm" placeholder="passphrase..." type="password" value={confirm} onChange={(e) => setConfirm(e.target.value.trim())} /> {isValid ? ( <></> ) : ( <FormErrorMessage>Passphrases are different.</FormErrorMessage> )} </FormControl> <Button leftIcon={<SecretIcon />} size="md" width="100%" variant="solid" isDisabled={!isValid} isLoading={loading} onClick={onSetPassphrase} colorScheme="yellow" backgroundColor="yellow.200" > Set passphrase </Button> </VStack> ); }; interface props { setEncryptionKey: (key: string, wrappedKey: WrappedKey) => Promise<void>; } const PassphraseForm: FC<props> = (props: props) => { const [passphrase, setPassphrase] = useState(''); const { setEncryptionKey } = props; const { data: userInfo } = useUserInfo(); const { data } = useAppData(); const handleClick = async (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => { event.preventDefault(); event.stopPropagation(); if (data) {
await setEncryptionKey(passphrase, data.encryptionKey);
} }; return ( <VStack spacing="1rem"> <FormControl> <FormLabel fontSize="md" fontWeight="semibold" margin={0}> <HStack justifyContent="space-between"> <Text>Passphrase</Text> <Text>{userInfo?.email ? `[${userInfo.email}]` : ''}</Text> </HStack> </FormLabel> <Input marginTop="0.8rem" autoFocus placeholder="passphrase..." size="md" type="password" value={passphrase} onChange={(e) => setPassphrase(e.target.value.trim())} /> </FormControl> <Button leftIcon={<ShieldLockIcon />} size="lg" width="100%" onClick={handleClick} isDisabled={!passphrase} colorScheme="yellow" backgroundColor="yellow.200" > Unlock </Button> </VStack> ); }; const PassphraseInput: FC<props> = (props: props) => { const { data, isLoading } = useAppData(); const { setEncryptionKey } = props; return ( <> {isLoading ? ( <Box display="flex" alignItems="center" justifyContent="center"> <Spinner emptyColor="gray.200" thickness="3px" size="lg" color="blue.500" speed="0.4s" /> </Box> ) : ( <> {data != null ? ( <PassphraseForm setEncryptionKey={setEncryptionKey} /> ) : ( <SetPassphrase /> )} </> )} </> ); }; export default PassphraseInput;
src/components/PassphraseInput.tsx
9OP-Encryptly-ef8661c
[ { "filename": "src/components/DropZone.tsx", "retrieved_chunk": " const toast = useToast();\n const handleDrop = async (event: React.DragEvent<HTMLInputElement>) => {\n event.preventDefault();\n setDragOver(false);\n const items = [...event.dataTransfer.items];\n const files = await handleDataItem(items);\n try {\n if ([...files].length) {\n await onUpload([...files]);\n }", "score": 44.8499899023206 }, { "filename": "src/components/UploadButton.tsx", "retrieved_chunk": "import { FC, useRef } from 'react';\nimport { Button } from '@chakra-ui/react';\ninterface UploadButtonProps {\n onUpload: (files: File[]) => Promise<void>;\n}\nconst UploadButton: FC<UploadButtonProps> = (props: UploadButtonProps) => {\n const { onUpload } = props;\n const inputRef = useRef<HTMLInputElement | null>(null);\n const handleClick = () => inputRef.current?.click();\n const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {", "score": 42.52011325063709 }, { "filename": "src/components/UploadButton.tsx", "retrieved_chunk": " event.preventDefault();\n const items = [...(event.target.files || [])];\n // const files = await handleDataItem(items as DataTransferItem[]);\n if (items) {\n if ([...items].length) {\n await onUpload([...items]);\n }\n }\n };\n return (", "score": 39.19742915548632 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": "import DeleteButton from './DeleteButton';\ninterface props {\n files: FileMetadata[];\n isFetching: boolean;\n}\ntype SortOrder = 'ASC' | 'DESC';\nconst FileTable: FC<props> = (props: props) => {\n const { files, isFetching } = props;\n const [sortedFiles, setSortedFiles] = useState<FileMetadata[]>(files);\n const [nameOrder, setNameOrder] = useState<SortOrder>('DESC');", "score": 34.85644412260504 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " const { search, setFilesCount, setStorageCount } = props;\n const [selected, setSelected] = useState(1);\n const { data, isLoading, isValidating } = useListFiles();\n const pagination = 8;\n const isFetching = useMemo(() => isLoading || isValidating, [isLoading, isValidating]);\n const filteredFiles = useMemo(() => {\n let filtered = data || [];\n if (search) {\n filtered =\n filtered.filter((f) => f.name.toLowerCase().includes(search.toLowerCase())) || [];", "score": 33.004800662442705 } ]
typescript
await setEncryptionKey(passphrase, data.encryptionKey);
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js' /** * Compiles an object schema node to JS string output. */ export class ObjectNodeCompiler extends BaseNode { #node: ObjectNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ObjectNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Returns known field names for the object */ #getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] { let fieldNames = node.properties.map((child) => child.fieldName) const groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) } /** * Returns field names of a group. */ #getGroupFieldNames(group: ObjectGroupNode): string[] { return group.conditions.flatMap
((condition) => {
return this.#getFieldNames(condition.schema) }) } /** * Compiles object children to JS output */ #compileObjectChildren() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent)) return buffer.toString() } /** * Compiles object groups with conditions to JS output. */ #compileObjectGroups() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent)) return buffer.toString() } /** * Compiles an object groups recursively */ #compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) { group.conditions.forEach((condition, index) => { const guardBuffer = buffer.child() condition.schema.properties.forEach((child) => { this.#compiler.compileNode(child, guardBuffer, parent) }) condition.schema.groups.forEach((child) => { this.#compileObjectGroup(child, guardBuffer, parent) }) buffer.writeStatement( defineConditionalGuard({ variableName: this.field.variableName, conditional: index === 0 ? 'if' : 'else if', conditionalFnRefId: condition.conditionalFnRefId, guardedCodeSnippet: guardBuffer.toString(), }) ) }) /** * Define else block */ if (group.elseConditionalFnRefId && group.conditions.length) { buffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: group.elseConditionalFnRefId, }) ) } } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + object children validations * validation inside `if object field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: '{}', })}${this.#buffer.newLine}${this.#compileObjectChildren()}${ this.#buffer.newLine }${this.#compileObjectGroups()}${this.#buffer.newLine}${defineMoveProperties({ variableName: this.field.variableName, allowUnknownProperties: this.#node.allowUnknownProperties, fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [], })}`, }) /** * Wrapping field validations + "isObjectValidBlock" inside * `if value is object` check. * * Pre step: 3 */ const isValueAnObject = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({ variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, conditional: 'else if', })}` ) } }
src/compiler/nodes/object.ts
vinejs-compiler-8909bb5
[ { "filename": "src/types.ts", "retrieved_chunk": "}\n/**\n * A compiler object group produces a single sub object based upon\n * the defined conditions.\n */\nexport type ObjectGroupNode = {\n type: 'group'\n /**\n * An optional function to call when all of the conditions\n * are false.", "score": 38.95149274477291 }, { "filename": "src/types.ts", "retrieved_chunk": " /**\n * Object known properties\n */\n properties: CompilerNodes[]\n /**\n * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]", "score": 37.2358903478832 }, { "filename": "src/types.ts", "retrieved_chunk": " * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]\n }\n }[]\n}\n/**\n * Shape of the tuple node accepted by the compiler", "score": 33.1465634744161 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " #compileUnionChildren() {\n const childrenBuffer = this.#buffer.child()\n this.#node.conditions.forEach((child, index) => {\n const conditionalBuffer = this.#buffer.child()\n /**\n * Parse the value once the condition is true\n */\n if ('parseFnId' in child.schema) {\n conditionalBuffer.writeStatement(\n callParseFunction({", "score": 21.478720920422056 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " #compileTupleChildren() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'tuple',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => {", "score": 17.352117568907047 } ]
typescript
((condition) => {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineArrayGuard } from '../../scripts/array/guard.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import type { CompilerField, CompilerParent, TupleNode } from '../../types.js' import { defineArrayInitialOutput } from '../../scripts/array/initial_output.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles a tuple schema node to JS string output. */ export class TupleNodeCompiler extends BaseNode { #node: TupleNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: TupleNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Compiles the tuple children to a JS fragment */ #compileTupleChildren() { const buffer = this.#buffer.child() const parent = { type: 'tuple', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const
this.#node.properties.forEach((child) => {
this.#compiler.compileNode(child, buffer, parent) }) return buffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + tuple validation * validation inside `if array field is valid` block. * * Pre step: 3 */ const isArrayValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineArrayInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: this.#node.allowUnknownProperties ? `copyProperties(${this.field.variableName}.value)` : `[]`, })}${this.#compileTupleChildren()}`, }) /** * Wrapping field validations + "isArrayValidBlock" inside * `if value is array` check. * * Pre step: 3 */ const isValueAnArrayBlock = defineArrayGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${this.#buffer.newLine}${isArrayValidBlock}`, }) /** * Step 3: Define `if value is an array` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({ allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, variableName: this.field.variableName, conditional: 'else if', })}` ) } }
src/compiler/nodes/tuple.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))\n return buffer.toString()", "score": 54.692901244177826 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " */\n #compileRecordElements() {\n const buffer = this.#buffer.child()\n const recordElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, recordElementsBuffer, {\n type: 'record',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,", "score": 43.540346617056606 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " */\n #compileArrayElements() {\n const arrayElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, arrayElementsBuffer, {\n type: 'array',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n })", "score": 39.84468714605625 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " }\n /**\n * Compiles object groups with conditions to JS output.\n */\n #compileObjectGroups() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,", "score": 36.226015289339415 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " group.conditions.forEach((condition, index) => {\n const guardBuffer = buffer.child()\n condition.schema.properties.forEach((child) => {\n this.#compiler.compileNode(child, guardBuffer, parent)\n })\n condition.schema.groups.forEach((child) => {\n this.#compileObjectGroup(child, guardBuffer, parent)\n })\n buffer.writeStatement(\n defineConditionalGuard({", "score": 29.95707007197289 } ]
typescript
this.#node.properties.forEach((child) => {
import { forwardRef, ReactNode, RefObject, useEffect, useImperativeHandle, useState, } from 'react'; import { revalidateListFiles, useEncryptFile, useUploadFile } from '@app/hooks'; import { ToastId, useToast } from '@chakra-ui/react'; import UploadFeedback from './UploadToast'; interface UploadProps { ref: RefObject<any>; children: ReactNode; } export interface UploadHandle { onSubmit: (file: File[]) => Promise<void>; } const Upload = forwardRef<UploadHandle, UploadProps>((props: UploadProps, ref: any) => { const { children } = props; const toast = useToast(); const [submitCount, setSubmitCount] = useState(0); const [steps, setSteps] = useState<{ [name: string]: 'ENCRYPTING' | 'UPLOADING'; }>({}); const [progress, setProgress] = useState<{ [name: string]: number }>({}); const [toastId, setToastId] = useState<ToastId>(''); const [files, setFiles] = useState<File[]>([]); const uploadFile = useUploadFile(); const encryptFile = useEncryptFile(); useImperativeHandle<UploadHandle, any>(ref, () => ({ async onSubmit(files: File[]) { await onSubmit(files); }, })); useEffect(() => { if (toastId) { toast.update(toastId, { render: (
) => <UploadFeedback files={files} steps={steps} progress={progress} />, });
} }, [steps, progress, files]); useEffect(() => { if (submitCount === 0 && toastId) { toast.close(toastId); toast({ position: 'bottom-right', duration: 5000, isClosable: true, title: `Uploaded`, description: `${files.length} file(s)`, status: 'success', }); setToastId(''); setProgress({}); setSteps({}); setFiles([]); } }, [submitCount]); const onSubmit = async (fls: File[]) => { if (!fls.length) { return; } setSubmitCount((count) => count + 1); setFiles((prev) => [...prev, ...fls]); if (!toastId) { setToastId( toast({ position: 'bottom-right', duration: null, isClosable: true, render: () => ( <UploadFeedback files={files} steps={steps} progress={progress} /> ), }), ); } await Promise.all( fls.map(async (file) => { setSteps((prev) => ({ ...prev, [file.name]: 'ENCRYPTING' })); const data = await encryptFile(file); setSteps((prev) => ({ ...prev, [file.name]: 'UPLOADING' })); const gen = await uploadFile({ name: file.name, data }); for await (const value of gen) { setProgress((prev) => ({ ...prev, [file.name]: value })); } }), ); await revalidateListFiles(); setSubmitCount((count) => count - 1); }; return <>{children}</>; }); export default Upload;
src/components/Upload.tsx
9OP-Encryptly-ef8661c
[ { "filename": "src/components/UploadToast.tsx", "retrieved_chunk": " VStack,\n} from '@chakra-ui/react';\nimport { CheckIcon, ShieldLockIcon } from './Icons';\ninterface props {\n files: File[];\n steps: { [name: string]: 'ENCRYPTING' | 'UPLOADING' };\n progress: { [name: string]: number };\n}\nconst UploadFeedback: FC<props> = (props: props) => {\n const { files, progress, steps } = props;", "score": 42.054338525004695 }, { "filename": "src/pages/home.tsx", "retrieved_chunk": "const Home: FC = () => {\n const [search, setSearch] = useState('');\n const [filesCount, setFilesCount] = useState(0);\n const [storageCount, setStorageCount] = useState(0);\n const ref = useRef<UploadHandle>(null);\n const handleUpload = async (files: File[]) => {\n await ref?.current?.onSubmit(files);\n };\n return (\n <Upload ref={ref}>", "score": 24.15853909421246 }, { "filename": "src/components/DropZone.tsx", "retrieved_chunk": " const toast = useToast();\n const handleDrop = async (event: React.DragEvent<HTMLInputElement>) => {\n event.preventDefault();\n setDragOver(false);\n const items = [...event.dataTransfer.items];\n const files = await handleDataItem(items);\n try {\n if ([...files].length) {\n await onUpload([...files]);\n }", "score": 21.806596148052556 }, { "filename": "src/components/DeleteButton.tsx", "retrieved_chunk": " const { onOpen, onClose, isOpen } = useDisclosure();\n const { fileId } = props;\n const { data: files } = useListFiles();\n const deleteFile = useDeleteFile();\n const toast = useToast();\n const file = useMemo(() => files?.find(({ id }) => id === fileId), [files]);\n const onDelete = async () => {\n await deleteFile(fileId);\n toast({\n status: 'info',", "score": 19.69815133284878 }, { "filename": "src/components/UploadButton.tsx", "retrieved_chunk": " event.preventDefault();\n const items = [...(event.target.files || [])];\n // const files = await handleDataItem(items as DataTransferItem[]);\n if (items) {\n if ([...items].length) {\n await onUpload([...items]);\n }\n }\n };\n return (", "score": 17.49114264699795 } ]
typescript
) => <UploadFeedback files={files} steps={steps} progress={progress} />, });
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { callParseFunction } from '../../scripts/union/parse.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import type { CompilerField, CompilerParent, UnionNode } from '../../types.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' /** * Compiles a union schema node to JS string output. */ export class UnionNodeCompiler extends BaseNode { #compiler: Compiler #node: UnionNode #buffer: CompilerBuffer #parent: CompilerParent constructor( node: UnionNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#parent = parent this.#compiler = compiler } /** * Compiles union children by wrapping each conditon inside a conditional * guard block */ #compileUnionChildren() { const childrenBuffer = this.#buffer.child() this.#node.conditions
.forEach((child, index) => {
const conditionalBuffer = this.#buffer.child() /** * Parse the value once the condition is true */ if ('parseFnId' in child.schema) { conditionalBuffer.writeStatement( callParseFunction({ parseFnRefId: child.schema.parseFnId, variableName: this.field.variableName, }) ) } this.#compiler.compileNode(child.schema, conditionalBuffer, this.#parent, this.field) childrenBuffer.writeStatement( defineConditionalGuard({ conditional: index === 0 ? 'if' : 'else if', variableName: this.field.variableName, conditionalFnRefId: child.conditionalFnRefId, guardedCodeSnippet: conditionalBuffer.toString(), }) ) conditionalBuffer.flush() }) /** * Define else block */ if (this.#node.elseConditionalFnRefId && this.#node.conditions.length) { childrenBuffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: this.#node.elseConditionalFnRefId, }) ) } return childrenBuffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Compile union children wrapped inside predicate * condition. */ this.#buffer.writeStatement(this.#compileUnionChildren()) } }
src/compiler/nodes/union.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " group.conditions.forEach((condition, index) => {\n const guardBuffer = buffer.child()\n condition.schema.properties.forEach((child) => {\n this.#compiler.compileNode(child, guardBuffer, parent)\n })\n condition.schema.groups.forEach((child) => {\n this.#compileObjectGroup(child, guardBuffer, parent)\n })\n buffer.writeStatement(\n defineConditionalGuard({", "score": 29.1856268199667 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))\n return buffer.toString()", "score": 18.918394199076253 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " */\n #compileRecordElements() {\n const buffer = this.#buffer.child()\n const recordElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, recordElementsBuffer, {\n type: 'record',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,", "score": 17.831995967224273 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " #compileTupleChildren() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'tuple',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => {", "score": 16.912619967466693 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " }\n /**\n * Compiles object groups with conditions to JS output.\n */\n #compileObjectGroups() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,", "score": 16.506851306575836 } ]
typescript
.forEach((child, index) => {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineArrayLoop } from '../../scripts/array/loop.js' import { defineArrayGuard } from '../../scripts/array/guard.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import type { CompilerField, CompilerParent, ArrayNode } from '../../types.js' import { defineArrayInitialOutput } from '../../scripts/array/initial_output.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles an array schema node to JS string output. */ export class ArrayNodeCompiler extends BaseNode { #node: ArrayNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ArrayNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Compiles the array elements to a JS fragment */ #compileArrayElements() { const arrayElementsBuffer = this.#buffer.child() this.#compiler
.compileNode(this.#node.each, arrayElementsBuffer, {
type: 'array', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, }) const buffer = this.#buffer.child() buffer.writeStatement( defineArrayLoop({ variableName: this.field.variableName, startingIndex: 0, loopCodeSnippet: arrayElementsBuffer.toString(), }) ) arrayElementsBuffer.flush() return buffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + array elements * validation inside `if array field is valid` block. * * Pre step: 3 */ const isArrayValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineArrayInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: `[]`, })}${this.#buffer.newLine}${this.#compileArrayElements()}`, }) /** * Wrapping field validations + "isArrayValidBlock" inside * `if value is array` check. * * Pre step: 3 */ const isValueAnArrayBlock = defineArrayGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${this.#buffer.newLine}${isArrayValidBlock}`, }) /** * Step 3: Define `if value is an array` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({ allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, variableName: this.field.variableName, conditional: 'else if', })}` ) } }
src/compiler/nodes/array.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " parent: CompilerParent,\n parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }\n /**\n * Compiles the record elements to a JS fragment", "score": 25.027526652629636 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " */\n #compileRecordElements() {\n const buffer = this.#buffer.child()\n const recordElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, recordElementsBuffer, {\n type: 'record',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,", "score": 21.787099099136576 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }\n /**\n * Compiles the tuple children to a JS fragment\n */", "score": 21.670927238976844 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#parent = parent\n this.#compiler = compiler\n }\n /**\n * Compiles union children by wrapping each conditon inside a conditional\n * guard block\n */", "score": 19.29599126026689 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))\n return buffer.toString()", "score": 19.14729897949463 } ]
typescript
.compileNode(this.#node.each, arrayElementsBuffer, {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { CompilerBuffer } from './buffer.js' import { TupleNodeCompiler } from './nodes/tuple.js' import { ArrayNodeCompiler } from './nodes/array.js' import { UnionNodeCompiler } from './nodes/union.js' import { RecordNodeCompiler } from './nodes/record.js' import { ObjectNodeCompiler } from './nodes/object.js' import { createRootField } from './fields/root_field.js' import { LiteralNodeCompiler } from './nodes/literal.js' import { createArrayField } from './fields/array_field.js' import { createTupleField } from './fields/tuple_field.js' import { reportErrors } from '../scripts/report_errors.js' import { createObjectField } from './fields/object_field.js' import { createRecordField } from './fields/record_field.js' import { defineInlineFunctions } from '../scripts/define_inline_functions.js' import { defineInlineErrorMessages } from '../scripts/define_error_messages.js' import type { Refs, RootNode, CompilerField, CompilerNodes, CompilerParent, CompilerOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' /** * Representation of an async function */ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor /** * Compiler is used to compile an array of schema nodes into a re-usable * JavaScript. */ export class Compiler { /** * Variables counter is used to generate unique variable * names with a counter suffix. */ variablesCounter: number = 0 /** * An array of nodes to process */ #rootNode: RootNode /** * Options to configure the compiler behavior */ #options: CompilerOptions /** * Buffer for collection the JS output string */ #buffer: CompilerBuffer = new CompilerBuffer() constructor(rootNode: RootNode, options?: CompilerOptions) { this.#rootNode = rootNode this.#options = options || { convertEmptyStringsToNull: false } } /** * Initiates the JS output */ #initiateJSOutput() { this.#buffer.writeStatement( defineInlineErrorMessages({ required: 'value is required', object: 'value is not a valid object', array: 'value is not a valid array', ...this.#options.messages, }) ) this.#buffer.writeStatement(defineInlineFunctions(this.#options)) this.#buffer.writeStatement('let out;') } /** * Finished the JS output */ #finishJSOutput() { this.#buffer.writeStatement(reportErrors()) this.#buffer.writeStatement('return out;') } /** * Compiles all the nodes */ #compileNodes() { this.compileNode(this.#rootNode.schema, this.#buffer, { type: 'root', variableName: 'root', outputExpression: 'out', fieldPathExpression: 'out', wildCardPath: '', }) } /** * Returns compiled output as a function */ #toAsyncFunction<T extends Record<string, any>>(): ( data: any, meta: Record<string, any>, refs: Refs, messagesProvider: MessagesProviderContact, errorReporter: ErrorReporterContract ) => Promise<T> { return new AsyncFunction( 'root', 'meta', 'refs', 'messagesProvider', 'errorReporter', this.#buffer.toString() ) } /** * Converts a node to a field. Optionally accepts a parent node to create * a field for a specific parent type. */ createFieldFor(node: CompilerNodes, parent: CompilerParent) { switch (parent.type) { case 'array': return createArrayField(parent) case 'root': return createRootField(parent) case 'object': return createObjectField(node, this.variablesCounter, parent) case 'tuple': return createTupleField(node, parent) case 'record': return createRecordField(parent) } } /** * Compiles a given compiler node */ compileNode( node: CompilerNodes, buffer: CompilerBuffer, parent: CompilerParent, parentField?: CompilerField ) { switch (node.type) { case 'literal': return new LiteralNodeCompiler(node, buffer, this, parent, parentField).compile() case 'array': return new ArrayNodeCompiler(node, buffer, this, parent, parentField).compile() case 'record': return new RecordNodeCompiler(node, buffer, this, parent, parentField).compile() case 'object': return new ObjectNodeCompiler(node, buffer, this, parent, parentField).compile() case 'tuple': return new TupleNodeCompiler(node, buffer, this, parent, parentField).compile() case 'union': return new UnionNodeCompiler(node, buffer, this, parent, parentField).compile() } } /** * Compile schema nodes to an async function */ compile() { this.#initiateJSOutput() this.#compileNodes() this.#finishJSOutput() const outputFunction = this.#toAsyncFunction() this.variablesCounter = 0 this.#buffer
.flush() return outputFunction }
}
src/compiler/main.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n buffer.writeStatement(\n defineArrayLoop({\n variableName: this.field.variableName,\n startingIndex: 0,\n loopCodeSnippet: arrayElementsBuffer.toString(),\n })\n )\n arrayElementsBuffer.flush()\n return buffer.toString()", "score": 13.740677637659383 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " })\n buffer.writeStatement(\n defineRecordLoop({\n variableName: this.field.variableName,\n loopCodeSnippet: recordElementsBuffer.toString(),\n })\n )\n recordElementsBuffer.flush()\n return buffer.toString()\n }", "score": 8.723999292080409 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " this.#compiler.compileNode(child, buffer, parent)\n })\n return buffer.toString()\n }\n compile() {\n /**\n * Define 1: Define field variable\n */\n this.defineField(this.#buffer)\n /**", "score": 8.20173253690365 }, { "filename": "src/compiler/buffer.ts", "retrieved_chunk": " * Returns the buffer contents as string\n */\n toString() {\n return this.#content\n }\n /**\n * Flush in-memory string\n */\n flush() {\n this.#content = ''", "score": 8.111396180407064 }, { "filename": "src/refs_builder.ts", "retrieved_chunk": "export function refsBuilder(): RefsStore {\n let counter = 0\n const refs: Refs = {}\n return {\n toJSON() {\n return refs\n },\n /**\n * Track a value inside refs\n */", "score": 7.622807657232325 } ]
typescript
.flush() return outputFunction }
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineArrayLoop } from '../../scripts/array/loop.js' import { defineArrayGuard } from '../../scripts/array/guard.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import type { CompilerField, CompilerParent, ArrayNode } from '../../types.js' import { defineArrayInitialOutput } from '../../scripts/array/initial_output.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles an array schema node to JS string output. */ export class ArrayNodeCompiler extends BaseNode { #node: ArrayNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ArrayNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Compiles the array elements to a JS fragment */ #compileArrayElements() { const arrayElementsBuffer = this.#buffer.child()
this.#compiler.compileNode(this.#node.each, arrayElementsBuffer, {
type: 'array', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, }) const buffer = this.#buffer.child() buffer.writeStatement( defineArrayLoop({ variableName: this.field.variableName, startingIndex: 0, loopCodeSnippet: arrayElementsBuffer.toString(), }) ) arrayElementsBuffer.flush() return buffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + array elements * validation inside `if array field is valid` block. * * Pre step: 3 */ const isArrayValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineArrayInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: `[]`, })}${this.#buffer.newLine}${this.#compileArrayElements()}`, }) /** * Wrapping field validations + "isArrayValidBlock" inside * `if value is array` check. * * Pre step: 3 */ const isValueAnArrayBlock = defineArrayGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${this.#buffer.newLine}${isArrayValidBlock}`, }) /** * Step 3: Define `if value is an array` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({ allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, variableName: this.field.variableName, conditional: 'else if', })}` ) } }
src/compiler/nodes/array.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " parent: CompilerParent,\n parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }\n /**\n * Compiles the record elements to a JS fragment", "score": 28.517665520757408 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }\n /**\n * Compiles the tuple children to a JS fragment\n */", "score": 25.227614399483702 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " */\n #compileRecordElements() {\n const buffer = this.#buffer.child()\n const recordElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, recordElementsBuffer, {\n type: 'record',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,", "score": 23.748374042298508 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#parent = parent\n this.#compiler = compiler\n }\n /**\n * Compiles union children by wrapping each conditon inside a conditional\n * guard block\n */", "score": 22.711983352902557 }, { "filename": "src/compiler/main.ts", "retrieved_chunk": " case 'record':\n return createRecordField(parent)\n }\n }\n /**\n * Compiles a given compiler node\n */\n compileNode(\n node: CompilerNodes,\n buffer: CompilerBuffer,", "score": 21.385353281283866 } ]
typescript
this.#compiler.compileNode(this.#node.each, arrayElementsBuffer, {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { CompilerBuffer } from './buffer.js' import { TupleNodeCompiler } from './nodes/tuple.js' import { ArrayNodeCompiler } from './nodes/array.js' import { UnionNodeCompiler } from './nodes/union.js' import { RecordNodeCompiler } from './nodes/record.js' import { ObjectNodeCompiler } from './nodes/object.js' import { createRootField } from './fields/root_field.js' import { LiteralNodeCompiler } from './nodes/literal.js' import { createArrayField } from './fields/array_field.js' import { createTupleField } from './fields/tuple_field.js' import { reportErrors } from '../scripts/report_errors.js' import { createObjectField } from './fields/object_field.js' import { createRecordField } from './fields/record_field.js' import { defineInlineFunctions } from '../scripts/define_inline_functions.js' import { defineInlineErrorMessages } from '../scripts/define_error_messages.js' import type { Refs, RootNode, CompilerField, CompilerNodes, CompilerParent, CompilerOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' /** * Representation of an async function */ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor /** * Compiler is used to compile an array of schema nodes into a re-usable * JavaScript. */ export class Compiler { /** * Variables counter is used to generate unique variable * names with a counter suffix. */ variablesCounter: number = 0 /** * An array of nodes to process */ #rootNode: RootNode /** * Options to configure the compiler behavior */ #options: CompilerOptions /** * Buffer for collection the JS output string */ #buffer: CompilerBuffer = new CompilerBuffer() constructor(rootNode: RootNode, options?: CompilerOptions) { this.#rootNode = rootNode this.#options = options || { convertEmptyStringsToNull: false } } /** * Initiates the JS output */ #initiateJSOutput() { this.
#buffer.writeStatement( defineInlineErrorMessages({
required: 'value is required', object: 'value is not a valid object', array: 'value is not a valid array', ...this.#options.messages, }) ) this.#buffer.writeStatement(defineInlineFunctions(this.#options)) this.#buffer.writeStatement('let out;') } /** * Finished the JS output */ #finishJSOutput() { this.#buffer.writeStatement(reportErrors()) this.#buffer.writeStatement('return out;') } /** * Compiles all the nodes */ #compileNodes() { this.compileNode(this.#rootNode.schema, this.#buffer, { type: 'root', variableName: 'root', outputExpression: 'out', fieldPathExpression: 'out', wildCardPath: '', }) } /** * Returns compiled output as a function */ #toAsyncFunction<T extends Record<string, any>>(): ( data: any, meta: Record<string, any>, refs: Refs, messagesProvider: MessagesProviderContact, errorReporter: ErrorReporterContract ) => Promise<T> { return new AsyncFunction( 'root', 'meta', 'refs', 'messagesProvider', 'errorReporter', this.#buffer.toString() ) } /** * Converts a node to a field. Optionally accepts a parent node to create * a field for a specific parent type. */ createFieldFor(node: CompilerNodes, parent: CompilerParent) { switch (parent.type) { case 'array': return createArrayField(parent) case 'root': return createRootField(parent) case 'object': return createObjectField(node, this.variablesCounter, parent) case 'tuple': return createTupleField(node, parent) case 'record': return createRecordField(parent) } } /** * Compiles a given compiler node */ compileNode( node: CompilerNodes, buffer: CompilerBuffer, parent: CompilerParent, parentField?: CompilerField ) { switch (node.type) { case 'literal': return new LiteralNodeCompiler(node, buffer, this, parent, parentField).compile() case 'array': return new ArrayNodeCompiler(node, buffer, this, parent, parentField).compile() case 'record': return new RecordNodeCompiler(node, buffer, this, parent, parentField).compile() case 'object': return new ObjectNodeCompiler(node, buffer, this, parent, parentField).compile() case 'tuple': return new TupleNodeCompiler(node, buffer, this, parent, parentField).compile() case 'union': return new UnionNodeCompiler(node, buffer, this, parent, parentField).compile() } } /** * Compile schema nodes to an async function */ compile() { this.#initiateJSOutput() this.#compileNodes() this.#finishJSOutput() const outputFunction = this.#toAsyncFunction() this.variablesCounter = 0 this.#buffer.flush() return outputFunction } }
src/compiler/main.ts
vinejs-compiler-8909bb5
[ { "filename": "src/scripts/define_inline_functions.ts", "retrieved_chunk": " * validation runtime code.\n */\nexport function defineInlineFunctions(options: { convertEmptyStringsToNull: boolean }) {\n return `function report(message, rule, field, args) {\n field.isValid = false;\n errorReporter.report(messagesProvider.getMessage(message, rule, field, args), rule, field, args);\n};\nfunction defineValue(value, field) {\n ${options.convertEmptyStringsToNull ? `if (value === '') { value = null; }` : ''}\n field.value = value;", "score": 17.190448338674337 }, { "filename": "src/types.ts", "retrieved_chunk": " validator(value: unknown, options: any, field: FieldContext): any\n /**\n * Options to pass\n */\n options?: any\n}\n/**\n * The shape of parse function picked from the refs\n */\nexport type ParseFn = (value: unknown, ctx: Pick<FieldContext, 'data' | 'parent' | 'meta'>) => any", "score": 11.050907187710798 }, { "filename": "src/scripts/field/validations.ts", "retrieved_chunk": " bail: boolean,\n dropMissingCheck: boolean\n) {\n const rule = `refs['${ruleFnId}']`\n const callable = `${rule}.validator(${variableName}.value, ${rule}.options, ${variableName});`\n /**\n * Add \"isValid\" condition when the bail flag is turned on.\n */\n const bailCondition = bail ? `${variableName}.isValid` : ''\n /**", "score": 7.813066692196776 }, { "filename": "src/compiler/nodes/literal.ts", "retrieved_chunk": " */\n this.#buffer.writeStatement(\n defineFieldValidations({\n variableName: this.field.variableName,\n validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: false,\n })\n )\n /**", "score": 7.355463370246593 }, { "filename": "src/scripts/define_error_messages.ts", "retrieved_chunk": " * Returns JS fragment for inline error messages for errors raised\n * by the compiler.\n */\nexport function defineInlineErrorMessages(\n messages: Required<Exclude<CompilerOptions['messages'], undefined>>\n) {\n return `const REQUIRED = '${messages.required}';\nconst NOT_AN_OBJECT = '${messages.object}';\nconst NOT_AN_ARRAY = '${messages.array}';`\n}", "score": 6.096369868387627 } ]
typescript
#buffer.writeStatement( defineInlineErrorMessages({
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineArrayLoop } from '../../scripts/array/loop.js' import { defineArrayGuard } from '../../scripts/array/guard.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import type { CompilerField, CompilerParent, ArrayNode } from '../../types.js' import { defineArrayInitialOutput } from '../../scripts/array/initial_output.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles an array schema node to JS string output. */ export class ArrayNodeCompiler extends BaseNode { #node: ArrayNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ArrayNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Compiles the array elements to a JS fragment */ #compileArrayElements() { const arrayElementsBuffer = this.#buffer.
child() this.#compiler.compileNode(this.#node.each, arrayElementsBuffer, {
type: 'array', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, }) const buffer = this.#buffer.child() buffer.writeStatement( defineArrayLoop({ variableName: this.field.variableName, startingIndex: 0, loopCodeSnippet: arrayElementsBuffer.toString(), }) ) arrayElementsBuffer.flush() return buffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + array elements * validation inside `if array field is valid` block. * * Pre step: 3 */ const isArrayValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineArrayInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: `[]`, })}${this.#buffer.newLine}${this.#compileArrayElements()}`, }) /** * Wrapping field validations + "isArrayValidBlock" inside * `if value is array` check. * * Pre step: 3 */ const isValueAnArrayBlock = defineArrayGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${this.#buffer.newLine}${isArrayValidBlock}`, }) /** * Step 3: Define `if value is an array` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({ allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, variableName: this.field.variableName, conditional: 'else if', })}` ) } }
src/compiler/nodes/array.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " parent: CompilerParent,\n parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }\n /**\n * Compiles the record elements to a JS fragment", "score": 25.027526652629636 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " */\n #compileRecordElements() {\n const buffer = this.#buffer.child()\n const recordElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, recordElementsBuffer, {\n type: 'record',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,", "score": 21.787099099136576 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }\n /**\n * Compiles the tuple children to a JS fragment\n */", "score": 21.670927238976844 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#parent = parent\n this.#compiler = compiler\n }\n /**\n * Compiles union children by wrapping each conditon inside a conditional\n * guard block\n */", "score": 19.29599126026689 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))\n return buffer.toString()", "score": 19.14729897949463 } ]
typescript
child() this.#compiler.compileNode(this.#node.each, arrayElementsBuffer, {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { CompilerBuffer } from './buffer.js' import { TupleNodeCompiler } from './nodes/tuple.js' import { ArrayNodeCompiler } from './nodes/array.js' import { UnionNodeCompiler } from './nodes/union.js' import { RecordNodeCompiler } from './nodes/record.js' import { ObjectNodeCompiler } from './nodes/object.js' import { createRootField } from './fields/root_field.js' import { LiteralNodeCompiler } from './nodes/literal.js' import { createArrayField } from './fields/array_field.js' import { createTupleField } from './fields/tuple_field.js' import { reportErrors } from '../scripts/report_errors.js' import { createObjectField } from './fields/object_field.js' import { createRecordField } from './fields/record_field.js' import { defineInlineFunctions } from '../scripts/define_inline_functions.js' import { defineInlineErrorMessages } from '../scripts/define_error_messages.js' import type { Refs, RootNode, CompilerField, CompilerNodes, CompilerParent, CompilerOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' /** * Representation of an async function */ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor /** * Compiler is used to compile an array of schema nodes into a re-usable * JavaScript. */ export class Compiler { /** * Variables counter is used to generate unique variable * names with a counter suffix. */ variablesCounter: number = 0 /** * An array of nodes to process */ #rootNode: RootNode /** * Options to configure the compiler behavior */ #options: CompilerOptions /** * Buffer for collection the JS output string */ #buffer: CompilerBuffer = new CompilerBuffer() constructor(rootNode: RootNode, options?: CompilerOptions) { this.#rootNode = rootNode this.#options = options || { convertEmptyStringsToNull: false } } /** * Initiates the JS output */ #initiateJSOutput() { this.#buffer.writeStatement( defineInlineErrorMessages({ required: 'value is required', object: 'value is not a valid object', array: 'value is not a valid array', ...this.#options.messages, }) ) this.#buffer.writeStatement(defineInlineFunctions(this.#options)) this.#buffer.writeStatement('let out;') } /** * Finished the JS output */ #finishJSOutput() { this.#buffer
.writeStatement(reportErrors()) this.#buffer.writeStatement('return out;') }
/** * Compiles all the nodes */ #compileNodes() { this.compileNode(this.#rootNode.schema, this.#buffer, { type: 'root', variableName: 'root', outputExpression: 'out', fieldPathExpression: 'out', wildCardPath: '', }) } /** * Returns compiled output as a function */ #toAsyncFunction<T extends Record<string, any>>(): ( data: any, meta: Record<string, any>, refs: Refs, messagesProvider: MessagesProviderContact, errorReporter: ErrorReporterContract ) => Promise<T> { return new AsyncFunction( 'root', 'meta', 'refs', 'messagesProvider', 'errorReporter', this.#buffer.toString() ) } /** * Converts a node to a field. Optionally accepts a parent node to create * a field for a specific parent type. */ createFieldFor(node: CompilerNodes, parent: CompilerParent) { switch (parent.type) { case 'array': return createArrayField(parent) case 'root': return createRootField(parent) case 'object': return createObjectField(node, this.variablesCounter, parent) case 'tuple': return createTupleField(node, parent) case 'record': return createRecordField(parent) } } /** * Compiles a given compiler node */ compileNode( node: CompilerNodes, buffer: CompilerBuffer, parent: CompilerParent, parentField?: CompilerField ) { switch (node.type) { case 'literal': return new LiteralNodeCompiler(node, buffer, this, parent, parentField).compile() case 'array': return new ArrayNodeCompiler(node, buffer, this, parent, parentField).compile() case 'record': return new RecordNodeCompiler(node, buffer, this, parent, parentField).compile() case 'object': return new ObjectNodeCompiler(node, buffer, this, parent, parentField).compile() case 'tuple': return new TupleNodeCompiler(node, buffer, this, parent, parentField).compile() case 'union': return new UnionNodeCompiler(node, buffer, this, parent, parentField).compile() } } /** * Compile schema nodes to an async function */ compile() { this.#initiateJSOutput() this.#compileNodes() this.#finishJSOutput() const outputFunction = this.#toAsyncFunction() this.variablesCounter = 0 this.#buffer.flush() return outputFunction } }
src/compiler/main.ts
vinejs-compiler-8909bb5
[ { "filename": "src/scripts/define_inline_functions.ts", "retrieved_chunk": " out = Array((k = val.length))\n while (k--) out[k] = (tmp = val[k]) && typeof tmp == 'object' ? copyProperties(tmp) : tmp\n return out\n }\n if (Object.prototype.toString.call(val) === '[object Object]') {\n out = {} // null\n for (k in val) {\n out[k] = (tmp = val[k]) && typeof tmp == 'object' ? copyProperties(tmp) : tmp\n }\n return out", "score": 17.35540725420801 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " })\n buffer.writeStatement(\n defineRecordLoop({\n variableName: this.field.variableName,\n loopCodeSnippet: recordElementsBuffer.toString(),\n })\n )\n recordElementsBuffer.flush()\n return buffer.toString()\n }", "score": 15.643542178382887 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n buffer.writeStatement(\n defineArrayLoop({\n variableName: this.field.variableName,\n startingIndex: 0,\n loopCodeSnippet: arrayElementsBuffer.toString(),\n })\n )\n arrayElementsBuffer.flush()\n return buffer.toString()", "score": 15.223228779284616 }, { "filename": "src/scripts/define_inline_functions.ts", "retrieved_chunk": " }\n if (Array.isArray(field.value)) {\n return true;\n }\n field.report(NOT_AN_ARRAY, 'array', field);\n return false;\n};\nfunction copyProperties(val) {\n let k, out, tmp;\n if (Array.isArray(val)) {", "score": 14.506576246511642 }, { "filename": "src/compiler/buffer.ts", "retrieved_chunk": " writeStatement(statement: string) {\n this.#content = `${this.#content}${this.newLine}${statement}`\n }\n /**\n * Creates a child buffer\n */\n child() {\n return new CompilerBuffer()\n }\n /**", "score": 13.537298558910258 } ]
typescript
.writeStatement(reportErrors()) this.#buffer.writeStatement('return out;') }
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValueOutput } from '../../scripts/field/value_output.js' import type { LiteralNode, CompilerParent, CompilerField } from '../../types.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles a literal schema node to JS string output. */ export class LiteralNodeCompiler extends BaseNode { #node: LiteralNode #buffer: CompilerBuffer constructor( node: LiteralNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define block to validate the existence of field */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Step 3: Define code to run validations on field */ this.#buffer.writeStatement( defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: false, }) ) /** * Step 4: Define block to save the output value or the null value */ this.#buffer.writeStatement( `${defineFieldValueOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, transformFnRefId: this.#node
.transformFnId, })}${this.#buffer.newLine}${defineFieldNullOutput({
variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, transformFnRefId: this.#node.transformFnId, conditional: 'else if', })}` ) } }
src/compiler/nodes/literal.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " })\n /**\n * Step 3: Define `if value is an array` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(\n `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,", "score": 33.710300047044186 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " /**\n * Step 3: Define `if value is an object` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(\n `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({\n variableName: this.field.variableName,\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n conditional: 'else if',", "score": 32.50816736637013 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isObjectValidBlock}`,\n })\n /**\n * Step 3: Define `if value is an object` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(", "score": 24.360212638257835 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " variableName: this.field.variableName,\n validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isArrayValidBlock}`,\n })\n /**\n * Step 3: Define `if value is an array` block and `else if value is null`\n * block.\n */", "score": 23.75325678529178 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " this.#buffer.writeStatement(\n `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n conditional: 'else if',\n })}`\n )\n }\n}", "score": 23.37280288857864 } ]
typescript
.transformFnId, })}${this.#buffer.newLine}${defineFieldNullOutput({
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js' /** * Compiles an object schema node to JS string output. */ export class ObjectNodeCompiler extends BaseNode { #node: ObjectNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ObjectNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Returns known field names for the object */ #getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] { let fieldNames = node.properties.map((child) => child.fieldName) const groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) } /** * Returns field names of a group. */ #getGroupFieldNames(group: ObjectGroupNode): string[] { return group.conditions.flatMap((
condition) => {
return this.#getFieldNames(condition.schema) }) } /** * Compiles object children to JS output */ #compileObjectChildren() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent)) return buffer.toString() } /** * Compiles object groups with conditions to JS output. */ #compileObjectGroups() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent)) return buffer.toString() } /** * Compiles an object groups recursively */ #compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) { group.conditions.forEach((condition, index) => { const guardBuffer = buffer.child() condition.schema.properties.forEach((child) => { this.#compiler.compileNode(child, guardBuffer, parent) }) condition.schema.groups.forEach((child) => { this.#compileObjectGroup(child, guardBuffer, parent) }) buffer.writeStatement( defineConditionalGuard({ variableName: this.field.variableName, conditional: index === 0 ? 'if' : 'else if', conditionalFnRefId: condition.conditionalFnRefId, guardedCodeSnippet: guardBuffer.toString(), }) ) }) /** * Define else block */ if (group.elseConditionalFnRefId && group.conditions.length) { buffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: group.elseConditionalFnRefId, }) ) } } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + object children validations * validation inside `if object field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: '{}', })}${this.#buffer.newLine}${this.#compileObjectChildren()}${ this.#buffer.newLine }${this.#compileObjectGroups()}${this.#buffer.newLine}${defineMoveProperties({ variableName: this.field.variableName, allowUnknownProperties: this.#node.allowUnknownProperties, fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [], })}`, }) /** * Wrapping field validations + "isObjectValidBlock" inside * `if value is object` check. * * Pre step: 3 */ const isValueAnObject = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({ variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, conditional: 'else if', })}` ) } }
src/compiler/nodes/object.ts
vinejs-compiler-8909bb5
[ { "filename": "src/types.ts", "retrieved_chunk": "}\n/**\n * A compiler object group produces a single sub object based upon\n * the defined conditions.\n */\nexport type ObjectGroupNode = {\n type: 'group'\n /**\n * An optional function to call when all of the conditions\n * are false.", "score": 38.95149274477291 }, { "filename": "src/types.ts", "retrieved_chunk": " /**\n * Object known properties\n */\n properties: CompilerNodes[]\n /**\n * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]", "score": 37.2358903478832 }, { "filename": "src/types.ts", "retrieved_chunk": " * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]\n }\n }[]\n}\n/**\n * Shape of the tuple node accepted by the compiler", "score": 33.1465634744161 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " #compileUnionChildren() {\n const childrenBuffer = this.#buffer.child()\n this.#node.conditions.forEach((child, index) => {\n const conditionalBuffer = this.#buffer.child()\n /**\n * Parse the value once the condition is true\n */\n if ('parseFnId' in child.schema) {\n conditionalBuffer.writeStatement(\n callParseFunction({", "score": 21.478720920422056 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " #compileTupleChildren() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'tuple',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => {", "score": 17.352117568907047 } ]
typescript
condition) => {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js' /** * Compiles an object schema node to JS string output. */ export class ObjectNodeCompiler extends BaseNode { #node: ObjectNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ObjectNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Returns known field names for the object */ #getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] { let fieldNames = node.properties.map((child) => child.fieldName) const groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) } /** * Returns field names of a group. */ #getGroupFieldNames(group: ObjectGroupNode): string[] { return group.conditions.flatMap((condition) => { return this.#getFieldNames(condition.schema) }) } /** * Compiles object children to JS output */ #compileObjectChildren() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent)) return buffer.toString() } /** * Compiles object groups with conditions to JS output. */ #compileObjectGroups() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent)) return buffer.toString() } /** * Compiles an object groups recursively */ #compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) {
group.conditions.forEach((condition, index) => {
const guardBuffer = buffer.child() condition.schema.properties.forEach((child) => { this.#compiler.compileNode(child, guardBuffer, parent) }) condition.schema.groups.forEach((child) => { this.#compileObjectGroup(child, guardBuffer, parent) }) buffer.writeStatement( defineConditionalGuard({ variableName: this.field.variableName, conditional: index === 0 ? 'if' : 'else if', conditionalFnRefId: condition.conditionalFnRefId, guardedCodeSnippet: guardBuffer.toString(), }) ) }) /** * Define else block */ if (group.elseConditionalFnRefId && group.conditions.length) { buffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: group.elseConditionalFnRefId, }) ) } } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + object children validations * validation inside `if object field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: '{}', })}${this.#buffer.newLine}${this.#compileObjectChildren()}${ this.#buffer.newLine }${this.#compileObjectGroups()}${this.#buffer.newLine}${defineMoveProperties({ variableName: this.field.variableName, allowUnknownProperties: this.#node.allowUnknownProperties, fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [], })}`, }) /** * Wrapping field validations + "isObjectValidBlock" inside * `if value is object` check. * * Pre step: 3 */ const isValueAnObject = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({ variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, conditional: 'else if', })}` ) } }
src/compiler/nodes/object.ts
vinejs-compiler-8909bb5
[ { "filename": "src/types.ts", "retrieved_chunk": " /**\n * Object known properties\n */\n properties: CompilerNodes[]\n /**\n * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]", "score": 34.38788820583946 }, { "filename": "src/types.ts", "retrieved_chunk": "}\n/**\n * A compiler object group produces a single sub object based upon\n * the defined conditions.\n */\nexport type ObjectGroupNode = {\n type: 'group'\n /**\n * An optional function to call when all of the conditions\n * are false.", "score": 33.52246399331587 }, { "filename": "src/types.ts", "retrieved_chunk": " * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]\n }\n }[]\n}\n/**\n * Shape of the tuple node accepted by the compiler", "score": 33.51973366129072 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " #compileTupleChildren() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'tuple',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => {", "score": 30.844047684111068 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " #compileUnionChildren() {\n const childrenBuffer = this.#buffer.child()\n this.#node.conditions.forEach((child, index) => {\n const conditionalBuffer = this.#buffer.child()\n /**\n * Parse the value once the condition is true\n */\n if ('parseFnId' in child.schema) {\n conditionalBuffer.writeStatement(\n callParseFunction({", "score": 27.147293305475355 } ]
typescript
group.conditions.forEach((condition, index) => {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js' /** * Compiles an object schema node to JS string output. */ export class ObjectNodeCompiler extends BaseNode { #node: ObjectNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ObjectNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Returns known field names for the object */ #getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] { let fieldNames = node.properties.map((child) => child.fieldName) const groupsFieldNames = node.groups.flatMap
((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) }
/** * Returns field names of a group. */ #getGroupFieldNames(group: ObjectGroupNode): string[] { return group.conditions.flatMap((condition) => { return this.#getFieldNames(condition.schema) }) } /** * Compiles object children to JS output */ #compileObjectChildren() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent)) return buffer.toString() } /** * Compiles object groups with conditions to JS output. */ #compileObjectGroups() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent)) return buffer.toString() } /** * Compiles an object groups recursively */ #compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) { group.conditions.forEach((condition, index) => { const guardBuffer = buffer.child() condition.schema.properties.forEach((child) => { this.#compiler.compileNode(child, guardBuffer, parent) }) condition.schema.groups.forEach((child) => { this.#compileObjectGroup(child, guardBuffer, parent) }) buffer.writeStatement( defineConditionalGuard({ variableName: this.field.variableName, conditional: index === 0 ? 'if' : 'else if', conditionalFnRefId: condition.conditionalFnRefId, guardedCodeSnippet: guardBuffer.toString(), }) ) }) /** * Define else block */ if (group.elseConditionalFnRefId && group.conditions.length) { buffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: group.elseConditionalFnRefId, }) ) } } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + object children validations * validation inside `if object field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: '{}', })}${this.#buffer.newLine}${this.#compileObjectChildren()}${ this.#buffer.newLine }${this.#compileObjectGroups()}${this.#buffer.newLine}${defineMoveProperties({ variableName: this.field.variableName, allowUnknownProperties: this.#node.allowUnknownProperties, fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [], })}`, }) /** * Wrapping field validations + "isObjectValidBlock" inside * `if value is object` check. * * Pre step: 3 */ const isValueAnObject = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({ variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, conditional: 'else if', })}` ) } }
src/compiler/nodes/object.ts
vinejs-compiler-8909bb5
[ { "filename": "src/types.ts", "retrieved_chunk": " /**\n * Object known properties\n */\n properties: CompilerNodes[]\n /**\n * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]", "score": 35.71584559543323 }, { "filename": "src/types.ts", "retrieved_chunk": " * A collection of object groups to merge into the main object.\n * Each group is a collection of conditionals with a sub-object\n * inside them.\n */\n groups: ObjectGroupNode[]\n }\n }[]\n}\n/**\n * Shape of the tuple node accepted by the compiler", "score": 24.861571657428954 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " #compileTupleChildren() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'tuple',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => {", "score": 21.27983454995614 }, { "filename": "src/types.ts", "retrieved_chunk": " /**\n * Tuple known properties\n */\n properties: CompilerNodes[]\n}\n/**\n * Shape of the record node accepted by the compiler\n */\nexport type RecordNode = FieldNode & {\n type: 'record'", "score": 18.446556078948163 }, { "filename": "src/compiler/fields/tuple_field.ts", "retrieved_chunk": " node: Pick<FieldNode, 'fieldName' | 'propertyName'>,\n parent: CompilerParent\n): CompilerField {\n /**\n * Commented to see if a use case arrives for using this.\n */\n // const fieldPathExpression =\n // parent.fieldPathExpression !== `''`\n // ? `${parent.fieldPathExpression} + '.' + '${node.fieldName}'`\n // : `'${node.fieldName}'`", "score": 17.989914995965766 } ]
typescript
((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) }
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { callParseFunction } from '../../scripts/union/parse.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import type { CompilerField, CompilerParent, UnionNode } from '../../types.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' /** * Compiles a union schema node to JS string output. */ export class UnionNodeCompiler extends BaseNode { #compiler: Compiler #node: UnionNode #buffer: CompilerBuffer #parent: CompilerParent constructor( node: UnionNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#parent = parent this.#compiler = compiler } /** * Compiles union children by wrapping each conditon inside a conditional * guard block */ #compileUnionChildren() { const childrenBuffer = this.#buffer.child() this.#node
.conditions.forEach((child, index) => {
const conditionalBuffer = this.#buffer.child() /** * Parse the value once the condition is true */ if ('parseFnId' in child.schema) { conditionalBuffer.writeStatement( callParseFunction({ parseFnRefId: child.schema.parseFnId, variableName: this.field.variableName, }) ) } this.#compiler.compileNode(child.schema, conditionalBuffer, this.#parent, this.field) childrenBuffer.writeStatement( defineConditionalGuard({ conditional: index === 0 ? 'if' : 'else if', variableName: this.field.variableName, conditionalFnRefId: child.conditionalFnRefId, guardedCodeSnippet: conditionalBuffer.toString(), }) ) conditionalBuffer.flush() }) /** * Define else block */ if (this.#node.elseConditionalFnRefId && this.#node.conditions.length) { childrenBuffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: this.#node.elseConditionalFnRefId, }) ) } return childrenBuffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Compile union children wrapped inside predicate * condition. */ this.#buffer.writeStatement(this.#compileUnionChildren()) } }
src/compiler/nodes/union.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " group.conditions.forEach((condition, index) => {\n const guardBuffer = buffer.child()\n condition.schema.properties.forEach((child) => {\n this.#compiler.compileNode(child, guardBuffer, parent)\n })\n condition.schema.groups.forEach((child) => {\n this.#compileObjectGroup(child, guardBuffer, parent)\n })\n buffer.writeStatement(\n defineConditionalGuard({", "score": 29.1856268199667 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))\n return buffer.toString()", "score": 18.918394199076253 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " */\n #compileRecordElements() {\n const buffer = this.#buffer.child()\n const recordElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, recordElementsBuffer, {\n type: 'record',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,", "score": 17.831995967224273 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " #compileTupleChildren() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'tuple',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => {", "score": 16.912619967466693 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " }\n /**\n * Compiles object groups with conditions to JS output.\n */\n #compileObjectGroups() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,", "score": 16.506851306575836 } ]
typescript
.conditions.forEach((child, index) => {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js' /** * Compiles an object schema node to JS string output. */ export class ObjectNodeCompiler extends BaseNode { #node: ObjectNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ObjectNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Returns known field names for the object */ #getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] { let fieldNames = node.properties.map((child) => child.fieldName) const groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) } /** * Returns field names of a group. */ #getGroupFieldNames(group: ObjectGroupNode): string[] { return group.conditions.flatMap((condition) => { return this.#getFieldNames(condition.schema) }) } /** * Compiles object children to JS output */ #compileObjectChildren() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent)) return buffer.toString() } /** * Compiles object groups with conditions to JS output. */ #compileObjectGroups() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent)) return buffer.toString() } /** * Compiles an object groups recursively */ #compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) { group.conditions.forEach((condition, index) => { const guardBuffer = buffer.child() condition.schema.properties.forEach((child) => { this.#compiler.compileNode(child, guardBuffer, parent) }) condition.schema.groups.forEach((child) => { this.#compileObjectGroup(child, guardBuffer, parent) }) buffer.writeStatement( defineConditionalGuard({ variableName: this.field.variableName, conditional: index === 0 ? 'if' : 'else if', conditionalFnRefId: condition.conditionalFnRefId, guardedCodeSnippet: guardBuffer.toString(), }) ) }) /** * Define else block */ if (group.elseConditionalFnRefId && group.conditions.length) { buffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: group.elseConditionalFnRefId, }) ) } } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + object children validations * validation inside `if object field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: '{}', })}${this.#buffer.newLine}${this.#compileObjectChildren()}${ this.#buffer.newLine }${this.#compileObjectGroups()}${this.#buffer.newLine}${defineMoveProperties({ variableName: this.field.variableName, allowUnknownProperties: this.#node.allowUnknownProperties, fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [], })}`, }) /** * Wrapping field validations + "isObjectValidBlock" inside * `if value is object` check. * * Pre step: 3 */ const isValueAnObject = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement(
`${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({
variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, conditional: 'else if', })}` ) } }
src/compiler/nodes/object.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isObjectValidBlock}`,\n })\n /**\n * Step 3: Define `if value is an object` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(", "score": 62.53669939963605 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " variableName: this.field.variableName,\n validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isArrayValidBlock}`,\n })\n /**\n * Step 3: Define `if value is an array` block and `else if value is null`\n * block.\n */", "score": 53.013571460744544 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " })\n /**\n * Step 3: Define `if value is an array` block and `else if value is null`\n * block.\n */\n this.#buffer.writeStatement(\n `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,", "score": 45.144161675553995 }, { "filename": "src/compiler/nodes/literal.ts", "retrieved_chunk": " * Step 4: Define block to save the output value or the null value\n */\n this.#buffer.writeStatement(\n `${defineFieldValueOutput({\n variableName: this.field.variableName,\n outputExpression: this.field.outputExpression,\n transformFnRefId: this.#node.transformFnId,\n })}${this.#buffer.newLine}${defineFieldNullOutput({\n variableName: this.field.variableName,\n allowNull: this.#node.allowNull,", "score": 25.86321992438523 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " * Pre step: 3\n */\n const isValueAnArrayBlock = defineArrayGuard({\n variableName: this.field.variableName,\n guardedCodeSnippet: `${defineFieldValidations({\n variableName: this.field.variableName,\n validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isArrayValidBlock}`,", "score": 23.00582824190429 } ]
typescript
`${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineRecordLoop } from '../../scripts/record/loop.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import type { CompilerField, CompilerParent, RecordNode } from '../../types.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles a record schema node to JS string output. */ export class RecordNodeCompiler extends BaseNode { #node: RecordNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: RecordNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Compiles the record elements to a JS fragment */ #compileRecordElements() { const buffer = this.#buffer.child() const recordElementsBuffer = this.#buffer.child() this.#compiler.compileNode(this.#node.each, recordElementsBuffer, { type: 'record', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, }) buffer.writeStatement( defineRecordLoop({ variableName: this.field.variableName, loopCodeSnippet: recordElementsBuffer.toString(), }) ) recordElementsBuffer.flush() return buffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + tuple validation + array elements * validation inside `if array field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: `{}`, })}${this.#compileRecordElements()}`, }) /** * Wrapping field validations + "isArrayValidBlock" inside * `if value is array` check. * * Pre step: 3 */
const isValueAnObjectBlock = defineObjectGuard({
variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${this.#buffer.newLine}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObjectBlock}${this.#buffer.newLine}${defineFieldNullOutput({ allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, variableName: this.field.variableName, conditional: 'else if', })}` ) } }
src/compiler/nodes/record.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " })\n /**\n * Wrapping field validations + \"isArrayValidBlock\" inside\n * `if value is array` check.\n *\n * Pre step: 3\n */\n const isValueAnArrayBlock = defineArrayGuard({\n variableName: this.field.variableName,\n guardedCodeSnippet: `${defineFieldValidations({", "score": 36.61484605556192 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " outputExpression: this.field.outputExpression,\n outputValueExpression: this.#node.allowUnknownProperties\n ? `copyProperties(${this.field.variableName}.value)`\n : `[]`,\n })}${this.#compileTupleChildren()}`,\n })\n /**\n * Wrapping field validations + \"isArrayValidBlock\" inside\n * `if value is array` check.\n *", "score": 26.855253026602025 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " variableName: this.field.variableName,\n allowUnknownProperties: this.#node.allowUnknownProperties,\n fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [],\n })}`,\n })\n /**\n * Wrapping field validations + \"isObjectValidBlock\" inside\n * `if value is object` check.\n *\n * Pre step: 3", "score": 25.99989424025043 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " * Wrapping initialization of output + tuple validation\n * validation inside `if array field is valid` block.\n *\n * Pre step: 3\n */\n const isArrayValidBlock = defineIsValidGuard({\n variableName: this.field.variableName,\n bail: this.#node.bail,\n guardedCodeSnippet: `${defineArrayInitialOutput({\n variableName: this.field.variableName,", "score": 23.770156712437416 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " isOptional: this.#node.isOptional,\n variableName: this.field.variableName,\n })\n )\n /**\n * Wrapping initialization of output + object children validations\n * validation inside `if object field is valid` block.\n *\n * Pre step: 3\n */", "score": 22.17116789493159 } ]
typescript
const isValueAnObjectBlock = defineObjectGuard({
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js' /** * Compiles an object schema node to JS string output. */ export class ObjectNodeCompiler extends BaseNode { #node: ObjectNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ObjectNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Returns known field names for the object */ #getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] { let fieldNames = node.properties.map((child) => child.fieldName) const groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) } /** * Returns field names of a group. */ #getGroupFieldNames(group: ObjectGroupNode): string[] { return group.conditions.flatMap((condition) => { return this.#getFieldNames(condition.schema) }) } /** * Compiles object children to JS output */ #compileObjectChildren() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.properties.forEach((
child) => this.#compiler.compileNode(child, buffer, parent)) return buffer.toString() }
/** * Compiles object groups with conditions to JS output. */ #compileObjectGroups() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent)) return buffer.toString() } /** * Compiles an object groups recursively */ #compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) { group.conditions.forEach((condition, index) => { const guardBuffer = buffer.child() condition.schema.properties.forEach((child) => { this.#compiler.compileNode(child, guardBuffer, parent) }) condition.schema.groups.forEach((child) => { this.#compileObjectGroup(child, guardBuffer, parent) }) buffer.writeStatement( defineConditionalGuard({ variableName: this.field.variableName, conditional: index === 0 ? 'if' : 'else if', conditionalFnRefId: condition.conditionalFnRefId, guardedCodeSnippet: guardBuffer.toString(), }) ) }) /** * Define else block */ if (group.elseConditionalFnRefId && group.conditions.length) { buffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: group.elseConditionalFnRefId, }) ) } } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + object children validations * validation inside `if object field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: '{}', })}${this.#buffer.newLine}${this.#compileObjectChildren()}${ this.#buffer.newLine }${this.#compileObjectGroups()}${this.#buffer.newLine}${defineMoveProperties({ variableName: this.field.variableName, allowUnknownProperties: this.#node.allowUnknownProperties, fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [], })}`, }) /** * Wrapping field validations + "isObjectValidBlock" inside * `if value is object` check. * * Pre step: 3 */ const isValueAnObject = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({ variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, conditional: 'else if', })}` ) } }
src/compiler/nodes/object.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " #compileTupleChildren() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'tuple',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => {", "score": 54.1735343688697 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " */\n #compileRecordElements() {\n const buffer = this.#buffer.child()\n const recordElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, recordElementsBuffer, {\n type: 'record',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,", "score": 45.35346474041425 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " */\n #compileArrayElements() {\n const arrayElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, arrayElementsBuffer, {\n type: 'array',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n })", "score": 42.89883877593658 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " this.#compiler.compileNode(child, buffer, parent)\n })\n return buffer.toString()\n }\n compile() {\n /**\n * Define 1: Define field variable\n */\n this.defineField(this.#buffer)\n /**", "score": 28.43315169097926 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n buffer.writeStatement(\n defineArrayLoop({\n variableName: this.field.variableName,\n startingIndex: 0,\n loopCodeSnippet: arrayElementsBuffer.toString(),\n })\n )\n arrayElementsBuffer.flush()\n return buffer.toString()", "score": 25.700053262331668 } ]
typescript
child) => this.#compiler.compileNode(child, buffer, parent)) return buffer.toString() }
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ValidationNode } from '../../types.js' /** * Options accepts by the validation script */ type ValidationOptions = { bail: boolean variableName: string validations: ValidationNode[] /** * Drop missing conditional check regardless of whether * rule is implicit or not */ dropMissingCheck: boolean } /** * Helper to generate a conditional based upon enabled conditions. */ function wrapInConditional(conditions: [string, string], wrappingCode: string) { const [first, second] = conditions if (first && second) { return `if (${first} && ${second}) { ${wrappingCode} }` } if (first) { return `if (${first}) { ${wrappingCode} }` } if (second) { return `if (${second}) { ${wrappingCode} }` } return wrappingCode } /** * Emits code for executing a validation function */ function emitValidationSnippet( { isAsync, implicit,
ruleFnId }: ValidationNode, variableName: string, bail: boolean, dropMissingCheck: boolean ) {
const rule = `refs['${ruleFnId}']` const callable = `${rule}.validator(${variableName}.value, ${rule}.options, ${variableName});` /** * Add "isValid" condition when the bail flag is turned on. */ const bailCondition = bail ? `${variableName}.isValid` : '' /** * Add the "!is_[variableName]_missing" conditional when the rule is not implicit. */ const implicitCondition = implicit || dropMissingCheck ? '' : `${variableName}.isDefined` /** * Wrapping the validation invocation inside conditionals based upon * enabled flags. */ return wrapInConditional( [bailCondition, implicitCondition], isAsync ? `await ${callable}` : `${callable}` ) } /** * Returns JS fragment for executing validations for a given field. */ export function defineFieldValidations({ bail, validations, variableName, dropMissingCheck, }: ValidationOptions) { return `${validations .map((one) => emitValidationSnippet(one, variableName, bail, dropMissingCheck)) .join('\n')}` }
src/scripts/field/validations.ts
vinejs-compiler-8909bb5
[ { "filename": "src/types.ts", "retrieved_chunk": " */\nexport type ValidationNode = {\n /**\n * Rule implementation function id.\n */\n ruleFnId: RefIdentifier\n /**\n * Is this an async rule. This flag helps creating an optimized output\n */\n isAsync: boolean", "score": 23.61079764531545 }, { "filename": "src/scripts/field/is_valid_guard.ts", "retrieved_chunk": " bail: boolean\n guardedCodeSnippet: string\n}\n/**\n * Returns JS fragment to wrap code inside a valid guard\n */\nexport function defineIsValidGuard({ variableName, bail, guardedCodeSnippet }: ObjectGuardOptions) {\n if (!bail) {\n return guardedCodeSnippet\n }", "score": 17.274009877900532 }, { "filename": "src/scripts/field/existence_validations.ts", "retrieved_chunk": " isOptional: boolean\n allowNull: boolean\n}\n/**\n * Returns JS fragment to validate a field's value for existence.\n */\nexport function defineFieldExistenceValidations({\n allowNull,\n isOptional,\n variableName,", "score": 14.246369628845885 }, { "filename": "src/types.ts", "retrieved_chunk": " /**\n * The rules are skipped when the value of a field is \"null\" or \"undefined\".\n * Unless, the \"implicit\" flag is true\n */\n implicit: boolean\n}\n/**\n * Shape of field inside a schema.\n */\nexport type FieldNode = {", "score": 12.869008880234688 }, { "filename": "src/types.ts", "retrieved_chunk": " * The error reporter is used for reporting validation\n * errors.\n */\nexport interface ErrorReporterContract {\n /**\n * A boolean to known if there are one or more\n * errors.\n */\n hasErrors: boolean\n /**", "score": 10.926340215224457 } ]
typescript
ruleFnId }: ValidationNode, variableName: string, bail: boolean, dropMissingCheck: boolean ) {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { callParseFunction } from '../../scripts/union/parse.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import type { CompilerField, CompilerParent, UnionNode } from '../../types.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' /** * Compiles a union schema node to JS string output. */ export class UnionNodeCompiler extends BaseNode { #compiler: Compiler #node: UnionNode #buffer: CompilerBuffer #parent: CompilerParent constructor( node: UnionNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#parent = parent this.#compiler = compiler } /** * Compiles union children by wrapping each conditon inside a conditional * guard block */ #compileUnionChildren() { const childrenBuffer = this.#buffer.child() this.#node.conditions.forEach((child, index) => { const conditionalBuffer = this.#buffer.child() /** * Parse the value once the condition is true */ if ('parseFnId' in child.schema) { conditionalBuffer.writeStatement( callParseFunction({ parseFnRefId: child.schema.parseFnId, variableName: this.field.variableName, }) ) }
this.#compiler.compileNode(child.schema, conditionalBuffer, this.#parent, this.field) childrenBuffer.writeStatement( defineConditionalGuard({
conditional: index === 0 ? 'if' : 'else if', variableName: this.field.variableName, conditionalFnRefId: child.conditionalFnRefId, guardedCodeSnippet: conditionalBuffer.toString(), }) ) conditionalBuffer.flush() }) /** * Define else block */ if (this.#node.elseConditionalFnRefId && this.#node.conditions.length) { childrenBuffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: this.#node.elseConditionalFnRefId, }) ) } return childrenBuffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Compile union children wrapped inside predicate * condition. */ this.#buffer.writeStatement(this.#compileUnionChildren()) } }
src/compiler/nodes/union.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " group.conditions.forEach((condition, index) => {\n const guardBuffer = buffer.child()\n condition.schema.properties.forEach((child) => {\n this.#compiler.compileNode(child, guardBuffer, parent)\n })\n condition.schema.groups.forEach((child) => {\n this.#compileObjectGroup(child, guardBuffer, parent)\n })\n buffer.writeStatement(\n defineConditionalGuard({", "score": 32.34117951369155 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))\n return buffer.toString()", "score": 18.326886079357646 }, { "filename": "src/scripts/union/parse.ts", "retrieved_chunk": " variableName: string\n parseFnRefId?: RefIdentifier\n}\n/**\n * Returns JS fragment to call the parse function on the union conditional\n * schema.\n */\nexport function callParseFunction({ parseFnRefId, variableName }: FieldOptions) {\n if (parseFnRefId) {\n return `${variableName}.value = refs['${parseFnRefId}'](${variableName}.value);`", "score": 17.541088124295246 }, { "filename": "src/compiler/main.ts", "retrieved_chunk": " */\n #finishJSOutput() {\n this.#buffer.writeStatement(reportErrors())\n this.#buffer.writeStatement('return out;')\n }\n /**\n * Compiles all the nodes\n */\n #compileNodes() {\n this.compileNode(this.#rootNode.schema, this.#buffer, {", "score": 17.01263442794499 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " this.#compiler.compileNode(child, buffer, parent)\n })\n return buffer.toString()\n }\n compile() {\n /**\n * Define 1: Define field variable\n */\n this.defineField(this.#buffer)\n /**", "score": 15.830176306425308 } ]
typescript
this.#compiler.compileNode(child.schema, conditionalBuffer, this.#parent, this.field) childrenBuffer.writeStatement( defineConditionalGuard({
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ValidationNode } from '../../types.js' /** * Options accepts by the validation script */ type ValidationOptions = { bail: boolean variableName: string validations: ValidationNode[] /** * Drop missing conditional check regardless of whether * rule is implicit or not */ dropMissingCheck: boolean } /** * Helper to generate a conditional based upon enabled conditions. */ function wrapInConditional(conditions: [string, string], wrappingCode: string) { const [first, second] = conditions if (first && second) { return `if (${first} && ${second}) { ${wrappingCode} }` } if (first) { return `if (${first}) { ${wrappingCode} }` } if (second) { return `if (${second}) { ${wrappingCode} }` } return wrappingCode } /** * Emits code for executing a validation function */ function emitValidationSnippet(
{ isAsync, implicit, ruleFnId }: ValidationNode, variableName: string, bail: boolean, dropMissingCheck: boolean ) {
const rule = `refs['${ruleFnId}']` const callable = `${rule}.validator(${variableName}.value, ${rule}.options, ${variableName});` /** * Add "isValid" condition when the bail flag is turned on. */ const bailCondition = bail ? `${variableName}.isValid` : '' /** * Add the "!is_[variableName]_missing" conditional when the rule is not implicit. */ const implicitCondition = implicit || dropMissingCheck ? '' : `${variableName}.isDefined` /** * Wrapping the validation invocation inside conditionals based upon * enabled flags. */ return wrapInConditional( [bailCondition, implicitCondition], isAsync ? `await ${callable}` : `${callable}` ) } /** * Returns JS fragment for executing validations for a given field. */ export function defineFieldValidations({ bail, validations, variableName, dropMissingCheck, }: ValidationOptions) { return `${validations .map((one) => emitValidationSnippet(one, variableName, bail, dropMissingCheck)) .join('\n')}` }
src/scripts/field/validations.ts
vinejs-compiler-8909bb5
[ { "filename": "src/types.ts", "retrieved_chunk": " */\nexport type ValidationNode = {\n /**\n * Rule implementation function id.\n */\n ruleFnId: RefIdentifier\n /**\n * Is this an async rule. This flag helps creating an optimized output\n */\n isAsync: boolean", "score": 23.61079764531545 }, { "filename": "src/scripts/field/is_valid_guard.ts", "retrieved_chunk": " bail: boolean\n guardedCodeSnippet: string\n}\n/**\n * Returns JS fragment to wrap code inside a valid guard\n */\nexport function defineIsValidGuard({ variableName, bail, guardedCodeSnippet }: ObjectGuardOptions) {\n if (!bail) {\n return guardedCodeSnippet\n }", "score": 17.274009877900532 }, { "filename": "src/scripts/field/existence_validations.ts", "retrieved_chunk": " isOptional: boolean\n allowNull: boolean\n}\n/**\n * Returns JS fragment to validate a field's value for existence.\n */\nexport function defineFieldExistenceValidations({\n allowNull,\n isOptional,\n variableName,", "score": 14.246369628845885 }, { "filename": "src/types.ts", "retrieved_chunk": " /**\n * The rules are skipped when the value of a field is \"null\" or \"undefined\".\n * Unless, the \"implicit\" flag is true\n */\n implicit: boolean\n}\n/**\n * Shape of field inside a schema.\n */\nexport type FieldNode = {", "score": 12.869008880234688 }, { "filename": "src/types.ts", "retrieved_chunk": " * The error reporter is used for reporting validation\n * errors.\n */\nexport interface ErrorReporterContract {\n /**\n * A boolean to known if there are one or more\n * errors.\n */\n hasErrors: boolean\n /**", "score": 10.926340215224457 } ]
typescript
{ isAsync, implicit, ruleFnId }: ValidationNode, variableName: string, bail: boolean, dropMissingCheck: boolean ) {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineRecordLoop } from '../../scripts/record/loop.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import type { CompilerField, CompilerParent, RecordNode } from '../../types.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles a record schema node to JS string output. */ export class RecordNodeCompiler extends BaseNode { #node: RecordNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: RecordNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Compiles the record elements to a JS fragment */ #compileRecordElements() { const buffer = this.#buffer.child() const recordElementsBuffer = this.#buffer.child() this.#compiler
.compileNode(this.#node.each, recordElementsBuffer, {
type: 'record', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, }) buffer.writeStatement( defineRecordLoop({ variableName: this.field.variableName, loopCodeSnippet: recordElementsBuffer.toString(), }) ) recordElementsBuffer.flush() return buffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + tuple validation + array elements * validation inside `if array field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: `{}`, })}${this.#compileRecordElements()}`, }) /** * Wrapping field validations + "isArrayValidBlock" inside * `if value is array` check. * * Pre step: 3 */ const isValueAnObjectBlock = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${this.#buffer.newLine}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObjectBlock}${this.#buffer.newLine}${defineFieldNullOutput({ allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, variableName: this.field.variableName, conditional: 'else if', })}` ) } }
src/compiler/nodes/record.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))\n return buffer.toString()", "score": 25.329800598727008 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " parent: CompilerParent,\n parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }\n /**\n * Compiles the array elements to a JS fragment", "score": 24.951624323551567 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " group.conditions.forEach((condition, index) => {\n const guardBuffer = buffer.child()\n condition.schema.properties.forEach((child) => {\n this.#compiler.compileNode(child, guardBuffer, parent)\n })\n condition.schema.groups.forEach((child) => {\n this.#compileObjectGroup(child, guardBuffer, parent)\n })\n buffer.writeStatement(\n defineConditionalGuard({", "score": 24.009369417239736 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " */\n #compileArrayElements() {\n const arrayElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, arrayElementsBuffer, {\n type: 'array',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n })", "score": 22.81307420218863 }, { "filename": "src/compiler/main.ts", "retrieved_chunk": " case 'record':\n return createRecordField(parent)\n }\n }\n /**\n * Compiles a given compiler node\n */\n compileNode(\n node: CompilerNodes,\n buffer: CompilerBuffer,", "score": 22.461253734614743 } ]
typescript
.compileNode(this.#node.each, recordElementsBuffer, {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { callParseFunction } from '../../scripts/union/parse.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import type { CompilerField, CompilerParent, UnionNode } from '../../types.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' /** * Compiles a union schema node to JS string output. */ export class UnionNodeCompiler extends BaseNode { #compiler: Compiler #node: UnionNode #buffer: CompilerBuffer #parent: CompilerParent constructor( node: UnionNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#parent = parent this.#compiler = compiler } /** * Compiles union children by wrapping each conditon inside a conditional * guard block */ #compileUnionChildren() {
const childrenBuffer = this.#buffer.child() this.#node.conditions.forEach((child, index) => {
const conditionalBuffer = this.#buffer.child() /** * Parse the value once the condition is true */ if ('parseFnId' in child.schema) { conditionalBuffer.writeStatement( callParseFunction({ parseFnRefId: child.schema.parseFnId, variableName: this.field.variableName, }) ) } this.#compiler.compileNode(child.schema, conditionalBuffer, this.#parent, this.field) childrenBuffer.writeStatement( defineConditionalGuard({ conditional: index === 0 ? 'if' : 'else if', variableName: this.field.variableName, conditionalFnRefId: child.conditionalFnRefId, guardedCodeSnippet: conditionalBuffer.toString(), }) ) conditionalBuffer.flush() }) /** * Define else block */ if (this.#node.elseConditionalFnRefId && this.#node.conditions.length) { childrenBuffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: this.#node.elseConditionalFnRefId, }) ) } return childrenBuffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Compile union children wrapped inside predicate * condition. */ this.#buffer.writeStatement(this.#compileUnionChildren()) } }
src/compiler/nodes/union.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " group.conditions.forEach((condition, index) => {\n const guardBuffer = buffer.child()\n condition.schema.properties.forEach((child) => {\n this.#compiler.compileNode(child, guardBuffer, parent)\n })\n condition.schema.groups.forEach((child) => {\n this.#compileObjectGroup(child, guardBuffer, parent)\n })\n buffer.writeStatement(\n defineConditionalGuard({", "score": 33.4309842091123 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))\n return buffer.toString()", "score": 22.89353865007845 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " #compileTupleChildren() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'tuple',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => {", "score": 19.91918450281131 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " }\n /**\n * Compiles object groups with conditions to JS output.\n */\n #compileObjectGroups() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,", "score": 19.817407347001637 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }\n /**\n * Compiles the tuple children to a JS fragment\n */", "score": 18.83746414098518 } ]
typescript
const childrenBuffer = this.#buffer.child() this.#node.conditions.forEach((child, index) => {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineArrayGuard } from '../../scripts/array/guard.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import type { CompilerField, CompilerParent, TupleNode } from '../../types.js' import { defineArrayInitialOutput } from '../../scripts/array/initial_output.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles a tuple schema node to JS string output. */ export class TupleNodeCompiler extends BaseNode { #node: TupleNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: TupleNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Compiles the tuple children to a JS fragment */ #compileTupleChildren() { const buffer = this.#buffer.child() const parent = { type: 'tuple', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.properties.forEach((child) => {
this.#compiler.compileNode(child, buffer, parent) }) return buffer.toString() }
compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + tuple validation * validation inside `if array field is valid` block. * * Pre step: 3 */ const isArrayValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineArrayInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: this.#node.allowUnknownProperties ? `copyProperties(${this.field.variableName}.value)` : `[]`, })}${this.#compileTupleChildren()}`, }) /** * Wrapping field validations + "isArrayValidBlock" inside * `if value is array` check. * * Pre step: 3 */ const isValueAnArrayBlock = defineArrayGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${this.#buffer.newLine}${isArrayValidBlock}`, }) /** * Step 3: Define `if value is an array` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({ allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, variableName: this.field.variableName, conditional: 'else if', })}` ) } }
src/compiler/nodes/tuple.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))\n return buffer.toString()", "score": 56.05991606191001 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " */\n #compileRecordElements() {\n const buffer = this.#buffer.child()\n const recordElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, recordElementsBuffer, {\n type: 'record',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,", "score": 42.40201705888352 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " */\n #compileArrayElements() {\n const arrayElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, arrayElementsBuffer, {\n type: 'array',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n })", "score": 40.053204457476724 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " group.conditions.forEach((condition, index) => {\n const guardBuffer = buffer.child()\n condition.schema.properties.forEach((child) => {\n this.#compiler.compileNode(child, guardBuffer, parent)\n })\n condition.schema.groups.forEach((child) => {\n this.#compileObjectGroup(child, guardBuffer, parent)\n })\n buffer.writeStatement(\n defineConditionalGuard({", "score": 30.900527209133617 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " }\n /**\n * Compiles object groups with conditions to JS output.\n */\n #compileObjectGroups() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,", "score": 30.820002900567363 } ]
typescript
this.#compiler.compileNode(child, buffer, parent) }) return buffer.toString() }
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineRecordLoop } from '../../scripts/record/loop.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import type { CompilerField, CompilerParent, RecordNode } from '../../types.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles a record schema node to JS string output. */ export class RecordNodeCompiler extends BaseNode { #node: RecordNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: RecordNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Compiles the record elements to a JS fragment */ #compileRecordElements() { const buffer = this.#buffer.child() const recordElementsBuffer = this.#buffer.child() this.#compiler.compileNode(this.
#node.each, recordElementsBuffer, {
type: 'record', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, }) buffer.writeStatement( defineRecordLoop({ variableName: this.field.variableName, loopCodeSnippet: recordElementsBuffer.toString(), }) ) recordElementsBuffer.flush() return buffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + tuple validation + array elements * validation inside `if array field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: `{}`, })}${this.#compileRecordElements()}`, }) /** * Wrapping field validations + "isArrayValidBlock" inside * `if value is array` check. * * Pre step: 3 */ const isValueAnObjectBlock = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${this.#buffer.newLine}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObjectBlock}${this.#buffer.newLine}${defineFieldNullOutput({ allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, variableName: this.field.variableName, conditional: 'else if', })}` ) } }
src/compiler/nodes/record.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))\n return buffer.toString()", "score": 25.329800598727008 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " parent: CompilerParent,\n parentField?: CompilerField\n ) {\n super(node, compiler, parent, parentField)\n this.#node = node\n this.#buffer = buffer\n this.#compiler = compiler\n }\n /**\n * Compiles the array elements to a JS fragment", "score": 24.951624323551567 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " group.conditions.forEach((condition, index) => {\n const guardBuffer = buffer.child()\n condition.schema.properties.forEach((child) => {\n this.#compiler.compileNode(child, guardBuffer, parent)\n })\n condition.schema.groups.forEach((child) => {\n this.#compileObjectGroup(child, guardBuffer, parent)\n })\n buffer.writeStatement(\n defineConditionalGuard({", "score": 24.009369417239736 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " */\n #compileArrayElements() {\n const arrayElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, arrayElementsBuffer, {\n type: 'array',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n })", "score": 22.81307420218863 }, { "filename": "src/compiler/main.ts", "retrieved_chunk": " case 'record':\n return createRecordField(parent)\n }\n }\n /**\n * Compiles a given compiler node\n */\n compileNode(\n node: CompilerNodes,\n buffer: CompilerBuffer,", "score": 22.461253734614743 } ]
typescript
#node.each, recordElementsBuffer, {
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineObjectGuard } from '../../scripts/object/guard.js' import { defineElseCondition } from '../../scripts/define_else_conditon.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js' import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js' import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js' /** * Compiles an object schema node to JS string output. */ export class ObjectNodeCompiler extends BaseNode { #node: ObjectNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: ObjectNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Returns known field names for the object */ #getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] { let fieldNames = node.properties.map((child) => child.fieldName) const groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group)) return fieldNames.concat(groupsFieldNames) } /** * Returns field names of a group. */ #getGroupFieldNames(group: ObjectGroupNode): string[] { return group.conditions.flatMap((condition) => { return this.#getFieldNames(condition.schema) }) } /** * Compiles object children to JS output */ #compileObjectChildren() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent)) return buffer.toString() } /** * Compiles object groups with conditions to JS output. */ #compileObjectGroups() { const buffer = this.#buffer.child() const parent = { type: 'object', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent)) return buffer.toString() } /** * Compiles an object groups recursively */ #compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) { group.conditions.forEach((condition, index) => { const guardBuffer = buffer.child() condition.schema.properties.forEach((child) => { this.#compiler.compileNode(child, guardBuffer, parent) }) condition.schema.groups.forEach((child) => { this.#compileObjectGroup(child, guardBuffer, parent) }) buffer.writeStatement( defineConditionalGuard({ variableName: this.field.variableName, conditional: index === 0 ? 'if' : 'else if', conditionalFnRefId: condition.conditionalFnRefId, guardedCodeSnippet: guardBuffer.toString(), }) ) }) /** * Define else block */ if (group.elseConditionalFnRefId && group.conditions.length) { buffer.writeStatement( defineElseCondition({ variableName: this.field.variableName, conditionalFnRefId: group.elseConditionalFnRefId, }) ) } } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + object children validations * validation inside `if object field is valid` block. * * Pre step: 3 */ const isObjectValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineObjectInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: '{}', })}${this.#buffer.newLine}${this.#compileObjectChildren()}${ this.#buffer.newLine }${this.#compileObjectGroups()}${this.#buffer
.newLine}${defineMoveProperties({
variableName: this.field.variableName, allowUnknownProperties: this.#node.allowUnknownProperties, fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [], })}`, }) /** * Wrapping field validations + "isObjectValidBlock" inside * `if value is object` check. * * Pre step: 3 */ const isValueAnObject = defineObjectGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${isObjectValidBlock}`, }) /** * Step 3: Define `if value is an object` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({ variableName: this.field.variableName, allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, conditional: 'else if', })}` ) } }
src/compiler/nodes/object.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " * Pre step: 3\n */\n const isArrayValidBlock = defineIsValidGuard({\n variableName: this.field.variableName,\n bail: this.#node.bail,\n guardedCodeSnippet: `${defineArrayInitialOutput({\n variableName: this.field.variableName,\n outputExpression: this.field.outputExpression,\n outputValueExpression: `[]`,\n })}${this.#buffer.newLine}${this.#compileArrayElements()}`,", "score": 42.1188010617708 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " */\n const isObjectValidBlock = defineIsValidGuard({\n variableName: this.field.variableName,\n bail: this.#node.bail,\n guardedCodeSnippet: `${defineObjectInitialOutput({\n variableName: this.field.variableName,\n outputExpression: this.field.outputExpression,\n outputValueExpression: `{}`,\n })}${this.#compileRecordElements()}`,\n })", "score": 36.73828952058418 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " * Pre step: 3\n */\n const isValueAnArrayBlock = defineArrayGuard({\n variableName: this.field.variableName,\n guardedCodeSnippet: `${defineFieldValidations({\n variableName: this.field.variableName,\n validations: this.#node.validations,\n bail: this.#node.bail,\n dropMissingCheck: true,\n })}${this.#buffer.newLine}${isArrayValidBlock}`,", "score": 33.693691714006505 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " this.#buffer.writeStatement(\n `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n conditional: 'else if',\n })}`\n )\n }\n}", "score": 31.72983754591742 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " `${isValueAnObjectBlock}${this.#buffer.newLine}${defineFieldNullOutput({\n allowNull: this.#node.allowNull,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n conditional: 'else if',\n })}`\n )\n }\n}", "score": 31.459159114265688 } ]
typescript
.newLine}${defineMoveProperties({
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata); const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger.log(`New account created: ${OZcontractAddress}`); } catch (error) { logger.error(`Error while creating new account: ${error}`); } }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false ); if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return;
const quickPick = vscode.window.createQuickPick<IAccountQP>();
quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork"); const provider = getNetworkProvider(context); console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress, selectedAccount.privateKey, "1" ); logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({ classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, }); logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false, gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, }; fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/treeView/AccountTreeView/AccountTreeDataProvider.ts", "retrieved_chunk": " return element;\n }\n async getChildren(element?: Account): Promise<Account[]> {\n const accounts: Array<JSONAccountType> | undefined = getDeployedAccounts(this.context);\n const undeployedAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(this.context);\n if ((accounts === undefined && undeployedAccounts === undefined)){\n return [];\n } else {\n const leaves = [];\n if (accounts !== undefined) {", "score": 37.4394648192714 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": "};\nexport const accountDeployStatus = (\n accounts: Array<JSONAccountType>,\n selectedNetwork: string,\n status: boolean\n) => {\n const networks = [\"goerli-alpha\", \"goerli-alpha-2\", \"mainnet-alpha\"];\n let result: Array<JSONAccountType> | undefined;\n switch (selectedNetwork) {\n case networks[0]: {", "score": 23.256791950633104 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " createAddressFile(`${label}.json`);\n};\nexport const selectCompiledContract = (context: vscode.ExtensionContext) => {\n const contracts = loadAllCompiledContract();\n if (contracts === undefined) {\n logger.log(\"No Contract available.\");\n return;\n }\n const quickPick = vscode.window.createQuickPick<IContractQP>();\n quickPick.items = contracts.map((contract: string) => ({", "score": 21.49204939831711 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " try {\n const contractInfo: Array<ABIFragment> = getContractABI(\n path_,\n selectedContract\n ).abi;\n if (contractInfo === undefined) return;\n const quickPick = vscode.window.createQuickPick<IFunctionQP>();\n quickPick.items = contractInfo.map((account: ABIFragment) => ({\n label: account.name,\n }));", "score": 19.480580101816052 }, { "filename": "src/config/network.ts", "retrieved_chunk": " }\n });\n quickPick.onDidHide(() => {\n quickPick.dispose();\n });\n quickPick.show();\n};\nexport const getNetworkProvider = (\n context: vscode.ExtensionContext\n): Provider | undefined => {", "score": 16.946562676132256 } ]
typescript
const quickPick = vscode.window.createQuickPick<IAccountQP>();
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata); const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger.log(`New account created: ${OZcontractAddress}`); } catch (error) { logger.error(`Error while creating new account: ${error}`); } }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false ); if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork");
const provider = getNetworkProvider(context);
console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress, selectedAccount.privateKey, "1" ); logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({ classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, }); logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false, gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, }; fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/extension.ts", "retrieved_chunk": " if (node.context === \"deployedAccount\") {\n void context.workspaceState.update(\"account\", node.account.accountAddress);\n logger.log(`${node.account.accountAddress} selected`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n abiTreeDataProvider.refresh();\n } else {", "score": 40.27623394200329 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 37.35339391515577 }, { "filename": "src/extension.ts", "retrieved_chunk": " treeDataProvider: accountTreeDataProvider,\n });\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount: string | undefined = context.workspaceState.get(\"account\") as string;\n accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}` : \"Select a deployed account , or create an account and deploy it\";\n // ABI Tree View\n const abiTreeDataProvider = new AbiTreeDataProvider(\n context\n );\n const abiTreeView = vscode.window.createTreeView(\"starkode.abis\", {", "score": 35.367390938907064 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const provider = getNetworkProvider(context) as Provider;\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");", "score": 32.48070639571306 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " logger.error(\"Error: Please open your solidity project to vscode\");\n return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const provider = getNetworkProvider(context) as Provider;\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {", "score": 30.03239465989303 } ]
typescript
const provider = getNetworkProvider(context);
/* * @vinejs/compiler * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseNode } from './base.js' import type { Compiler } from '../main.js' import type { CompilerBuffer } from '../buffer.js' import { defineArrayGuard } from '../../scripts/array/guard.js' import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js' import { defineFieldNullOutput } from '../../scripts/field/null_output.js' import { defineFieldValidations } from '../../scripts/field/validations.js' import type { CompilerField, CompilerParent, TupleNode } from '../../types.js' import { defineArrayInitialOutput } from '../../scripts/array/initial_output.js' import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js' /** * Compiles a tuple schema node to JS string output. */ export class TupleNodeCompiler extends BaseNode { #node: TupleNode #buffer: CompilerBuffer #compiler: Compiler constructor( node: TupleNode, buffer: CompilerBuffer, compiler: Compiler, parent: CompilerParent, parentField?: CompilerField ) { super(node, compiler, parent, parentField) this.#node = node this.#buffer = buffer this.#compiler = compiler } /** * Compiles the tuple children to a JS fragment */ #compileTupleChildren() { const buffer = this.#buffer.child() const parent = { type: 'tuple', fieldPathExpression: this.field.fieldPathExpression, outputExpression: this.field.outputExpression, variableName: this.field.variableName, wildCardPath: this.field.wildCardPath, } as const this
.#node.properties.forEach((child) => {
this.#compiler.compileNode(child, buffer, parent) }) return buffer.toString() } compile() { /** * Define 1: Define field variable */ this.defineField(this.#buffer) /** * Step 2: Define code to validate the existence of field. */ this.#buffer.writeStatement( defineFieldExistenceValidations({ allowNull: this.#node.allowNull, isOptional: this.#node.isOptional, variableName: this.field.variableName, }) ) /** * Wrapping initialization of output + tuple validation * validation inside `if array field is valid` block. * * Pre step: 3 */ const isArrayValidBlock = defineIsValidGuard({ variableName: this.field.variableName, bail: this.#node.bail, guardedCodeSnippet: `${defineArrayInitialOutput({ variableName: this.field.variableName, outputExpression: this.field.outputExpression, outputValueExpression: this.#node.allowUnknownProperties ? `copyProperties(${this.field.variableName}.value)` : `[]`, })}${this.#compileTupleChildren()}`, }) /** * Wrapping field validations + "isArrayValidBlock" inside * `if value is array` check. * * Pre step: 3 */ const isValueAnArrayBlock = defineArrayGuard({ variableName: this.field.variableName, guardedCodeSnippet: `${defineFieldValidations({ variableName: this.field.variableName, validations: this.#node.validations, bail: this.#node.bail, dropMissingCheck: true, })}${this.#buffer.newLine}${isArrayValidBlock}`, }) /** * Step 3: Define `if value is an array` block and `else if value is null` * block. */ this.#buffer.writeStatement( `${isValueAnArrayBlock}${this.#buffer.newLine}${defineFieldNullOutput({ allowNull: this.#node.allowNull, outputExpression: this.field.outputExpression, variableName: this.field.variableName, conditional: 'else if', })}` ) } }
src/compiler/nodes/tuple.ts
vinejs-compiler-8909bb5
[ { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))\n return buffer.toString()", "score": 54.692901244177826 }, { "filename": "src/compiler/nodes/record.ts", "retrieved_chunk": " */\n #compileRecordElements() {\n const buffer = this.#buffer.child()\n const recordElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, recordElementsBuffer, {\n type: 'record',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,", "score": 43.540346617056606 }, { "filename": "src/compiler/nodes/array.ts", "retrieved_chunk": " */\n #compileArrayElements() {\n const arrayElementsBuffer = this.#buffer.child()\n this.#compiler.compileNode(this.#node.each, arrayElementsBuffer, {\n type: 'array',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,\n variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n })", "score": 39.84468714605625 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " }\n /**\n * Compiles object groups with conditions to JS output.\n */\n #compileObjectGroups() {\n const buffer = this.#buffer.child()\n const parent = {\n type: 'object',\n fieldPathExpression: this.field.fieldPathExpression,\n outputExpression: this.field.outputExpression,", "score": 36.226015289339415 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " group.conditions.forEach((condition, index) => {\n const guardBuffer = buffer.child()\n condition.schema.properties.forEach((child) => {\n this.#compiler.compileNode(child, guardBuffer, parent)\n })\n condition.schema.groups.forEach((child) => {\n this.#compileObjectGroup(child, guardBuffer, parent)\n })\n buffer.writeStatement(\n defineConditionalGuard({", "score": 29.95707007197289 } ]
typescript
.#node.properties.forEach((child) => {
import * as vscode from "vscode"; import * as fs from "fs"; import path, { resolve } from "path"; import { logger } from "../lib"; import { ABIFragment, IContractQP, IFunctionQP } from "../types"; import { createABIFile, createAddressFile } from "../utils/functions"; import { getAccountInfo } from "./account"; import { Account, CairoAssembly, Contract, ec, Provider } from "starknet"; import { getNetworkProvider } from "./network"; export const loadAllCompiledContract = () => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const compiledCairoContract = fs .readdirSync(path_) .filter((file) => exportPathOfJSONfiles(path_, file)); return compiledCairoContract; }; const exportPathOfJSONfiles = (path_: string, file: string) => { const filePath = path.join(path_, file); if (path.extname(filePath) === ".json") { const fileData = fs.readFileSync(filePath, { encoding: "utf-8", }); if (JSON.parse(fileData).program) return filePath; if (JSON.parse(fileData).contract_class_version) { return filePath; } } }; export const setContract = async (context: vscode.ExtensionContext, label: string) => { if (label === undefined) { // logger.log("No Contract selected."); return; } void context.workspaceState.update("selectedContract", `${label}.json`); logger.log(`${label} contract selected`); createABIFile(`${label}.json`); createAddressFile(`${label}.json`); }; export const selectCompiledContract = (context: vscode.ExtensionContext) => { const contracts = loadAllCompiledContract(); if (contracts === undefined) { logger.log("No Contract available."); return; } const quickPick = vscode.window.createQuickPick<IContractQP>(); quickPick.items = contracts.map((contract: string) => ({ label: contract.substring(0, contract.length - 5), })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Contract"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; setContract(context, label); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getContractInfo = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_address.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const getContractABI = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_abi.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const isCairo1Contract = (fileName: string): boolean => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return false; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileData = fs.readFileSync( path.join(path_, fileName), { encoding: "utf-8" } ); return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; }; export const declareContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider
= getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const fileName = selectedContract.substring(0, selectedContract.length - 5); if ( !fs.existsSync(path.join(path_, selectedContract)) || !fs.existsSync(path.join(path_, `${fileName}.casm`)) ) { logger.log(`${fileName}.json or ${fileName}.casm must be present.`); return; } const compiledContract = fs.readFileSync( path.join(path_, selectedContract), { encoding: "ascii", } ); const casmFileData = fs .readFileSync(path.join(path_, `${fileName}.casm`)) .toString("ascii"); const casmAssembly: CairoAssembly = JSON.parse(casmFileData); logger.log("Declaring contract..."); const declareResponse = await account.declareAndDeploy({ contract: compiledContract, casm: casmAssembly, }); logger.log( `declare transaction hash: ${declareResponse.deploy.transaction_hash}` ); logger.log(`declare classHash: ${declareResponse.deploy.classHash}`); logger.log("transaction successful"); } catch (error) { logger.log(`Error while contract declaration: ${error}`); } }; export const deployContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); logger.log("Deploying contract..."); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contractInfo = getContractInfo(path_, selectedContract); if (contractInfo.classHash === "") { logger.log("No classHash available for selected contract."); return; } const deployResponse = await account.deployContract({ classHash: contractInfo.classHash, }); logger.log(`transaction hash: ${deployResponse.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(deployResponse.transaction_hash); const { abi: testAbi } = await provider.getClassAt( deployResponse.contract_address ); if (testAbi === undefined) { throw new Error("no abi."); } const myTestContract = new Contract( testAbi, deployResponse.contract_address, provider ); await provider.waitForTransaction(myTestContract.transaction_hash); logger.log(`contract deployed successfully: ${myTestContract.address}`); } catch (error) { logger.log(`Error while contract deployment: ${error}`); } }; export const executeContractFunction = async ( context: vscode.ExtensionContext ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = await getSelectedFunction(path_, selectedContract); const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; export const executeContractFunctionFromTreeView = async ( context: vscode.ExtensionContext, functionabi: ABIFragment ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = functionabi; const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; const getSelectedFunction = ( path_: string, selectedContract: string ): Promise<ABIFragment> => { return new Promise((resolve, reject) => { try { const contractInfo: Array<ABIFragment> = getContractABI( path_, selectedContract ).abi; if (contractInfo === undefined) return; const quickPick = vscode.window.createQuickPick<IFunctionQP>(); quickPick.items = contractInfo.map((account: ABIFragment) => ({ label: account.name, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Function"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; quickPick.dispose(); const functionItem = contractInfo.filter( (i: ABIFragment) => i.name === label ); if (functionItem.length === 0) throw new Error("No function is selected"); resolve(functionItem[0]); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); } catch (error) { reject(error); } }); };
src/config/contract.ts
7finney-starkode-2fba517
[ { "filename": "src/utils/functions.ts", "retrieved_chunk": " }\n};\nexport const createAddressFile = (file: string) => {\n try {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const fileName = file.substring(0, file.length - 5);", "score": 52.32279971911178 }, { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " getTreeItem(element: Abi): TreeItem {\n return element;\n }\n async getChildren(element?: Abi): Promise<Abi[] | undefined> {\n const leaves: Abi[] = [];\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return undefined;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;", "score": 47.8237173962942 }, { "filename": "src/treeView/ABITreeView/functions.ts", "retrieved_chunk": "}\nexport const editInput = async (input: Abi, abiTreeDataProvider: any, fileName: string) => {\n let filePath = \"\";\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return [];\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const file = fileName.substring(0, fileName.length - 5);\n filePath = path.join(path_, \"starkode\", file, `${file}_abi.json`);", "score": 44.14269723592632 }, { "filename": "src/extension.ts", "retrieved_chunk": " if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`);\n watcher.onDidChange((event: vscode.Uri) => {\n const contractName: string | undefined = context.workspaceState.get(\"selectedContract\");\n if (contractName === undefined) {\n abiTreeView.message = \"Select a contract and its ABI functions will appear here.\";", "score": 42.646005617060325 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport * as fs from \"fs\";\nimport path from \"path\";\nimport { logger } from \"../lib\";\nimport { ABIFragment, JSONAccountType, TIsAccountDeployed } from \"../types\";\nexport const createABIFile = (file: string) => {\n try {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return;", "score": 39.08052905220421 } ]
typescript
= getNetworkProvider(context) as Provider;
import * as vscode from "vscode"; import * as fs from "fs"; import path, { resolve } from "path"; import { logger } from "../lib"; import { ABIFragment, IContractQP, IFunctionQP } from "../types"; import { createABIFile, createAddressFile } from "../utils/functions"; import { getAccountInfo } from "./account"; import { Account, CairoAssembly, Contract, ec, Provider } from "starknet"; import { getNetworkProvider } from "./network"; export const loadAllCompiledContract = () => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const compiledCairoContract = fs .readdirSync(path_) .filter((file) => exportPathOfJSONfiles(path_, file)); return compiledCairoContract; }; const exportPathOfJSONfiles = (path_: string, file: string) => { const filePath = path.join(path_, file); if (path.extname(filePath) === ".json") { const fileData = fs.readFileSync(filePath, { encoding: "utf-8", }); if (JSON.parse(fileData).program) return filePath; if (JSON.parse(fileData).contract_class_version) { return filePath; } } }; export const setContract = async (context: vscode.ExtensionContext, label: string) => { if (label === undefined) { // logger.log("No Contract selected."); return; } void context.workspaceState.update("selectedContract", `${label}.json`); logger.log(`${label} contract selected`); createABIFile(`${label}.json`); createAddressFile(`${label}.json`); }; export const selectCompiledContract = (context: vscode.ExtensionContext) => { const contracts = loadAllCompiledContract(); if (contracts === undefined) { logger.log("No Contract available."); return; } const quickPick = vscode.window.createQuickPick
<IContractQP>();
quickPick.items = contracts.map((contract: string) => ({ label: contract.substring(0, contract.length - 5), })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Contract"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; setContract(context, label); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getContractInfo = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_address.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const getContractABI = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_abi.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const isCairo1Contract = (fileName: string): boolean => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return false; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileData = fs.readFileSync( path.join(path_, fileName), { encoding: "utf-8" } ); return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; }; export const declareContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const fileName = selectedContract.substring(0, selectedContract.length - 5); if ( !fs.existsSync(path.join(path_, selectedContract)) || !fs.existsSync(path.join(path_, `${fileName}.casm`)) ) { logger.log(`${fileName}.json or ${fileName}.casm must be present.`); return; } const compiledContract = fs.readFileSync( path.join(path_, selectedContract), { encoding: "ascii", } ); const casmFileData = fs .readFileSync(path.join(path_, `${fileName}.casm`)) .toString("ascii"); const casmAssembly: CairoAssembly = JSON.parse(casmFileData); logger.log("Declaring contract..."); const declareResponse = await account.declareAndDeploy({ contract: compiledContract, casm: casmAssembly, }); logger.log( `declare transaction hash: ${declareResponse.deploy.transaction_hash}` ); logger.log(`declare classHash: ${declareResponse.deploy.classHash}`); logger.log("transaction successful"); } catch (error) { logger.log(`Error while contract declaration: ${error}`); } }; export const deployContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); logger.log("Deploying contract..."); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contractInfo = getContractInfo(path_, selectedContract); if (contractInfo.classHash === "") { logger.log("No classHash available for selected contract."); return; } const deployResponse = await account.deployContract({ classHash: contractInfo.classHash, }); logger.log(`transaction hash: ${deployResponse.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(deployResponse.transaction_hash); const { abi: testAbi } = await provider.getClassAt( deployResponse.contract_address ); if (testAbi === undefined) { throw new Error("no abi."); } const myTestContract = new Contract( testAbi, deployResponse.contract_address, provider ); await provider.waitForTransaction(myTestContract.transaction_hash); logger.log(`contract deployed successfully: ${myTestContract.address}`); } catch (error) { logger.log(`Error while contract deployment: ${error}`); } }; export const executeContractFunction = async ( context: vscode.ExtensionContext ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = await getSelectedFunction(path_, selectedContract); const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; export const executeContractFunctionFromTreeView = async ( context: vscode.ExtensionContext, functionabi: ABIFragment ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = functionabi; const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; const getSelectedFunction = ( path_: string, selectedContract: string ): Promise<ABIFragment> => { return new Promise((resolve, reject) => { try { const contractInfo: Array<ABIFragment> = getContractABI( path_, selectedContract ).abi; if (contractInfo === undefined) return; const quickPick = vscode.window.createQuickPick<IFunctionQP>(); quickPick.items = contractInfo.map((account: ABIFragment) => ({ label: account.name, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Function"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; quickPick.dispose(); const functionItem = contractInfo.filter( (i: ABIFragment) => i.name === label ); if (functionItem.length === 0) throw new Error("No function is selected"); resolve(functionItem[0]); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); } catch (error) { reject(error); } }); };
src/config/contract.ts
7finney-starkode-2fba517
[ { "filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport { isCairo1Contract, loadAllCompiledContract } from \"../../config/contract\";\nexport class ContractTreeDataProvider implements vscode.TreeDataProvider<Contract> {\n constructor(private workspaceRoot: string | undefined) { }\n getTreeItem(element: Contract): vscode.TreeItem {\n return element;\n }\n async getChildren(element?: Contract): Promise<Contract[]> {\n const contracts = loadAllCompiledContract();\n if (contracts === undefined || contracts.length === 0) {", "score": 24.456677100958622 }, { "filename": "src/extension.ts", "retrieved_chunk": " );\n let contractTreeView = vscode.window.createTreeView(\"starkode.contracts\", {\n treeDataProvider: contractTreeDataProvider,\n });\n // if contract tree view is empty\n const contracts = loadAllCompiledContract();\n if (contracts === undefined || contracts.length === 0) {\n contractTreeView.message = \"No contract found. Please compile your contract.\";\n }\n contractTreeView.onDidChangeSelection(event => {", "score": 22.893558778864833 }, { "filename": "src/config/account.ts", "retrieved_chunk": " context: vscode.ExtensionContext\n) => {\n const accounts: Array<JSONAccountType> | undefined =\n await getDeployedAccounts(context);\n if (accounts === undefined) return;\n const quickPick = vscode.window.createQuickPick<IAccountQP>();\n quickPick.items = accounts.map((account: JSONAccountType) => ({\n label: account.accountAddress,\n }));\n quickPick.onDidChangeActive(() => {", "score": 20.138713543297225 }, { "filename": "src/config/account.ts", "retrieved_chunk": " false\n );\n if (accounts === undefined || accounts.length === 0) {\n logger.log(`No undeployed account available on ${selectedNetwork}`);\n return;\n }\n return accounts;\n};\nexport const selectNotDeployedAccount = async (\n context: vscode.ExtensionContext", "score": 18.96966654843511 }, { "filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts", "retrieved_chunk": " vscode.window.showInformationMessage(\"No Contracts in workspace\");\n return [];\n } else {\n const leaves = [];\n for (const file of contracts) {\n leaves.push(new Contract(\n file.slice(0, -5),\n vscode.TreeItemCollapsibleState.None,\n \"contract\",\n isCairo1Contract(file) ? \"file-code\" : \"file-text\"", "score": 18.748288138708613 } ]
typescript
<IContractQP>();
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata);
const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, {
accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger.log(`New account created: ${OZcontractAddress}`); } catch (error) { logger.error(`Error while creating new account: ${error}`); } }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false ); if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork"); const provider = getNetworkProvider(context); console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress, selectedAccount.privateKey, "1" ); logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({ classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, }); logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false, gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, }; fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/config/contract.ts", "retrieved_chunk": " const fileData = fs.readFileSync(\n path.join(path_, \"starkode\", file, `${file}_address.json`),\n { encoding: \"utf-8\" }\n );\n const parsedFileData = JSON.parse(fileData);\n return parsedFileData;\n } catch (error) {\n // console.log(error);\n return undefined;\n }", "score": 36.722586727095795 }, { "filename": "src/config/contract.ts", "retrieved_chunk": "};\nexport const getContractABI = (path_: string, fileName: string) => {\n try {\n const file = fileName.substring(0, fileName.length - 5);\n const fileData = fs.readFileSync(\n path.join(path_, \"starkode\", file, `${file}_abi.json`),\n { encoding: \"utf-8\" }\n );\n const parsedFileData = JSON.parse(fileData);\n return parsedFileData;", "score": 33.977172674927715 }, { "filename": "src/config/contract.ts", "retrieved_chunk": "const exportPathOfJSONfiles = (path_: string, file: string) => {\n const filePath = path.join(path_, file);\n if (path.extname(filePath) === \".json\") {\n const fileData = fs.readFileSync(filePath, {\n encoding: \"utf-8\",\n });\n if (JSON.parse(fileData).program) return filePath;\n if (JSON.parse(fileData).contract_class_version) {\n return filePath;\n }", "score": 25.23554577103923 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " ) {\n const filePath = path.join(path_, file);\n const fileData = fs.readFileSync(filePath, { encoding: \"utf-8\" });\n const isCairo1Contract =\n JSON.parse(fileData).contract_class_version === \"0.1.0\" ? true : false;\n const abi: Array<ABIFragment> = JSON.parse(fileData).abi;\n const abiFunctions = abi.filter((e) => e.type === \"function\");\n const functionsValue = abiFunctions.map((func) => {\n return {\n type: func.type,", "score": 23.744495634504233 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const fileData = fs.readFileSync(\n path.join(path_, fileName),\n { encoding: \"utf-8\" }\n );\n return JSON.parse(fileData).contract_class_version === \"0.1.0\" ? true : false;\n};\nexport const declareContract = async (context: vscode.ExtensionContext) => {\n try {\n if (vscode.workspace.workspaceFolders === undefined) {", "score": 20.90572614451223 } ]
typescript
const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, {
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console.log('Selected nodes:', selectedNodes[0].label); } }); // Account Tree View
const accountTreeDataProvider = new AccountTreeDataProvider( context );
const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await editInput(node, abiTreeDataProvider, selectedContract); }), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/config/contract.ts", "retrieved_chunk": " label: contract.substring(0, contract.length - 5),\n }));\n quickPick.onDidChangeActive(() => {\n quickPick.placeholder = \"Select Contract\";\n });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n setContract(context, label);\n quickPick.dispose();", "score": 16.965870345937127 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 16.71891645351228 }, { "filename": "src/config/account.ts", "retrieved_chunk": " });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n void context.workspaceState.update(\"undeployedAccount\", label);\n logger.log(`${label} selected`);\n quickPick.dispose();\n }\n });\n quickPick.onDidHide(() => {", "score": 15.924898762848303 }, { "filename": "src/config/account.ts", "retrieved_chunk": " quickPick.placeholder = \"Select account\";\n });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n void context.workspaceState.update(\"account\", label);\n logger.log(`${label} selected`);\n quickPick.dispose();\n }\n });", "score": 15.563080496176836 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " quickPick.onDidChangeActive(() => {\n quickPick.placeholder = \"Select Function\";\n });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n quickPick.dispose();\n const functionItem = contractInfo.filter(\n (i: ABIFragment) => i.name === label\n );", "score": 14.506083619252697 } ]
typescript
const accountTreeDataProvider = new AccountTreeDataProvider( context );
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata); const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger
.log(`New account created: ${OZcontractAddress}`);
} catch (error) { logger.error(`Error while creating new account: ${error}`); } }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false ); if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork"); const provider = getNetworkProvider(context); console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress, selectedAccount.privateKey, "1" ); logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({ classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, }); logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false, gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, }; fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/utils/functions.ts", "retrieved_chunk": " fs.writeFileSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_abi.json`),\n JSON.stringify({ isCairo1: isCairo1Contract, abi: functionsValue }, null, 2)\n );\n logger.log(\"ABI file created successfully.\");\n } else {\n logger.log(`${fileName}_abi.json already exist.`);\n }\n } catch (error) {\n logger.log(`Error while writing to file: ${error}`);", "score": 18.741387133037957 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " if (\n !fs.existsSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_address.json`)\n )\n ) {\n fs.writeFileSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_address.json`),\n JSON.stringify({\n name: fileName,\n address: \"\",", "score": 17.055250523886297 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " classHash: \"\",\n }, null, 2)\n );\n logger.log(\"Address file created successfully.\");\n } else {\n logger.log(`${fileName}_address.json already exist.`);\n }\n } catch (error) {\n logger.log(`Error while writing to file: ${error}`);\n }", "score": 8.650057292953651 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const fileData = fs.readFileSync(\n path.join(path_, \"starkode\", file, `${file}_address.json`),\n { encoding: \"utf-8\" }\n );\n const parsedFileData = JSON.parse(fileData);\n return parsedFileData;\n } catch (error) {\n // console.log(error);\n return undefined;\n }", "score": 7.683165515434694 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " {\n encoding: \"ascii\",\n }\n );\n const casmFileData = fs\n .readFileSync(path.join(path_, `${fileName}.casm`))\n .toString(\"ascii\");\n const casmAssembly: CairoAssembly = JSON.parse(casmFileData);\n logger.log(\"Declaring contract...\");\n const declareResponse = await account.declareAndDeploy({", "score": 7.492469893016954 } ]
typescript
.log(`New account created: ${OZcontractAddress}`);
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console.log('Selected nodes:', selectedNodes[0].label); } }); // Account Tree View const accountTreeDataProvider = new AccountTreeDataProvider( context ); const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => {
await editContractAddress(node, context);
}), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await editInput(node, abiTreeDataProvider, selectedContract); }), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/config/account.ts", "retrieved_chunk": "};\nexport const deleteAccount = async (context: vscode.ExtensionContext,node: any) => {\n const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {\n encoding: \"utf-8\",\n });\n const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);\n const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress);\n fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2));\n};\nexport const selectDeployedAccount = async (", "score": 47.356838362088574 }, { "filename": "src/treeView/ContractTreeView/function.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport { Contract as ContractTreeItem } from \"./ContractTreeDataProvider\";\nimport { logger } from \"../../lib\";\nimport path = require(\"path\");\nexport const refreshContract = async (node: ContractTreeItem, contractTreeDataProvider: any): Promise<vscode.TreeView<ContractTreeItem>> => {\n return vscode.window.createTreeView(\"starkode.contracts\", { treeDataProvider: contractTreeDataProvider, });\n};\nexport const editContractAddress = async (input : any,context: vscode.ExtensionContext) => {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Open or Create a cairo project.\");", "score": 44.33697166149795 }, { "filename": "src/config/account.ts", "retrieved_chunk": " quickPick.dispose();\n });\n quickPick.show();\n};\nexport const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => {\n const presentAccounts: Array<JSONAccountType> | undefined =\n await getNotDeployedAccounts(context);\n const unDeployedAccount = await context.workspaceState.get(\n \"undeployedAccount\"\n );", "score": 19.565397691996115 }, { "filename": "src/config/account.ts", "retrieved_chunk": " constructorCalldata: selectedAccount.constructorCallData,\n addressSalt: selectedAccount.accountPubKey,\n });\n logger.log(`Transaction hash: ${transaction_hash}`);\n await provider.waitForTransaction(transaction_hash);\n await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount);\n logger.log(`Account deployed successfully at address: ${contract_address}`);\n accountTreeDataProvider.refresh();\n};\nconst updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => {", "score": 16.26073966640898 }, { "filename": "src/treeView/ABITreeView/functions.ts", "retrieved_chunk": "}\nexport const editInput = async (input: Abi, abiTreeDataProvider: any, fileName: string) => {\n let filePath = \"\";\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return [];\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const file = fileName.substring(0, fileName.length - 5);\n filePath = path.join(path_, \"starkode\", file, `${file}_abi.json`);", "score": 13.200174015974811 } ]
typescript
await editContractAddress(node, context);
import * as vscode from "vscode"; import * as fs from "fs"; import path, { resolve } from "path"; import { logger } from "../lib"; import { ABIFragment, IContractQP, IFunctionQP } from "../types"; import { createABIFile, createAddressFile } from "../utils/functions"; import { getAccountInfo } from "./account"; import { Account, CairoAssembly, Contract, ec, Provider } from "starknet"; import { getNetworkProvider } from "./network"; export const loadAllCompiledContract = () => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const compiledCairoContract = fs .readdirSync(path_) .filter((file) => exportPathOfJSONfiles(path_, file)); return compiledCairoContract; }; const exportPathOfJSONfiles = (path_: string, file: string) => { const filePath = path.join(path_, file); if (path.extname(filePath) === ".json") { const fileData = fs.readFileSync(filePath, { encoding: "utf-8", }); if (JSON.parse(fileData).program) return filePath; if (JSON.parse(fileData).contract_class_version) { return filePath; } } }; export const setContract = async (context: vscode.ExtensionContext, label: string) => { if (label === undefined) { // logger.log("No Contract selected."); return; } void context.workspaceState.update("selectedContract", `${label}.json`); logger.log(`${label} contract selected`); createABIFile(`${label}.json`); createAddressFile(`${label}.json`); }; export const selectCompiledContract = (context: vscode.ExtensionContext) => { const contracts = loadAllCompiledContract(); if (contracts === undefined) { logger.log("No Contract available."); return; } const quickPick = vscode.window.createQuickPick<IContractQP>(); quickPick.items = contracts.map((contract: string) => ({ label: contract.substring(0, contract.length - 5), })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Contract"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; setContract(context, label); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getContractInfo = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_address.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const getContractABI = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_abi.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const isCairo1Contract = (fileName: string): boolean => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return false; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileData = fs.readFileSync( path.join(path_, fileName), { encoding: "utf-8" } ); return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; }; export const declareContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const fileName = selectedContract.substring(0, selectedContract.length - 5); if ( !fs.existsSync(path.join(path_, selectedContract)) || !fs.existsSync(path.join(path_, `${fileName}.casm`)) ) { logger.log(`${fileName}.json or ${fileName}.casm must be present.`); return; } const compiledContract = fs.readFileSync( path.join(path_, selectedContract), { encoding: "ascii", } ); const casmFileData = fs .readFileSync(path.join(path_, `${fileName}.casm`)) .toString("ascii"); const casmAssembly: CairoAssembly = JSON.parse(casmFileData); logger.log("Declaring contract..."); const declareResponse = await account.declareAndDeploy({ contract: compiledContract, casm: casmAssembly, }); logger.log( `declare transaction hash: ${declareResponse.deploy.transaction_hash}` ); logger.log(`declare classHash: ${declareResponse.deploy.classHash}`); logger.log("transaction successful"); } catch (error) { logger.log(`Error while contract declaration: ${error}`); } }; export const deployContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); logger.log("Deploying contract..."); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contractInfo = getContractInfo(path_, selectedContract); if (contractInfo.classHash === "") { logger.log("No classHash available for selected contract."); return; } const deployResponse = await account.deployContract({ classHash: contractInfo.classHash, }); logger.log(`transaction hash: ${deployResponse.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(deployResponse.transaction_hash); const { abi: testAbi } = await provider.getClassAt( deployResponse.contract_address ); if (testAbi === undefined) { throw new Error("no abi."); } const myTestContract = new Contract( testAbi, deployResponse.contract_address, provider ); await provider.waitForTransaction(myTestContract.transaction_hash); logger.log(`contract deployed successfully: ${myTestContract.address}`); } catch (error) { logger.log(`Error while contract deployment: ${error}`); } }; export const executeContractFunction = async ( context: vscode.ExtensionContext ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = await getSelectedFunction(path_, selectedContract); const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; export const executeContractFunctionFromTreeView = async ( context: vscode.ExtensionContext, functionabi: ABIFragment ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = functionabi; const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; const getSelectedFunction = ( path_: string, selectedContract: string ): Promise<ABIFragment> => { return new Promise((resolve, reject) => { try { const contractInfo: Array<ABIFragment> = getContractABI( path_, selectedContract ).abi; if (contractInfo === undefined) return; const quickPick =
vscode.window.createQuickPick<IFunctionQP>();
quickPick.items = contractInfo.map((account: ABIFragment) => ({ label: account.name, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Function"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; quickPick.dispose(); const functionItem = contractInfo.filter( (i: ABIFragment) => i.name === label ); if (functionItem.length === 0) throw new Error("No function is selected"); resolve(functionItem[0]); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); } catch (error) { reject(error); } }); };
src/config/contract.ts
7finney-starkode-2fba517
[ { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " const selectedContract: string | undefined = this.context.workspaceState.get(\"selectedContract\") as string;\n const data = getContractABI(path_,selectedContract);\n const inputFunction: Array<ABIFragment> | undefined = selectedContract !== undefined ? data === undefined ? undefined : data.abi :\n [];\n if (inputFunction === undefined) {\n return undefined;\n } \n else {\n if (!element) {\n for (const entry of inputFunction) {", "score": 24.058196392521022 }, { "filename": "src/extension.ts", "retrieved_chunk": " treeDataProvider: abiTreeDataProvider,\n });\n const contractName: string | undefined = context.workspaceState.get(\"selectedContract\");\n if (!contractName || contractName === undefined) {\n abiTreeView.message = \"Select a contract and its ABI functions will appear here.\";\n }\n else {\n const contractInfo = getContractInfo(path_, contractName);\n if (contractInfo !== undefined) {\n abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;", "score": 17.738980014619365 }, { "filename": "src/config/account.ts", "retrieved_chunk": " context: vscode.ExtensionContext\n) => {\n const accounts: Array<JSONAccountType> | undefined =\n await getDeployedAccounts(context);\n if (accounts === undefined) return;\n const quickPick = vscode.window.createQuickPick<IAccountQP>();\n quickPick.items = accounts.map((account: JSONAccountType) => ({\n label: account.accountAddress,\n }));\n quickPick.onDidChangeActive(() => {", "score": 16.848247787719547 }, { "filename": "src/config/account.ts", "retrieved_chunk": ") => {\n const accounts: Array<JSONAccountType> | undefined =\n await getNotDeployedAccounts(context);\n if (accounts === undefined) return;\n const quickPick = vscode.window.createQuickPick<IAccountQP>();\n quickPick.items = accounts.map((account: JSONAccountType) => ({\n label: account.accountAddress,\n }));\n quickPick.onDidChangeActive(() => {\n quickPick.placeholder = \"Select account\";", "score": 16.654743358486925 }, { "filename": "src/extension.ts", "retrieved_chunk": " } else {\n abiTreeView.message = undefined;\n const contractInfo = getContractInfo(path_, contractName);\n abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;\n }\n abiTreeDataProvider.refresh();\n });\n // Contract Tree View\n const contractTreeDataProvider = new ContractTreeDataProvider(\n vscode.workspace.workspaceFolders?.[0].uri.fsPath", "score": 16.348880472453523 } ]
typescript
vscode.window.createQuickPick<IFunctionQP>();
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata); const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger.log(`New account created: ${OZcontractAddress}`); } catch (error) { logger.error(`Error while creating new account: ${error}`); } }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false );
if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork"); const provider = getNetworkProvider(context); console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress, selectedAccount.privateKey, "1" ); logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({ classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, }); logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false, gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, }; fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/config/contract.ts", "retrieved_chunk": " const fileData = fs.readFileSync(\n path.join(path_, \"starkode\", file, `${file}_address.json`),\n { encoding: \"utf-8\" }\n );\n const parsedFileData = JSON.parse(fileData);\n return parsedFileData;\n } catch (error) {\n // console.log(error);\n return undefined;\n }", "score": 45.988113313381845 }, { "filename": "src/config/contract.ts", "retrieved_chunk": "};\nexport const getContractABI = (path_: string, fileName: string) => {\n try {\n const file = fileName.substring(0, fileName.length - 5);\n const fileData = fs.readFileSync(\n path.join(path_, \"starkode\", file, `${file}_abi.json`),\n { encoding: \"utf-8\" }\n );\n const parsedFileData = JSON.parse(fileData);\n return parsedFileData;", "score": 42.08708728218302 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " ) {\n const filePath = path.join(path_, file);\n const fileData = fs.readFileSync(filePath, { encoding: \"utf-8\" });\n const isCairo1Contract =\n JSON.parse(fileData).contract_class_version === \"0.1.0\" ? true : false;\n const abi: Array<ABIFragment> = JSON.parse(fileData).abi;\n const abiFunctions = abi.filter((e) => e.type === \"function\");\n const functionsValue = abiFunctions.map((func) => {\n return {\n type: func.type,", "score": 37.18879855036705 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": "};\nexport const accountDeployStatus = (\n accounts: Array<JSONAccountType>,\n selectedNetwork: string,\n status: boolean\n) => {\n const networks = [\"goerli-alpha\", \"goerli-alpha-2\", \"mainnet-alpha\"];\n let result: Array<JSONAccountType> | undefined;\n switch (selectedNetwork) {\n case networks[0]: {", "score": 34.95343478033427 }, { "filename": "src/config/contract.ts", "retrieved_chunk": "const exportPathOfJSONfiles = (path_: string, file: string) => {\n const filePath = path.join(path_, file);\n if (path.extname(filePath) === \".json\") {\n const fileData = fs.readFileSync(filePath, {\n encoding: \"utf-8\",\n });\n if (JSON.parse(fileData).program) return filePath;\n if (JSON.parse(fileData).contract_class_version) {\n return filePath;\n }", "score": 34.72397492084065 } ]
typescript
const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false );
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console.log('Selected nodes:', selectedNodes[0].label); } }); // Account Tree View const accountTreeDataProvider = new AccountTreeDataProvider( context ); const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }),
vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => {
contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await editInput(node, abiTreeDataProvider, selectedContract); }), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/utils/functions.ts", "retrieved_chunk": " }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const fileName = file.substring(0, file.length - 5);\n if (!fs.existsSync(path.join(path_, \"starkode\", fileName))) {\n fs.mkdirSync(path.join(path_, \"starkode\", fileName),{recursive: true});\n }\n if (\n !fs.existsSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_abi.json`)\n )", "score": 38.31532835962889 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " if (\n !fs.existsSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_address.json`)\n )\n ) {\n fs.writeFileSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_address.json`),\n JSON.stringify({\n name: fileName,\n address: \"\",", "score": 33.10448547085092 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const fileData = fs.readFileSync(\n path.join(path_, \"starkode\", file, `${file}_address.json`),\n { encoding: \"utf-8\" }\n );\n const parsedFileData = JSON.parse(fileData);\n return parsedFileData;\n } catch (error) {\n // console.log(error);\n return undefined;\n }", "score": 30.333372382739668 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const fileName = selectedContract.substring(0, selectedContract.length - 5);\n if (\n !fs.existsSync(path.join(path_, selectedContract)) ||\n !fs.existsSync(path.join(path_, `${fileName}.casm`))\n ) {\n logger.log(`${fileName}.json or ${fileName}.casm must be present.`);\n return;\n }\n const compiledContract = fs.readFileSync(\n path.join(path_, selectedContract),", "score": 24.18216230352005 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " fs.writeFileSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_abi.json`),\n JSON.stringify({ isCairo1: isCairo1Contract, abi: functionsValue }, null, 2)\n );\n logger.log(\"ABI file created successfully.\");\n } else {\n logger.log(`${fileName}_abi.json already exist.`);\n }\n } catch (error) {\n logger.log(`Error while writing to file: ${error}`);", "score": 23.606506431534243 } ]
typescript
vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => {
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console.log('Selected nodes:', selectedNodes[0].label); } }); // Account Tree View const accountTreeDataProvider = new AccountTreeDataProvider( context ); const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => {
contractTreeView = await refreshContract(node, contractTreeDataProvider);
contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await editInput(node, abiTreeDataProvider, selectedContract); }), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/utils/functions.ts", "retrieved_chunk": " }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const fileName = file.substring(0, file.length - 5);\n if (!fs.existsSync(path.join(path_, \"starkode\", fileName))) {\n fs.mkdirSync(path.join(path_, \"starkode\", fileName),{recursive: true});\n }\n if (\n !fs.existsSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_abi.json`)\n )", "score": 38.31532835962889 }, { "filename": "src/treeView/ContractTreeView/function.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport { Contract as ContractTreeItem } from \"./ContractTreeDataProvider\";\nimport { logger } from \"../../lib\";\nimport path = require(\"path\");\nexport const refreshContract = async (node: ContractTreeItem, contractTreeDataProvider: any): Promise<vscode.TreeView<ContractTreeItem>> => {\n return vscode.window.createTreeView(\"starkode.contracts\", { treeDataProvider: contractTreeDataProvider, });\n};\nexport const editContractAddress = async (input : any,context: vscode.ExtensionContext) => {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Open or Create a cairo project.\");", "score": 33.843925959372434 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " if (\n !fs.existsSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_address.json`)\n )\n ) {\n fs.writeFileSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_address.json`),\n JSON.stringify({\n name: fileName,\n address: \"\",", "score": 33.10448547085092 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const fileData = fs.readFileSync(\n path.join(path_, \"starkode\", file, `${file}_address.json`),\n { encoding: \"utf-8\" }\n );\n const parsedFileData = JSON.parse(fileData);\n return parsedFileData;\n } catch (error) {\n // console.log(error);\n return undefined;\n }", "score": 30.333372382739668 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const fileName = selectedContract.substring(0, selectedContract.length - 5);\n if (\n !fs.existsSync(path.join(path_, selectedContract)) ||\n !fs.existsSync(path.join(path_, `${fileName}.casm`))\n ) {\n logger.log(`${fileName}.json or ${fileName}.casm must be present.`);\n return;\n }\n const compiledContract = fs.readFileSync(\n path.join(path_, selectedContract),", "score": 24.18216230352005 } ]
typescript
contractTreeView = await refreshContract(node, contractTreeDataProvider);
import * as vscode from "vscode"; import * as fs from "fs"; import path, { resolve } from "path"; import { logger } from "../lib"; import { ABIFragment, IContractQP, IFunctionQP } from "../types"; import { createABIFile, createAddressFile } from "../utils/functions"; import { getAccountInfo } from "./account"; import { Account, CairoAssembly, Contract, ec, Provider } from "starknet"; import { getNetworkProvider } from "./network"; export const loadAllCompiledContract = () => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const compiledCairoContract = fs .readdirSync(path_) .filter((file) => exportPathOfJSONfiles(path_, file)); return compiledCairoContract; }; const exportPathOfJSONfiles = (path_: string, file: string) => { const filePath = path.join(path_, file); if (path.extname(filePath) === ".json") { const fileData = fs.readFileSync(filePath, { encoding: "utf-8", }); if (JSON.parse(fileData).program) return filePath; if (JSON.parse(fileData).contract_class_version) { return filePath; } } }; export const setContract = async (context: vscode.ExtensionContext, label: string) => { if (label === undefined) { // logger.log("No Contract selected."); return; } void context.workspaceState.update("selectedContract", `${label}.json`); logger.log(`${label} contract selected`); createABIFile(`${label}.json`); createAddressFile(`${label}.json`); }; export const selectCompiledContract = (context: vscode.ExtensionContext) => { const contracts = loadAllCompiledContract(); if (contracts === undefined) { logger.log("No Contract available."); return; } const quickPick = vscode.window.createQuickPick<IContractQP>(); quickPick.items = contracts.map((contract: string) => ({ label: contract.substring(0, contract.length - 5), })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Contract"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; setContract(context, label); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getContractInfo = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_address.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const getContractABI = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_abi.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const isCairo1Contract = (fileName: string): boolean => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return false; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileData = fs.readFileSync( path.join(path_, fileName), { encoding: "utf-8" } ); return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; }; export const declareContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo
= getAccountInfo(context, selectedAccount);
const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const fileName = selectedContract.substring(0, selectedContract.length - 5); if ( !fs.existsSync(path.join(path_, selectedContract)) || !fs.existsSync(path.join(path_, `${fileName}.casm`)) ) { logger.log(`${fileName}.json or ${fileName}.casm must be present.`); return; } const compiledContract = fs.readFileSync( path.join(path_, selectedContract), { encoding: "ascii", } ); const casmFileData = fs .readFileSync(path.join(path_, `${fileName}.casm`)) .toString("ascii"); const casmAssembly: CairoAssembly = JSON.parse(casmFileData); logger.log("Declaring contract..."); const declareResponse = await account.declareAndDeploy({ contract: compiledContract, casm: casmAssembly, }); logger.log( `declare transaction hash: ${declareResponse.deploy.transaction_hash}` ); logger.log(`declare classHash: ${declareResponse.deploy.classHash}`); logger.log("transaction successful"); } catch (error) { logger.log(`Error while contract declaration: ${error}`); } }; export const deployContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); logger.log("Deploying contract..."); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contractInfo = getContractInfo(path_, selectedContract); if (contractInfo.classHash === "") { logger.log("No classHash available for selected contract."); return; } const deployResponse = await account.deployContract({ classHash: contractInfo.classHash, }); logger.log(`transaction hash: ${deployResponse.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(deployResponse.transaction_hash); const { abi: testAbi } = await provider.getClassAt( deployResponse.contract_address ); if (testAbi === undefined) { throw new Error("no abi."); } const myTestContract = new Contract( testAbi, deployResponse.contract_address, provider ); await provider.waitForTransaction(myTestContract.transaction_hash); logger.log(`contract deployed successfully: ${myTestContract.address}`); } catch (error) { logger.log(`Error while contract deployment: ${error}`); } }; export const executeContractFunction = async ( context: vscode.ExtensionContext ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = await getSelectedFunction(path_, selectedContract); const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; export const executeContractFunctionFromTreeView = async ( context: vscode.ExtensionContext, functionabi: ABIFragment ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = functionabi; const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; const getSelectedFunction = ( path_: string, selectedContract: string ): Promise<ABIFragment> => { return new Promise((resolve, reject) => { try { const contractInfo: Array<ABIFragment> = getContractABI( path_, selectedContract ).abi; if (contractInfo === undefined) return; const quickPick = vscode.window.createQuickPick<IFunctionQP>(); quickPick.items = contractInfo.map((account: ABIFragment) => ({ label: account.name, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Function"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; quickPick.dispose(); const functionItem = contractInfo.filter( (i: ABIFragment) => i.name === label ); if (functionItem.length === 0) throw new Error("No function is selected"); resolve(functionItem[0]); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); } catch (error) { reject(error); } }); };
src/config/contract.ts
7finney-starkode-2fba517
[ { "filename": "src/extension.ts", "retrieved_chunk": " if (node.context === \"deployedAccount\") {\n void context.workspaceState.update(\"account\", node.account.accountAddress);\n logger.log(`${node.account.accountAddress} selected`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n abiTreeDataProvider.refresh();\n } else {", "score": 38.03628510533673 }, { "filename": "src/extension.ts", "retrieved_chunk": " }),\n vscode.commands.registerCommand(\"starkode.deploycontract\", async (node: any) => {\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n if (selectedContract === undefined) {\n logger.log(\"No Contract selected\");\n return;\n }\n if (selectedContract.slice(0, -5) !== node.label) {", "score": 34.8971075610636 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 33.937806186730796 }, { "filename": "src/extension.ts", "retrieved_chunk": " treeDataProvider: accountTreeDataProvider,\n });\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount: string | undefined = context.workspaceState.get(\"account\") as string;\n accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}` : \"Select a deployed account , or create an account and deploy it\";\n // ABI Tree View\n const abiTreeDataProvider = new AbiTreeDataProvider(\n context\n );\n const abiTreeView = vscode.window.createTreeView(\"starkode.abis\", {", "score": 33.12782557016993 }, { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " const selectedContract: string | undefined = this.context.workspaceState.get(\"selectedContract\") as string;\n const data = getContractABI(path_,selectedContract);\n const inputFunction: Array<ABIFragment> | undefined = selectedContract !== undefined ? data === undefined ? undefined : data.abi :\n [];\n if (inputFunction === undefined) {\n return undefined;\n } \n else {\n if (!element) {\n for (const entry of inputFunction) {", "score": 28.64102933768479 } ]
typescript
= getAccountInfo(context, selectedAccount);
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console.log('Selected nodes:', selectedNodes[0].label); } }); // Account Tree View const accountTreeDataProvider = new AccountTreeDataProvider( context ); const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await
updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider);
}), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await editInput(node, abiTreeDataProvider, selectedContract); }), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/config/network.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport { logger } from \"../lib\";\nimport { INetworkQP } from \"../types\";\nimport { Provider, SequencerProviderOptions } from \"starknet\";\nimport { Account } from \"../treeView/AccountTreeView/AccountTreeDataProvider\";\nexport const NETWORKS = [\"goerli-alpha\", \"goerli-alpha-2\", \"mainnet-alpha\"];\nexport const updateSelectedNetwork = async (\n context: vscode.ExtensionContext,\n accountTreeView: vscode.TreeView<Account>,\n accountTreeDataProvider: any", "score": 17.072656789325627 }, { "filename": "src/config/account.ts", "retrieved_chunk": " quickPick.dispose();\n });\n quickPick.show();\n};\nexport const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => {\n const presentAccounts: Array<JSONAccountType> | undefined =\n await getNotDeployedAccounts(context);\n const unDeployedAccount = await context.workspaceState.get(\n \"undeployedAccount\"\n );", "score": 15.39168438273506 }, { "filename": "src/config/account.ts", "retrieved_chunk": " constructorCalldata: selectedAccount.constructorCallData,\n addressSalt: selectedAccount.accountPubKey,\n });\n logger.log(`Transaction hash: ${transaction_hash}`);\n await provider.waitForTransaction(transaction_hash);\n await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount);\n logger.log(`Account deployed successfully at address: ${contract_address}`);\n accountTreeDataProvider.refresh();\n};\nconst updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => {", "score": 15.241712764823461 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 12.712010495869663 }, { "filename": "src/treeView/ContractTreeView/function.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport { Contract as ContractTreeItem } from \"./ContractTreeDataProvider\";\nimport { logger } from \"../../lib\";\nimport path = require(\"path\");\nexport const refreshContract = async (node: ContractTreeItem, contractTreeDataProvider: any): Promise<vscode.TreeView<ContractTreeItem>> => {\n return vscode.window.createTreeView(\"starkode.contracts\", { treeDataProvider: contractTreeDataProvider, });\n};\nexport const editContractAddress = async (input : any,context: vscode.ExtensionContext) => {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Open or Create a cairo project.\");", "score": 10.757020735422747 } ]
typescript
updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider);
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console.log('Selected nodes:', selectedNodes[0].label); } }); // Account Tree View const accountTreeDataProvider = new AccountTreeDataProvider( context ); const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await
editInput(node, abiTreeDataProvider, selectedContract);
}), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/treeView/ContractTreeView/function.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport { Contract as ContractTreeItem } from \"./ContractTreeDataProvider\";\nimport { logger } from \"../../lib\";\nimport path = require(\"path\");\nexport const refreshContract = async (node: ContractTreeItem, contractTreeDataProvider: any): Promise<vscode.TreeView<ContractTreeItem>> => {\n return vscode.window.createTreeView(\"starkode.contracts\", { treeDataProvider: contractTreeDataProvider, });\n};\nexport const editContractAddress = async (input : any,context: vscode.ExtensionContext) => {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Open or Create a cairo project.\");", "score": 35.699246218909934 }, { "filename": "src/config/account.ts", "retrieved_chunk": "};\nexport const deleteAccount = async (context: vscode.ExtensionContext,node: any) => {\n const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {\n encoding: \"utf-8\",\n });\n const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);\n const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress);\n fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2));\n};\nexport const selectDeployedAccount = async (", "score": 26.565088778089404 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");\n return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n const functionABI = functionabi;", "score": 22.19011112982358 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const provider = getNetworkProvider(context) as Provider;\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");", "score": 21.99674328482866 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");\n return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n logger.log(\"Deploying contract...\");", "score": 21.85471817741859 } ]
typescript
editInput(node, abiTreeDataProvider, selectedContract);
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata); const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger.log(`New account created: ${OZcontractAddress}`); } catch (error) { logger.error(`Error while creating new account: ${error}`); } }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false ); if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork"); const provider = getNetworkProvider(context); console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress, selectedAccount.privateKey, "1" ); logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({
classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, });
logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false, gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, }; fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/extension.ts", "retrieved_chunk": " if (node.context === \"deployedAccount\") {\n void context.workspaceState.update(\"account\", node.account.accountAddress);\n logger.log(`${node.account.accountAddress} selected`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n abiTreeDataProvider.refresh();\n } else {", "score": 29.392529261509992 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");\n return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n logger.log(\"Deploying contract...\");", "score": 26.745025452353335 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 24.44244029666602 }, { "filename": "src/extension.ts", "retrieved_chunk": " treeDataProvider: accountTreeDataProvider,\n });\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount: string | undefined = context.workspaceState.get(\"account\") as string;\n accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}` : \"Select a deployed account , or create an account and deploy it\";\n // ABI Tree View\n const abiTreeDataProvider = new AbiTreeDataProvider(\n context\n );\n const abiTreeView = vscode.window.createTreeView(\"starkode.abis\", {", "score": 24.27649875407195 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");\n return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n const functionABI = functionabi;", "score": 22.27748510367029 } ]
typescript
classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, });
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { logger } from "../lib"; import { ABIFragment, JSONAccountType, TIsAccountDeployed } from "../types"; export const createABIFile = (file: string) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileName = file.substring(0, file.length - 5); if (!fs.existsSync(path.join(path_, "starkode", fileName))) { fs.mkdirSync(path.join(path_, "starkode", fileName),{recursive: true}); } if ( !fs.existsSync( path.join(path_, "starkode", fileName, `${fileName}_abi.json`) ) ) { const filePath = path.join(path_, file); const fileData = fs.readFileSync(filePath, { encoding: "utf-8" }); const isCairo1Contract = JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; const abi: Array<ABIFragment> = JSON.parse(fileData).abi; const abiFunctions = abi.filter((e) => e.type === "function"); const functionsValue = abiFunctions.map((func) => { return { type: func.type, name: func.name, inputs: func.inputs.map((e) => { return { ...e, value: "" }; }), stateMutability: func.stateMutability ? func.stateMutability : func.state_mutability, outputs: func.outputs, }; }); fs.writeFileSync( path.join(path_, "starkode", fileName, `${fileName}_abi.json`), JSON.stringify({ isCairo1: isCairo1Contract, abi: functionsValue }, null, 2) ); logger.log("ABI file created successfully."); } else { logger.log(`${fileName}_abi.json already exist.`); } } catch (error) { logger.log(`Error while writing to file: ${error}`); } }; export const createAddressFile = (file: string) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileName = file.substring(0, file.length - 5); if ( !fs.existsSync( path.join(path_, "starkode", fileName, `${fileName}_address.json`) ) ) { fs.writeFileSync( path.join(path_, "starkode", fileName, `${fileName}_address.json`), JSON.stringify({ name: fileName, address: "", classHash: "", }, null, 2) ); logger.log("Address file created successfully."); } else { logger.log(`${fileName}_address.json already exist.`); } } catch (error) { logger.log(`Error while writing to file: ${error}`); } }; export const accountDeployStatus = ( accounts:
Array<JSONAccountType>, selectedNetwork: string, status: boolean ) => {
const networks = ["goerli-alpha", "goerli-alpha-2", "mainnet-alpha"]; let result: Array<JSONAccountType> | undefined; switch (selectedNetwork) { case networks[0]: { result = accounts.filter((e) => e.isDeployed.gAlpha === status); break; } case networks[1]: { result = accounts.filter((e) => e.isDeployed.gAlpha2 === status); break; } case networks[2]: { result = accounts.filter((e) => e.isDeployed.mainnet === status); break; } default: break; } return result; };
src/utils/functions.ts
7finney-starkode-2fba517
[ { "filename": "src/config/contract.ts", "retrieved_chunk": " } catch (error) {\n // console.log(error);\n return undefined;\n }\n};\nexport const isCairo1Contract = (fileName: string): boolean => {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return false;\n }", "score": 20.112589348084857 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " } catch (error) {\n logger.log(`Error while contract deployment: ${error}`);\n }\n};\nexport const executeContractFunction = async (\n context: vscode.ExtensionContext\n) => {\n try {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");", "score": 19.337086130313484 }, { "filename": "src/config/account.ts", "retrieved_chunk": " logger.error(`Error while creating new account: ${error}`);\n }\n};\nexport const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => {\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n if (selectedNetwork === undefined) {\n logger.log(\"Network not selected\");\n return;\n }\n if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) {", "score": 17.331013917455472 }, { "filename": "src/config/account.ts", "retrieved_chunk": " const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(\n parsedFileData,\n selectedNetwork,\n true\n );\n if (accounts === undefined || accounts.length === 0) {\n logger.log(`No deployed account available on ${selectedNetwork}`);\n return;\n }\n return accounts;", "score": 16.72494748633792 }, { "filename": "src/config/account.ts", "retrieved_chunk": " gAlpha: selectedNetwork === NETWORKS[0] ? true : false,\n gAlpha2: selectedNetwork === NETWORKS[1] ? true : false,\n mainnet: selectedNetwork === NETWORKS[2] ? true : false,\n };\n fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => {\n if (err) {\n console.error('Error writing file:', err);\n return;\n }\n console.log('JSON file successfully updated.');", "score": 16.598463106542066 } ]
typescript
Array<JSONAccountType>, selectedNetwork: string, status: boolean ) => {
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) {
console.log('Selected nodes:', selectedNodes[0].label);
} }); // Account Tree View const accountTreeDataProvider = new AccountTreeDataProvider( context ); const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await editInput(node, abiTreeDataProvider, selectedContract); }), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/config/contract.ts", "retrieved_chunk": " createAddressFile(`${label}.json`);\n};\nexport const selectCompiledContract = (context: vscode.ExtensionContext) => {\n const contracts = loadAllCompiledContract();\n if (contracts === undefined) {\n logger.log(\"No Contract available.\");\n return;\n }\n const quickPick = vscode.window.createQuickPick<IContractQP>();\n quickPick.items = contracts.map((contract: string) => ({", "score": 32.323032057388524 }, { "filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport { isCairo1Contract, loadAllCompiledContract } from \"../../config/contract\";\nexport class ContractTreeDataProvider implements vscode.TreeDataProvider<Contract> {\n constructor(private workspaceRoot: string | undefined) { }\n getTreeItem(element: Contract): vscode.TreeItem {\n return element;\n }\n async getChildren(element?: Contract): Promise<Contract[]> {\n const contracts = loadAllCompiledContract();\n if (contracts === undefined || contracts.length === 0) {", "score": 30.948444533204572 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " label: contract.substring(0, contract.length - 5),\n }));\n quickPick.onDidChangeActive(() => {\n quickPick.placeholder = \"Select Contract\";\n });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n setContract(context, label);\n quickPick.dispose();", "score": 27.911440309903288 }, { "filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts", "retrieved_chunk": " vscode.window.showInformationMessage(\"No Contracts in workspace\");\n return [];\n } else {\n const leaves = [];\n for (const file of contracts) {\n leaves.push(new Contract(\n file.slice(0, -5),\n vscode.TreeItemCollapsibleState.None,\n \"contract\",\n isCairo1Contract(file) ? \"file-code\" : \"file-text\"", "score": 20.619884230482505 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 19.454464446549473 } ]
typescript
console.log('Selected nodes:', selectedNodes[0].label);
import * as vscode from "vscode"; import * as fs from "fs"; import path, { resolve } from "path"; import { logger } from "../lib"; import { ABIFragment, IContractQP, IFunctionQP } from "../types"; import { createABIFile, createAddressFile } from "../utils/functions"; import { getAccountInfo } from "./account"; import { Account, CairoAssembly, Contract, ec, Provider } from "starknet"; import { getNetworkProvider } from "./network"; export const loadAllCompiledContract = () => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const compiledCairoContract = fs .readdirSync(path_) .filter((file) => exportPathOfJSONfiles(path_, file)); return compiledCairoContract; }; const exportPathOfJSONfiles = (path_: string, file: string) => { const filePath = path.join(path_, file); if (path.extname(filePath) === ".json") { const fileData = fs.readFileSync(filePath, { encoding: "utf-8", }); if (JSON.parse(fileData).program) return filePath; if (JSON.parse(fileData).contract_class_version) { return filePath; } } }; export const setContract = async (context: vscode.ExtensionContext, label: string) => { if (label === undefined) { // logger.log("No Contract selected."); return; } void context.workspaceState.update("selectedContract", `${label}.json`); logger.log(`${label} contract selected`); createABIFile(`${label}.json`); createAddressFile(`${label}.json`); }; export const selectCompiledContract = (context: vscode.ExtensionContext) => { const contracts = loadAllCompiledContract(); if (contracts === undefined) { logger.log("No Contract available."); return; } const quickPick = vscode.window.createQuickPick<IContractQP>(); quickPick.items = contracts.map((contract: string) => ({ label: contract.substring(0, contract.length - 5), })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Contract"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; setContract(context, label); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getContractInfo = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_address.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const getContractABI = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_abi.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const isCairo1Contract = (fileName: string): boolean => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return false; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileData = fs.readFileSync( path.join(path_, fileName), { encoding: "utf-8" } ); return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; }; export const declareContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const fileName = selectedContract.substring(0, selectedContract.length - 5); if ( !fs.existsSync(path.join(path_, selectedContract)) || !fs.existsSync(path.join(path_, `${fileName}.casm`)) ) { logger.log(`${fileName}.json or ${fileName}.casm must be present.`); return; } const compiledContract = fs.readFileSync( path.join(path_, selectedContract), { encoding: "ascii", } ); const casmFileData = fs .readFileSync(path.join(path_, `${fileName}.casm`)) .toString("ascii"); const casmAssembly: CairoAssembly = JSON.parse(casmFileData); logger.log("Declaring contract..."); const declareResponse = await account.declareAndDeploy({ contract: compiledContract, casm: casmAssembly, }); logger.log( `declare transaction hash: ${declareResponse.deploy.transaction_hash}` ); logger.log(`declare classHash: ${declareResponse.deploy.classHash}`); logger.log("transaction successful"); } catch (error) { logger.log(`Error while contract declaration: ${error}`); } }; export const deployContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); logger.log("Deploying contract..."); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contractInfo = getContractInfo(path_, selectedContract); if (contractInfo.classHash === "") { logger.log("No classHash available for selected contract."); return; } const deployResponse = await account.deployContract({ classHash: contractInfo.classHash, }); logger.log(`transaction hash: ${deployResponse.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(deployResponse.transaction_hash); const { abi: testAbi } = await provider.getClassAt( deployResponse.contract_address ); if (testAbi === undefined) { throw new Error("no abi."); } const myTestContract = new Contract( testAbi, deployResponse.contract_address, provider ); await provider.waitForTransaction(myTestContract.transaction_hash); logger.log(`contract deployed successfully: ${myTestContract.address}`); } catch (error) { logger.log(`Error while contract deployment: ${error}`); } }; export const executeContractFunction = async ( context: vscode.ExtensionContext ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = await getSelectedFunction(path_, selectedContract); const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; export const executeContractFunctionFromTreeView = async ( context: vscode.ExtensionContext, functionabi
: ABIFragment ) => {
try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = functionabi; const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; const getSelectedFunction = ( path_: string, selectedContract: string ): Promise<ABIFragment> => { return new Promise((resolve, reject) => { try { const contractInfo: Array<ABIFragment> = getContractABI( path_, selectedContract ).abi; if (contractInfo === undefined) return; const quickPick = vscode.window.createQuickPick<IFunctionQP>(); quickPick.items = contractInfo.map((account: ABIFragment) => ({ label: account.name, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Function"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; quickPick.dispose(); const functionItem = contractInfo.filter( (i: ABIFragment) => i.name === label ); if (functionItem.length === 0) throw new Error("No function is selected"); resolve(functionItem[0]); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); } catch (error) { reject(error); } }); };
src/config/contract.ts
7finney-starkode-2fba517
[ { "filename": "src/config/account.ts", "retrieved_chunk": " logger.error(`Error while creating new account: ${error}`);\n }\n};\nexport const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => {\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n if (selectedNetwork === undefined) {\n logger.log(\"Network not selected\");\n return;\n }\n if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) {", "score": 12.58957576355319 }, { "filename": "src/extension.ts", "retrieved_chunk": " vscode.window.showInformationMessage(\"Starkode activated.\");\n } catch (error) {\n console.log(error);\n }\n }),\n vscode.commands.registerCommand(\"starkode.refreshContracts\", async (node: ContractTreeItem) => {\n contractTreeView = await refreshContract(node, contractTreeDataProvider);\n contractTreeView.message = undefined;\n }),\n vscode.commands.registerCommand(\"starkode.useContract\", async (node: ContractTreeItem) => {", "score": 12.024293059118742 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " classHash: \"\",\n }, null, 2)\n );\n logger.log(\"Address file created successfully.\");\n } else {\n logger.log(`${fileName}_address.json already exist.`);\n }\n } catch (error) {\n logger.log(`Error while writing to file: ${error}`);\n }", "score": 11.964015732450044 }, { "filename": "src/config/account.ts", "retrieved_chunk": " },\n },\n ];\n fs.writeFileSync(\n `${context.extensionPath}/accounts.json`,\n JSON.stringify(writeNewAccount)\n );\n }\n logger.log(`New account created: ${OZcontractAddress}`);\n } catch (error) {", "score": 11.006662628197141 }, { "filename": "src/config/account.ts", "retrieved_chunk": " });\n } else {\n console.error('Element not found in JSON file.');\n }\n });\n};\nexport const getDeployedAccounts = (context: vscode.ExtensionContext) => {\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n if (selectedNetwork === undefined){\n // logger.log(\"Network not selected\");", "score": 10.676417264241392 } ]
typescript
: ABIFragment ) => {
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const
contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath );
let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console.log('Selected nodes:', selectedNodes[0].label); } }); // Account Tree View const accountTreeDataProvider = new AccountTreeDataProvider( context ); const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await editInput(node, abiTreeDataProvider, selectedContract); }), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/treeView/ABITreeView/functions.ts", "retrieved_chunk": "}\nexport const editInput = async (input: Abi, abiTreeDataProvider: any, fileName: string) => {\n let filePath = \"\";\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return [];\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const file = fileName.substring(0, fileName.length - 5);\n filePath = path.join(path_, \"starkode\", file, `${file}_abi.json`);", "score": 17.996021445492413 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " }\n};\nexport const createAddressFile = (file: string) => {\n try {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const fileName = file.substring(0, file.length - 5);", "score": 16.91500353272542 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const account = new Account(\n provider,\n accountInfo.accountAddress,\n accountInfo.privateKey,\n \"0\"\n );\n const contractInfo = getContractInfo(path_, selectedContract);\n if (contractInfo.classHash === \"\") {\n logger.log(\"No classHash available for selected contract.\");\n return;", "score": 16.84532096256146 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const fileData = fs.readFileSync(\n path.join(path_, fileName),\n { encoding: \"utf-8\" }\n );\n return JSON.parse(fileData).contract_class_version === \"0.1.0\" ? true : false;\n};\nexport const declareContract = async (context: vscode.ExtensionContext) => {\n try {\n if (vscode.workspace.workspaceFolders === undefined) {", "score": 15.094652768958634 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const compiledCairoContract = fs\n .readdirSync(path_)\n .filter((file) => exportPathOfJSONfiles(path_, file));\n return compiledCairoContract;\n};", "score": 14.986571241903478 } ]
typescript
contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath );
import * as vscode from "vscode"; import * as fs from "fs"; import path, { resolve } from "path"; import { logger } from "../lib"; import { ABIFragment, IContractQP, IFunctionQP } from "../types"; import { createABIFile, createAddressFile } from "../utils/functions"; import { getAccountInfo } from "./account"; import { Account, CairoAssembly, Contract, ec, Provider } from "starknet"; import { getNetworkProvider } from "./network"; export const loadAllCompiledContract = () => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const compiledCairoContract = fs .readdirSync(path_) .filter((file) => exportPathOfJSONfiles(path_, file)); return compiledCairoContract; }; const exportPathOfJSONfiles = (path_: string, file: string) => { const filePath = path.join(path_, file); if (path.extname(filePath) === ".json") { const fileData = fs.readFileSync(filePath, { encoding: "utf-8", }); if (JSON.parse(fileData).program) return filePath; if (JSON.parse(fileData).contract_class_version) { return filePath; } } }; export const setContract = async (context: vscode.ExtensionContext, label: string) => { if (label === undefined) { // logger.log("No Contract selected."); return; } void context.workspaceState.update("selectedContract", `${label}.json`); logger.log(`${label} contract selected`); createABIFile(`${label}.json`); createAddressFile(`${label}.json`); }; export const selectCompiledContract = (context: vscode.ExtensionContext) => { const contracts = loadAllCompiledContract(); if (contracts === undefined) { logger.log("No Contract available."); return; } const quickPick = vscode.window.createQuickPick<IContractQP>(); quickPick.items = contracts.map((contract: string) => ({ label: contract.substring(0, contract.length - 5), })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Contract"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; setContract(context, label); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getContractInfo = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_address.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const getContractABI = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_abi.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const isCairo1Contract = (fileName: string): boolean => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return false; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileData = fs.readFileSync( path.join(path_, fileName), { encoding: "utf-8" } ); return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; }; export const declareContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const fileName = selectedContract.substring(0, selectedContract.length - 5); if ( !fs.existsSync(path.join(path_, selectedContract)) || !fs.existsSync(path.join(path_, `${fileName}.casm`)) ) { logger.log(`${fileName}.json or ${fileName}.casm must be present.`); return; } const compiledContract = fs.readFileSync( path.join(path_, selectedContract), { encoding: "ascii", } ); const casmFileData = fs .readFileSync(path.join(path_, `${fileName}.casm`)) .toString("ascii"); const casmAssembly: CairoAssembly = JSON.parse(casmFileData); logger.log("Declaring contract..."); const declareResponse = await account.declareAndDeploy({ contract: compiledContract, casm: casmAssembly, }); logger.log( `declare transaction hash: ${declareResponse.deploy.transaction_hash}` ); logger.log(`declare classHash: ${declareResponse.deploy.classHash}`); logger.log("transaction successful"); } catch (error) { logger.log(`Error while contract declaration: ${error}`); } }; export const deployContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); logger.log("Deploying contract..."); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contractInfo = getContractInfo(path_, selectedContract); if (contractInfo.classHash === "") { logger.log("No classHash available for selected contract."); return; } const deployResponse = await account.deployContract({ classHash: contractInfo.classHash, }); logger.log(`transaction hash: ${deployResponse.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(deployResponse.transaction_hash); const { abi: testAbi } = await provider.getClassAt( deployResponse.contract_address ); if (testAbi === undefined) { throw new Error("no abi."); } const myTestContract = new Contract( testAbi, deployResponse.contract_address, provider ); await provider.waitForTransaction(myTestContract.transaction_hash); logger.log(`contract deployed successfully: ${myTestContract.address}`); } catch (error) { logger.log(`Error while contract deployment: ${error}`); } }; export const executeContractFunction = async ( context: vscode.ExtensionContext ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = await getSelectedFunction(path_, selectedContract); const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> =
functionABI.inputs.map((e) => {
return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; export const executeContractFunctionFromTreeView = async ( context: vscode.ExtensionContext, functionabi: ABIFragment ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = functionabi; const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; const getSelectedFunction = ( path_: string, selectedContract: string ): Promise<ABIFragment> => { return new Promise((resolve, reject) => { try { const contractInfo: Array<ABIFragment> = getContractABI( path_, selectedContract ).abi; if (contractInfo === undefined) return; const quickPick = vscode.window.createQuickPick<IFunctionQP>(); quickPick.items = contractInfo.map((account: ABIFragment) => ({ label: account.name, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Function"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; quickPick.dispose(); const functionItem = contractInfo.filter( (i: ABIFragment) => i.name === label ); if (functionItem.length === 0) throw new Error("No function is selected"); resolve(functionItem[0]); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); } catch (error) { reject(error); } }); };
src/config/contract.ts
7finney-starkode-2fba517
[ { "filename": "src/extension.ts", "retrieved_chunk": " if (node.context === \"deployedAccount\") {\n void context.workspaceState.update(\"account\", node.account.accountAddress);\n logger.log(`${node.account.accountAddress} selected`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n abiTreeDataProvider.refresh();\n } else {", "score": 33.5218741816626 }, { "filename": "src/extension.ts", "retrieved_chunk": " }),\n vscode.commands.registerCommand(\"starkode.deploycontract\", async (node: any) => {\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n if (selectedContract === undefined) {\n logger.log(\"No Contract selected\");\n return;\n }\n if (selectedContract.slice(0, -5) !== node.label) {", "score": 30.126153843376926 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 29.82067278235484 }, { "filename": "src/extension.ts", "retrieved_chunk": " treeDataProvider: accountTreeDataProvider,\n });\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount: string | undefined = context.workspaceState.get(\"account\") as string;\n accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}` : \"Select a deployed account , or create an account and deploy it\";\n // ABI Tree View\n const abiTreeDataProvider = new AbiTreeDataProvider(\n context\n );\n const abiTreeView = vscode.window.createTreeView(\"starkode.abis\", {", "score": 29.294273801217788 }, { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " const selectedContract: string | undefined = this.context.workspaceState.get(\"selectedContract\") as string;\n const data = getContractABI(path_,selectedContract);\n const inputFunction: Array<ABIFragment> | undefined = selectedContract !== undefined ? data === undefined ? undefined : data.abi :\n [];\n if (inputFunction === undefined) {\n return undefined;\n } \n else {\n if (!element) {\n for (const entry of inputFunction) {", "score": 29.238951743702348 } ]
typescript
functionABI.inputs.map((e) => {
import * as vscode from "vscode"; import * as fs from "fs"; import path, { resolve } from "path"; import { logger } from "../lib"; import { ABIFragment, IContractQP, IFunctionQP } from "../types"; import { createABIFile, createAddressFile } from "../utils/functions"; import { getAccountInfo } from "./account"; import { Account, CairoAssembly, Contract, ec, Provider } from "starknet"; import { getNetworkProvider } from "./network"; export const loadAllCompiledContract = () => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const compiledCairoContract = fs .readdirSync(path_) .filter((file) => exportPathOfJSONfiles(path_, file)); return compiledCairoContract; }; const exportPathOfJSONfiles = (path_: string, file: string) => { const filePath = path.join(path_, file); if (path.extname(filePath) === ".json") { const fileData = fs.readFileSync(filePath, { encoding: "utf-8", }); if (JSON.parse(fileData).program) return filePath; if (JSON.parse(fileData).contract_class_version) { return filePath; } } }; export const setContract = async (context: vscode.ExtensionContext, label: string) => { if (label === undefined) { // logger.log("No Contract selected."); return; } void context.workspaceState.update("selectedContract", `${label}.json`); logger.log(`${label} contract selected`); createABIFile(`${label}.json`); createAddressFile(`${label}.json`); }; export const selectCompiledContract = (context: vscode.ExtensionContext) => { const contracts = loadAllCompiledContract(); if (contracts === undefined) { logger.log("No Contract available."); return; }
const quickPick = vscode.window.createQuickPick<IContractQP>();
quickPick.items = contracts.map((contract: string) => ({ label: contract.substring(0, contract.length - 5), })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Contract"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; setContract(context, label); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getContractInfo = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_address.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const getContractABI = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_abi.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const isCairo1Contract = (fileName: string): boolean => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return false; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileData = fs.readFileSync( path.join(path_, fileName), { encoding: "utf-8" } ); return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; }; export const declareContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const fileName = selectedContract.substring(0, selectedContract.length - 5); if ( !fs.existsSync(path.join(path_, selectedContract)) || !fs.existsSync(path.join(path_, `${fileName}.casm`)) ) { logger.log(`${fileName}.json or ${fileName}.casm must be present.`); return; } const compiledContract = fs.readFileSync( path.join(path_, selectedContract), { encoding: "ascii", } ); const casmFileData = fs .readFileSync(path.join(path_, `${fileName}.casm`)) .toString("ascii"); const casmAssembly: CairoAssembly = JSON.parse(casmFileData); logger.log("Declaring contract..."); const declareResponse = await account.declareAndDeploy({ contract: compiledContract, casm: casmAssembly, }); logger.log( `declare transaction hash: ${declareResponse.deploy.transaction_hash}` ); logger.log(`declare classHash: ${declareResponse.deploy.classHash}`); logger.log("transaction successful"); } catch (error) { logger.log(`Error while contract declaration: ${error}`); } }; export const deployContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); logger.log("Deploying contract..."); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contractInfo = getContractInfo(path_, selectedContract); if (contractInfo.classHash === "") { logger.log("No classHash available for selected contract."); return; } const deployResponse = await account.deployContract({ classHash: contractInfo.classHash, }); logger.log(`transaction hash: ${deployResponse.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(deployResponse.transaction_hash); const { abi: testAbi } = await provider.getClassAt( deployResponse.contract_address ); if (testAbi === undefined) { throw new Error("no abi."); } const myTestContract = new Contract( testAbi, deployResponse.contract_address, provider ); await provider.waitForTransaction(myTestContract.transaction_hash); logger.log(`contract deployed successfully: ${myTestContract.address}`); } catch (error) { logger.log(`Error while contract deployment: ${error}`); } }; export const executeContractFunction = async ( context: vscode.ExtensionContext ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = await getSelectedFunction(path_, selectedContract); const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; export const executeContractFunctionFromTreeView = async ( context: vscode.ExtensionContext, functionabi: ABIFragment ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = functionabi; const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; const getSelectedFunction = ( path_: string, selectedContract: string ): Promise<ABIFragment> => { return new Promise((resolve, reject) => { try { const contractInfo: Array<ABIFragment> = getContractABI( path_, selectedContract ).abi; if (contractInfo === undefined) return; const quickPick = vscode.window.createQuickPick<IFunctionQP>(); quickPick.items = contractInfo.map((account: ABIFragment) => ({ label: account.name, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Function"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; quickPick.dispose(); const functionItem = contractInfo.filter( (i: ABIFragment) => i.name === label ); if (functionItem.length === 0) throw new Error("No function is selected"); resolve(functionItem[0]); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); } catch (error) { reject(error); } }); };
src/config/contract.ts
7finney-starkode-2fba517
[ { "filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport { isCairo1Contract, loadAllCompiledContract } from \"../../config/contract\";\nexport class ContractTreeDataProvider implements vscode.TreeDataProvider<Contract> {\n constructor(private workspaceRoot: string | undefined) { }\n getTreeItem(element: Contract): vscode.TreeItem {\n return element;\n }\n async getChildren(element?: Contract): Promise<Contract[]> {\n const contracts = loadAllCompiledContract();\n if (contracts === undefined || contracts.length === 0) {", "score": 24.456677100958622 }, { "filename": "src/extension.ts", "retrieved_chunk": " );\n let contractTreeView = vscode.window.createTreeView(\"starkode.contracts\", {\n treeDataProvider: contractTreeDataProvider,\n });\n // if contract tree view is empty\n const contracts = loadAllCompiledContract();\n if (contracts === undefined || contracts.length === 0) {\n contractTreeView.message = \"No contract found. Please compile your contract.\";\n }\n contractTreeView.onDidChangeSelection(event => {", "score": 22.893558778864833 }, { "filename": "src/config/account.ts", "retrieved_chunk": " context: vscode.ExtensionContext\n) => {\n const accounts: Array<JSONAccountType> | undefined =\n await getDeployedAccounts(context);\n if (accounts === undefined) return;\n const quickPick = vscode.window.createQuickPick<IAccountQP>();\n quickPick.items = accounts.map((account: JSONAccountType) => ({\n label: account.accountAddress,\n }));\n quickPick.onDidChangeActive(() => {", "score": 21.530510769489094 }, { "filename": "src/config/account.ts", "retrieved_chunk": ") => {\n const accounts: Array<JSONAccountType> | undefined =\n await getNotDeployedAccounts(context);\n if (accounts === undefined) return;\n const quickPick = vscode.window.createQuickPick<IAccountQP>();\n quickPick.items = accounts.map((account: JSONAccountType) => ({\n label: account.accountAddress,\n }));\n quickPick.onDidChangeActive(() => {\n quickPick.placeholder = \"Select account\";", "score": 19.159734579449164 }, { "filename": "src/config/account.ts", "retrieved_chunk": " false\n );\n if (accounts === undefined || accounts.length === 0) {\n logger.log(`No undeployed account available on ${selectedNetwork}`);\n return;\n }\n return accounts;\n};\nexport const selectNotDeployedAccount = async (\n context: vscode.ExtensionContext", "score": 18.96966654843511 } ]
typescript
const quickPick = vscode.window.createQuickPick<IContractQP>();
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console.log('Selected nodes:', selectedNodes[0].label); } }); // Account Tree View const accountTreeDataProvider = new AccountTreeDataProvider( context ); const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider =
new AbiTreeDataProvider( context );
const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await editInput(node, abiTreeDataProvider, selectedContract); }), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 72.20834176128588 }, { "filename": "src/config/account.ts", "retrieved_chunk": " if (presentAccounts === undefined) return;\n const isAccountPresent: any = presentAccounts.filter(\n (account) => account.accountAddress === unDeployedAccount\n );\n const selectedAccount: JSONAccountType = isAccountPresent[0];\n const selectedNetwork = context.workspaceState.get(\"selectedNetwork\");\n const provider = getNetworkProvider(context);\n console.log(`Account address: ${selectedAccount.accountAddress}`);\n if (provider === undefined) return;\n const account = new Account(", "score": 43.527582345117935 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");\n return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n const functionABI = functionabi;", "score": 42.51358002183221 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");\n return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n logger.log(\"Deploying contract...\");", "score": 41.7570509309892 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const provider = getNetworkProvider(context) as Provider;\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");", "score": 39.24381183615431 } ]
typescript
new AbiTreeDataProvider( context );
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata); const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger.log(`New account created: ${OZcontractAddress}`); } catch (error) { logger.error(`Error while creating new account: ${error}`); } }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false ); if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork"); const provider = getNetworkProvider(context); console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress, selectedAccount.privateKey, "1" ); logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({ classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount
.constructorCallData, addressSalt: selectedAccount.accountPubKey, });
logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false, gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, }; fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/extension.ts", "retrieved_chunk": " if (node.context === \"deployedAccount\") {\n void context.workspaceState.update(\"account\", node.account.accountAddress);\n logger.log(`${node.account.accountAddress} selected`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n abiTreeDataProvider.refresh();\n } else {", "score": 29.392529261509992 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");\n return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n logger.log(\"Deploying contract...\");", "score": 26.745025452353335 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 24.44244029666602 }, { "filename": "src/extension.ts", "retrieved_chunk": " treeDataProvider: accountTreeDataProvider,\n });\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount: string | undefined = context.workspaceState.get(\"account\") as string;\n accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}` : \"Select a deployed account , or create an account and deploy it\";\n // ABI Tree View\n const abiTreeDataProvider = new AbiTreeDataProvider(\n context\n );\n const abiTreeView = vscode.window.createTreeView(\"starkode.abis\", {", "score": 24.27649875407195 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");\n return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n const functionABI = functionabi;", "score": 22.27748510367029 } ]
typescript
.constructorCallData, addressSalt: selectedAccount.accountPubKey, });
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata); const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger.log(`New account created: ${OZcontractAddress}`); } catch (error) { logger.error(`Error while creating new account: ${error}`); } }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false ); if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({
label: account.accountAddress, }));
quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork"); const provider = getNetworkProvider(context); console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress, selectedAccount.privateKey, "1" ); logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({ classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, }); logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false, gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, }; fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/treeView/AccountTreeView/AccountTreeDataProvider.ts", "retrieved_chunk": " return element;\n }\n async getChildren(element?: Account): Promise<Account[]> {\n const accounts: Array<JSONAccountType> | undefined = getDeployedAccounts(this.context);\n const undeployedAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(this.context);\n if ((accounts === undefined && undeployedAccounts === undefined)){\n return [];\n } else {\n const leaves = [];\n if (accounts !== undefined) {", "score": 40.644353263742225 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " try {\n const contractInfo: Array<ABIFragment> = getContractABI(\n path_,\n selectedContract\n ).abi;\n if (contractInfo === undefined) return;\n const quickPick = vscode.window.createQuickPick<IFunctionQP>();\n quickPick.items = contractInfo.map((account: ABIFragment) => ({\n label: account.name,\n }));", "score": 34.52801805809601 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " createAddressFile(`${label}.json`);\n};\nexport const selectCompiledContract = (context: vscode.ExtensionContext) => {\n const contracts = loadAllCompiledContract();\n if (contracts === undefined) {\n logger.log(\"No Contract available.\");\n return;\n }\n const quickPick = vscode.window.createQuickPick<IContractQP>();\n quickPick.items = contracts.map((contract: string) => ({", "score": 31.986731253101684 }, { "filename": "src/config/network.ts", "retrieved_chunk": ") => {\n const quickPick = vscode.window.createQuickPick<INetworkQP>();\n quickPick.items = NETWORKS.map((name: string) => ({\n label: name,\n }));\n quickPick.onDidChangeActive(() => {\n quickPick.placeholder = \"Select network\";\n });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {", "score": 28.058233164476306 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": "};\nexport const accountDeployStatus = (\n accounts: Array<JSONAccountType>,\n selectedNetwork: string,\n status: boolean\n) => {\n const networks = [\"goerli-alpha\", \"goerli-alpha-2\", \"mainnet-alpha\"];\n let result: Array<JSONAccountType> | undefined;\n switch (selectedNetwork) {\n case networks[0]: {", "score": 27.418133206765013 } ]
typescript
label: account.accountAddress, }));
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata); const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger.log(`New account created: ${OZcontractAddress}`); } catch (error) { logger.error(`Error while creating new account: ${error}`); } }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false ); if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork"); const provider = getNetworkProvider(context); console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress,
selectedAccount.privateKey, "1" );
logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({ classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, }); logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false, gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, }; fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/extension.ts", "retrieved_chunk": " if (node.context === \"deployedAccount\") {\n void context.workspaceState.update(\"account\", node.account.accountAddress);\n logger.log(`${node.account.accountAddress} selected`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n abiTreeDataProvider.refresh();\n } else {", "score": 42.74978486024361 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " logger.log(\"No account selected.\");\n return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n const account = new Account(\n provider,\n accountInfo.accountAddress,\n accountInfo.privateKey,\n \"0\"\n );", "score": 39.155119569081506 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 36.645807427095356 }, { "filename": "src/extension.ts", "retrieved_chunk": " treeDataProvider: accountTreeDataProvider,\n });\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount: string | undefined = context.workspaceState.get(\"account\") as string;\n accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}` : \"Select a deployed account , or create an account and deploy it\";\n // ABI Tree View\n const abiTreeDataProvider = new AbiTreeDataProvider(\n context\n );\n const abiTreeView = vscode.window.createTreeView(\"starkode.abis\", {", "score": 35.1705264158293 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const provider = getNetworkProvider(context) as Provider;\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");", "score": 32.06813625908281 } ]
typescript
selectedAccount.privateKey, "1" );
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata); const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger.log(`New account created: ${OZcontractAddress}`); } catch (error) {
logger.error(`Error while creating new account: ${error}`);
} }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false ); if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork"); const provider = getNetworkProvider(context); console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress, selectedAccount.privateKey, "1" ); logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({ classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, }); logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false, gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, }; fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/utils/functions.ts", "retrieved_chunk": " fs.writeFileSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_abi.json`),\n JSON.stringify({ isCairo1: isCairo1Contract, abi: functionsValue }, null, 2)\n );\n logger.log(\"ABI file created successfully.\");\n } else {\n logger.log(`${fileName}_abi.json already exist.`);\n }\n } catch (error) {\n logger.log(`Error while writing to file: ${error}`);", "score": 31.17966434606426 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " classHash: \"\",\n }, null, 2)\n );\n logger.log(\"Address file created successfully.\");\n } else {\n logger.log(`${fileName}_address.json already exist.`);\n }\n } catch (error) {\n logger.log(`Error while writing to file: ${error}`);\n }", "score": 23.412368019395842 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " } catch (error) {\n logger.log(`Error while contract deployment: ${error}`);\n }\n};\nexport const executeContractFunction = async (\n context: vscode.ExtensionContext\n) => {\n try {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");", "score": 17.54830943350285 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " if (\n !fs.existsSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_address.json`)\n )\n ) {\n fs.writeFileSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_address.json`),\n JSON.stringify({\n name: fileName,\n address: \"\",", "score": 17.055250523886297 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " contract: compiledContract,\n casm: casmAssembly,\n });\n logger.log(\n `declare transaction hash: ${declareResponse.deploy.transaction_hash}`\n );\n logger.log(`declare classHash: ${declareResponse.deploy.classHash}`);\n logger.log(\"transaction successful\");\n } catch (error) {\n logger.log(`Error while contract declaration: ${error}`);", "score": 16.40879128763332 } ]
typescript
logger.error(`Error while creating new account: ${error}`);
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata); const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger.log(`New account created: ${OZcontractAddress}`); } catch (error) { logger.error(`Error while creating new account: ${error}`); } }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false ); if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork"); const provider = getNetworkProvider(context); console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress, selectedAccount.privateKey, "1" ); logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({ classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, }); logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false,
gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, };
fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/utils/functions.ts", "retrieved_chunk": " result = accounts.filter((e) => e.isDeployed.gAlpha === status);\n break;\n }\n case networks[1]: {\n result = accounts.filter((e) => e.isDeployed.gAlpha2 === status);\n break;\n }\n case networks[2]: {\n result = accounts.filter((e) => e.isDeployed.mainnet === status);\n break;", "score": 41.70659489094422 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n let networkBaseUrl: string | undefined = undefined;\n switch (selectedNetwork) {\n case NETWORKS[0]: {\n networkBaseUrl = \"https://alpha4.starknet.io\";\n break;\n }\n case NETWORKS[1]: {\n networkBaseUrl = \"https://alpha4-2.starknet.io\";\n break;", "score": 40.32886601419804 }, { "filename": "src/extension.ts", "retrieved_chunk": " if (node.context === \"deployedAccount\") {\n void context.workspaceState.update(\"account\", node.account.accountAddress);\n logger.log(`${node.account.accountAddress} selected`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n abiTreeDataProvider.refresh();\n } else {", "score": 33.53745654474782 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const fileData = fs.readFileSync(\n path.join(path_, fileName),\n { encoding: \"utf-8\" }\n );\n return JSON.parse(fileData).contract_class_version === \"0.1.0\" ? true : false;\n};\nexport const declareContract = async (context: vscode.ExtensionContext) => {\n try {\n if (vscode.workspace.workspaceFolders === undefined) {", "score": 33.02266670408931 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": "};\nexport const accountDeployStatus = (\n accounts: Array<JSONAccountType>,\n selectedNetwork: string,\n status: boolean\n) => {\n const networks = [\"goerli-alpha\", \"goerli-alpha-2\", \"mainnet-alpha\"];\n let result: Array<JSONAccountType> | undefined;\n switch (selectedNetwork) {\n case networks[0]: {", "score": 32.97659264074632 } ]
typescript
gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork === NETWORKS[2] ? true : false, };
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console.log('Selected nodes:', selectedNodes[0].label); } }); // Account Tree View const accountTreeDataProvider = new AccountTreeDataProvider( context ); const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string;
await editInput(node, abiTreeDataProvider, selectedContract);
}), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/treeView/ContractTreeView/function.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport { Contract as ContractTreeItem } from \"./ContractTreeDataProvider\";\nimport { logger } from \"../../lib\";\nimport path = require(\"path\");\nexport const refreshContract = async (node: ContractTreeItem, contractTreeDataProvider: any): Promise<vscode.TreeView<ContractTreeItem>> => {\n return vscode.window.createTreeView(\"starkode.contracts\", { treeDataProvider: contractTreeDataProvider, });\n};\nexport const editContractAddress = async (input : any,context: vscode.ExtensionContext) => {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Open or Create a cairo project.\");", "score": 35.699246218909934 }, { "filename": "src/config/account.ts", "retrieved_chunk": "};\nexport const deleteAccount = async (context: vscode.ExtensionContext,node: any) => {\n const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {\n encoding: \"utf-8\",\n });\n const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);\n const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress);\n fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2));\n};\nexport const selectDeployedAccount = async (", "score": 26.565088778089404 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");\n return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n const functionABI = functionabi;", "score": 22.19011112982358 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const provider = getNetworkProvider(context) as Provider;\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");", "score": 21.99674328482866 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount === undefined) {\n logger.log(\"No account selected.\");\n return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n logger.log(\"Deploying contract...\");", "score": 21.85471817741859 } ]
typescript
await editInput(node, abiTreeDataProvider, selectedContract);
import * as vscode from "vscode"; import * as fs from "fs"; import { Account, ec, json, stark, Provider, hash, CallData, Signer, } from "starknet"; import { logger } from "../lib"; import { IAccountQP, JSONAccountType } from "../types"; import { NETWORKS, getNetworkProvider } from "./network"; import { accountDeployStatus } from "../utils/functions"; export const createOZAccount = async (context: vscode.ExtensionContext) => { try { const privateKey = stark.randomAddress(); const publicKey = await new Signer(privateKey).getPubKey(); const OZaccountClassHash = "0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb"; const OZaccountConstructorCallData = CallData.compile({ publicKey: publicKey, }); const OZcontractAddress = hash.calculateContractAddressFromHash( publicKey, OZaccountClassHash, OZaccountConstructorCallData, 0 ); if (fs.existsSync(`${context.extensionPath}/accounts.json`)) { const filedata = fs.readFileSync( `${context.extensionPath}/accounts.json`, { encoding: "utf-8", } ); const parsedFileData = JSON.parse(filedata); const writeNewAccount: Array<JSONAccountType> = [ ...parsedFileData, { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } else { const writeNewAccount: Array<JSONAccountType> = [ { accountHash: OZaccountClassHash, constructorCallData: OZaccountConstructorCallData, accountPubKey: publicKey, accountAddress: OZcontractAddress, privateKey: privateKey, isDeployed: { gAlpha: false, gAlpha2: false, mainnet: false, }, }, ]; fs.writeFileSync( `${context.extensionPath}/accounts.json`, JSON.stringify(writeNewAccount) ); } logger.log(`New account created: ${OZcontractAddress}`); } catch (error) { logger.error(`Error while creating new account: ${error}`); } }; export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined) { logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, false ); if (accounts === undefined || accounts.length === 0) { logger.log(`No undeployed account available on ${selectedNetwork}`); return; } return accounts; }; export const selectNotDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("undeployedAccount", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => { const presentAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(context); const unDeployedAccount = await context.workspaceState.get( "undeployedAccount" ); if (presentAccounts === undefined) return; const isAccountPresent: any = presentAccounts.filter( (account) => account.accountAddress === unDeployedAccount ); const selectedAccount: JSONAccountType = isAccountPresent[0]; const selectedNetwork = context.workspaceState.get("selectedNetwork"); const provider = getNetworkProvider(context); console.log(`Account address: ${selectedAccount.accountAddress}`); if (provider === undefined) return; const account = new Account( provider, selectedAccount.accountAddress, selectedAccount.privateKey, "1" ); logger.log( `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}` ); const { contract_address, transaction_hash } = await account.deployAccount({ classHash: selectedAccount.accountHash, constructorCalldata: selectedAccount.constructorCallData, addressSalt: selectedAccount.accountPubKey, }); logger.log(`Transaction hash: ${transaction_hash}`); await provider.waitForTransaction(transaction_hash); await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount); logger.log(`Account deployed successfully at address: ${contract_address}`); accountTreeDataProvider.refresh(); }; const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => { const selectedNetwork = context.workspaceState.get("selectedNetwork"); fs.readFile(path, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const accounts = JSON.parse(data); const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress); if (indexToUpdate !== -1) { accounts[indexToUpdate].isDeployed = { gAlpha: selectedNetwork === NETWORKS[0] ? true : false, gAlpha2: selectedNetwork === NETWORKS[1] ? true : false, mainnet: selectedNetwork
=== NETWORKS[2] ? true : false, };
fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file successfully updated.'); }); } else { console.error('Element not found in JSON file.'); } }); }; export const getDeployedAccounts = (context: vscode.ExtensionContext) => { const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); if (selectedNetwork === undefined){ // logger.log("Network not selected"); return; } if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) { logger.log("No deployed account exist."); return; } const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const accounts: Array<JSONAccountType> | undefined = accountDeployStatus( parsedFileData, selectedNetwork, true ); if (accounts === undefined || accounts.length === 0) { logger.log(`No deployed account available on ${selectedNetwork}`); return; } return accounts; }; export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => { const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, { encoding: "utf-8", }); const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData); const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress); fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2)); }; export const selectDeployedAccount = async ( context: vscode.ExtensionContext ) => { const accounts: Array<JSONAccountType> | undefined = await getDeployedAccounts(context); if (accounts === undefined) return; const quickPick = vscode.window.createQuickPick<IAccountQP>(); quickPick.items = accounts.map((account: JSONAccountType) => ({ label: account.accountAddress, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select account"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; void context.workspaceState.update("account", label); logger.log(`${label} selected`); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getAccountInfo = ( context: vscode.ExtensionContext, accountAddress: string ) => { const accounts = getDeployedAccounts(context) as JSONAccountType[]; const selectedAccountInfo = accounts.filter( (account) => account.accountAddress === accountAddress ); return selectedAccountInfo[0]; };
src/config/account.ts
7finney-starkode-2fba517
[ { "filename": "src/utils/functions.ts", "retrieved_chunk": " result = accounts.filter((e) => e.isDeployed.gAlpha === status);\n break;\n }\n case networks[1]: {\n result = accounts.filter((e) => e.isDeployed.gAlpha2 === status);\n break;\n }\n case networks[2]: {\n result = accounts.filter((e) => e.isDeployed.mainnet === status);\n break;", "score": 41.70659489094422 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n let networkBaseUrl: string | undefined = undefined;\n switch (selectedNetwork) {\n case NETWORKS[0]: {\n networkBaseUrl = \"https://alpha4.starknet.io\";\n break;\n }\n case NETWORKS[1]: {\n networkBaseUrl = \"https://alpha4-2.starknet.io\";\n break;", "score": 40.32886601419804 }, { "filename": "src/extension.ts", "retrieved_chunk": " if (node.context === \"deployedAccount\") {\n void context.workspaceState.update(\"account\", node.account.accountAddress);\n logger.log(`${node.account.accountAddress} selected`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n abiTreeDataProvider.refresh();\n } else {", "score": 33.53745654474782 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": "};\nexport const accountDeployStatus = (\n accounts: Array<JSONAccountType>,\n selectedNetwork: string,\n status: boolean\n) => {\n const networks = [\"goerli-alpha\", \"goerli-alpha-2\", \"mainnet-alpha\"];\n let result: Array<JSONAccountType> | undefined;\n switch (selectedNetwork) {\n case networks[0]: {", "score": 32.97659264074632 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const fileData = fs.readFileSync(\n path.join(path_, fileName),\n { encoding: \"utf-8\" }\n );\n return JSON.parse(fileData).contract_class_version === \"0.1.0\" ? true : false;\n};\nexport const declareContract = async (context: vscode.ExtensionContext) => {\n try {\n if (vscode.workspace.workspaceFolders === undefined) {", "score": 32.60451569942129 } ]
typescript
=== NETWORKS[2] ? true : false, };
import * as vscode from "vscode"; import * as fs from "fs"; import path, { resolve } from "path"; import { logger } from "../lib"; import { ABIFragment, IContractQP, IFunctionQP } from "../types"; import { createABIFile, createAddressFile } from "../utils/functions"; import { getAccountInfo } from "./account"; import { Account, CairoAssembly, Contract, ec, Provider } from "starknet"; import { getNetworkProvider } from "./network"; export const loadAllCompiledContract = () => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const compiledCairoContract = fs .readdirSync(path_) .filter((file) => exportPathOfJSONfiles(path_, file)); return compiledCairoContract; }; const exportPathOfJSONfiles = (path_: string, file: string) => { const filePath = path.join(path_, file); if (path.extname(filePath) === ".json") { const fileData = fs.readFileSync(filePath, { encoding: "utf-8", }); if (JSON.parse(fileData).program) return filePath; if (JSON.parse(fileData).contract_class_version) { return filePath; } } }; export const setContract = async (context: vscode.ExtensionContext, label: string) => { if (label === undefined) { // logger.log("No Contract selected."); return; } void context.workspaceState.update("selectedContract", `${label}.json`); logger.log(`${label} contract selected`); createABIFile(`${label}.json`); createAddressFile(`${label}.json`); }; export const selectCompiledContract = (context: vscode.ExtensionContext) => { const contracts = loadAllCompiledContract(); if (contracts === undefined) { logger.log("No Contract available."); return; } const quickPick = vscode.window.createQuickPick<IContractQP>(); quickPick.items = contracts.map((contract: string) => ({ label: contract.substring(0, contract.length - 5), })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Contract"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; setContract(context, label); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getContractInfo = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_address.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const getContractABI = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_abi.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const isCairo1Contract = (fileName: string): boolean => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return false; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileData = fs.readFileSync( path.join(path_, fileName), { encoding: "utf-8" } ); return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; }; export const declareContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const fileName = selectedContract.substring(0, selectedContract.length - 5); if ( !fs.existsSync(path.join(path_, selectedContract)) || !fs.existsSync(path.join(path_, `${fileName}.casm`)) ) { logger.log(`${fileName}.json or ${fileName}.casm must be present.`); return; } const compiledContract = fs.readFileSync( path.join(path_, selectedContract), { encoding: "ascii", } ); const casmFileData = fs .readFileSync(path.join(path_, `${fileName}.casm`)) .toString("ascii"); const casmAssembly: CairoAssembly = JSON.parse(casmFileData); logger.log("Declaring contract..."); const declareResponse = await account.declareAndDeploy({ contract: compiledContract, casm: casmAssembly, }); logger.log( `declare transaction hash: ${declareResponse.deploy.transaction_hash}` ); logger.log(`declare classHash: ${declareResponse.deploy.classHash}`); logger.log("transaction successful"); } catch (error) { logger.log(`Error while contract declaration: ${error}`); } }; export const deployContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); logger.log("Deploying contract..."); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contractInfo = getContractInfo(path_, selectedContract); if (contractInfo.classHash === "") { logger.log("No classHash available for selected contract."); return; } const deployResponse = await account.deployContract({ classHash: contractInfo.classHash, }); logger.log(`transaction hash: ${deployResponse.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(deployResponse.transaction_hash); const { abi: testAbi } = await provider.getClassAt( deployResponse.contract_address ); if (testAbi === undefined) { throw new Error("no abi."); } const myTestContract = new Contract( testAbi, deployResponse.contract_address, provider ); await provider.waitForTransaction(myTestContract.transaction_hash); logger.log(`contract deployed successfully: ${myTestContract.address}`); } catch (error) { logger.log(`Error while contract deployment: ${error}`); } }; export const executeContractFunction = async ( context: vscode.ExtensionContext ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = await getSelectedFunction(path_, selectedContract); const contractInfo = getContractInfo(path_, selectedContract);
const params_: Array<any> = functionABI.inputs.map((e) => {
return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; export const executeContractFunctionFromTreeView = async ( context: vscode.ExtensionContext, functionabi: ABIFragment ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = functionabi; const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; const getSelectedFunction = ( path_: string, selectedContract: string ): Promise<ABIFragment> => { return new Promise((resolve, reject) => { try { const contractInfo: Array<ABIFragment> = getContractABI( path_, selectedContract ).abi; if (contractInfo === undefined) return; const quickPick = vscode.window.createQuickPick<IFunctionQP>(); quickPick.items = contractInfo.map((account: ABIFragment) => ({ label: account.name, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Function"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; quickPick.dispose(); const functionItem = contractInfo.filter( (i: ABIFragment) => i.name === label ); if (functionItem.length === 0) throw new Error("No function is selected"); resolve(functionItem[0]); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); } catch (error) { reject(error); } }); };
src/config/contract.ts
7finney-starkode-2fba517
[ { "filename": "src/extension.ts", "retrieved_chunk": " if (node.context === \"deployedAccount\") {\n void context.workspaceState.update(\"account\", node.account.accountAddress);\n logger.log(`${node.account.accountAddress} selected`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n abiTreeDataProvider.refresh();\n } else {", "score": 35.53391801008084 }, { "filename": "src/extension.ts", "retrieved_chunk": " }),\n vscode.commands.registerCommand(\"starkode.deploycontract\", async (node: any) => {\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n if (selectedContract === undefined) {\n logger.log(\"No Contract selected\");\n return;\n }\n if (selectedContract.slice(0, -5) !== node.label) {", "score": 32.98354687393021 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 31.85556123292053 }, { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " const selectedContract: string | undefined = this.context.workspaceState.get(\"selectedContract\") as string;\n const data = getContractABI(path_,selectedContract);\n const inputFunction: Array<ABIFragment> | undefined = selectedContract !== undefined ? data === undefined ? undefined : data.abi :\n [];\n if (inputFunction === undefined) {\n return undefined;\n } \n else {\n if (!element) {\n for (const entry of inputFunction) {", "score": 31.842911623905366 }, { "filename": "src/extension.ts", "retrieved_chunk": " treeDataProvider: accountTreeDataProvider,\n });\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount: string | undefined = context.workspaceState.get(\"account\") as string;\n accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}` : \"Select a deployed account , or create an account and deploy it\";\n // ABI Tree View\n const abiTreeDataProvider = new AbiTreeDataProvider(\n context\n );\n const abiTreeView = vscode.window.createTreeView(\"starkode.abis\", {", "score": 31.50768935523578 } ]
typescript
const params_: Array<any> = functionABI.inputs.map((e) => {
import * as vscode from "vscode"; import * as fs from "fs"; import path, { resolve } from "path"; import { logger } from "../lib"; import { ABIFragment, IContractQP, IFunctionQP } from "../types"; import { createABIFile, createAddressFile } from "../utils/functions"; import { getAccountInfo } from "./account"; import { Account, CairoAssembly, Contract, ec, Provider } from "starknet"; import { getNetworkProvider } from "./network"; export const loadAllCompiledContract = () => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const compiledCairoContract = fs .readdirSync(path_) .filter((file) => exportPathOfJSONfiles(path_, file)); return compiledCairoContract; }; const exportPathOfJSONfiles = (path_: string, file: string) => { const filePath = path.join(path_, file); if (path.extname(filePath) === ".json") { const fileData = fs.readFileSync(filePath, { encoding: "utf-8", }); if (JSON.parse(fileData).program) return filePath; if (JSON.parse(fileData).contract_class_version) { return filePath; } } }; export const setContract = async (context: vscode.ExtensionContext, label: string) => { if (label === undefined) { // logger.log("No Contract selected."); return; } void context.workspaceState.update("selectedContract", `${label}.json`); logger.log(`${label} contract selected`); createABIFile(`${label}.json`); createAddressFile(`${label}.json`); }; export const selectCompiledContract = (context: vscode.ExtensionContext) => { const contracts = loadAllCompiledContract(); if (contracts === undefined) { logger.log("No Contract available."); return; } const quickPick = vscode.window.createQuickPick<IContractQP>(); quickPick.items = contracts.map((contract: string) => ({ label: contract.substring(0, contract.length - 5), })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Contract"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; setContract(context, label); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getContractInfo = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_address.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const getContractABI = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_abi.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const isCairo1Contract = (fileName: string): boolean => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return false; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileData = fs.readFileSync( path.join(path_, fileName), { encoding: "utf-8" } ); return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; }; export const declareContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const fileName = selectedContract.substring(0, selectedContract.length - 5); if ( !fs.existsSync(path.join(path_, selectedContract)) || !fs.existsSync(path.join(path_, `${fileName}.casm`)) ) { logger.log(`${fileName}.json or ${fileName}.casm must be present.`); return; } const compiledContract = fs.readFileSync( path.join(path_, selectedContract), { encoding: "ascii", } ); const casmFileData = fs .readFileSync(path.join(path_, `${fileName}.casm`)) .toString("ascii"); const casmAssembly: CairoAssembly = JSON.parse(casmFileData); logger.log("Declaring contract..."); const declareResponse = await account.declareAndDeploy({ contract: compiledContract, casm: casmAssembly, }); logger.log( `declare transaction hash: ${declareResponse.deploy.transaction_hash}` ); logger.log(`declare classHash: ${declareResponse.deploy.classHash}`); logger.log("transaction successful"); } catch (error) { logger.log(`Error while contract declaration: ${error}`); } }; export const deployContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); logger.log("Deploying contract..."); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contractInfo = getContractInfo(path_, selectedContract); if (contractInfo.classHash === "") { logger.log("No classHash available for selected contract."); return; } const deployResponse = await account.deployContract({ classHash: contractInfo.classHash, }); logger.log(`transaction hash: ${deployResponse.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(deployResponse.transaction_hash); const { abi: testAbi } = await provider.getClassAt( deployResponse.contract_address ); if (testAbi === undefined) { throw new Error("no abi."); } const myTestContract = new Contract( testAbi, deployResponse.contract_address, provider ); await provider.waitForTransaction(myTestContract.transaction_hash); logger.log(`contract deployed successfully: ${myTestContract.address}`); } catch (error) { logger.log(`Error while contract deployment: ${error}`); } }; export const executeContractFunction = async ( context: vscode.ExtensionContext ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = await getSelectedFunction(path_, selectedContract); const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; export const executeContractFunctionFromTreeView = async ( context: vscode.ExtensionContext, functionabi: ABIFragment ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = functionabi; const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; const getSelectedFunction = ( path_: string, selectedContract: string ): Promise<ABIFragment> => { return new Promise((resolve, reject) => { try { const contractInfo: Array<ABIFragment> = getContractABI( path_, selectedContract ).abi; if (contractInfo === undefined) return;
const quickPick = vscode.window.createQuickPick<IFunctionQP>();
quickPick.items = contractInfo.map((account: ABIFragment) => ({ label: account.name, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Function"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; quickPick.dispose(); const functionItem = contractInfo.filter( (i: ABIFragment) => i.name === label ); if (functionItem.length === 0) throw new Error("No function is selected"); resolve(functionItem[0]); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); } catch (error) { reject(error); } }); };
src/config/contract.ts
7finney-starkode-2fba517
[ { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " const selectedContract: string | undefined = this.context.workspaceState.get(\"selectedContract\") as string;\n const data = getContractABI(path_,selectedContract);\n const inputFunction: Array<ABIFragment> | undefined = selectedContract !== undefined ? data === undefined ? undefined : data.abi :\n [];\n if (inputFunction === undefined) {\n return undefined;\n } \n else {\n if (!element) {\n for (const entry of inputFunction) {", "score": 29.82929435634579 }, { "filename": "src/extension.ts", "retrieved_chunk": " treeDataProvider: abiTreeDataProvider,\n });\n const contractName: string | undefined = context.workspaceState.get(\"selectedContract\");\n if (!contractName || contractName === undefined) {\n abiTreeView.message = \"Select a contract and its ABI functions will appear here.\";\n }\n else {\n const contractInfo = getContractInfo(path_, contractName);\n if (contractInfo !== undefined) {\n abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;", "score": 20.823697491373252 }, { "filename": "src/config/account.ts", "retrieved_chunk": " context: vscode.ExtensionContext\n) => {\n const accounts: Array<JSONAccountType> | undefined =\n await getDeployedAccounts(context);\n if (accounts === undefined) return;\n const quickPick = vscode.window.createQuickPick<IAccountQP>();\n quickPick.items = accounts.map((account: JSONAccountType) => ({\n label: account.accountAddress,\n }));\n quickPick.onDidChangeActive(() => {", "score": 16.848247787719547 }, { "filename": "src/config/account.ts", "retrieved_chunk": ") => {\n const accounts: Array<JSONAccountType> | undefined =\n await getNotDeployedAccounts(context);\n if (accounts === undefined) return;\n const quickPick = vscode.window.createQuickPick<IAccountQP>();\n quickPick.items = accounts.map((account: JSONAccountType) => ({\n label: account.accountAddress,\n }));\n quickPick.onDidChangeActive(() => {\n quickPick.placeholder = \"Select account\";", "score": 16.654743358486925 }, { "filename": "src/extension.ts", "retrieved_chunk": " } else {\n abiTreeView.message = undefined;\n const contractInfo = getContractInfo(path_, contractName);\n abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;\n }\n abiTreeDataProvider.refresh();\n });\n // Contract Tree View\n const contractTreeDataProvider = new ContractTreeDataProvider(\n vscode.workspace.workspaceFolders?.[0].uri.fsPath", "score": 16.348880472453523 } ]
typescript
const quickPick = vscode.window.createQuickPick<IFunctionQP>();
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console.log('Selected nodes:', selectedNodes[0].label); } }); // Account Tree View const accountTreeDataProvider = new AccountTreeDataProvider( context ); const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.
log(`${node.account.accountAddress} selected`);
const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await editInput(node, abiTreeDataProvider, selectedContract); }), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/config/account.ts", "retrieved_chunk": "};\nexport const deleteAccount = async (context: vscode.ExtensionContext,node: any) => {\n const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {\n encoding: \"utf-8\",\n });\n const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);\n const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress);\n fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2));\n};\nexport const selectDeployedAccount = async (", "score": 38.37447254630659 }, { "filename": "src/treeView/ContractTreeView/function.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport { Contract as ContractTreeItem } from \"./ContractTreeDataProvider\";\nimport { logger } from \"../../lib\";\nimport path = require(\"path\");\nexport const refreshContract = async (node: ContractTreeItem, contractTreeDataProvider: any): Promise<vscode.TreeView<ContractTreeItem>> => {\n return vscode.window.createTreeView(\"starkode.contracts\", { treeDataProvider: contractTreeDataProvider, });\n};\nexport const editContractAddress = async (input : any,context: vscode.ExtensionContext) => {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Open or Create a cairo project.\");", "score": 22.794111343397027 }, { "filename": "src/config/account.ts", "retrieved_chunk": " quickPick.placeholder = \"Select account\";\n });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n void context.workspaceState.update(\"account\", label);\n logger.log(`${label} selected`);\n quickPick.dispose();\n }\n });", "score": 22.004578188628784 }, { "filename": "src/config/account.ts", "retrieved_chunk": " if (presentAccounts === undefined) return;\n const isAccountPresent: any = presentAccounts.filter(\n (account) => account.accountAddress === unDeployedAccount\n );\n const selectedAccount: JSONAccountType = isAccountPresent[0];\n const selectedNetwork = context.workspaceState.get(\"selectedNetwork\");\n const provider = getNetworkProvider(context);\n console.log(`Account address: ${selectedAccount.accountAddress}`);\n if (provider === undefined) return;\n const account = new Account(", "score": 19.49763238222275 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " }\n};\nexport const setContract = async (context: vscode.ExtensionContext, label: string) => {\n if (label === undefined) {\n // logger.log(\"No Contract selected.\");\n return;\n }\n void context.workspaceState.update(\"selectedContract\", `${label}.json`);\n logger.log(`${label} contract selected`);\n createABIFile(`${label}.json`);", "score": 19.49465732900034 } ]
typescript
log(`${node.account.accountAddress} selected`);
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console
.log('Selected nodes:', selectedNodes[0].label);
} }); // Account Tree View const accountTreeDataProvider = new AccountTreeDataProvider( context ); const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await editInput(node, abiTreeDataProvider, selectedContract); }), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/config/contract.ts", "retrieved_chunk": " createAddressFile(`${label}.json`);\n};\nexport const selectCompiledContract = (context: vscode.ExtensionContext) => {\n const contracts = loadAllCompiledContract();\n if (contracts === undefined) {\n logger.log(\"No Contract available.\");\n return;\n }\n const quickPick = vscode.window.createQuickPick<IContractQP>();\n quickPick.items = contracts.map((contract: string) => ({", "score": 32.323032057388524 }, { "filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport { isCairo1Contract, loadAllCompiledContract } from \"../../config/contract\";\nexport class ContractTreeDataProvider implements vscode.TreeDataProvider<Contract> {\n constructor(private workspaceRoot: string | undefined) { }\n getTreeItem(element: Contract): vscode.TreeItem {\n return element;\n }\n async getChildren(element?: Contract): Promise<Contract[]> {\n const contracts = loadAllCompiledContract();\n if (contracts === undefined || contracts.length === 0) {", "score": 30.948444533204572 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " label: contract.substring(0, contract.length - 5),\n }));\n quickPick.onDidChangeActive(() => {\n quickPick.placeholder = \"Select Contract\";\n });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n setContract(context, label);\n quickPick.dispose();", "score": 27.911440309903288 }, { "filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts", "retrieved_chunk": " vscode.window.showInformationMessage(\"No Contracts in workspace\");\n return [];\n } else {\n const leaves = [];\n for (const file of contracts) {\n leaves.push(new Contract(\n file.slice(0, -5),\n vscode.TreeItemCollapsibleState.None,\n \"contract\",\n isCairo1Contract(file) ? \"file-code\" : \"file-text\"", "score": 20.619884230482505 }, { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 19.454464446549473 } ]
typescript
.log('Selected nodes:', selectedNodes[0].label);
import { action, computed, makeObservable, observable } from 'mobx'; import { clone, every, forEach, pickBy, some } from 'lodash'; import Field from '../Field'; import type { FormFields, FormParams, FormSubmitAction, FormValues } from './types'; import { valuesOf, wrapInAsyncAction } from './utils'; import type { ValueType } from '../utils/types'; import deprecatedMethod from '../utils/deprecatedMethod'; export default class Form { private _fields: FormFields; private submitAction: FormSubmitAction; private _isSubmitting: boolean; constructor( { fields, onSubmit = () => undefined }: FormParams ) { this._fields = fields; this.submitAction = wrapInAsyncAction( onSubmit ); this._isSubmitting = false; this.attachFields(); makeObservable<Form, '_fields' | 'submitAction' | '_isSubmitting' >( this, { _fields: observable, submitAction: observable, _isSubmitting: observable, fields: computed, values: computed, dirtyValues: computed, isValid: computed, isDirty: computed, isReadyToSubmit: computed, isSubmitting: computed, submit: action, clear: action, reset: action, showErrors: action } ); } get fields(): FormFields { return clone( this._fields ); } get values(): FormValues { return valuesOf( this._fields ); } get dirtyValues(): FormValues { return valuesOf( this.dirtyFields ); } get isValid() { return every( this.enabledFields, field => field.isValid ); } get isDirty() { return some( this._fields, field => field.isDirty ); } get isReadyToSubmit() { return this.isValid && this.isDirty && !this.isSubmitting; } get isSubmitting() { return this._isSubmitting; }
field<FieldType extends Field<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) {
return this._fields[ fieldKey ] as FieldType; } select<FieldType extends Field<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) { deprecatedMethod( 'Form', 'select', { alternative: 'field', docsPath: '/reference/Form.md#field' } ); return this.field<FieldType>( fieldKey ); } eachField( actionOnField: ( field: Field<unknown> ) => void ) { forEach( this._fields, actionOnField ); } submit(): Promise<void> { this.syncFieldErrors(); if ( !this.isValid || this.isSubmitting ) return Promise.resolve(); return this.executeSubmitAction(); } clear() { this.eachField( field => field.clear() ); } reset() { this.eachField( field => field.reset() ); } showErrors( errors: Record<string, string> ) { forEach( errors, ( error, fieldKey ) => this.showErrorOnField( fieldKey, error ) ); } private attachFields() { forEach( this._fields, field => field.attachToForm( this ) ); } private get dirtyFields() { return this.pickFieldsBy( field => field.isDirty ); } private get enabledFields() { return this.pickFieldsBy( field => !field.isDisabled ); } private pickFieldsBy( predicate: ( field: Field<unknown> ) => boolean ): FormFields { return pickBy( this._fields, predicate ); } private syncFieldErrors() { forEach( this._fields, field => field.syncError() ); } private executeSubmitAction() { this._isSubmitting = true; return this.submitAction( this ) .finally( action( () => { this._isSubmitting = false; } ) ); } private showErrorOnField( fieldKey: string, error: string ) { this._fields[ fieldKey ]?.showError( error ); } } export type { FormParams, FormValues };
src/Form/index.ts
amalgamaco-mobx-form-ad7afec
[ { "filename": "src/Field/index.ts", "retrieved_chunk": "\tget isValid() {\n\t\treturn this._state.isValid;\n\t}\n\tget isDirty() {\n\t\treturn this._state.isDirty;\n\t}\n\tget error() {\n\t\treturn this._presentedError;\n\t}\n\tget isDisabled() {", "score": 41.08802401142886 }, { "filename": "src/utils/FieldState/index.ts", "retrieved_chunk": "\tget isDirty() {\n\t\treturn this._value !== this._initialValue;\n\t}\n\tget isDisabled() {\n\t\treturn this._isDisabled;\n\t}\n\tget error() {\n\t\treturn this.failedValidationResult?.error;\n\t}\n\tget parentForm() {", "score": 34.42433512900016 }, { "filename": "src/utils/FieldState/index.ts", "retrieved_chunk": "\t\tthis._isDisabled = disabled;\n\t\tmakeAutoObservable( this );\n\t\tthis.setUpOnChangeReaction();\n\t}\n\tget value() {\n\t\treturn this._value;\n\t}\n\tget isValid() {\n\t\treturn !this.failedValidationResult;\n\t}", "score": 25.711416174945548 }, { "filename": "src/utils/FieldState/index.ts", "retrieved_chunk": "\t\t\t() => this._value,\n\t\t\t( newValue: ValueType ) => this._onChange?.( newValue, this._parentForm )\n\t\t);\n\t}\n\tprivate get failedValidationResult() {\n\t\treturn this.validationResults.find( result => !result.isValid );\n\t}\n\tprivate get validationResults() {\n\t\treturn this._validators.map(\n\t\t\tvalidator => validator( this._value, this._parentForm, this.label )", "score": 22.77526932971629 }, { "filename": "src/Field/index.ts", "retrieved_chunk": "\t\t\tshowError: action,\n\t\t\tattachToForm: action\n\t\t} );\n\t}\n\tget label() {\n\t\treturn this._state.label;\n\t}\n\tget value() {\n\t\treturn this._state.value;\n\t}", "score": 21.46188193300895 } ]
typescript
field<FieldType extends Field<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) {
import { action, computed, makeObservable, observable } from 'mobx'; import { clone, every, forEach, pickBy, some } from 'lodash'; import Field from '../Field'; import type { FormFields, FormParams, FormSubmitAction, FormValues } from './types'; import { valuesOf, wrapInAsyncAction } from './utils'; import type { ValueType } from '../utils/types'; import deprecatedMethod from '../utils/deprecatedMethod'; export default class Form { private _fields: FormFields; private submitAction: FormSubmitAction; private _isSubmitting: boolean; constructor( { fields, onSubmit = () => undefined }: FormParams ) { this._fields = fields; this.submitAction = wrapInAsyncAction( onSubmit ); this._isSubmitting = false; this.attachFields(); makeObservable<Form, '_fields' | 'submitAction' | '_isSubmitting' >( this, { _fields: observable, submitAction: observable, _isSubmitting: observable, fields: computed, values: computed, dirtyValues: computed, isValid: computed, isDirty: computed, isReadyToSubmit: computed, isSubmitting: computed, submit: action, clear: action, reset: action, showErrors: action } ); } get fields(): FormFields { return clone( this._fields ); } get values(): FormValues { return valuesOf( this._fields ); } get dirtyValues(): FormValues { return valuesOf( this.dirtyFields ); } get isValid() { return every( this.enabledFields, field => field.isValid ); } get isDirty() { return some( this._fields, field => field.isDirty ); } get isReadyToSubmit() { return this.isValid && this.isDirty && !this.isSubmitting; } get isSubmitting() { return this._isSubmitting; } field
<FieldType extends Field<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) {
return this._fields[ fieldKey ] as FieldType; } select<FieldType extends Field<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) { deprecatedMethod( 'Form', 'select', { alternative: 'field', docsPath: '/reference/Form.md#field' } ); return this.field<FieldType>( fieldKey ); } eachField( actionOnField: ( field: Field<unknown> ) => void ) { forEach( this._fields, actionOnField ); } submit(): Promise<void> { this.syncFieldErrors(); if ( !this.isValid || this.isSubmitting ) return Promise.resolve(); return this.executeSubmitAction(); } clear() { this.eachField( field => field.clear() ); } reset() { this.eachField( field => field.reset() ); } showErrors( errors: Record<string, string> ) { forEach( errors, ( error, fieldKey ) => this.showErrorOnField( fieldKey, error ) ); } private attachFields() { forEach( this._fields, field => field.attachToForm( this ) ); } private get dirtyFields() { return this.pickFieldsBy( field => field.isDirty ); } private get enabledFields() { return this.pickFieldsBy( field => !field.isDisabled ); } private pickFieldsBy( predicate: ( field: Field<unknown> ) => boolean ): FormFields { return pickBy( this._fields, predicate ); } private syncFieldErrors() { forEach( this._fields, field => field.syncError() ); } private executeSubmitAction() { this._isSubmitting = true; return this.submitAction( this ) .finally( action( () => { this._isSubmitting = false; } ) ); } private showErrorOnField( fieldKey: string, error: string ) { this._fields[ fieldKey ]?.showError( error ); } } export type { FormParams, FormValues };
src/Form/index.ts
amalgamaco-mobx-form-ad7afec
[ { "filename": "src/Field/index.ts", "retrieved_chunk": "\tget isValid() {\n\t\treturn this._state.isValid;\n\t}\n\tget isDirty() {\n\t\treturn this._state.isDirty;\n\t}\n\tget error() {\n\t\treturn this._presentedError;\n\t}\n\tget isDisabled() {", "score": 32.63931788820821 }, { "filename": "src/utils/FieldState/index.ts", "retrieved_chunk": "\tget isDirty() {\n\t\treturn this._value !== this._initialValue;\n\t}\n\tget isDisabled() {\n\t\treturn this._isDisabled;\n\t}\n\tget error() {\n\t\treturn this.failedValidationResult?.error;\n\t}\n\tget parentForm() {", "score": 27.310872855578992 }, { "filename": "src/utils/FieldState/index.ts", "retrieved_chunk": "\t\tthis._isDisabled = disabled;\n\t\tmakeAutoObservable( this );\n\t\tthis.setUpOnChangeReaction();\n\t}\n\tget value() {\n\t\treturn this._value;\n\t}\n\tget isValid() {\n\t\treturn !this.failedValidationResult;\n\t}", "score": 22.412555760926942 }, { "filename": "src/utils/FieldState/index.ts", "retrieved_chunk": "\t\t\t() => this._value,\n\t\t\t( newValue: ValueType ) => this._onChange?.( newValue, this._parentForm )\n\t\t);\n\t}\n\tprivate get failedValidationResult() {\n\t\treturn this.validationResults.find( result => !result.isValid );\n\t}\n\tprivate get validationResults() {\n\t\treturn this._validators.map(\n\t\t\tvalidator => validator( this._value, this._parentForm, this.label )", "score": 20.122188468674576 }, { "filename": "src/Field/index.ts", "retrieved_chunk": "\t\t\tshowError: action,\n\t\t\tattachToForm: action\n\t\t} );\n\t}\n\tget label() {\n\t\treturn this._state.label;\n\t}\n\tget value() {\n\t\treturn this._state.value;\n\t}", "score": 18.115102046087895 } ]
typescript
<FieldType extends Field<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) {
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { logger } from "../lib"; import { ABIFragment, JSONAccountType, TIsAccountDeployed } from "../types"; export const createABIFile = (file: string) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileName = file.substring(0, file.length - 5); if (!fs.existsSync(path.join(path_, "starkode", fileName))) { fs.mkdirSync(path.join(path_, "starkode", fileName),{recursive: true}); } if ( !fs.existsSync( path.join(path_, "starkode", fileName, `${fileName}_abi.json`) ) ) { const filePath = path.join(path_, file); const fileData = fs.readFileSync(filePath, { encoding: "utf-8" }); const isCairo1Contract = JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; const abi: Array<ABIFragment> = JSON.parse(fileData).abi; const abiFunctions = abi.filter((e) => e.type === "function"); const functionsValue = abiFunctions.map((func) => { return { type: func.type, name: func.name, inputs: func.inputs.map((e) => { return { ...e, value: "" }; }), stateMutability: func.stateMutability ? func.stateMutability : func.state_mutability, outputs: func.outputs, }; }); fs.writeFileSync( path.join(path_, "starkode", fileName, `${fileName}_abi.json`), JSON.stringify({ isCairo1: isCairo1Contract, abi: functionsValue }, null, 2) ); logger.log("ABI file created successfully."); } else { logger.log(`${fileName}_abi.json already exist.`); } } catch (error) { logger.log(`Error while writing to file: ${error}`); } }; export const createAddressFile = (file: string) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileName = file.substring(0, file.length - 5); if ( !fs.existsSync( path.join(path_, "starkode", fileName, `${fileName}_address.json`) ) ) { fs.writeFileSync( path.join(path_, "starkode", fileName, `${fileName}_address.json`), JSON.stringify({ name: fileName, address: "", classHash: "", }, null, 2) ); logger.log("Address file created successfully."); } else { logger.log(`${fileName}_address.json already exist.`); } } catch (error) { logger.log(`Error while writing to file: ${error}`); } }; export const accountDeployStatus = (
accounts: Array<JSONAccountType>, selectedNetwork: string, status: boolean ) => {
const networks = ["goerli-alpha", "goerli-alpha-2", "mainnet-alpha"]; let result: Array<JSONAccountType> | undefined; switch (selectedNetwork) { case networks[0]: { result = accounts.filter((e) => e.isDeployed.gAlpha === status); break; } case networks[1]: { result = accounts.filter((e) => e.isDeployed.gAlpha2 === status); break; } case networks[2]: { result = accounts.filter((e) => e.isDeployed.mainnet === status); break; } default: break; } return result; };
src/utils/functions.ts
7finney-starkode-2fba517
[ { "filename": "src/config/contract.ts", "retrieved_chunk": " } catch (error) {\n // console.log(error);\n return undefined;\n }\n};\nexport const isCairo1Contract = (fileName: string): boolean => {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return false;\n }", "score": 20.112589348084857 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " } catch (error) {\n logger.log(`Error while contract deployment: ${error}`);\n }\n};\nexport const executeContractFunction = async (\n context: vscode.ExtensionContext\n) => {\n try {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");", "score": 19.337086130313484 }, { "filename": "src/config/account.ts", "retrieved_chunk": " logger.error(`Error while creating new account: ${error}`);\n }\n};\nexport const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => {\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n if (selectedNetwork === undefined) {\n logger.log(\"Network not selected\");\n return;\n }\n if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) {", "score": 17.331013917455472 }, { "filename": "src/config/account.ts", "retrieved_chunk": " const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(\n parsedFileData,\n selectedNetwork,\n true\n );\n if (accounts === undefined || accounts.length === 0) {\n logger.log(`No deployed account available on ${selectedNetwork}`);\n return;\n }\n return accounts;", "score": 16.72494748633792 }, { "filename": "src/config/account.ts", "retrieved_chunk": " gAlpha: selectedNetwork === NETWORKS[0] ? true : false,\n gAlpha2: selectedNetwork === NETWORKS[1] ? true : false,\n mainnet: selectedNetwork === NETWORKS[2] ? true : false,\n };\n fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => {\n if (err) {\n console.error('Error writing file:', err);\n return;\n }\n console.log('JSON file successfully updated.');", "score": 16.598463106542066 } ]
typescript
accounts: Array<JSONAccountType>, selectedNetwork: string, status: boolean ) => {
import { action, computed, makeObservable, observable } from 'mobx'; import { clone, every, forEach, pickBy, some } from 'lodash'; import Field from '../Field'; import type { FormFields, FormParams, FormSubmitAction, FormValues } from './types'; import { valuesOf, wrapInAsyncAction } from './utils'; import type { ValueType } from '../utils/types'; import deprecatedMethod from '../utils/deprecatedMethod'; export default class Form { private _fields: FormFields; private submitAction: FormSubmitAction; private _isSubmitting: boolean; constructor( { fields, onSubmit = () => undefined }: FormParams ) { this._fields = fields; this.submitAction = wrapInAsyncAction( onSubmit ); this._isSubmitting = false; this.attachFields(); makeObservable<Form, '_fields' | 'submitAction' | '_isSubmitting' >( this, { _fields: observable, submitAction: observable, _isSubmitting: observable, fields: computed, values: computed, dirtyValues: computed, isValid: computed, isDirty: computed, isReadyToSubmit: computed, isSubmitting: computed, submit: action, clear: action, reset: action, showErrors: action } ); } get fields(): FormFields { return clone( this._fields ); } get values(): FormValues { return valuesOf( this._fields ); } get dirtyValues(): FormValues { return valuesOf( this.dirtyFields ); } get isValid() { return every( this.enabledFields, field => field.isValid ); } get isDirty() { return some( this._fields, field => field.isDirty ); } get isReadyToSubmit() { return this.isValid && this.isDirty && !this.isSubmitting; } get isSubmitting() { return this._isSubmitting; } field<FieldType extends Field
<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) {
return this._fields[ fieldKey ] as FieldType; } select<FieldType extends Field<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) { deprecatedMethod( 'Form', 'select', { alternative: 'field', docsPath: '/reference/Form.md#field' } ); return this.field<FieldType>( fieldKey ); } eachField( actionOnField: ( field: Field<unknown> ) => void ) { forEach( this._fields, actionOnField ); } submit(): Promise<void> { this.syncFieldErrors(); if ( !this.isValid || this.isSubmitting ) return Promise.resolve(); return this.executeSubmitAction(); } clear() { this.eachField( field => field.clear() ); } reset() { this.eachField( field => field.reset() ); } showErrors( errors: Record<string, string> ) { forEach( errors, ( error, fieldKey ) => this.showErrorOnField( fieldKey, error ) ); } private attachFields() { forEach( this._fields, field => field.attachToForm( this ) ); } private get dirtyFields() { return this.pickFieldsBy( field => field.isDirty ); } private get enabledFields() { return this.pickFieldsBy( field => !field.isDisabled ); } private pickFieldsBy( predicate: ( field: Field<unknown> ) => boolean ): FormFields { return pickBy( this._fields, predicate ); } private syncFieldErrors() { forEach( this._fields, field => field.syncError() ); } private executeSubmitAction() { this._isSubmitting = true; return this.submitAction( this ) .finally( action( () => { this._isSubmitting = false; } ) ); } private showErrorOnField( fieldKey: string, error: string ) { this._fields[ fieldKey ]?.showError( error ); } } export type { FormParams, FormValues };
src/Form/index.ts
amalgamaco-mobx-form-ad7afec
[ { "filename": "src/Field/index.ts", "retrieved_chunk": "\tget isValid() {\n\t\treturn this._state.isValid;\n\t}\n\tget isDirty() {\n\t\treturn this._state.isDirty;\n\t}\n\tget error() {\n\t\treturn this._presentedError;\n\t}\n\tget isDisabled() {", "score": 32.63931788820821 }, { "filename": "src/utils/FieldState/index.ts", "retrieved_chunk": "\tget isDirty() {\n\t\treturn this._value !== this._initialValue;\n\t}\n\tget isDisabled() {\n\t\treturn this._isDisabled;\n\t}\n\tget error() {\n\t\treturn this.failedValidationResult?.error;\n\t}\n\tget parentForm() {", "score": 27.310872855578992 }, { "filename": "src/utils/FieldState/index.ts", "retrieved_chunk": "\t\tthis._isDisabled = disabled;\n\t\tmakeAutoObservable( this );\n\t\tthis.setUpOnChangeReaction();\n\t}\n\tget value() {\n\t\treturn this._value;\n\t}\n\tget isValid() {\n\t\treturn !this.failedValidationResult;\n\t}", "score": 22.412555760926942 }, { "filename": "src/utils/FieldState/index.ts", "retrieved_chunk": "\t\t\t() => this._value,\n\t\t\t( newValue: ValueType ) => this._onChange?.( newValue, this._parentForm )\n\t\t);\n\t}\n\tprivate get failedValidationResult() {\n\t\treturn this.validationResults.find( result => !result.isValid );\n\t}\n\tprivate get validationResults() {\n\t\treturn this._validators.map(\n\t\t\tvalidator => validator( this._value, this._parentForm, this.label )", "score": 20.122188468674576 }, { "filename": "src/Field/index.ts", "retrieved_chunk": "\t\t\tshowError: action,\n\t\t\tattachToForm: action\n\t\t} );\n\t}\n\tget label() {\n\t\treturn this._state.label;\n\t}\n\tget value() {\n\t\treturn this._state.value;\n\t}", "score": 18.115102046087895 } ]
typescript
<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) {
import { action, computed, makeObservable, observable } from 'mobx'; import { clone, every, forEach, pickBy, some } from 'lodash'; import Field from '../Field'; import type { FormFields, FormParams, FormSubmitAction, FormValues } from './types'; import { valuesOf, wrapInAsyncAction } from './utils'; import type { ValueType } from '../utils/types'; import deprecatedMethod from '../utils/deprecatedMethod'; export default class Form { private _fields: FormFields; private submitAction: FormSubmitAction; private _isSubmitting: boolean; constructor( { fields, onSubmit = () => undefined }: FormParams ) { this._fields = fields; this.submitAction = wrapInAsyncAction( onSubmit ); this._isSubmitting = false; this.attachFields(); makeObservable<Form, '_fields' | 'submitAction' | '_isSubmitting' >( this, { _fields: observable, submitAction: observable, _isSubmitting: observable, fields: computed, values: computed, dirtyValues: computed, isValid: computed, isDirty: computed, isReadyToSubmit: computed, isSubmitting: computed, submit: action, clear: action, reset: action, showErrors: action } ); } get fields(): FormFields { return clone( this._fields ); } get values(): FormValues { return valuesOf( this._fields ); } get dirtyValues(): FormValues { return valuesOf( this.dirtyFields ); } get isValid() { return every( this.enabledFields, field => field.isValid ); } get isDirty() { return some( this._fields, field => field.isDirty ); } get isReadyToSubmit() { return this.isValid && this.isDirty && !this.isSubmitting; } get isSubmitting() { return this._isSubmitting; } field<FieldType extends Field<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) { return this._fields[ fieldKey ] as FieldType; } select<FieldType extends Field<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) { deprecatedMethod( 'Form', 'select', { alternative: 'field', docsPath: '/reference/Form.md#field' } ); return this.field<FieldType>( fieldKey ); }
eachField( actionOnField: ( field: Field<unknown> ) => void ) {
forEach( this._fields, actionOnField ); } submit(): Promise<void> { this.syncFieldErrors(); if ( !this.isValid || this.isSubmitting ) return Promise.resolve(); return this.executeSubmitAction(); } clear() { this.eachField( field => field.clear() ); } reset() { this.eachField( field => field.reset() ); } showErrors( errors: Record<string, string> ) { forEach( errors, ( error, fieldKey ) => this.showErrorOnField( fieldKey, error ) ); } private attachFields() { forEach( this._fields, field => field.attachToForm( this ) ); } private get dirtyFields() { return this.pickFieldsBy( field => field.isDirty ); } private get enabledFields() { return this.pickFieldsBy( field => !field.isDisabled ); } private pickFieldsBy( predicate: ( field: Field<unknown> ) => boolean ): FormFields { return pickBy( this._fields, predicate ); } private syncFieldErrors() { forEach( this._fields, field => field.syncError() ); } private executeSubmitAction() { this._isSubmitting = true; return this.submitAction( this ) .finally( action( () => { this._isSubmitting = false; } ) ); } private showErrorOnField( fieldKey: string, error: string ) { this._fields[ fieldKey ]?.showError( error ); } } export type { FormParams, FormValues };
src/Form/index.ts
amalgamaco-mobx-form-ad7afec
[ { "filename": "src/Form/types.ts", "retrieved_chunk": "import Field from '../Field';\nimport type Form from '.';\nexport type FormSubmitCallback = ( form: Form ) => void | Promise<void>;\nexport type FormSubmitAction = ( form: Form ) => Promise<void>;\nexport interface FormParams {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tfields: Record<string, Field<any>>,\n\tonSubmit?: FormSubmitCallback\n}\nexport type FormFields = Record<string, Field<unknown>>;", "score": 28.400736473720926 }, { "filename": "src/Form/utils.ts", "retrieved_chunk": "import { mapValues } from 'lodash';\nimport type Form from '.';\nimport { FormFields, FormSubmitAction, FormSubmitCallback } from './types';\nexport function wrapInAsyncAction( onSubmit: FormSubmitCallback ) {\n\treturn (\n\t\t( form: Form ) => Promise.resolve( onSubmit( form ) )\n\t) as FormSubmitAction;\n}\nexport function valuesOf( fields: FormFields ) {\n\treturn mapValues( fields, field => field.value );", "score": 25.498846737778933 }, { "filename": "src/ManualField/index.ts", "retrieved_chunk": "import { action, makeObservable } from 'mobx';\nimport Field, { FieldParams } from '../Field';\nexport default class ManualField<ValueType> extends Field<ValueType> {\n\tconstructor( params: FieldParams<ValueType> ) {\n\t\tsuper( params );\n\t\tmakeObservable( this, {\n\t\t\tchange: action\n\t\t} );\n\t}\n\tchange( newValue: ValueType ) {", "score": 19.548907480445266 }, { "filename": "src/Input/types.ts", "retrieved_chunk": "import type { FieldParams } from '../Field';\nimport type Form from '../Form';\nexport type InputErrorDisplayConfig = 'onWrite' | 'onBlur' | 'onSubmit';\nexport type InputCallback = ( form?: Form ) => void;\nexport interface InputParams<ValueType> extends FieldParams<ValueType> {\n\tplaceholder?: string,\n\tshowErrors?: InputErrorDisplayConfig,\n\tonFocus?: InputCallback,\n\tonBlur?: InputCallback\n}", "score": 19.285146857863104 }, { "filename": "src/utils/types.ts", "retrieved_chunk": "import type Field from '../Field';\nimport type { FieldParams } from '../Field';\nexport type ValueType<F> =\n\tF extends Field<infer V> ? V :\n\tF extends FieldParams<infer V> ? V :\n\tnever;\nexport type WithOptionalDefaultValue<FieldParamsType> = Omit<FieldParamsType, 'defaultValue'> & {\n\tdefaultValue?: ValueType<FieldParamsType>\n};\nexport type DeepPartial<T> = {", "score": 18.72259860691178 } ]
typescript
eachField( actionOnField: ( field: Field<unknown> ) => void ) {
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { createOZAccount, deleteAccount, deployAccount, selectDeployedAccount, selectNotDeployedAccount, } from "./config/account"; import { declareContract, deployContract, executeContractFunction, executeContractFunctionFromTreeView, getContractInfo, isCairo1Contract, loadAllCompiledContract, selectCompiledContract, setContract, } from "./config/contract"; import { updateSelectedNetwork } from "./config/network"; import { logger } from "./lib"; import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function"; import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider"; import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider"; import { editInput } from "./treeView/ABITreeView/functions"; import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider"; export function activate(context: vscode.ExtensionContext) { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`); watcher.onDidChange((event: vscode.Uri) => { const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, contractName); abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }); // Contract Tree View const contractTreeDataProvider = new ContractTreeDataProvider( vscode.workspace.workspaceFolders?.[0].uri.fsPath ); let contractTreeView = vscode.window.createTreeView("starkode.contracts", { treeDataProvider: contractTreeDataProvider, }); // if contract tree view is empty const contracts = loadAllCompiledContract(); if (contracts === undefined || contracts.length === 0) { contractTreeView.message = "No contract found. Please compile your contract."; } contractTreeView.onDidChangeSelection(event => { const selectedNodes = event.selection; if (selectedNodes && selectedNodes.length > 0) { console.log('Selected nodes:', selectedNodes[0].label); } }); // Account Tree View const accountTreeDataProvider
= new AccountTreeDataProvider( context );
const accountTreeView = vscode.window.createTreeView("starkode.account", { treeDataProvider: accountTreeDataProvider, }); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount: string | undefined = context.workspaceState.get("account") as string; accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it"; // ABI Tree View const abiTreeDataProvider = new AbiTreeDataProvider( context ); const abiTreeView = vscode.window.createTreeView("starkode.abis", { treeDataProvider: abiTreeDataProvider, }); const contractName: string | undefined = context.workspaceState.get("selectedContract"); if (!contractName || contractName === undefined) { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } else { const contractInfo = getContractInfo(path_, contractName); if (contractInfo !== undefined) { abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`; } else { abiTreeView.message = "Select a contract and its ABI functions will appear here."; } } context.subscriptions.push( vscode.commands.registerCommand("starkode.activate", () => { try { if (!fs.existsSync(path.join(path_, "starkode"))) { fs.mkdirSync(path.join(path_, "starkode")); } vscode.window.showInformationMessage("Starkode activated."); } catch (error) { console.log(error); } }), vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { contractTreeView = await refreshContract(node, contractTreeDataProvider); contractTreeView.message = undefined; }), vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => { setContract(context, node.label); abiTreeView.message = undefined; const contractInfo = getContractInfo(path_, `${node.label}.json`); if (contractInfo !== undefined) { abiTreeView.description = `${node.label} @ ${contractInfo.address}`; } abiTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.useAccount", async (node: any) => { console.log(node); if (node.context === "deployedAccount") { void context.workspaceState.update("account", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); const selectedNetwork: any = context.workspaceState.get("selectedNetwork"); const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount !== undefined) { accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`; } abiTreeDataProvider.refresh(); } else { vscode.window.showErrorMessage("Please deploy the account first."); } }), vscode.commands.registerCommand("starkode.createAccountTreeView", async () => { createOZAccount(context); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.selectNetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => { void context.workspaceState.update("undeployedAccount", node.account.accountAddress); logger.log(`${node.account.accountAddress} selected`); await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => { vscode.env.clipboard.writeText(node.account.accountAddress); }), vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => { await deleteAccount(context, node); accountTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => { await editContractAddress(node, context); }), vscode.commands.registerCommand("starkode.editInput", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; await editInput(node, abiTreeDataProvider, selectedContract); }), vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => { const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; if (selectedContract === undefined) { logger.log("No Contract selected"); return; } if (selectedContract.slice(0, -5) !== node.label) { logger.log("Please select the contract first."); } else { if (isCairo1Contract(selectedContract)) { await vscode.commands.executeCommand("starkode.declareContract"); } else { await vscode.commands.executeCommand("starkode.deployContract"); } } }), vscode.commands.registerCommand("starkode.selectnetwork", async () => { await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.createaccount", async () => { createOZAccount(context); contractTreeDataProvider.refresh(); }), vscode.commands.registerCommand("starkode.unDeployedAccount", async () => { selectNotDeployedAccount(context); }), vscode.commands.registerCommand("starkode.declareContract", async () => { await declareContract(context); }), vscode.commands.registerCommand("starkode.deployaccount", async () => { await deployAccount(context, accountTreeDataProvider); }), vscode.commands.registerCommand("starkode.selectaccount", async () => { await selectDeployedAccount(context); }), vscode.commands.registerCommand("starkode.selectContract", async () => { selectCompiledContract(context); }), vscode.commands.registerCommand("starkode.deployContract", async () => { await deployContract(context); }), vscode.commands.registerCommand("starkode.callFunction", async () => { await executeContractFunction(context); }), vscode.commands.registerCommand("starkode.callContract", async (node: any) => { await executeContractFunctionFromTreeView(context, node.abi); }) ); }
src/extension.ts
7finney-starkode-2fba517
[ { "filename": "src/config/network.ts", "retrieved_chunk": " const { label } = selection[0];\n void context.workspaceState.update(\"selectedNetwork\", label);\n quickPick.dispose();\n logger.success(`Selected network is ${label}`);\n const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n const selectedAccount = context.workspaceState.get(\"account\") as string;\n if (selectedAccount !== undefined) {\n accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + \"...\" + selectedAccount.slice(-5)} | ${selectedNetwork}`;\n }\n accountTreeDataProvider.refresh();", "score": 16.71891645351228 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " label: contract.substring(0, contract.length - 5),\n }));\n quickPick.onDidChangeActive(() => {\n quickPick.placeholder = \"Select Contract\";\n });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n setContract(context, label);\n quickPick.dispose();", "score": 13.873988506946136 }, { "filename": "src/config/account.ts", "retrieved_chunk": " });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n void context.workspaceState.update(\"undeployedAccount\", label);\n logger.log(`${label} selected`);\n quickPick.dispose();\n }\n });\n quickPick.onDidHide(() => {", "score": 12.641149068302076 }, { "filename": "src/config/account.ts", "retrieved_chunk": " quickPick.placeholder = \"Select account\";\n });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n void context.workspaceState.update(\"account\", label);\n logger.log(`${label} selected`);\n quickPick.dispose();\n }\n });", "score": 12.378151759014765 }, { "filename": "src/config/account.ts", "retrieved_chunk": " if (presentAccounts === undefined) return;\n const isAccountPresent: any = presentAccounts.filter(\n (account) => account.accountAddress === unDeployedAccount\n );\n const selectedAccount: JSONAccountType = isAccountPresent[0];\n const selectedNetwork = context.workspaceState.get(\"selectedNetwork\");\n const provider = getNetworkProvider(context);\n console.log(`Account address: ${selectedAccount.accountAddress}`);\n if (provider === undefined) return;\n const account = new Account(", "score": 11.517118582570692 } ]
typescript
= new AccountTreeDataProvider( context );
import * as vscode from "vscode"; import * as fs from "fs"; import path, { resolve } from "path"; import { logger } from "../lib"; import { ABIFragment, IContractQP, IFunctionQP } from "../types"; import { createABIFile, createAddressFile } from "../utils/functions"; import { getAccountInfo } from "./account"; import { Account, CairoAssembly, Contract, ec, Provider } from "starknet"; import { getNetworkProvider } from "./network"; export const loadAllCompiledContract = () => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const compiledCairoContract = fs .readdirSync(path_) .filter((file) => exportPathOfJSONfiles(path_, file)); return compiledCairoContract; }; const exportPathOfJSONfiles = (path_: string, file: string) => { const filePath = path.join(path_, file); if (path.extname(filePath) === ".json") { const fileData = fs.readFileSync(filePath, { encoding: "utf-8", }); if (JSON.parse(fileData).program) return filePath; if (JSON.parse(fileData).contract_class_version) { return filePath; } } }; export const setContract = async (context: vscode.ExtensionContext, label: string) => { if (label === undefined) { // logger.log("No Contract selected."); return; } void context.workspaceState.update("selectedContract", `${label}.json`); logger.log(`${label} contract selected`); createABIFile(`${label}.json`); createAddressFile(`${label}.json`); }; export const selectCompiledContract = (context: vscode.ExtensionContext) => { const contracts = loadAllCompiledContract(); if (contracts === undefined) { logger.log("No Contract available."); return; } const quickPick = vscode.window.createQuickPick<IContractQP>(); quickPick.items = contracts.map((contract: string) => ({ label: contract.substring(0, contract.length - 5), })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Contract"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; setContract(context, label); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getContractInfo = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_address.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const getContractABI = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_abi.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const isCairo1Contract = (fileName: string): boolean => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return false; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileData = fs.readFileSync( path.join(path_, fileName), { encoding: "utf-8" } ); return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; }; export const declareContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const fileName = selectedContract.substring(0, selectedContract.length - 5); if ( !fs.existsSync(path.join(path_, selectedContract)) || !fs.existsSync(path.join(path_, `${fileName}.casm`)) ) { logger.log(`${fileName}.json or ${fileName}.casm must be present.`); return; } const compiledContract = fs.readFileSync( path.join(path_, selectedContract), { encoding: "ascii", } ); const casmFileData = fs .readFileSync(path.join(path_, `${fileName}.casm`)) .toString("ascii"); const casmAssembly: CairoAssembly = JSON.parse(casmFileData); logger.log("Declaring contract..."); const declareResponse = await account.declareAndDeploy({ contract: compiledContract, casm: casmAssembly, }); logger.log( `declare transaction hash: ${declareResponse.deploy.transaction_hash}` ); logger.log(`declare classHash: ${declareResponse.deploy.classHash}`); logger.log("transaction successful"); } catch (error) { logger.log(`Error while contract declaration: ${error}`); } }; export const deployContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); logger.log("Deploying contract..."); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contractInfo = getContractInfo(path_, selectedContract); if (contractInfo.classHash === "") { logger.log("No classHash available for selected contract."); return; } const deployResponse = await account.deployContract({ classHash: contractInfo.classHash, }); logger.log(`transaction hash: ${deployResponse.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(deployResponse.transaction_hash); const { abi: testAbi } = await provider.getClassAt( deployResponse.contract_address ); if (testAbi === undefined) { throw new Error("no abi."); } const myTestContract = new Contract( testAbi, deployResponse.contract_address, provider ); await provider.waitForTransaction(myTestContract.transaction_hash); logger.log(`contract deployed successfully: ${myTestContract.address}`); } catch (error) { logger.log(`Error while contract deployment: ${error}`); } }; export const executeContractFunction = async ( context: vscode.ExtensionContext ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = await getSelectedFunction(path_, selectedContract); const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" ||
functionABI.state_mutability === "view" ) {
const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; export const executeContractFunctionFromTreeView = async ( context: vscode.ExtensionContext, functionabi: ABIFragment ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = functionabi; const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; const getSelectedFunction = ( path_: string, selectedContract: string ): Promise<ABIFragment> => { return new Promise((resolve, reject) => { try { const contractInfo: Array<ABIFragment> = getContractABI( path_, selectedContract ).abi; if (contractInfo === undefined) return; const quickPick = vscode.window.createQuickPick<IFunctionQP>(); quickPick.items = contractInfo.map((account: ABIFragment) => ({ label: account.name, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Function"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; quickPick.dispose(); const functionItem = contractInfo.filter( (i: ABIFragment) => i.name === label ); if (functionItem.length === 0) throw new Error("No function is selected"); resolve(functionItem[0]); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); } catch (error) { reject(error); } }); };
src/config/contract.ts
7finney-starkode-2fba517
[ { "filename": "src/utils/functions.ts", "retrieved_chunk": " name: func.name,\n inputs: func.inputs.map((e) => {\n return { ...e, value: \"\" };\n }),\n stateMutability: func.stateMutability\n ? func.stateMutability\n : func.state_mutability,\n outputs: func.outputs,\n };\n });", "score": 32.32227516510035 }, { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " const selectedContract: string | undefined = this.context.workspaceState.get(\"selectedContract\") as string;\n const data = getContractABI(path_,selectedContract);\n const inputFunction: Array<ABIFragment> | undefined = selectedContract !== undefined ? data === undefined ? undefined : data.abi :\n [];\n if (inputFunction === undefined) {\n return undefined;\n } \n else {\n if (!element) {\n for (const entry of inputFunction) {", "score": 23.413139309033348 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " ) {\n const filePath = path.join(path_, file);\n const fileData = fs.readFileSync(filePath, { encoding: \"utf-8\" });\n const isCairo1Contract =\n JSON.parse(fileData).contract_class_version === \"0.1.0\" ? true : false;\n const abi: Array<ABIFragment> = JSON.parse(fileData).abi;\n const abiFunctions = abi.filter((e) => e.type === \"function\");\n const functionsValue = abiFunctions.map((func) => {\n return {\n type: func.type,", "score": 21.379399001676667 }, { "filename": "src/extension.ts", "retrieved_chunk": " treeDataProvider: abiTreeDataProvider,\n });\n const contractName: string | undefined = context.workspaceState.get(\"selectedContract\");\n if (!contractName || contractName === undefined) {\n abiTreeView.message = \"Select a contract and its ABI functions will appear here.\";\n }\n else {\n const contractInfo = getContractInfo(path_, contractName);\n if (contractInfo !== undefined) {\n abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;", "score": 21.27494552701408 }, { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " if (entry.type === \"function\") {\n const colapse = (entry.inputs && entry.inputs.length > 0)\n ? TreeItemCollapsibleState.Expanded\n : TreeItemCollapsibleState.None;\n leaves.push(\n new Abi(\n entry.name,\n entry,\n entry.stateMutability === \"view\" || entry.stateMutability === \"external\" ? \"abiReadFunction\" : \"abiFunction\",\n null,", "score": 20.31126548204103 } ]
typescript
functionABI.state_mutability === "view" ) {
import * as vscode from "vscode"; import * as fs from "fs"; import path from "path"; import { logger } from "../lib"; import { ABIFragment, JSONAccountType, TIsAccountDeployed } from "../types"; export const createABIFile = (file: string) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileName = file.substring(0, file.length - 5); if (!fs.existsSync(path.join(path_, "starkode", fileName))) { fs.mkdirSync(path.join(path_, "starkode", fileName),{recursive: true}); } if ( !fs.existsSync( path.join(path_, "starkode", fileName, `${fileName}_abi.json`) ) ) { const filePath = path.join(path_, file); const fileData = fs.readFileSync(filePath, { encoding: "utf-8" }); const isCairo1Contract = JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; const abi: Array<ABIFragment> = JSON.parse(fileData).abi; const abiFunctions = abi.filter((e) => e.type === "function"); const functionsValue = abiFunctions.map((func) => { return { type: func.type, name: func.name, inputs: func.inputs.map((e) => { return { ...e, value: "" }; }), stateMutability: func.stateMutability ? func.stateMutability : func.state_mutability,
outputs: func.outputs, };
}); fs.writeFileSync( path.join(path_, "starkode", fileName, `${fileName}_abi.json`), JSON.stringify({ isCairo1: isCairo1Contract, abi: functionsValue }, null, 2) ); logger.log("ABI file created successfully."); } else { logger.log(`${fileName}_abi.json already exist.`); } } catch (error) { logger.log(`Error while writing to file: ${error}`); } }; export const createAddressFile = (file: string) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileName = file.substring(0, file.length - 5); if ( !fs.existsSync( path.join(path_, "starkode", fileName, `${fileName}_address.json`) ) ) { fs.writeFileSync( path.join(path_, "starkode", fileName, `${fileName}_address.json`), JSON.stringify({ name: fileName, address: "", classHash: "", }, null, 2) ); logger.log("Address file created successfully."); } else { logger.log(`${fileName}_address.json already exist.`); } } catch (error) { logger.log(`Error while writing to file: ${error}`); } }; export const accountDeployStatus = ( accounts: Array<JSONAccountType>, selectedNetwork: string, status: boolean ) => { const networks = ["goerli-alpha", "goerli-alpha-2", "mainnet-alpha"]; let result: Array<JSONAccountType> | undefined; switch (selectedNetwork) { case networks[0]: { result = accounts.filter((e) => e.isDeployed.gAlpha === status); break; } case networks[1]: { result = accounts.filter((e) => e.isDeployed.gAlpha2 === status); break; } case networks[2]: { result = accounts.filter((e) => e.isDeployed.mainnet === status); break; } default: break; } return result; };
src/utils/functions.ts
7finney-starkode-2fba517
[ { "filename": "src/types/index.ts", "retrieved_chunk": " value: string;\n}\ninterface outputType {\n name: string;\n type: string;\n}\nexport interface ABIFragment {\n inputs: Array<inputType>;\n name: string;\n stateMutability: string;", "score": 38.07410595687221 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " const contractInfo = getContractInfo(path_, selectedContract);\n const params_: Array<any> = functionABI.inputs.map((e) => {\n return e.value;\n });\n const params: Array<any> = params_ !== undefined ? params_ : [];\n if (\n functionABI.stateMutability === \"view\" ||\n functionABI.state_mutability === \"view\"\n ) {\n const Abi = getContractABI(path_, selectedContract).abi;", "score": 33.808538049951935 }, { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " if (entry.type === \"function\") {\n const colapse = (entry.inputs && entry.inputs.length > 0)\n ? TreeItemCollapsibleState.Expanded\n : TreeItemCollapsibleState.None;\n leaves.push(\n new Abi(\n entry.name,\n entry,\n entry.stateMutability === \"view\" || entry.stateMutability === \"external\" ? \"abiReadFunction\" : \"abiFunction\",\n null,", "score": 33.21489037536779 }, { "filename": "src/types/index.ts", "retrieved_chunk": " type: string;\n outputs: Array<outputType>;\n state_mutability?: string;\n}", "score": 28.311744950175015 }, { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " [],\n colapse\n )\n );\n }\n }\n } else if (element.abi.type === \"function\") {\n const value: any = inputFunction.find((i: any) => i.name === element.abi.name);\n for (const input of value.inputs) {\n leaves.push(", "score": 23.7061036407081 } ]
typescript
outputs: func.outputs, };
import * as vscode from "vscode"; import * as fs from "fs"; import path, { resolve } from "path"; import { logger } from "../lib"; import { ABIFragment, IContractQP, IFunctionQP } from "../types"; import { createABIFile, createAddressFile } from "../utils/functions"; import { getAccountInfo } from "./account"; import { Account, CairoAssembly, Contract, ec, Provider } from "starknet"; import { getNetworkProvider } from "./network"; export const loadAllCompiledContract = () => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const compiledCairoContract = fs .readdirSync(path_) .filter((file) => exportPathOfJSONfiles(path_, file)); return compiledCairoContract; }; const exportPathOfJSONfiles = (path_: string, file: string) => { const filePath = path.join(path_, file); if (path.extname(filePath) === ".json") { const fileData = fs.readFileSync(filePath, { encoding: "utf-8", }); if (JSON.parse(fileData).program) return filePath; if (JSON.parse(fileData).contract_class_version) { return filePath; } } }; export const setContract = async (context: vscode.ExtensionContext, label: string) => { if (label === undefined) { // logger.log("No Contract selected."); return; } void context.workspaceState.update("selectedContract", `${label}.json`); logger.log(`${label} contract selected`); createABIFile(`${label}.json`); createAddressFile(`${label}.json`); }; export const selectCompiledContract = (context: vscode.ExtensionContext) => { const contracts = loadAllCompiledContract(); if (contracts === undefined) { logger.log("No Contract available."); return; } const quickPick = vscode.window.createQuickPick<IContractQP>(); quickPick.items = contracts.map((contract: string) => ({ label: contract.substring(0, contract.length - 5), })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Contract"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; setContract(context, label); quickPick.dispose(); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); }; export const getContractInfo = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_address.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const getContractABI = (path_: string, fileName: string) => { try { const file = fileName.substring(0, fileName.length - 5); const fileData = fs.readFileSync( path.join(path_, "starkode", file, `${file}_abi.json`), { encoding: "utf-8" } ); const parsedFileData = JSON.parse(fileData); return parsedFileData; } catch (error) { // console.log(error); return undefined; } }; export const isCairo1Contract = (fileName: string): boolean => { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return false; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const fileData = fs.readFileSync( path.join(path_, fileName), { encoding: "utf-8" } ); return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false; }; export const declareContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const fileName = selectedContract.substring(0, selectedContract.length - 5); if ( !fs.existsSync(path.join(path_, selectedContract)) || !fs.existsSync(path.join(path_, `${fileName}.casm`)) ) { logger.log(`${fileName}.json or ${fileName}.casm must be present.`); return; } const compiledContract = fs.readFileSync( path.join(path_, selectedContract), { encoding: "ascii", } ); const casmFileData = fs .readFileSync(path.join(path_, `${fileName}.casm`)) .toString("ascii"); const casmAssembly: CairoAssembly = JSON.parse(casmFileData); logger.log("Declaring contract..."); const declareResponse = await account.declareAndDeploy({ contract: compiledContract, casm: casmAssembly, }); logger.log( `declare transaction hash: ${declareResponse.deploy.transaction_hash}` ); logger.log(`declare classHash: ${declareResponse.deploy.classHash}`); logger.log("transaction successful"); } catch (error) { logger.log(`Error while contract declaration: ${error}`); } }; export const deployContract = async (context: vscode.ExtensionContext) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); logger.log("Deploying contract..."); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contractInfo = getContractInfo(path_, selectedContract); if (contractInfo.classHash === "") { logger.log("No classHash available for selected contract."); return; } const deployResponse = await account.deployContract({ classHash: contractInfo.classHash, }); logger.log(`transaction hash: ${deployResponse.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(deployResponse.transaction_hash); const { abi: testAbi } = await provider.getClassAt( deployResponse.contract_address ); if (testAbi === undefined) { throw new Error("no abi."); } const myTestContract = new Contract( testAbi, deployResponse.contract_address, provider ); await provider.waitForTransaction(myTestContract.transaction_hash); logger.log(`contract deployed successfully: ${myTestContract.address}`); } catch (error) { logger.log(`Error while contract deployment: ${error}`); } }; export const executeContractFunction = async ( context: vscode.ExtensionContext ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = await getSelectedFunction(path_, selectedContract); const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider);
logger.log(`calling function: ${functionABI.name}`);
const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; export const executeContractFunctionFromTreeView = async ( context: vscode.ExtensionContext, functionabi: ABIFragment ) => { try { if (vscode.workspace.workspaceFolders === undefined) { logger.error("Error: Please open your solidity project to vscode"); return; } const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath; const provider = getNetworkProvider(context) as Provider; const selectedContract: string = context.workspaceState.get( "selectedContract" ) as string; const selectedAccount = context.workspaceState.get("account") as string; if (selectedAccount === undefined) { logger.log("No account selected."); return; } const accountInfo = getAccountInfo(context, selectedAccount); const functionABI = functionabi; const contractInfo = getContractInfo(path_, selectedContract); const params_: Array<any> = functionABI.inputs.map((e) => { return e.value; }); const params: Array<any> = params_ !== undefined ? params_ : []; if ( functionABI.stateMutability === "view" || functionABI.state_mutability === "view" ) { const Abi = getContractABI(path_, selectedContract).abi; const contract = new Contract(Abi, contractInfo.address, provider); logger.log(`calling function: ${functionABI.name}`); const functionCall: any = await contract.call(`${functionABI.name}`); logger.log(`result: ${functionCall.res.toString()}`); } else { const Abi = getContractABI(path_, selectedContract).abi; logger.log(`calling function: ${functionABI.name}`); const account = new Account( provider, accountInfo.accountAddress, accountInfo.privateKey, "0" ); const contract = new Contract(Abi, contractInfo.address, provider); contract.connect(account); const result = await contract.invoke(functionABI.name, params); logger.log(`transaction hash: ${result.transaction_hash}`); logger.log("waiting for transaction success..."); await provider.waitForTransaction(result.transaction_hash); logger.log("transaction successfull"); } } catch (error) { logger.log(error); } }; const getSelectedFunction = ( path_: string, selectedContract: string ): Promise<ABIFragment> => { return new Promise((resolve, reject) => { try { const contractInfo: Array<ABIFragment> = getContractABI( path_, selectedContract ).abi; if (contractInfo === undefined) return; const quickPick = vscode.window.createQuickPick<IFunctionQP>(); quickPick.items = contractInfo.map((account: ABIFragment) => ({ label: account.name, })); quickPick.onDidChangeActive(() => { quickPick.placeholder = "Select Function"; }); quickPick.onDidChangeSelection((selection: any) => { if (selection[0] != null) { const { label } = selection[0]; quickPick.dispose(); const functionItem = contractInfo.filter( (i: ABIFragment) => i.name === label ); if (functionItem.length === 0) throw new Error("No function is selected"); resolve(functionItem[0]); } }); quickPick.onDidHide(() => { quickPick.dispose(); }); quickPick.show(); } catch (error) { reject(error); } }); };
src/config/contract.ts
7finney-starkode-2fba517
[ { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " if (entry.type === \"function\") {\n const colapse = (entry.inputs && entry.inputs.length > 0)\n ? TreeItemCollapsibleState.Expanded\n : TreeItemCollapsibleState.None;\n leaves.push(\n new Abi(\n entry.name,\n entry,\n entry.stateMutability === \"view\" || entry.stateMutability === \"external\" ? \"abiReadFunction\" : \"abiFunction\",\n null,", "score": 26.04881572950429 }, { "filename": "src/utils/functions.ts", "retrieved_chunk": " name: func.name,\n inputs: func.inputs.map((e) => {\n return { ...e, value: \"\" };\n }),\n stateMutability: func.stateMutability\n ? func.stateMutability\n : func.state_mutability,\n outputs: func.outputs,\n };\n });", "score": 22.844264391865302 }, { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " [],\n colapse\n )\n );\n }\n }\n } else if (element.abi.type === \"function\") {\n const value: any = inputFunction.find((i: any) => i.name === element.abi.name);\n for (const input of value.inputs) {\n leaves.push(", "score": 20.143622757451702 }, { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": " const selectedContract: string | undefined = this.context.workspaceState.get(\"selectedContract\") as string;\n const data = getContractABI(path_,selectedContract);\n const inputFunction: Array<ABIFragment> | undefined = selectedContract !== undefined ? data === undefined ? undefined : data.abi :\n [];\n if (inputFunction === undefined) {\n return undefined;\n } \n else {\n if (!element) {\n for (const entry of inputFunction) {", "score": 19.712188528353146 }, { "filename": "src/extension.ts", "retrieved_chunk": " treeDataProvider: abiTreeDataProvider,\n });\n const contractName: string | undefined = context.workspaceState.get(\"selectedContract\");\n if (!contractName || contractName === undefined) {\n abiTreeView.message = \"Select a contract and its ABI functions will appear here.\";\n }\n else {\n const contractInfo = getContractInfo(path_, contractName);\n if (contractInfo !== undefined) {\n abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;", "score": 17.871468919547073 } ]
typescript
logger.log(`calling function: ${functionABI.name}`);