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/trainer/Trainer.spec.ts", "retrieved_chunk": " items: [\n new Item({\n id: \"1\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n }),\n ],", "score": 0.840412974357605 }, { "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": 0.839580774307251 }, { "filename": "src/app/entities/pokemon/Pokemon.ts", "retrieved_chunk": " }\n // Predicates\n isAwake(): boolean {\n return this.life > 0;\n }\n // Actions\n attack(target: Pokemon): void {\n const damage = this._stats.attack - target.stats.defense;\n if (damage > 0) {\n target.life -= damage;", "score": 0.8306597471237183 }, { "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": 0.8247364163398743 }, { "filename": "src/app/entities/item/Item.ts", "retrieved_chunk": "export class Item {\n _id: string;\n _name: string;\n _increaseLife: number;\n _increaseAttack: number;\n _increaseDefense: number;\n _increaseSpeed: number;\n constructor(props: {\n id: string;\n name: string;", "score": 0.82196044921875 } ]
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/trainer/Trainer.spec.ts", "retrieved_chunk": " items: [\n new Item({\n id: \"1\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n }),\n ],", "score": 0.849228024482727 }, { "filename": "src/app/entities/pokemon/Pokemon.ts", "retrieved_chunk": " }\n // Predicates\n isAwake(): boolean {\n return this.life > 0;\n }\n // Actions\n attack(target: Pokemon): void {\n const damage = this._stats.attack - target.stats.defense;\n if (damage > 0) {\n target.life -= damage;", "score": 0.8434419631958008 }, { "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": 0.8392828702926636 }, { "filename": "src/app/entities/item/Item.ts", "retrieved_chunk": "export class Item {\n _id: string;\n _name: string;\n _increaseLife: number;\n _increaseAttack: number;\n _increaseDefense: number;\n _increaseSpeed: number;\n constructor(props: {\n id: string;\n name: string;", "score": 0.8383803367614746 }, { "filename": "src/app/entities/pokemon/Pokemon.spec.ts", "retrieved_chunk": " name: \"Pikachu\",\n stats: new BattleStats({\n attack: 100,\n defense: 100,\n speed: 100,\n }),\n level: 25,\n life: 100,\n moves: [\n new PokemonMove({", "score": 0.8379241824150085 } ]
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/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": 0.8877873420715332 }, { "filename": "src/app/use-cases/battle/CreateBattleUseCase.spec.ts", "retrieved_chunk": " id: \"123\",\n name: \"Kanto\",\n prize: 1000,\n registrationFee: 100,\n }),\n });\n for (let i = 0; i < 3; i++) {\n trainer2.pokemons.push(\n new Pokemon({\n id: crypto.randomUUID(),", "score": 0.8783477544784546 }, { "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": 0.8760915398597717 }, { "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": 0.8745325207710266 }, { "filename": "src/app/entities/tournament/Tournament.spec.ts", "retrieved_chunk": " });\n trainer2 = new Trainer({\n id: \"2\",\n name: \"Misty\",\n city: \"Cerulean City\",\n age: 20,\n level: 1,\n pokemons: [],\n items: [],\n league: null,", "score": 0.8737272620201111 } ]
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/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": 0.8702795505523682 }, { "filename": "src/app/entities/item/Item.ts", "retrieved_chunk": " increaseLife: number;\n increaseAttack: number;\n increaseDefense: number;\n increaseSpeed: number;\n }) {\n this._id = props.id;\n this._name = props.name;\n this._increaseLife = props.increaseLife;\n this._increaseAttack = props.increaseAttack;\n this._increaseDefense = props.increaseDefense;", "score": 0.8688132762908936 }, { "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": 0.8556908369064331 }, { "filename": "src/app/value_objects/PokemonMove.ts", "retrieved_chunk": "export class PokemonMove {\n private _name: string;\n private _type: string;\n private _category: string;\n private _power: number;\n private _accuracy: number;\n private _powerPoints: number;\n constructor(props: {\n name: string;\n type: string;", "score": 0.8525192737579346 }, { "filename": "src/app/value_objects/PokemonMove.ts", "retrieved_chunk": " category: string;\n power: number;\n accuracy: number;\n powerPoints: number;\n }) {\n this._name = props.name;\n this._type = props.type;\n this._category = props.category;\n this._power = props.power;\n this._accuracy = props.accuracy;", "score": 0.8414222002029419 } ]
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/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": 0.8990212082862854 }, { "filename": "src/app/entities/item/Item.ts", "retrieved_chunk": " increaseLife: number;\n increaseAttack: number;\n increaseDefense: number;\n increaseSpeed: number;\n }) {\n this._id = props.id;\n this._name = props.name;\n this._increaseLife = props.increaseLife;\n this._increaseAttack = props.increaseAttack;\n this._increaseDefense = props.increaseDefense;", "score": 0.8617609739303589 }, { "filename": "src/app/entities/tournament/Tournament.ts", "retrieved_chunk": " _leagues: League[];\n constructor(props: { id: string; name: string; description: string }) {\n this._id = props.id;\n this._name = props.name;\n this._description = props.description;\n this._trainers = [];\n this._leagues = [];\n this._createdAt = null;\n this._startedAt = null;\n this._finishedAt = null;", "score": 0.8573264479637146 }, { "filename": "src/app/value_objects/PokemonMove.ts", "retrieved_chunk": " category: string;\n power: number;\n accuracy: number;\n powerPoints: number;\n }) {\n this._name = props.name;\n this._type = props.type;\n this._category = props.category;\n this._power = props.power;\n this._accuracy = props.accuracy;", "score": 0.8570321202278137 }, { "filename": "src/app/value_objects/PokemonMove.ts", "retrieved_chunk": " this._powerPoints = props.powerPoints;\n }\n get name() {\n return this._name;\n }\n get type() {\n return this._type;\n }\n get category() {\n return this._category;", "score": 0.8548734188079834 } ]
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/trainer/Trainer.spec.ts", "retrieved_chunk": " items: [\n new Item({\n id: \"1\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n }),\n ],", "score": 0.8429766893386841 }, { "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": 0.8408198952674866 }, { "filename": "src/app/entities/pokemon/Pokemon.ts", "retrieved_chunk": " }\n // Predicates\n isAwake(): boolean {\n return this.life > 0;\n }\n // Actions\n attack(target: Pokemon): void {\n const damage = this._stats.attack - target.stats.defense;\n if (damage > 0) {\n target.life -= damage;", "score": 0.8299775123596191 }, { "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": 0.8265378475189209 }, { "filename": "src/app/entities/item/Item.ts", "retrieved_chunk": "export class Item {\n _id: string;\n _name: string;\n _increaseLife: number;\n _increaseAttack: number;\n _increaseDefense: number;\n _increaseSpeed: number;\n constructor(props: {\n id: string;\n name: string;", "score": 0.8241963982582092 } ]
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/__tests__/repositories/InMemoryPokemonRepository.ts", "retrieved_chunk": " const index = this.pokemons.findIndex(\n (pokemon) => pokemon.id === entity.id\n );\n this.pokemons[index] = entity;\n }\n}", "score": 0.8377509713172913 }, { "filename": "src/app/entities/trainer/Trainer.spec.ts", "retrieved_chunk": " items: [\n new Item({\n id: \"1\",\n name: \"Potion\",\n increaseLife: 20,\n increaseAttack: 0,\n increaseDefense: 0,\n increaseSpeed: 0,\n }),\n ],", "score": 0.8302014470100403 }, { "filename": "src/app/entities/trainer/Trainer.spec.ts", "retrieved_chunk": " league: null,\n });\n });\n it(\"should create a trainer\", () => {\n expect(trainer).toBeDefined();\n });\n it(\"should apply item\", () => {\n const pikachu = trainer.pokemons[0];\n const potion = trainer.items[0];\n trainer.applyItem(potion, pikachu);", "score": 0.8270934224128723 }, { "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": 0.8230065703392029 }, { "filename": "src/app/entities/item/Item.ts", "retrieved_chunk": "export class Item {\n _id: string;\n _name: string;\n _increaseLife: number;\n _increaseAttack: number;\n _increaseDefense: number;\n _increaseSpeed: number;\n constructor(props: {\n id: string;\n name: string;", "score": 0.8225473165512085 } ]
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/UploadToast.tsx", "retrieved_chunk": " {steps[f.name] === 'ENCRYPTING' && (\n <ShieldLockIcon boxSize=\"1rem\" color=\"white\" />\n )}\n {steps[f.name] === 'UPLOADING' &&\n (value < 100 ? (\n <CircularProgress\n value={value}\n color=\"blue.700\"\n trackColor=\"white\"\n size=\"16px\"", "score": 0.8666164875030518 }, { "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": 0.8401681184768677 }, { "filename": "src/components/Icons.tsx", "retrieved_chunk": "} from 'react-icons/io5';\nimport {\n MdCheck,\n MdChevronLeft,\n MdChevronRight,\n MdClose,\n MdDarkMode,\n MdDownload,\n MdGridView,\n MdLightMode,", "score": 0.826494038105011 }, { "filename": "src/components/Icons.tsx", "retrieved_chunk": "export const ShieldLockIcon = iconFactory(BsShieldLockFill);\nexport const CheckIcon = iconFactory(MdCheck);\nexport const ArrowUpIcon = iconFactory(FaChevronUp);\nexport const ArrowDownIcon = iconFactory(FaChevronDown);\nexport const DocumentIcon = iconFactory(IoDocumentOutline);\nexport const FolderIcon = iconFactory(IoFolderOutline);\nexport const CreateFolderIcon = iconFactory(IoFolderOpenOutline);\nexport const ChevronLeftIcon = iconFactory(MdChevronLeft);\nexport const ChevronRightIcon = iconFactory(MdChevronRight);\nexport const GithubIcon = iconFactory(SiGithub);", "score": 0.819815993309021 }, { "filename": "src/components/Icons.tsx", "retrieved_chunk": "import { IconType } from 'react-icons';\nimport { BsShieldLockFill } from 'react-icons/bs';\nimport { FaChevronDown, FaChevronUp } from 'react-icons/fa';\nimport { FcGoogle } from 'react-icons/fc';\nimport { IoMdKey } from 'react-icons/io';\nimport {\n IoDocumentOutline,\n IoFolderOpenOutline,\n IoFolderOutline,\n IoTrashBin,", "score": 0.8192932605743408 } ]
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/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": 0.8602682948112488 }, { "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": 0.8590541481971741 }, { "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": 0.8582909107208252 }, { "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": 0.8551657199859619 }, { "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": 0.8548257350921631 } ]
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/UploadToast.tsx", "retrieved_chunk": " {steps[f.name] === 'ENCRYPTING' && (\n <ShieldLockIcon boxSize=\"1rem\" color=\"white\" />\n )}\n {steps[f.name] === 'UPLOADING' &&\n (value < 100 ? (\n <CircularProgress\n value={value}\n color=\"blue.700\"\n trackColor=\"white\"\n size=\"16px\"", "score": 0.8791379928588867 }, { "filename": "src/components/Icons.tsx", "retrieved_chunk": "export const ShieldLockIcon = iconFactory(BsShieldLockFill);\nexport const CheckIcon = iconFactory(MdCheck);\nexport const ArrowUpIcon = iconFactory(FaChevronUp);\nexport const ArrowDownIcon = iconFactory(FaChevronDown);\nexport const DocumentIcon = iconFactory(IoDocumentOutline);\nexport const FolderIcon = iconFactory(IoFolderOutline);\nexport const CreateFolderIcon = iconFactory(IoFolderOpenOutline);\nexport const ChevronLeftIcon = iconFactory(MdChevronLeft);\nexport const ChevronRightIcon = iconFactory(MdChevronRight);\nexport const GithubIcon = iconFactory(SiGithub);", "score": 0.840141773223877 }, { "filename": "src/components/Icons.tsx", "retrieved_chunk": "import { IconType } from 'react-icons';\nimport { BsShieldLockFill } from 'react-icons/bs';\nimport { FaChevronDown, FaChevronUp } from 'react-icons/fa';\nimport { FcGoogle } from 'react-icons/fc';\nimport { IoMdKey } from 'react-icons/io';\nimport {\n IoDocumentOutline,\n IoFolderOpenOutline,\n IoFolderOutline,\n IoTrashBin,", "score": 0.8292160034179688 }, { "filename": "src/components/Icons.tsx", "retrieved_chunk": "} from 'react-icons/io5';\nimport {\n MdCheck,\n MdChevronLeft,\n MdChevronRight,\n MdClose,\n MdDarkMode,\n MdDownload,\n MdGridView,\n MdLightMode,", "score": 0.8278450965881348 }, { "filename": "src/components/Icons.tsx", "retrieved_chunk": "export const UploadIcon = iconFactory(MdUpload);\nexport const RemoveIcon = iconFactory(MdClose);\nexport const NewFileIcon = iconFactory(VscNewFile);\nexport const LogoutIcon = iconFactory(MdLogout);\nexport const DarkModeIcon = iconFactory(MdDarkMode);\nexport const LightModeIcon = iconFactory(MdLightMode);\nexport const SearchIcon = iconFactory(MdSearch);\nexport const GridIcon = iconFactory(MdGridView);\nexport const ListIcon = iconFactory(MdList);\nexport const CloseIcon = iconFactory(MdOutlineClose);", "score": 0.8254998922348022 } ]
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/FileTable.tsx", "retrieved_chunk": " </Td>\n <Td border=\"0\">\n <HStack justifyContent=\"flex-end\">\n <DownloadButton fileId={file.id} />\n <DeleteButton fileId={file.id} />\n </HStack>\n </Td>\n </Tr>\n ))}\n </Tbody>", "score": 0.8637136220932007 }, { "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": 0.8551403284072876 }, { "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": 0.8545321226119995 }, { "filename": "src/components/DeleteButtonAppFolder.tsx", "retrieved_chunk": " </Button>\n );\n};\nexport default DeleteAppDataFolder;", "score": 0.8382969498634338 }, { "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": 0.8357682228088379 } ]
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/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": 0.8625301122665405 }, { "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": 0.8571441173553467 }, { "filename": "src/components/PassphraseInput.tsx", "retrieved_chunk": " <Text>{userInfo?.email ? `[${userInfo.email}]` : ''}</Text>\n </HStack>\n </FormLabel>\n <Input\n marginTop=\"0.8rem\"\n autoFocus\n placeholder=\"passphrase...\"\n size=\"md\"\n type=\"password\"\n value={passphrase}", "score": 0.8529958128929138 }, { "filename": "src/pages/login.tsx", "retrieved_chunk": " <Stack spacing=\"2rem\" direction={{ base: 'column', xl: 'row' }}>\n <Box w={{ base: '100%', xl: '50%' }}>\n {showLoginButton ? (\n <GoogleLoginButton\n url={url}\n onSuccess={setAccessToken}\n onFailure={setError}\n />\n ) : (\n <PassphraseInput setEncryptionKey={setEncryptionKey} />", "score": 0.8441874384880066 }, { "filename": "src/pages/home.tsx", "retrieved_chunk": " storageCount={storageCount}\n />\n <UserCard />\n </Stack>\n <UploadButton onUpload={handleUpload} />\n <Card backgroundColor=\"purple.200\" w=\"100%\">\n <FileTable\n search={search}\n setFilesCount={setFilesCount}\n setStorageCount={setStorageCount}", "score": 0.83842533826828 } ]
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": " 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": 0.8656011819839478 }, { "filename": "src/components/DeleteButton.tsx", "retrieved_chunk": " </Button>\n </ModalFooter>\n </ModalContent>\n </Modal>\n );\n};\ninterface PropsButton {\n fileId: string;\n}\nconst DeleteButton: FC<PropsButton> = (props: PropsButton) => {", "score": 0.8331183791160583 }, { "filename": "src/components/DeleteButton.tsx", "retrieved_chunk": " )}\n </>\n );\n};\nexport default DeleteButton;", "score": 0.8325795531272888 }, { "filename": "src/pages/home.tsx", "retrieved_chunk": " storageCount={storageCount}\n />\n <UserCard />\n </Stack>\n <UploadButton onUpload={handleUpload} />\n <Card backgroundColor=\"purple.200\" w=\"100%\">\n <FileTable\n search={search}\n setFilesCount={setFilesCount}\n setStorageCount={setStorageCount}", "score": 0.8300338387489319 }, { "filename": "src/components/DownloadButton.tsx", "retrieved_chunk": "import { FC, useCallback, useRef, useState } from 'react';\nimport { useDecryptFile, useDownloadFile } from '@app/hooks';\nimport { saveFile } from '@app/lib/files';\nimport { IconButton, Spinner, useToast } from '@chakra-ui/react';\nimport { DownloadIcon, ShieldLockIcon } from './Icons';\ninterface props {\n fileId: string;\n}\nconst DownloadButton: FC<props> = (props: props) => {\n const { fileId } = props;", "score": 0.8279353380203247 } ]
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/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": 0.8688031435012817 }, { "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": 0.8454530239105225 }, { "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": 0.8434971570968628 }, { "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": 0.8434748649597168 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " /**\n * Define 1: Define field variable\n */\n this.defineField(this.#buffer)\n /**\n * Step 2: Compile union children wrapped inside predicate\n * condition.\n */\n this.#buffer.writeStatement(this.#compileUnionChildren())\n }", "score": 0.8424742817878723 } ]
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": 0.9118924140930176 }, { "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": 0.9095587730407715 }, { "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": 0.9062306880950928 }, { "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": 0.8970890045166016 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " /**\n * Define 1: Define field variable\n */\n this.defineField(this.#buffer)\n /**\n * Step 2: Define code to validate the existence of field.\n */\n this.#buffer.writeStatement(\n defineFieldExistenceValidations({\n allowNull: this.#node.allowNull,", "score": 0.8714556097984314 } ]
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/UploadToast.tsx", "retrieved_chunk": " {steps[f.name] === 'ENCRYPTING' && (\n <ShieldLockIcon boxSize=\"1rem\" color=\"white\" />\n )}\n {steps[f.name] === 'UPLOADING' &&\n (value < 100 ? (\n <CircularProgress\n value={value}\n color=\"blue.700\"\n trackColor=\"white\"\n size=\"16px\"", "score": 0.8665479421615601 }, { "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": 0.8401081562042236 }, { "filename": "src/components/Icons.tsx", "retrieved_chunk": "} from 'react-icons/io5';\nimport {\n MdCheck,\n MdChevronLeft,\n MdChevronRight,\n MdClose,\n MdDarkMode,\n MdDownload,\n MdGridView,\n MdLightMode,", "score": 0.8265887498855591 }, { "filename": "src/components/Icons.tsx", "retrieved_chunk": "export const ShieldLockIcon = iconFactory(BsShieldLockFill);\nexport const CheckIcon = iconFactory(MdCheck);\nexport const ArrowUpIcon = iconFactory(FaChevronUp);\nexport const ArrowDownIcon = iconFactory(FaChevronDown);\nexport const DocumentIcon = iconFactory(IoDocumentOutline);\nexport const FolderIcon = iconFactory(IoFolderOutline);\nexport const CreateFolderIcon = iconFactory(IoFolderOpenOutline);\nexport const ChevronLeftIcon = iconFactory(MdChevronLeft);\nexport const ChevronRightIcon = iconFactory(MdChevronRight);\nexport const GithubIcon = iconFactory(SiGithub);", "score": 0.8199164867401123 }, { "filename": "src/components/Icons.tsx", "retrieved_chunk": "import { IconType } from 'react-icons';\nimport { BsShieldLockFill } from 'react-icons/bs';\nimport { FaChevronDown, FaChevronUp } from 'react-icons/fa';\nimport { FcGoogle } from 'react-icons/fc';\nimport { IoMdKey } from 'react-icons/io';\nimport {\n IoDocumentOutline,\n IoFolderOpenOutline,\n IoFolderOutline,\n IoTrashBin,", "score": 0.8193897008895874 } ]
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/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": 0.8187418580055237 }, { "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": 0.8181193470954895 }, { "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": 0.7852270603179932 }, { "filename": "src/hooks/index.ts", "retrieved_chunk": " return async (fileId: string) => {\n await deleteFile(accessToken.value, fileId);\n await revalidateListFiles();\n };\n};\nexport const useAppData = () => {\n const { accessToken } = useContext(AppContext);\n return useSWR('appData', () => loadAppData(accessToken.value), {\n revalidateOnFocus: false,\n revalidateIfStale: false,", "score": 0.7797502279281616 }, { "filename": "src/models/index.ts", "retrieved_chunk": "export interface UserInfo {\n email: string;\n}\nexport interface StorageQuota {\n limit: number;\n usage: number;\n usageInDrive: number;\n}\nexport interface FileMetadata {\n id: string;", "score": 0.7768574953079224 } ]
typescript
: AppData => {
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": 0.8596312999725342 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " </Td>\n <Td border=\"0\">\n <HStack justifyContent=\"flex-end\">\n <DownloadButton fileId={file.id} />\n <DeleteButton fileId={file.id} />\n </HStack>\n </Td>\n </Tr>\n ))}\n </Tbody>", "score": 0.8565696477890015 }, { "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": 0.8468199372291565 }, { "filename": "src/components/DeleteButtonAppFolder.tsx", "retrieved_chunk": " </Button>\n );\n};\nexport default DeleteAppDataFolder;", "score": 0.8295445442199707 }, { "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": 0.8285285234451294 } ]
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 { 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/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": 0.8560890555381775 }, { "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": 0.8396090269088745 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " parseFnRefId: child.schema.parseFnId,\n variableName: this.field.variableName,\n })\n )\n }\n this.#compiler.compileNode(child.schema, conditionalBuffer, this.#parent, this.field)\n childrenBuffer.writeStatement(\n defineConditionalGuard({\n conditional: index === 0 ? 'if' : 'else if',\n variableName: this.field.variableName,", "score": 0.8387817144393921 }, { "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": 0.8369656801223755 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " childrenBuffer.writeStatement(\n defineElseCondition({\n variableName: this.field.variableName,\n conditionalFnRefId: this.#node.elseConditionalFnRefId,\n })\n )\n }\n return childrenBuffer.toString()\n }\n compile() {", "score": 0.8354837894439697 } ]
typescript
.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 { 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/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": 0.8730881214141846 }, { "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": 0.8638080954551697 }, { "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": 0.858055591583252 }, { "filename": "src/compiler/nodes/tuple.ts", "retrieved_chunk": " */\nexport class TupleNodeCompiler extends BaseNode {\n #node: TupleNode\n #buffer: CompilerBuffer\n #compiler: Compiler\n constructor(\n node: TupleNode,\n buffer: CompilerBuffer,\n compiler: Compiler,\n parent: CompilerParent,", "score": 0.8486717939376831 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": "import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js'\n/**\n * Compiles an object schema node to JS string output.\n */\nexport class ObjectNodeCompiler extends BaseNode {\n #node: ObjectNode\n #buffer: CompilerBuffer\n #compiler: Compiler\n constructor(\n node: ObjectNode,", "score": 0.8455290198326111 } ]
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": 0.9485235214233398 }, { "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": 0.9430610537528992 }, { "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": 0.9155886769294739 }, { "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": 0.9090343117713928 }, { "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": 0.8869077563285828 } ]
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/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": 0.9013158082962036 }, { "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": 0.8919596672058105 }, { "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": 0.8887929320335388 }, { "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": 0.8802742958068848 }, { "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": 0.8799355030059814 } ]
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/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": 0.8345019221305847 }, { "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": 0.8267161250114441 }, { "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": 0.8168767690658569 }, { "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": 0.811486005783081 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " childrenBuffer.writeStatement(\n defineElseCondition({\n variableName: this.field.variableName,\n conditionalFnRefId: this.#node.elseConditionalFnRefId,\n })\n )\n }\n return childrenBuffer.toString()\n }\n compile() {", "score": 0.8101295232772827 } ]
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": 0.843002200126648 }, { "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": 0.8200136423110962 }, { "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": 0.8197247982025146 }, { "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": 0.8143655061721802 }, { "filename": "src/types.ts", "retrieved_chunk": " /**\n * Name of the output property. This allows validating a field with a different name, but\n * storing its output value with a different name.\n */\n propertyName: string\n /**\n * Are we expecting this field to be undefined or null\n */\n isOptional: boolean\n /**", "score": 0.8021711111068726 } ]
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/nodes/base.ts", "retrieved_chunk": " parentField?: CompilerField\n ) {\n this.#parentField = parentField\n this.#node = node\n if (this.#parentField) {\n this.field = this.#parentField\n } else {\n compiler.variablesCounter++\n this.field = compiler.createFieldFor(node, parent)\n }", "score": 0.8703262209892273 }, { "filename": "src/compiler/fields/array_field.ts", "retrieved_chunk": "/*\n * @vinejs/compiler\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { CompilerField, CompilerParent } from '../../types.js'\nexport function createArrayField(parent: CompilerParent): CompilerField {", "score": 0.8612078428268433 }, { "filename": "src/compiler/fields/record_field.ts", "retrieved_chunk": "/*\n * @vinejs/compiler\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { CompilerField, CompilerParent } from '../../types.js'\nexport function createRecordField(parent: CompilerParent): CompilerField {", "score": 0.8554337620735168 }, { "filename": "src/compiler/fields/root_field.ts", "retrieved_chunk": "/*\n * @vinejs/compiler\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { CompilerField, CompilerParent } from '../../types.js'\nexport function createRootField(parent: CompilerParent): CompilerField {", "score": 0.8537745475769043 }, { "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": 0.8475275635719299 } ]
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": 0.899920642375946 }, { "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": 0.8941320180892944 }, { "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": 0.8930938839912415 }, { "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": 0.8869791030883789 }, { "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": 0.8797355890274048 } ]
typescript
`${defineFieldValueOutput({
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/StorageQuota.tsx", "retrieved_chunk": " value={(data?.usage / data?.limit) * 100}\n size=\"xs\"\n borderRadius=\"10px\"\n />\n <Text fontWeight=\"semibold\" fontSize=\"xs\" marginTop=\"0.2rem\">\n {formatBytes(data?.usage)} used on {formatBytes(data?.limit)}\n </Text>\n </Flex>\n ) : (\n <Spinner speed=\"0.65s\" emptyColor=\"gray.200\" color=\"blue.500\" />", "score": 0.827757716178894 }, { "filename": "src/pages/login.tsx", "retrieved_chunk": " right={0}\n width=\"15rem\"\n height=\"30rem\"\n opacity=\"0.6\"\n backgroundImage=\"radial-gradient(purple.500 4px, #fff0 0px);\"\n backgroundSize=\"60px 60px;\"\n />\n </Flex>\n </Flex>\n );", "score": 0.8175516128540039 }, { "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": 0.8119944334030151 }, { "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": 0.8101473450660706 }, { "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": 0.8080471158027649 } ]
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 { 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/base.ts", "retrieved_chunk": " parentField?: CompilerField\n ) {\n this.#parentField = parentField\n this.#node = node\n if (this.#parentField) {\n this.field = this.#parentField\n } else {\n compiler.variablesCounter++\n this.field = compiler.createFieldFor(node, parent)\n }", "score": 0.870380163192749 }, { "filename": "src/compiler/fields/array_field.ts", "retrieved_chunk": "/*\n * @vinejs/compiler\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { CompilerField, CompilerParent } from '../../types.js'\nexport function createArrayField(parent: CompilerParent): CompilerField {", "score": 0.8611206412315369 }, { "filename": "src/compiler/fields/record_field.ts", "retrieved_chunk": "/*\n * @vinejs/compiler\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { CompilerField, CompilerParent } from '../../types.js'\nexport function createRecordField(parent: CompilerParent): CompilerField {", "score": 0.8553746938705444 }, { "filename": "src/compiler/fields/root_field.ts", "retrieved_chunk": "/*\n * @vinejs/compiler\n *\n * (c) VineJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\nimport type { CompilerField, CompilerParent } from '../../types.js'\nexport function createRootField(parent: CompilerParent): CompilerField {", "score": 0.8537111878395081 }, { "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": 0.8475308418273926 } ]
typescript
return createTupleField(node, parent) case 'record': 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 { 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": 0.911763608455658 }, { "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": 0.9025468826293945 }, { "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": 0.8861198425292969 }, { "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": 0.8839843273162842 }, { "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": 0.880157470703125 } ]
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/pages/login.tsx", "retrieved_chunk": " <Stack spacing=\"2rem\" direction={{ base: 'column', xl: 'row' }}>\n <Box w={{ base: '100%', xl: '50%' }}>\n {showLoginButton ? (\n <GoogleLoginButton\n url={url}\n onSuccess={setAccessToken}\n onFailure={setError}\n />\n ) : (\n <PassphraseInput setEncryptionKey={setEncryptionKey} />", "score": 0.860224723815918 }, { "filename": "src/pages/login.tsx", "retrieved_chunk": " setError('');\n const digest = await sha256(passphrase);\n const key = await unwrapEncryptionKey(wrappedKey, digest);\n const exportKey = await exportEncryptionKey(key);\n encryptionKey.setValue(exportKey);\n } catch (err) {\n setError(`Failed unwrapping your encryption key`);\n }\n };\n const showLoginButton = useMemo(() => !accessToken.value, [accessToken.value]);", "score": 0.8579172492027283 }, { "filename": "src/components/UserCard.tsx", "retrieved_chunk": " </Modal>\n );\n};\nconst UserCard: FC = () => {\n const { onOpen, onClose, isOpen } = useDisclosure();\n const { data: user } = useUserInfo();\n const { encryptionKey } = useContext(AppContext);\n const ref = useRef<HTMLAnchorElement>(null);\n const onDownload = () => {\n saveFile([encryptionKey.value], `${user?.email}_key.txt`, 'text/plain', ref);", "score": 0.8542643785476685 }, { "filename": "src/pages/login.tsx", "retrieved_chunk": "import { FC, useContext, useEffect, useMemo, useState } from 'react';\n// import DeleteAppDataFolder from '@app/components/DeleteButtonAppFolder';\nimport { GithubIcon, LinkedinIcon } from '@app/components/Icons';\nimport GoogleLoginButton from '@app/components/LoginButton';\nimport PassphraseInput from '@app/components/PassphraseInput';\nimport ProductHuntBadge from '@app/components/ProductHuntBadge';\nimport { AppContext } from '@app/context';\nimport { useRecoverAccessToken } from '@app/hooks';\nimport { getUserInfo } from '@app/hooks/http';\nimport { getAuthorizationUrl } from '@app/lib/authorizationUrl';", "score": 0.8505383729934692 }, { "filename": "src/pages/login.tsx", "retrieved_chunk": " await getUserInfo(token);\n accessToken.setValue(token);\n setStorageAccessToken(token);\n } catch (err) {\n setError((err as Error).message);\n delStorageAccessToken();\n }\n };\n const setEncryptionKey = async (passphrase: string, wrappedKey: WrappedKey) => {\n try {", "score": 0.8458627462387085 } ]
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 * 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": 0.8206750154495239 }, { "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": 0.8180835247039795 }, { "filename": "src/compiler/fields/tuple_field.ts", "retrieved_chunk": " 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: `${parent.variableName}_item_${node.fieldName}`,\n valueExpression: `${parent.variableName}.value[${node.fieldName}]`,\n outputExpression: `${parent.variableName}_out[${node.propertyName}]`,", "score": 0.8115884065628052 }, { "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": 0.8094394207000732 }, { "filename": "src/compiler/fields/object_field.ts", "retrieved_chunk": " outputExpression: `${parent.variableName}_out['${node.propertyName}']`,\n isArrayMember: false,\n }\n}", "score": 0.8077882528305054 } ]
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": 0.916122317314148 }, { "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": 0.8916577100753784 }, { "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": 0.8799851536750793 }, { "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": 0.8778026700019836 }, { "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": 0.860633134841919 } ]
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": 0.8507721424102783 }, { "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": 0.8507124781608582 }, { "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": 0.8482261896133423 }, { "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": 0.8471870422363281 }, { "filename": "src/components/FileTable.tsx", "retrieved_chunk": " }, [filteredFiles, selected, pagination]);\n useEffect(() => {\n setFilesCount(filteredFiles?.length || 0);\n setStorageCount(filteredFiles?.reduce((acc, { size }) => acc + size, 0));\n }, [filteredFiles]);\n useEffect(() => {\n if (selected > pages && pages != 0) {\n setSelected(pages);\n }\n }, [pages]);", "score": 0.8444218039512634 } ]
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": 0.8944764137268066 }, { "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": 0.863983154296875 }, { "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": 0.8578110933303833 }, { "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": 0.8471933007240295 }, { "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": 0.8443984985351562 } ]
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": 0.888360321521759 }, { "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": 0.8862587213516235 }, { "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": 0.8793725371360779 }, { "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": 0.8646978735923767 }, { "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": 0.863355278968811 } ]
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/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": 0.8691143989562988 }, { "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": 0.8475422859191895 }, { "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": 0.8445563316345215 }, { "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": 0.8407962322235107 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " childrenBuffer.writeStatement(\n defineElseCondition({\n variableName: this.field.variableName,\n conditionalFnRefId: this.#node.elseConditionalFnRefId,\n })\n )\n }\n return childrenBuffer.toString()\n }\n compile() {", "score": 0.8356145024299622 } ]
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": 0.8923871517181396 }, { "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": 0.8853027820587158 }, { "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": 0.8819333910942078 }, { "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": 0.8649386167526245 }, { "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": 0.8629665374755859 } ]
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/object/initial_output.ts", "retrieved_chunk": " */\ntype OutputOptions = {\n variableName: string\n outputExpression: string\n outputValueExpression: string\n}\n/**\n * Returns JS fragment for writing the initial output for an object\n */\nexport function defineObjectInitialOutput({", "score": 0.8074809312820435 }, { "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": 0.8049473762512207 }, { "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": 0.8034017086029053 }, { "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": 0.8010690212249756 }, { "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": 0.8001741170883179 } ]
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": " */\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": 0.8874516487121582 }, { "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": 0.8849765062332153 }, { "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": 0.8751809000968933 }, { "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": 0.8639935851097107 }, { "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": 0.8624095320701599 } ]
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/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": 0.8334794044494629 }, { "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": 0.8261542916297913 }, { "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": 0.8161371946334839 }, { "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": 0.8106800317764282 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " childrenBuffer.writeStatement(\n defineElseCondition({\n variableName: this.field.variableName,\n conditionalFnRefId: this.#node.elseConditionalFnRefId,\n })\n )\n }\n return childrenBuffer.toString()\n }\n compile() {", "score": 0.8095799088478088 } ]
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": 0.9103134870529175 }, { "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": 0.9094939231872559 }, { "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": 0.9059433341026306 }, { "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": 0.8915086984634399 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " /**\n * Define 1: Define field variable\n */\n this.defineField(this.#buffer)\n /**\n * Step 2: Define code to validate the existence of field.\n */\n this.#buffer.writeStatement(\n defineFieldExistenceValidations({\n allowNull: this.#node.allowNull,", "score": 0.8705529570579529 } ]
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 * 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": 0.8171671628952026 }, { "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": 0.8153744339942932 }, { "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": 0.8122437000274658 }, { "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": 0.8084913492202759 }, { "filename": "src/compiler/fields/tuple_field.ts", "retrieved_chunk": " 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: `${parent.variableName}_item_${node.fieldName}`,\n valueExpression: `${parent.variableName}.value[${node.fieldName}]`,\n outputExpression: `${parent.variableName}_out[${node.propertyName}]`,", "score": 0.8079758286476135 } ]
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/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": 0.8528815507888794 }, { "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": 0.8524231314659119 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " parseFnRefId: child.schema.parseFnId,\n variableName: this.field.variableName,\n })\n )\n }\n this.#compiler.compileNode(child.schema, conditionalBuffer, this.#parent, this.field)\n childrenBuffer.writeStatement(\n defineConditionalGuard({\n conditional: index === 0 ? 'if' : 'else if',\n variableName: this.field.variableName,", "score": 0.8417843580245972 }, { "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": 0.8390161395072937 }, { "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": 0.83879154920578 } ]
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": 0.8422267436981201 }, { "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": 0.8198304176330566 }, { "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": 0.818599283695221 }, { "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": 0.814154863357544 }, { "filename": "src/types.ts", "retrieved_chunk": " /**\n * Name of the output property. This allows validating a field with a different name, but\n * storing its output value with a different name.\n */\n propertyName: string\n /**\n * Are we expecting this field to be undefined or null\n */\n isOptional: boolean\n /**", "score": 0.8009122610092163 } ]
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": 0.8959190249443054 }, { "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": 0.8651703596115112 }, { "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": 0.8557066917419434 }, { "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": 0.8486342430114746 }, { "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": 0.8455774188041687 } ]
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": 0.9617529511451721 }, { "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": 0.9435844421386719 }, { "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": 0.9169844388961792 }, { "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": 0.9127946496009827 }, { "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": 0.9084228277206421 } ]
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": 0.9157401323318481 }, { "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": 0.9128438234329224 }, { "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": 0.8902751207351685 }, { "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": 0.8885102868080139 }, { "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": 0.8876860737800598 } ]
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": 0.911267876625061 }, { "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": 0.895149827003479 }, { "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": 0.8883687257766724 }, { "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": 0.8826833367347717 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " childrenBuffer.writeStatement(\n defineElseCondition({\n variableName: this.field.variableName,\n conditionalFnRefId: this.#node.elseConditionalFnRefId,\n })\n )\n }\n return childrenBuffer.toString()\n }\n compile() {", "score": 0.8799283504486084 } ]
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/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": 0.8450849056243896 }, { "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": 0.8260014653205872 }, { "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": 0.8200435638427734 }, { "filename": "src/scripts/define_conditional_guard.ts", "retrieved_chunk": " conditionalFnRefId,\n guardedCodeSnippet,\n}: ConditionalGuardOptions) {\n return `${conditional}(refs['${conditionalFnRefId}'](${variableName}.value, ${variableName})) {\n${guardedCodeSnippet}\n}`\n}", "score": 0.817909300327301 }, { "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": 0.816180408000946 } ]
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": 0.9063753485679626 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " if (group.elseConditionalFnRefId && group.conditions.length) {\n buffer.writeStatement(\n defineElseCondition({\n variableName: this.field.variableName,\n conditionalFnRefId: group.elseConditionalFnRefId,\n })\n )\n }\n }\n compile() {", "score": 0.8909088373184204 }, { "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": 0.8713310956954956 }, { "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": 0.8668321967124939 }, { "filename": "src/compiler/nodes/literal.ts", "retrieved_chunk": " outputExpression: this.field.outputExpression,\n transformFnRefId: this.#node.transformFnId,\n conditional: 'else if',\n })}`\n )\n }\n}", "score": 0.8603349328041077 } ]
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/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": 0.8460487723350525 }, { "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": 0.8314210772514343 }, { "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": 0.8218342661857605 }, { "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": 0.8199624419212341 }, { "filename": "src/scripts/define_conditional_guard.ts", "retrieved_chunk": " conditionalFnRefId,\n guardedCodeSnippet,\n}: ConditionalGuardOptions) {\n return `${conditional}(refs['${conditionalFnRefId}'](${variableName}.value, ${variableName})) {\n${guardedCodeSnippet}\n}`\n}", "score": 0.8177645802497864 } ]
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/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": 0.9006085991859436 }, { "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": 0.8984042406082153 }, { "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": 0.8918828964233398 }, { "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": 0.8707024455070496 }, { "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": 0.8696645498275757 } ]
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": 0.8952990174293518 }, { "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": 0.8642096519470215 }, { "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": 0.8574477434158325 }, { "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": 0.8511275053024292 }, { "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": 0.8496933579444885 } ]
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": 0.9732155799865723 }, { "filename": "src/compiler/nodes/object.ts", "retrieved_chunk": " variableName: this.field.variableName,\n wildCardPath: this.field.wildCardPath,\n } as const\n this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent))\n return buffer.toString()\n }\n /**\n * Compiles an object groups recursively\n */\n #compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) {", "score": 0.8876962661743164 }, { "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": 0.8852643370628357 }, { "filename": "src/compiler/nodes/union.ts", "retrieved_chunk": " childrenBuffer.writeStatement(\n defineElseCondition({\n variableName: this.field.variableName,\n conditionalFnRefId: this.#node.elseConditionalFnRefId,\n })\n )\n }\n return childrenBuffer.toString()\n }\n compile() {", "score": 0.8806787729263306 }, { "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": 0.877470850944519 } ]
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/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": 0.9010418653488159 }, { "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": 0.8971675634384155 }, { "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": 0.8902692198753357 }, { "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": 0.87080317735672 }, { "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": 0.8672654628753662 } ]
typescript
#node.each, recordElementsBuffer, {
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": "import * as vscode from \"vscode\";\nimport * as fs from \"fs\";\nimport path from \"path\";\nimport {\n createOZAccount,\n deleteAccount,\n deployAccount,\n selectDeployedAccount,\n selectNotDeployedAccount,\n} from \"./config/account\";", "score": 0.8602346181869507 }, { "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": 0.854785680770874 }, { "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": 0.8545870780944824 }, { "filename": "src/treeView/AccountTreeView/AccountTreeDataProvider.ts", "retrieved_chunk": " for (const account of accounts) {\n leaves.push(new Account(\n account.accountAddress.slice(0, 5) + \"...\" + account.accountAddress.slice(-5),\n vscode.TreeItemCollapsibleState.None,\n \"deployedAccount\",\n account,\n \"verified\"\n ));\n }\n }", "score": 0.8540630340576172 }, { "filename": "src/treeView/AccountTreeView/AccountTreeDataProvider.ts", "retrieved_chunk": " if (undeployedAccounts !== undefined) {\n for (const account of undeployedAccounts) {\n leaves.push(new Account(\n account.accountAddress.slice(0, 5) + \"...\" + account.accountAddress.slice(-5),\n vscode.TreeItemCollapsibleState.None,\n \"undeployedAccount\",\n account,\n \"unverified\"\n ));\n }", "score": 0.8532834053039551 } ]
typescript
const quickPick = vscode.window.createQuickPick<IAccountQP>();
/* * @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 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": 0.89487224817276 }, { "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": 0.8853586912155151 }, { "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": 0.8683488965034485 }, { "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": 0.868231475353241 }, { "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": 0.8661607503890991 } ]
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/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": 0.8875908851623535 }, { "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": 0.8827418088912964 }, { "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": 0.8805723190307617 }, { "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": 0.8769497871398926 }, { "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": 0.8753199577331543 } ]
typescript
const provider = getNetworkProvider(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/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": 0.8871104717254639 }, { "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": 0.875066876411438 }, { "filename": "src/extension.ts", "retrieved_chunk": " await declareContract(context);\n }),\n vscode.commands.registerCommand(\"starkode.deployaccount\", async () => {\n await deployAccount(context, accountTreeDataProvider);\n }),\n vscode.commands.registerCommand(\"starkode.selectaccount\", async () => {\n await selectDeployedAccount(context);\n }),\n vscode.commands.registerCommand(\"starkode.selectContract\", async () => {\n selectCompiledContract(context);", "score": 0.8747916221618652 }, { "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": 0.8705468773841858 }, { "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": 0.8686737418174744 } ]
typescript
= getNetworkProvider(context) as Provider;
/* * @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": 0.9266761541366577 }, { "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": 0.8742753267288208 }, { "filename": "src/compiler/fields/tuple_field.ts", "retrieved_chunk": " 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: `${parent.variableName}_item_${node.fieldName}`,\n valueExpression: `${parent.variableName}.value[${node.fieldName}]`,\n outputExpression: `${parent.variableName}_out[${node.propertyName}]`,", "score": 0.8695271015167236 }, { "filename": "src/compiler/nodes/base.ts", "retrieved_chunk": " }\n protected defineField(buffer: CompilerBuffer) {\n if (!this.#parentField) {\n buffer.writeStatement(\n defineFieldVariables({\n fieldNameExpression: this.field.fieldNameExpression,\n isArrayMember: this.field.isArrayMember,\n parentValueExpression: this.field.parentValueExpression,\n valueExpression: this.field.valueExpression,\n variableName: this.field.variableName,", "score": 0.868102490901947 }, { "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": 0.8666937947273254 } ]
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/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": 0.8781557083129883 }, { "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": 0.8745208978652954 }, { "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": 0.8744785785675049 }, { "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": 0.8737687468528748 }, { "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": 0.8691812753677368 } ]
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/extension.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport * as fs from \"fs\";\nimport path from \"path\";\nimport {\n createOZAccount,\n deleteAccount,\n deployAccount,\n selectDeployedAccount,\n selectNotDeployedAccount,\n} from \"./config/account\";", "score": 0.8316619992256165 }, { "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": 0.8253260254859924 }, { "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": 0.82427579164505 }, { "filename": "src/treeView/AccountTreeView/AccountTreeDataProvider.ts", "retrieved_chunk": " }\n}\nexport class Account extends vscode.TreeItem {\n contextValue: string;\n constructor(\n public readonly label: string,\n public readonly collapsibleState: vscode.TreeItemCollapsibleState,\n public readonly context: string,\n public account: JSONAccountType | undefined,\n public readonly icon: string", "score": 0.8220770359039307 }, { "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": 0.8196249008178711 } ]
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/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": 0.870724081993103 }, { "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": 0.857842743396759 }, { "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": 0.8482212424278259 }, { "filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts", "retrieved_chunk": " ));\n }\n return leaves;\n }\n }\n private _onDidChangeTreeData: vscode.EventEmitter<Contract | undefined> =\n new vscode.EventEmitter<Contract | undefined>();\n readonly onDidChangeTreeData: vscode.Event<Contract | undefined> =\n this._onDidChangeTreeData.event;\n refresh(): void {", "score": 0.8453971743583679 }, { "filename": "src/treeView/AccountTreeView/AccountTreeDataProvider.ts", "retrieved_chunk": " }\n return leaves;\n }\n }\n private _onDidChangeTreeData: vscode.EventEmitter<Account | undefined> =\n new vscode.EventEmitter<Account | undefined>();\n readonly onDidChangeTreeData: vscode.Event<Account | undefined> =\n this._onDidChangeTreeData.event;\n refresh(): void {\n this._onDidChangeTreeData.fire(undefined);", "score": 0.8393079042434692 } ]
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": 0.845073401927948 }, { "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": 0.8403621315956116 }, { "filename": "src/extension.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport * as fs from \"fs\";\nimport path from \"path\";\nimport {\n createOZAccount,\n deleteAccount,\n deployAccount,\n selectDeployedAccount,\n selectNotDeployedAccount,\n} from \"./config/account\";", "score": 0.8226137161254883 }, { "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": 0.8200987577438354 }, { "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": 0.8150259852409363 } ]
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/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": 0.8780325651168823 }, { "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": 0.8691283464431763 }, { "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": 0.8516660928726196 }, { "filename": "src/treeView/ContractTreeView/function.ts", "retrieved_chunk": " return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const filePath = path.join(path_, \"starkode\", input.label, `${input.label}_address.json`);\n const document = await vscode.workspace.openTextDocument(filePath);\n const editor = await vscode.window.showTextDocument(document);\n};", "score": 0.8415721654891968 }, { "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": 0.8393875956535339 } ]
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": 0.8623102903366089 }, { "filename": "src/extension.ts", "retrieved_chunk": " } else {\n abiTreeView.message = \"Select a contract and its ABI functions will appear here.\";\n }\n }\n context.subscriptions.push(\n vscode.commands.registerCommand(\"starkode.activate\", () => {\n try {\n if (!fs.existsSync(path.join(path_, \"starkode\"))) {\n fs.mkdirSync(path.join(path_, \"starkode\"));\n }", "score": 0.8474225401878357 }, { "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": 0.8435609340667725 }, { "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": 0.8425723314285278 }, { "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": 0.8407135009765625 } ]
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/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": 0.8981313705444336 }, { "filename": "src/extension.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport * as fs from \"fs\";\nimport path from \"path\";\nimport {\n createOZAccount,\n deleteAccount,\n deployAccount,\n selectDeployedAccount,\n selectNotDeployedAccount,\n} from \"./config/account\";", "score": 0.8583582639694214 }, { "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": 0.8554902672767639 }, { "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": 0.8546785116195679 }, { "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": 0.853847861289978 } ]
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/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": 0.8798061609268188 }, { "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": 0.8665577173233032 }, { "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": 0.8554204106330872 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " }\n};\nexport const deployContract = async (context: vscode.ExtensionContext) => {\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 provider = getNetworkProvider(context) as Provider;", "score": 0.8504880666732788 }, { "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": 0.8504399061203003 } ]
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/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": 0.8878310322761536 }, { "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": 0.8566468358039856 }, { "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": 0.8562049865722656 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " }\n};\nexport const deployContract = async (context: vscode.ExtensionContext) => {\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 provider = getNetworkProvider(context) as Provider;", "score": 0.8515183329582214 }, { "filename": "src/treeView/ContractTreeView/function.ts", "retrieved_chunk": " return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const filePath = path.join(path_, \"starkode\", input.label, `${input.label}_address.json`);\n const document = await vscode.workspace.openTextDocument(filePath);\n const editor = await vscode.window.showTextDocument(document);\n};", "score": 0.8473304510116577 } ]
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/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": 0.8845826983451843 }, { "filename": "src/config/account.ts", "retrieved_chunk": " quickPick.onDidHide(() => {\n quickPick.dispose();\n });\n quickPick.show();\n};\nexport const getAccountInfo = (\n context: vscode.ExtensionContext,\n accountAddress: string\n) => {\n const accounts = getDeployedAccounts(context) as JSONAccountType[];", "score": 0.8809967637062073 }, { "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": 0.8750464916229248 }, { "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": 0.8748998641967773 }, { "filename": "src/config/account.ts", "retrieved_chunk": " logger.log(\"No account exist.\");\n return;\n }\n const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {\n encoding: \"utf-8\",\n });\n const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);\n const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(\n parsedFileData,\n selectedNetwork,", "score": 0.8745720982551575 } ]
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/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": 0.8924432992935181 }, { "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": 0.8796813488006592 }, { "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": 0.8727664351463318 }, { "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": 0.8692893385887146 }, { "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": 0.8691315650939941 } ]
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": 0.9139149785041809 }, { "filename": "src/treeView/ContractTreeView/function.ts", "retrieved_chunk": " return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const filePath = path.join(path_, \"starkode\", input.label, `${input.label}_address.json`);\n const document = await vscode.workspace.openTextDocument(filePath);\n const editor = await vscode.window.showTextDocument(document);\n};", "score": 0.8582797646522522 }, { "filename": "src/treeView/ABITreeView/functions.ts", "retrieved_chunk": " const document = await vscode.workspace.openTextDocument(filePath);\n const lineNumber = await search(filePath, `\"name\": \"${input.parent?.label}\"`);\n const line = await search(filePath, `\"name\": \"${input.abi.name}\"`, lineNumber.line);\n const cursorPosition = new vscode.Position(line.line + 2, line.character + 10);\n const editor = await vscode.window.showTextDocument(document);\n editor.selection = new vscode.Selection(cursorPosition, cursorPosition);\n editor.revealRange(new vscode.Range(cursorPosition, cursorPosition));\n abiTreeDataProvider.refresh(input);\n};", "score": 0.8541380167007446 }, { "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": 0.8461127281188965 }, { "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": 0.8459359407424927 } ]
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/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": 0.8969101905822754 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " }\n const deployResponse = await account.deployContract({\n classHash: contractInfo.classHash,\n });\n logger.log(`transaction hash: ${deployResponse.transaction_hash}`);\n logger.log(\"waiting for transaction success...\");\n await provider.waitForTransaction(deployResponse.transaction_hash);\n const { abi: testAbi } = await provider.getClassAt(\n deployResponse.contract_address\n );", "score": 0.875950276851654 }, { "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": 0.8733081817626953 }, { "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": 0.8681479692459106 }, { "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": 0.8540452718734741 } ]
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/account.ts", "retrieved_chunk": " logger.log(\"No account exist.\");\n return;\n }\n const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {\n encoding: \"utf-8\",\n });\n const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);\n const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(\n parsedFileData,\n selectedNetwork,", "score": 0.8776608109474182 }, { "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": 0.8730681538581848 }, { "filename": "src/config/account.ts", "retrieved_chunk": " const selectedNetwork = context.workspaceState.get(\"selectedNetwork\");\n fs.readFile(path, 'utf8', (err, data) => {\n if (err) {\n console.error('Error reading file:', err);\n return;\n }\n const accounts = JSON.parse(data);\n const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress);\n if (indexToUpdate !== -1) {\n accounts[indexToUpdate].isDeployed = {", "score": 0.8724715709686279 }, { "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": 0.8693390488624573 }, { "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": 0.8601360321044922 } ]
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": " 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": 0.8450418710708618 }, { "filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts", "retrieved_chunk": " ));\n }\n return leaves;\n }\n }\n private _onDidChangeTreeData: vscode.EventEmitter<Contract | undefined> =\n new vscode.EventEmitter<Contract | undefined>();\n readonly onDidChangeTreeData: vscode.Event<Contract | undefined> =\n this._onDidChangeTreeData.event;\n refresh(): void {", "score": 0.8431626558303833 }, { "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": 0.8416064977645874 }, { "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": 0.8413673639297485 }, { "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": 0.839275598526001 } ]
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/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": "import vscode, { TreeDataProvider, TreeItem, TreeItemCollapsibleState, EventEmitter, Event } from 'vscode';\nimport { Abi } from './AbiTreeItem';\nimport { ABIFragment } from '../../types';\nimport { getContractABI } from '../../config/contract';\nimport { logger } from '../../lib';\nexport class AbiTreeDataProvider implements TreeDataProvider<Abi> {\n context: vscode.ExtensionContext;\n constructor(context: vscode.ExtensionContext) {\n this.context = context;\n }", "score": 0.8461963534355164 }, { "filename": "src/extension.ts", "retrieved_chunk": " } else {\n abiTreeView.message = \"Select a contract and its ABI functions will appear here.\";\n }\n }\n context.subscriptions.push(\n vscode.commands.registerCommand(\"starkode.activate\", () => {\n try {\n if (!fs.existsSync(path.join(path_, \"starkode\"))) {\n fs.mkdirSync(path.join(path_, \"starkode\"));\n }", "score": 0.8442081212997437 }, { "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": 0.8426152467727661 }, { "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": 0.8422523736953735 }, { "filename": "src/extension.ts", "retrieved_chunk": " }),\n vscode.commands.registerCommand(\"starkode.deployContract\", async () => {\n await deployContract(context);\n }),\n vscode.commands.registerCommand(\"starkode.callFunction\", async () => {\n await executeContractFunction(context);\n }),\n vscode.commands.registerCommand(\"starkode.callContract\", async (node: any) => {\n await executeContractFunctionFromTreeView(context, node.abi);\n })", "score": 0.8394875526428223 } ]
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/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": 0.8649637699127197 }, { "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": 0.8609708547592163 }, { "filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts", "retrieved_chunk": "import vscode, { TreeDataProvider, TreeItem, TreeItemCollapsibleState, EventEmitter, Event } from 'vscode';\nimport { Abi } from './AbiTreeItem';\nimport { ABIFragment } from '../../types';\nimport { getContractABI } from '../../config/contract';\nimport { logger } from '../../lib';\nexport class AbiTreeDataProvider implements TreeDataProvider<Abi> {\n context: vscode.ExtensionContext;\n constructor(context: vscode.ExtensionContext) {\n this.context = context;\n }", "score": 0.860028088092804 }, { "filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts", "retrieved_chunk": " ));\n }\n return leaves;\n }\n }\n private _onDidChangeTreeData: vscode.EventEmitter<Contract | undefined> =\n new vscode.EventEmitter<Contract | undefined>();\n readonly onDidChangeTreeData: vscode.Event<Contract | undefined> =\n this._onDidChangeTreeData.event;\n refresh(): void {", "score": 0.8529373407363892 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " }\n });\n quickPick.onDidHide(() => {\n quickPick.dispose();\n });\n quickPick.show();\n};\nexport const getContractInfo = (path_: string, fileName: string) => {\n try {\n const file = fileName.substring(0, fileName.length - 5);", "score": 0.8485475778579712 } ]
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/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": 0.8926411867141724 }, { "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": 0.891151487827301 }, { "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": 0.8709507584571838 }, { "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": 0.8692255616188049 }, { "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": 0.868965744972229 } ]
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/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": 0.8828452229499817 }, { "filename": "src/extension.ts", "retrieved_chunk": " } else {\n abiTreeView.message = \"Select a contract and its ABI functions will appear here.\";\n }\n }\n context.subscriptions.push(\n vscode.commands.registerCommand(\"starkode.activate\", () => {\n try {\n if (!fs.existsSync(path.join(path_, \"starkode\"))) {\n fs.mkdirSync(path.join(path_, \"starkode\"));\n }", "score": 0.8790216445922852 }, { "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": 0.8734407424926758 }, { "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": 0.8723890781402588 }, { "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": 0.8717215657234192 } ]
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": 0.8940606713294983 }, { "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": 0.8860705494880676 }, { "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": 0.8780007362365723 }, { "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": 0.8730127811431885 }, { "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": 0.8713397979736328 } ]
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/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": 0.8919146060943604 }, { "filename": "src/config/contract.ts", "retrieved_chunk": " }\n const deployResponse = await account.deployContract({\n classHash: contractInfo.classHash,\n });\n logger.log(`transaction hash: ${deployResponse.transaction_hash}`);\n logger.log(\"waiting for transaction success...\");\n await provider.waitForTransaction(deployResponse.transaction_hash);\n const { abi: testAbi } = await provider.getClassAt(\n deployResponse.contract_address\n );", "score": 0.8747246265411377 }, { "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": 0.8664151430130005 }, { "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": 0.8620731830596924 }, { "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": 0.8475432395935059 } ]
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/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": 0.8726514577865601 }, { "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": 0.8704504370689392 }, { "filename": "src/extension.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport * as fs from \"fs\";\nimport path from \"path\";\nimport {\n createOZAccount,\n deleteAccount,\n deployAccount,\n selectDeployedAccount,\n selectNotDeployedAccount,\n} from \"./config/account\";", "score": 0.8644139766693115 }, { "filename": "src/extension.ts", "retrieved_chunk": " vscode.commands.registerCommand(\"starkode.deployAccountTreeView\", async (node: any) => {\n void context.workspaceState.update(\"undeployedAccount\", node.account.accountAddress);\n logger.log(`${node.account.accountAddress} selected`);\n await deployAccount(context, accountTreeDataProvider);\n }),\n vscode.commands.registerCommand(\"starkode.copyAccountAddress\", async (node: any) => {\n vscode.env.clipboard.writeText(node.account.accountAddress);\n }),\n vscode.commands.registerCommand(\"starkode.deleteAccount\", async (node: any) => {\n await deleteAccount(context, node);", "score": 0.8634985685348511 }, { "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": 0.8590061664581299 } ]
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/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": 0.920873761177063 }, { "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": 0.8862589001655579 }, { "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": 0.8852332234382629 }, { "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": 0.8833599090576172 }, { "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": 0.8793038725852966 } ]
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": 0.8642899990081787 }, { "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": 0.8583468198776245 }, { "filename": "src/extension.ts", "retrieved_chunk": "import * as vscode from \"vscode\";\nimport * as fs from \"fs\";\nimport path from \"path\";\nimport {\n createOZAccount,\n deleteAccount,\n deployAccount,\n selectDeployedAccount,\n selectNotDeployedAccount,\n} from \"./config/account\";", "score": 0.8343902826309204 }, { "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": 0.8295397758483887 }, { "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": 0.8241044282913208 } ]
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": "};\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": 0.8891671895980835 }, { "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": 0.8630028963088989 }, { "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": 0.8550425171852112 }, { "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": 0.8348263502120972 }, { "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": 0.8344711661338806 } ]
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": 0.9145814180374146 }, { "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": 0.8547923564910889 }, { "filename": "src/treeView/ABITreeView/functions.ts", "retrieved_chunk": " const document = await vscode.workspace.openTextDocument(filePath);\n const lineNumber = await search(filePath, `\"name\": \"${input.parent?.label}\"`);\n const line = await search(filePath, `\"name\": \"${input.abi.name}\"`, lineNumber.line);\n const cursorPosition = new vscode.Position(line.line + 2, line.character + 10);\n const editor = await vscode.window.showTextDocument(document);\n editor.selection = new vscode.Selection(cursorPosition, cursorPosition);\n editor.revealRange(new vscode.Range(cursorPosition, cursorPosition));\n abiTreeDataProvider.refresh(input);\n};", "score": 0.8500391244888306 }, { "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": 0.8495933413505554 }, { "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": 0.8493447303771973 } ]
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": "};\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": 0.8947268128395081 }, { "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": 0.8612509965896606 }, { "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": 0.8578750491142273 }, { "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": 0.8343745470046997 }, { "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": 0.8304416537284851 } ]
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/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": 0.8922324776649475 }, { "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": 0.8866049647331238 }, { "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": 0.861946165561676 }, { "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": 0.8610645532608032 }, { "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": 0.8598195314407349 } ]
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": 0.8707013130187988 }, { "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": 0.8550479412078857 }, { "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": 0.8510415554046631 }, { "filename": "src/extension.ts", "retrieved_chunk": " } else {\n abiTreeView.message = \"Select a contract and its ABI functions will appear here.\";\n }\n }\n context.subscriptions.push(\n vscode.commands.registerCommand(\"starkode.activate\", () => {\n try {\n if (!fs.existsSync(path.join(path_, \"starkode\"))) {\n fs.mkdirSync(path.join(path_, \"starkode\"));\n }", "score": 0.8486822843551636 }, { "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": 0.845029354095459 } ]
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/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": 0.8804192543029785 }, { "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": 0.8758416175842285 }, { "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": 0.8730878233909607 }, { "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": 0.8630454540252686 }, { "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": 0.8615683317184448 } ]
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/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": 0.8464206457138062 }, { "filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts", "retrieved_chunk": " ));\n }\n return leaves;\n }\n }\n private _onDidChangeTreeData: vscode.EventEmitter<Contract | undefined> =\n new vscode.EventEmitter<Contract | undefined>();\n readonly onDidChangeTreeData: vscode.Event<Contract | undefined> =\n this._onDidChangeTreeData.event;\n refresh(): void {", "score": 0.8448681235313416 }, { "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": 0.8420344591140747 }, { "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": 0.8391507863998413 }, { "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": 0.8381614685058594 } ]
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/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": 0.8420050740242004 }, { "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": 0.8197431564331055 }, { "filename": "src/Field/index.ts", "retrieved_chunk": "import {\n\taction, computed, makeObservable, observable\n} from 'mobx';\nimport FieldState from '../utils/FieldState';\nimport type { AnnotatedPrivateFieldProps, FieldParams } from './types';\nimport type Form from '../Form';\nexport default abstract class Field<ValueType> {\n\treadonly hint: string;\n\tprotected _state: FieldState<ValueType>;\n\tprotected _presentedError: string;", "score": 0.8054499626159668 }, { "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": 0.8009825944900513 }, { "filename": "src/utils/FieldState/types.ts", "retrieved_chunk": "\tdisabled?: boolean,\n\tonChange?: FieldOnChangeCallback<ValueType>\n}", "score": 0.8007068634033203 } ]
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/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": 0.8089174032211304 }, { "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": 0.8037115335464478 }, { "filename": "src/utils/FieldState/types.ts", "retrieved_chunk": "\tdisabled?: boolean,\n\tonChange?: FieldOnChangeCallback<ValueType>\n}", "score": 0.8029056787490845 }, { "filename": "src/Field/index.ts", "retrieved_chunk": "import {\n\taction, computed, makeObservable, observable\n} from 'mobx';\nimport FieldState from '../utils/FieldState';\nimport type { AnnotatedPrivateFieldProps, FieldParams } from './types';\nimport type Form from '../Form';\nexport default abstract class Field<ValueType> {\n\treadonly hint: string;\n\tprotected _state: FieldState<ValueType>;\n\tprotected _presentedError: string;", "score": 0.8027965426445007 }, { "filename": "src/Field/index.ts", "retrieved_chunk": "\t\tthis._state.attachToForm( form );\n\t}\n\tprotected hideError() {\n\t\tthis._presentedError = '';\n\t}\n\tprotected setValue( newValue: ValueType ) {\n\t\tthis._state.setValue( newValue );\n\t}\n}\nexport type { FieldParams };", "score": 0.7960090637207031 } ]
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/account.ts", "retrieved_chunk": " logger.log(\"No account exist.\");\n return;\n }\n const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {\n encoding: \"utf-8\",\n });\n const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);\n const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(\n parsedFileData,\n selectedNetwork,", "score": 0.8823911547660828 }, { "filename": "src/config/account.ts", "retrieved_chunk": " const selectedNetwork = context.workspaceState.get(\"selectedNetwork\");\n fs.readFile(path, 'utf8', (err, data) => {\n if (err) {\n console.error('Error reading file:', err);\n return;\n }\n const accounts = JSON.parse(data);\n const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress);\n if (indexToUpdate !== -1) {\n accounts[indexToUpdate].isDeployed = {", "score": 0.8739800453186035 }, { "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": 0.8733538389205933 }, { "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": 0.871688723564148 }, { "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": 0.8619214296340942 } ]
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/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": 0.8079621195793152 }, { "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": 0.7991601228713989 }, { "filename": "src/Field/index.ts", "retrieved_chunk": "import {\n\taction, computed, makeObservable, observable\n} from 'mobx';\nimport FieldState from '../utils/FieldState';\nimport type { AnnotatedPrivateFieldProps, FieldParams } from './types';\nimport type Form from '../Form';\nexport default abstract class Field<ValueType> {\n\treadonly hint: string;\n\tprotected _state: FieldState<ValueType>;\n\tprotected _presentedError: string;", "score": 0.7980931401252747 }, { "filename": "src/utils/FieldState/types.ts", "retrieved_chunk": "\tdisabled?: boolean,\n\tonChange?: FieldOnChangeCallback<ValueType>\n}", "score": 0.7914086580276489 }, { "filename": "src/Field/index.ts", "retrieved_chunk": "\t\tthis._state.attachToForm( form );\n\t}\n\tprotected hideError() {\n\t\tthis._presentedError = '';\n\t}\n\tprotected setValue( newValue: ValueType ) {\n\t\tthis._state.setValue( newValue );\n\t}\n}\nexport type { FieldParams };", "score": 0.7913414239883423 } ]
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": 0.790392279624939 }, { "filename": "src/Field/index.ts", "retrieved_chunk": "import {\n\taction, computed, makeObservable, observable\n} from 'mobx';\nimport FieldState from '../utils/FieldState';\nimport type { AnnotatedPrivateFieldProps, FieldParams } from './types';\nimport type Form from '../Form';\nexport default abstract class Field<ValueType> {\n\treadonly hint: string;\n\tprotected _state: FieldState<ValueType>;\n\tprotected _presentedError: string;", "score": 0.7859614491462708 }, { "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": 0.7740094661712646 }, { "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": 0.7736777067184448 }, { "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": 0.7697123289108276 } ]
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": 0.8825001120567322 }, { "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": 0.8599106669425964 }, { "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": 0.8381320238113403 }, { "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": 0.837988018989563 }, { "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": 0.8348531126976013 } ]
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/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": 0.9006634950637817 }, { "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": 0.8604676723480225 }, { "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": 0.8561943173408508 }, { "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": 0.8299652338027954 }, { "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": 0.8213038444519043 } ]
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/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": 0.8155041933059692 }, { "filename": "src/types/index.ts", "retrieved_chunk": " type: string;\n outputs: Array<outputType>;\n state_mutability?: string;\n}", "score": 0.8148481845855713 }, { "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": 0.7951284646987915 }, { "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": 0.7950025796890259 }, { "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": 0.7930401563644409 } ]
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": " 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": 0.8364856243133545 }, { "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": 0.820981502532959 }, { "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": 0.8170188069343567 }, { "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": 0.808199405670166 }, { "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": 0.7960227131843567 } ]
typescript
logger.log(`calling function: ${functionABI.name}`);