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/__tests__/repositories/InMemoryBattleRepository.ts",
"retrieved_chunk": " async save(entity: Battle) {\n this.battles.push(entity);\n }\n async delete(entity: Battle) {\n this.battles = this.battles.filter((battle) => battle.id !== entity.id);\n }\n async update(entity: Battle) {\n const index = this.battles.findIndex((battle) => battle.id === entity.id);\n this.battles[index] = entity;\n }",
"score": 0.8033543825149536
},
{
"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.8010023236274719
},
{
"filename": "src/app/entities/pokemon/Pokemon.ts",
"retrieved_chunk": " }\n set moves(moves: PokemonMove[]) {\n this._moves = moves;\n }\n // Equals\n equals(other: Pokemon): boolean {\n return (\n this.id === other.id &&\n this.name === other.name &&\n this.level === other.level &&",
"score": 0.794556736946106
},
{
"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.7875925302505493
},
{
"filename": "src/app/entities/pokemon/Pokemon.ts",
"retrieved_chunk": " this._trainerID = trainerID;\n }\n get stats(): BattleStats {\n return this._stats;\n }\n set stats(stats: BattleStats) {\n this._stats = stats;\n }\n get moves(): PokemonMove[] {\n return this._moves;",
"score": 0.7767410278320312
}
] | typescript | const newStats = new BattleStats({ |
import { BattleStats } from "../../value_objects/BattleStats";
import { Item } from "../item/Item";
import { League } from "../league/League";
import { Pokemon } from "../pokemon/Pokemon";
export class Trainer {
private _id: string;
private _name: string;
private _city: string;
private _age: number;
private _level: number;
private _pokemons: Pokemon[];
private _items: Item[];
private _league: League | null;
constructor(props: {
id: string;
name: string;
city: string;
age: number;
level: number;
pokemons: Pokemon[];
items: Item[];
league: League | null;
}) {
this._id = props.id;
this._name = props.name;
this._city = props.city;
this._age = props.age;
this._level = props.level;
this._pokemons = props.pokemons;
this._items = props.items;
this._league = props.league;
}
// Methods
addPokemon(pokemon: Pokemon) {
this._pokemons.push(pokemon);
}
removePokemon(pokemon: Pokemon): void {
this._pokemons = this._pokemons.filter((p) => p.equals(pokemon));
}
addItem(item: Item) {
this._items.push(item);
}
removeItem(item: Item): void {
this._items = this._items.filter((i) => i.equals(item));
}
applyItem(item: Item, pokemon: Pokemon): void {
pokemon.life += item.increaseLife;
const newStats = new BattleStats({
attack: pokemon.stats.attack + item.increaseAttack,
defense: pokemon.stats. | defense + item.increaseDefense,
speed: pokemon.stats.speed + item.increaseSpeed,
}); |
pokemon.stats = newStats;
}
// Getters and setters
get id(): string {
return this._id;
}
set id(id: string) {
this._id = id;
}
get name(): string {
return this._name;
}
set name(name: string) {
this._name = name;
}
get city(): string {
return this._city;
}
set city(city: string) {
this._city = city;
}
get age(): number {
return this._age;
}
set age(age: number) {
this._age = age;
}
get level(): number {
return this._level;
}
set level(level: number) {
this._level = level;
}
get pokemons() {
return this._pokemons;
}
set pokemons(pokemon: Pokemon[]) {
this._pokemons = pokemon;
}
get items() {
return this._items;
}
set items(items: Item[]) {
this._items = items;
}
get league() {
return this._league;
}
set league(league: League | null) {
this._league = league;
}
}
| src/app/entities/trainer/Trainer.ts | jnaraujo-poke-battle-manager-e4da436 | [
{
"filename": "src/app/entities/item/Item.ts",
"retrieved_chunk": " 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.7673293352127075
},
{
"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.7508895397186279
},
{
"filename": "src/app/use-cases/pokemon/AddPokemonUseCase.ts",
"retrieved_chunk": " life: life,\n type: type,\n stats: stats,\n moves: moves,\n });\n const trainerPokemons = await this.pokemonRepository.findByTrainerId(\n pokemon.trainerID\n );\n if (trainerPokemons.length >= 3) {\n throw new Error(\"Trainer already has 3 pokemons\");",
"score": 0.739812433719635
},
{
"filename": "src/app/entities/pokemon/Pokemon.ts",
"retrieved_chunk": " }\n set moves(moves: PokemonMove[]) {\n this._moves = moves;\n }\n // Equals\n equals(other: Pokemon): boolean {\n return (\n this.id === other.id &&\n this.name === other.name &&\n this.level === other.level &&",
"score": 0.7386289238929749
},
{
"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.7266845703125
}
] | typescript | defense + item.increaseDefense,
speed: pokemon.stats.speed + item.increaseSpeed,
}); |
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/UpdatePokemonUseCase.spec.ts",
"retrieved_chunk": " it(\"should throw an error if pokemon does not exist\", async () => {\n const pikachu = new Pokemon({\n id: \"123\",\n level: 25,\n life: 100,\n moves: [],\n name: \"Pikachu\",\n stats: new BattleStats({\n attack: 10,\n defense: 10,",
"score": 0.8444404602050781
},
{
"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.8408713340759277
},
{
"filename": "src/app/use-cases/trainer/CreateTrainerUseCase.spec.ts",
"retrieved_chunk": " it(\"should create a trainer\", async () => {\n const trainer = await createTrainerUseCase.execute({\n name: \"Ash\",\n city: \"Pallet\",\n age: 10,\n level: 1,\n pokemons: [],\n items: [],\n league: null,\n });",
"score": 0.8402778506278992
},
{
"filename": "src/app/entities/pokemon/Pokemon.ts",
"retrieved_chunk": " private _stats: BattleStats;\n private _moves: PokemonMove[];\n constructor(props: {\n id: string;\n name: string;\n level: number;\n life: number;\n type: string[];\n trainerID: string;\n stats: BattleStats;",
"score": 0.837846040725708
},
{
"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.834789514541626
}
] | 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": " return this._attack;\n }\n get defense() {\n return this._defense;\n }\n get speed() {\n return this._speed;\n }\n equals(other: BattleStats): boolean {\n return (",
"score": 0.8529665470123291
},
{
"filename": "src/app/entities/trainer/Trainer.ts",
"retrieved_chunk": " speed: pokemon.stats.speed + item.increaseSpeed,\n });\n pokemon.stats = newStats;\n }\n // Getters and setters\n get id(): string {\n return this._id;\n }\n set id(id: string) {\n this._id = id;",
"score": 0.8341371417045593
},
{
"filename": "src/app/entities/league/League.ts",
"retrieved_chunk": " this._startedAt = new Date();\n }\n finish(): void {\n this._finishedAt = new Date();\n }\n isFinished(): boolean {\n return this._finishedAt !== null;\n }\n equals(battle: League): boolean {\n return this._id === battle.id;",
"score": 0.8294075131416321
},
{
"filename": "src/app/entities/trainer/Trainer.ts",
"retrieved_chunk": " this._items.push(item);\n }\n removeItem(item: Item): void {\n this._items = this._items.filter((i) => i.equals(item));\n }\n applyItem(item: Item, pokemon: Pokemon): void {\n pokemon.life += item.increaseLife;\n const newStats = new BattleStats({\n attack: pokemon.stats.attack + item.increaseAttack,\n defense: pokemon.stats.defense + item.increaseDefense,",
"score": 0.8119175434112549
},
{
"filename": "src/app/use-cases/pokemon/AddPokemonUseCase.ts",
"retrieved_chunk": " life,\n type,\n stats,\n moves,\n }: AddPokemonRequest): Promise<Pokemon> {\n const pokemon = new Pokemon({\n id: crypto.randomUUID(),\n trainerID: trainerID,\n name: name,\n level: level,",
"score": 0.8019529581069946
}
] | typescript | .attack - target.stats.defense; |
import { BattleStats } from "../../value_objects/BattleStats";
import { Item } from "../item/Item";
import { League } from "../league/League";
import { Pokemon } from "../pokemon/Pokemon";
export class Trainer {
private _id: string;
private _name: string;
private _city: string;
private _age: number;
private _level: number;
private _pokemons: Pokemon[];
private _items: Item[];
private _league: League | null;
constructor(props: {
id: string;
name: string;
city: string;
age: number;
level: number;
pokemons: Pokemon[];
items: Item[];
league: League | null;
}) {
this._id = props.id;
this._name = props.name;
this._city = props.city;
this._age = props.age;
this._level = props.level;
this._pokemons = props.pokemons;
this._items = props.items;
this._league = props.league;
}
// Methods
addPokemon(pokemon: Pokemon) {
this._pokemons.push(pokemon);
}
removePokemon(pokemon: Pokemon): void {
| this._pokemons = this._pokemons.filter((p) => p.equals(pokemon)); |
}
addItem(item: Item) {
this._items.push(item);
}
removeItem(item: Item): void {
this._items = this._items.filter((i) => i.equals(item));
}
applyItem(item: Item, pokemon: Pokemon): void {
pokemon.life += item.increaseLife;
const newStats = new BattleStats({
attack: pokemon.stats.attack + item.increaseAttack,
defense: pokemon.stats.defense + item.increaseDefense,
speed: pokemon.stats.speed + item.increaseSpeed,
});
pokemon.stats = newStats;
}
// Getters and setters
get id(): string {
return this._id;
}
set id(id: string) {
this._id = id;
}
get name(): string {
return this._name;
}
set name(name: string) {
this._name = name;
}
get city(): string {
return this._city;
}
set city(city: string) {
this._city = city;
}
get age(): number {
return this._age;
}
set age(age: number) {
this._age = age;
}
get level(): number {
return this._level;
}
set level(level: number) {
this._level = level;
}
get pokemons() {
return this._pokemons;
}
set pokemons(pokemon: Pokemon[]) {
this._pokemons = pokemon;
}
get items() {
return this._items;
}
set items(items: Item[]) {
this._items = items;
}
get league() {
return this._league;
}
set league(league: League | null) {
this._league = league;
}
}
| src/app/entities/trainer/Trainer.ts | jnaraujo-poke-battle-manager-e4da436 | [
{
"filename": "src/app/__tests__/repositories/InMemoryPokemonRepository.ts",
"retrieved_chunk": " async findById(id: string): Promise<Pokemon | null> {\n return this.pokemons.find((pokemon) => pokemon.id === id) || null;\n }\n async save(entity: Pokemon): Promise<void> {\n this.pokemons.push(entity);\n }\n async delete(entity: Pokemon): Promise<void> {\n this.pokemons = this.pokemons.filter((pokemon) => pokemon.id !== entity.id);\n }\n async update(entity: Pokemon): Promise<void> {",
"score": 0.8425744771957397
},
{
"filename": "src/app/__tests__/repositories/InMemoryPokemonRepository.ts",
"retrieved_chunk": "import { Pokemon } from \"../../entities/pokemon/Pokemon\";\nimport { PokemonRepository } from \"../../repositories/PokemonRepository\";\nexport class InMemoryPokemonRepository implements PokemonRepository {\n private pokemons: Pokemon[] = [];\n async findByTrainerId(trainerId: string): Promise<Pokemon[]> {\n return this.pokemons.filter((pokemon) => pokemon.trainerID === trainerId);\n }\n async findAll(): Promise<Pokemon[]> {\n return this.pokemons;\n }",
"score": 0.8254621624946594
},
{
"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.8146116733551025
},
{
"filename": "src/app/use-cases/pokemon/UpdatePokemonUseCase.ts",
"retrieved_chunk": "import { Pokemon } from \"../../entities/pokemon/Pokemon\";\nimport { PokemonRepository } from \"../../repositories/PokemonRepository\";\ninterface UpdatePokemonRequest {\n pokemon: Pokemon;\n}\nexport class UpdatePokemonUseCase {\n constructor(private pokemonRepository: PokemonRepository) {}\n async execute({ pokemon }: UpdatePokemonRequest) {\n const doesPokemonExist = await this.pokemonRepository.findById(pokemon.id);\n if (!doesPokemonExist) {",
"score": 0.8000917434692383
},
{
"filename": "src/app/use-cases/pokemon/UpdatePokemonUseCase.spec.ts",
"retrieved_chunk": " (await inMemoryPokemonRepository.findById(pikachu.id))?.level\n ).toEqual(25);\n pikachu.level = 26;\n await updatePokemonUseCase.execute({\n pokemon: pikachu,\n });\n expect(\n (await inMemoryPokemonRepository.findById(pikachu.id))?.level\n ).toEqual(26);\n });",
"score": 0.7541055679321289
}
] | typescript | this._pokemons = this._pokemons.filter((p) => p.equals(pokemon)); |
import { BattleStats } from "../../value_objects/BattleStats";
import { Item } from "../item/Item";
import { League } from "../league/League";
import { Pokemon } from "../pokemon/Pokemon";
export class Trainer {
private _id: string;
private _name: string;
private _city: string;
private _age: number;
private _level: number;
private _pokemons: Pokemon[];
private _items: Item[];
private _league: League | null;
constructor(props: {
id: string;
name: string;
city: string;
age: number;
level: number;
pokemons: Pokemon[];
items: Item[];
league: League | null;
}) {
this._id = props.id;
this._name = props.name;
this._city = props.city;
this._age = props.age;
this._level = props.level;
this._pokemons = props.pokemons;
this._items = props.items;
this._league = props.league;
}
// Methods
addPokemon(pokemon: Pokemon) {
this._pokemons.push(pokemon);
}
removePokemon(pokemon: Pokemon): void {
this._pokemons = this._pokemons.filter((p) => p.equals(pokemon));
}
addItem(item: Item) {
this._items.push(item);
}
removeItem(item: Item): void {
this._items = this._items.filter((i) => i.equals(item));
}
applyItem(item: Item, pokemon: Pokemon): void {
pokemon.life += item.increaseLife;
const newStats = new BattleStats({
attack: pokemon.stats.attack + item.increaseAttack,
defense: pokemon.stats.defense + item.increaseDefense,
speed: pokemon.stats | .speed + item.increaseSpeed,
}); |
pokemon.stats = newStats;
}
// Getters and setters
get id(): string {
return this._id;
}
set id(id: string) {
this._id = id;
}
get name(): string {
return this._name;
}
set name(name: string) {
this._name = name;
}
get city(): string {
return this._city;
}
set city(city: string) {
this._city = city;
}
get age(): number {
return this._age;
}
set age(age: number) {
this._age = age;
}
get level(): number {
return this._level;
}
set level(level: number) {
this._level = level;
}
get pokemons() {
return this._pokemons;
}
set pokemons(pokemon: Pokemon[]) {
this._pokemons = pokemon;
}
get items() {
return this._items;
}
set items(items: Item[]) {
this._items = items;
}
get league() {
return this._league;
}
set league(league: League | null) {
this._league = league;
}
}
| src/app/entities/trainer/Trainer.ts | jnaraujo-poke-battle-manager-e4da436 | [
{
"filename": "src/app/entities/item/Item.ts",
"retrieved_chunk": " 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.7708420753479004
},
{
"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.7571191787719727
},
{
"filename": "src/app/use-cases/pokemon/AddPokemonUseCase.ts",
"retrieved_chunk": " life: life,\n type: type,\n stats: stats,\n moves: moves,\n });\n const trainerPokemons = await this.pokemonRepository.findByTrainerId(\n pokemon.trainerID\n );\n if (trainerPokemons.length >= 3) {\n throw new Error(\"Trainer already has 3 pokemons\");",
"score": 0.7472182512283325
},
{
"filename": "src/app/entities/pokemon/Pokemon.ts",
"retrieved_chunk": " }\n set moves(moves: PokemonMove[]) {\n this._moves = moves;\n }\n // Equals\n equals(other: Pokemon): boolean {\n return (\n this.id === other.id &&\n this.name === other.name &&\n this.level === other.level &&",
"score": 0.7436254024505615
},
{
"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.7319931983947754
}
] | 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": " 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.8226995468139648
},
{
"filename": "src/app/__tests__/repositories/InMemoryPokemonRepository.ts",
"retrieved_chunk": "import { Pokemon } from \"../../entities/pokemon/Pokemon\";\nimport { PokemonRepository } from \"../../repositories/PokemonRepository\";\nexport class InMemoryPokemonRepository implements PokemonRepository {\n private pokemons: Pokemon[] = [];\n async findByTrainerId(trainerId: string): Promise<Pokemon[]> {\n return this.pokemons.filter((pokemon) => pokemon.trainerID === trainerId);\n }\n async findAll(): Promise<Pokemon[]> {\n return this.pokemons;\n }",
"score": 0.7819118499755859
},
{
"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.7809139490127563
},
{
"filename": "src/app/entities/pokemon/Pokemon.ts",
"retrieved_chunk": " }\n set moves(moves: PokemonMove[]) {\n this._moves = moves;\n }\n // Equals\n equals(other: Pokemon): boolean {\n return (\n this.id === other.id &&\n this.name === other.name &&\n this.level === other.level &&",
"score": 0.776125967502594
},
{
"filename": "src/app/__tests__/repositories/InMemoryBattleRepository.ts",
"retrieved_chunk": " async save(entity: Battle) {\n this.battles.push(entity);\n }\n async delete(entity: Battle) {\n this.battles = this.battles.filter((battle) => battle.id !== entity.id);\n }\n async update(entity: Battle) {\n const index = this.battles.findIndex((battle) => battle.id === entity.id);\n this.battles[index] = entity;\n }",
"score": 0.7509207129478455
}
] | 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/PassphraseInput.tsx",
"retrieved_chunk": " />\n </Box>\n ) : (\n <>\n {data != null ? (\n <PassphraseForm setEncryptionKey={setEncryptionKey} />\n ) : (\n <SetPassphrase />\n )}\n </>",
"score": 0.8623446822166443
},
{
"filename": "src/components/UserCard.tsx",
"retrieved_chunk": " onClose();\n };\n return (\n <Modal isOpen={isOpen} onClose={onClose}>\n <ModalOverlay />\n <ModalContent backgroundColor=\"blue.500\">\n <ModalHeader>Info</ModalHeader>\n <ModalBody>\n Backup your encryption key securely. Anyone with access to your key is able to\n decrypt your files.",
"score": 0.822268009185791
},
{
"filename": "src/components/FileTable.tsx",
"retrieved_chunk": " <ArrowUpIcon boxSize=\"1rem\" />\n ) : (\n <ArrowDownIcon boxSize=\"1rem\" />\n )\n }\n />\n </HStack>\n </Th>\n );\n const handleSorting = useCallback(",
"score": 0.8202805519104004
},
{
"filename": "src/components/Pagination.tsx",
"retrieved_chunk": " </Button>\n )}\n {selected + 1 < range && (\n <Button size=\"xs\" onClick={onNext} variant=\"ghost\">\n {selected + 1}\n </Button>\n )}\n {selected <= range - 3 && <Text>...</Text>}\n {range !== 1 && (\n <Button",
"score": 0.8120568990707397
},
{
"filename": "src/components/DeleteButton.tsx",
"retrieved_chunk": " duration: 3000,\n position: 'bottom-right',\n isClosable: true,\n title: 'File deleted',\n description: file?.name,\n });\n };\n return (\n <>\n <IconButton",
"score": 0.7892658114433289
}
] | typescript | <ShieldLockIcon boxSize="1.5rem" />
) : (
<DownloadIcon boxSize="1.5rem" />
)
} |
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/PassphraseInput.tsx",
"retrieved_chunk": " />\n </Box>\n ) : (\n <>\n {data != null ? (\n <PassphraseForm setEncryptionKey={setEncryptionKey} />\n ) : (\n <SetPassphrase />\n )}\n </>",
"score": 0.8650115132331848
},
{
"filename": "src/components/FileTable.tsx",
"retrieved_chunk": " <ArrowUpIcon boxSize=\"1rem\" />\n ) : (\n <ArrowDownIcon boxSize=\"1rem\" />\n )\n }\n />\n </HStack>\n </Th>\n );\n const handleSorting = useCallback(",
"score": 0.8497424125671387
},
{
"filename": "src/components/Pagination.tsx",
"retrieved_chunk": " </Button>\n )}\n {selected + 1 < range && (\n <Button size=\"xs\" onClick={onNext} variant=\"ghost\">\n {selected + 1}\n </Button>\n )}\n {selected <= range - 3 && <Text>...</Text>}\n {range !== 1 && (\n <Button",
"score": 0.813535213470459
},
{
"filename": "src/components/UserCard.tsx",
"retrieved_chunk": " onClose();\n };\n return (\n <Modal isOpen={isOpen} onClose={onClose}>\n <ModalOverlay />\n <ModalContent backgroundColor=\"blue.500\">\n <ModalHeader>Info</ModalHeader>\n <ModalBody>\n Backup your encryption key securely. Anyone with access to your key is able to\n decrypt your files.",
"score": 0.8108986616134644
},
{
"filename": "src/components/Pagination.tsx",
"retrieved_chunk": " onClick={() => setSelected(range)}\n size=\"xs\"\n variant=\"ghost\"\n color={selected === range ? 'red.600' : ''}\n >\n {range}\n </Button>\n )}\n <IconButton\n aria-label=\"next\"",
"score": 0.7820230722427368
}
] | 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.8489097356796265
},
{
"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.8329662084579468
},
{
"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.8252421617507935
},
{
"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.8197788000106812
},
{
"filename": "src/components/UserCard.tsx",
"retrieved_chunk": "import LogoutButton from './LogoutButton';\ninterface PropsModal {\n onDownload: () => void;\n onClose: () => void;\n isOpen: boolean;\n}\nconst InfoModal: FC<PropsModal> = (props: PropsModal) => {\n const { onDownload, onClose, isOpen } = props;\n const handleDownload = () => {\n onDownload();",
"score": 0.8168848752975464
}
] | typescript | render: () => <UploadFeedback files={files} steps={steps} progress={progress} />,
}); |
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.8525636792182922
},
{
"filename": "src/components/PassphraseInput.tsx",
"retrieved_chunk": " <FormErrorMessage>Passphrases are different.</FormErrorMessage>\n )}\n </FormControl>\n <Button\n leftIcon={<SecretIcon />}\n size=\"md\"\n width=\"100%\"\n variant=\"solid\"\n isDisabled={!isValid}\n isLoading={loading}",
"score": 0.8430894613265991
},
{
"filename": "src/components/Pagination.tsx",
"retrieved_chunk": " alignItems=\"center\"\n marginTop=\"1rem\"\n color=\"gray.700\"\n >\n <HStack padding=\"0\" margin=\"0\" spacing=\"0.1rem\">\n <IconButton\n aria-label=\"previous\"\n icon={<ChevronLeftIcon boxSize=\"1.3rem\" />}\n onClick={onPrevious}\n size=\"xs\"",
"score": 0.8358997702598572
},
{
"filename": "src/components/Pagination.tsx",
"retrieved_chunk": " variant=\"ghost\"\n disabled={selected === 1}\n />\n <Button\n onClick={() => setSelected(1)}\n size=\"xs\"\n variant=\"ghost\"\n color={selected === 1 ? 'red.600' : ''}\n >\n 1",
"score": 0.8220911026000977
},
{
"filename": "src/components/FileTable.tsx",
"retrieved_chunk": " setOrder: Dispatch<SetStateAction<SortOrder>>;\n }) => (\n <Th padding={0} textTransform=\"capitalize\">\n <HStack spacing={1} marginBottom=\"0.6rem\">\n <Text fontSize=\"md\" color=\"black\">\n {title}\n </Text>\n <IconButton\n color=\"black\"\n variant=\"none\"",
"score": 0.8207246661186218
}
] | typescript | icon={<TrashIcon />} |
import { FC, useContext, useRef } from 'react';
import { AppContext } from '@app/context';
import { useUserInfo } from '@app/hooks';
import { saveFile } from '@app/lib/files';
import {
Button,
HStack,
Modal,
ModalBody,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
Tag,
Text,
useDisclosure,
VStack,
} from '@chakra-ui/react';
import Card from './Card';
import { SecretIcon } from './Icons';
import LogoutButton from './LogoutButton';
interface PropsModal {
onDownload: () => void;
onClose: () => void;
isOpen: boolean;
}
const InfoModal: FC<PropsModal> = (props: PropsModal) => {
const { onDownload, onClose, isOpen } = props;
const handleDownload = () => {
onDownload();
onClose();
};
return (
<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent backgroundColor="blue.500">
<ModalHeader>Info</ModalHeader>
<ModalBody>
Backup your encryption key securely. Anyone with access to your key is able to
decrypt your files.
<br />
<br />
<Tag colorScheme="blue">Do not store your key on Google Drive !</Tag>
</ModalBody>
<ModalFooter>
<Button onClick={handleDownload} colorScheme="blue">
Download my key
</Button>
</ModalFooter>
</ModalContent>
</Modal>
);
};
const UserCard: FC = () => {
const { onOpen, onClose, isOpen } = useDisclosure();
const { data: user } = useUserInfo();
const { encryptionKey } = useContext(AppContext);
const ref = useRef<HTMLAnchorElement>(null);
const onDownload = () => {
saveFile([encryptionKey.value], `${user?.email}_key.txt`, 'text/plain', ref);
};
return (
<Card backgroundColor="teal.200">
<VStack spacing="1.5rem" align="flex-end" justifyContent="flex-end" height="100%">
<Text fontSize="md" fontWeight="semibold">
[{user?.email}]
</Text>
<HStack justifyContent="space-between" w="100%">
<Button
colorScheme="black"
size="md"
| leftIcon={<SecretIcon boxSize="1.5rem" />} |
variant="link"
onClick={onOpen}
>
key
</Button>
<InfoModal onDownload={onDownload} onClose={onClose} isOpen={isOpen} />
<a hidden ref={ref} />
<LogoutButton />
</HStack>
</VStack>
</Card>
);
};
export default UserCard;
| src/components/UserCard.tsx | 9OP-Encryptly-ef8661c | [
{
"filename": "src/components/Pagination.tsx",
"retrieved_chunk": " alignItems=\"center\"\n marginTop=\"1rem\"\n color=\"gray.700\"\n >\n <HStack padding=\"0\" margin=\"0\" spacing=\"0.1rem\">\n <IconButton\n aria-label=\"previous\"\n icon={<ChevronLeftIcon boxSize=\"1.3rem\" />}\n onClick={onPrevious}\n size=\"xs\"",
"score": 0.8951830863952637
},
{
"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.886604905128479
},
{
"filename": "src/components/SearchBar.tsx",
"retrieved_chunk": " <HStack w=\"100%\" marginBottom=\"1rem\">\n <Tag size=\"md\" colorScheme=\"purple\" fontWeight=\"semibold\">\n Files: {filesCount}\n </Tag>\n <Tag size=\"md\" colorScheme=\"blue\" fontWeight=\"semibold\">\n Content: {formatBytes(storageCount)}\n </Tag>\n </HStack>\n <InputGroup width=\"18rem\" size=\"sm\" w=\"100%\">\n <InputLeftElement pointerEvents=\"none\" paddingLeft=\".4rem\">",
"score": 0.8859988451004028
},
{
"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.8789381980895996
},
{
"filename": "src/components/FileTable.tsx",
"retrieved_chunk": " setOrder: Dispatch<SetStateAction<SortOrder>>;\n }) => (\n <Th padding={0} textTransform=\"capitalize\">\n <HStack spacing={1} marginBottom=\"0.6rem\">\n <Text fontSize=\"md\" color=\"black\">\n {title}\n </Text>\n <IconButton\n color=\"black\"\n variant=\"none\"",
"score": 0.8722559213638306
}
] | 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/pages/login.tsx",
"retrieved_chunk": " </Stack>\n {error && (\n <Alert minWidth=\"100%\" status=\"error\" variant=\"subtle\">\n <AlertIcon />\n <Flex direction=\"column\">\n <AlertTitle>Connection failed</AlertTitle>\n <AlertDescription>{error}</AlertDescription>\n </Flex>\n </Alert>\n )}",
"score": 0.8134863972663879
},
{
"filename": "src/pages/login.tsx",
"retrieved_chunk": " Show me the code\n </Button>\n </Link>\n <HStack spacing=\"1rem\">\n <Link href=\"/terms\">\n <Button variant=\"link\" size=\"sm\">\n Terms\n </Button>\n </Link>\n <Link href=\"/privacy\">",
"score": 0.8078775405883789
},
{
"filename": "src/components/DeleteButton.tsx",
"retrieved_chunk": " <ModalHeader>Delete</ModalHeader>\n <ModalBody>\n Are your sure to delete <Tag colorScheme=\"red\">{file.name}</Tag> ?\n </ModalBody>\n <ModalFooter>\n <Button autoFocus mr={3} onClick={onClose} color=\"black\" isDisabled={deleting}>\n Cancel\n </Button>\n <Button onClick={handleDelete} isDisabled={deleting} colorScheme=\"red\">\n {deleting ? <Spinner /> : 'Delete'}",
"score": 0.8077285289764404
},
{
"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.7957168817520142
},
{
"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.7940433025360107
}
] | 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/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.8285115957260132
},
{
"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.8242723941802979
},
{
"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.7935796976089478
},
{
"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.7751268148422241
},
{
"filename": "src/compiler/nodes/array.ts",
"retrieved_chunk": " defineFieldExistenceValidations({\n allowNull: this.#node.allowNull,\n isOptional: this.#node.isOptional,\n variableName: this.field.variableName,\n })\n )\n /**\n * Wrapping initialization of output + array elements\n * validation inside `if array field is valid` block.\n *",
"score": 0.7746051549911499
}
] | 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.9198815822601318
},
{
"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.9114458560943604
},
{
"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.8909399509429932
},
{
"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.8748123645782471
},
{
"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.8714547753334045
}
] | typescript | })}${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/types.ts",
"retrieved_chunk": "/**\n * The root of the schema\n */\nexport type RootNode = {\n type: 'root'\n /**\n * Schema at the root level\n */\n schema: CompilerNodes\n}",
"score": 0.8948273062705994
},
{
"filename": "src/types.ts",
"retrieved_chunk": " field: FieldContext,\n args?: Record<string, any>\n ): string\n}\n/**\n * Options accepted by the compiler\n */\nexport type CompilerOptions = {\n /**\n * Convert empty string values to null for sake of",
"score": 0.8924936652183533
},
{
"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.8877317905426025
},
{
"filename": "src/types.ts",
"retrieved_chunk": " /**\n * The expression for the output value.\n */\n outputExpression: string\n}\n/**\n * Compiler field is used to compute the variable and property\n * names for the JS output.\n */\nexport type CompilerField = {",
"score": 0.8875436782836914
},
{
"filename": "src/scripts/field/value_output.ts",
"retrieved_chunk": " * Options accepts by the output script\n */\ntype OutputOptions = {\n outputExpression: string\n variableName: string\n transformFnRefId?: RefIdentifier\n}\n/**\n * Returns JS fragment for writing the validated value to the output.\n */",
"score": 0.8845146298408508
}
] | 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 { 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.8538283705711365
},
{
"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.8343420624732971
},
{
"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.8308053612709045
},
{
"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.8219019770622253
},
{
"filename": "src/compiler/main.ts",
"retrieved_chunk": " parent: CompilerParent,\n parentField?: CompilerField\n ) {\n switch (node.type) {\n case 'literal':\n return new LiteralNodeCompiler(node, buffer, this, parent, parentField).compile()\n case 'array':\n return new ArrayNodeCompiler(node, buffer, this, parent, parentField).compile()\n case 'record':\n return new RecordNodeCompiler(node, buffer, this, parent, parentField).compile()",
"score": 0.8131738901138306
}
] | typescript | .conditions.forEach((condition, index) => { |
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/PassphraseInput.tsx",
"retrieved_chunk": " />\n </Box>\n ) : (\n <>\n {data != null ? (\n <PassphraseForm setEncryptionKey={setEncryptionKey} />\n ) : (\n <SetPassphrase />\n )}\n </>",
"score": 0.8623446822166443
},
{
"filename": "src/components/UserCard.tsx",
"retrieved_chunk": " onClose();\n };\n return (\n <Modal isOpen={isOpen} onClose={onClose}>\n <ModalOverlay />\n <ModalContent backgroundColor=\"blue.500\">\n <ModalHeader>Info</ModalHeader>\n <ModalBody>\n Backup your encryption key securely. Anyone with access to your key is able to\n decrypt your files.",
"score": 0.822268009185791
},
{
"filename": "src/components/FileTable.tsx",
"retrieved_chunk": " <ArrowUpIcon boxSize=\"1rem\" />\n ) : (\n <ArrowDownIcon boxSize=\"1rem\" />\n )\n }\n />\n </HStack>\n </Th>\n );\n const handleSorting = useCallback(",
"score": 0.8202805519104004
},
{
"filename": "src/components/Pagination.tsx",
"retrieved_chunk": " </Button>\n )}\n {selected + 1 < range && (\n <Button size=\"xs\" onClick={onNext} variant=\"ghost\">\n {selected + 1}\n </Button>\n )}\n {selected <= range - 3 && <Text>...</Text>}\n {range !== 1 && (\n <Button",
"score": 0.8120568990707397
},
{
"filename": "src/components/DeleteButton.tsx",
"retrieved_chunk": " duration: 3000,\n position: 'bottom-right',\n isClosable: true,\n title: 'File deleted',\n description: file?.name,\n });\n };\n return (\n <>\n <IconButton",
"score": 0.7892658114433289
}
] | typescript | <DownloadIcon boxSize="1.5rem" />
)
} |
import { AppData, FileMetadata, StorageQuota, UserInfo } from '../models';
const JSONtoUserInfo = (json: any): UserInfo => {
const userInfo: UserInfo = {
email: json['emailAddress'],
};
return userInfo;
};
const JSONtoFileMetadata = (json: any): FileMetadata => {
const fileMetadata: FileMetadata = {
id: json['id'],
name: json['name'],
size: parseInt(json['size'] || 0),
createdTime: new Date(json['createdTime']),
mimeType: json['mimeType'],
};
return fileMetadata;
};
const JSONtoFilesMetadata = (json: any): FileMetadata[] => {
return json
.map((file: any): FileMetadata | undefined => {
if (file['trashed'] === true) {
return;
}
return JSONtoFileMetadata(file);
})
.filter((e: any) => e != null)
.sort((a: FileMetadata, b: FileMetadata) =>
a.createdTime && b.createdTime ? a.createdTime > b.createdTime : 0,
);
};
const JSONtoAppData = (json: any) | : AppData => { |
const appData: AppData = {
encryptionKey: {
enc: json['encryptionKey']['enc'],
salt: json['encryptionKey']['salt'],
},
};
return appData;
};
const JSONtoStorageQuota = (json: any): StorageQuota => {
const storageQuota: StorageQuota = {
limit: parseInt(json['limit']),
usage: parseInt(json['usage']),
usageInDrive: parseInt(json['usageInDrive']),
};
return storageQuota;
};
export const getUserInfo = async (token: string): Promise<UserInfo> => {
const res = await fetch('https://www.googleapis.com/drive/v3/about?fields=user', {
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
});
const json = await res.json();
if (!res.ok) {
const error = new Error('Failed fetching user.');
error.info = json;
error.status = res.status;
throw error;
}
return JSONtoUserInfo(json['user']);
};
export const revokeToken = async (token: string): Promise<void> => {
fetch(`https://oauth2.googleapis.com/revoke?token=${token}type=accesstoken`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
};
export const revokeApp = async (token: string): Promise<void> => {
fetch(`https://oauth2.googleapis.com/revoke`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
});
};
const CONFIG_FILE_NAME = 'config.json';
const APP_DATA_FOLDER = 'appDataFolder';
const createConfigFile = async (token: string): Promise<string> => {
const res = await fetch('https://www.googleapis.com/drive/v3/files?fields=id', {
method: 'POST',
body: JSON.stringify({
mimeType: 'application/json',
parents: [APP_DATA_FOLDER],
name: CONFIG_FILE_NAME,
}),
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
const json = await res.json();
return json['id'];
};
const uploadConfigFile = async (
token: string,
configFileId: string,
data: AppData,
): Promise<void> => {
const bytes = new TextEncoder().encode(JSON.stringify(data));
const file = new File([bytes], 'config.json', { type: 'application/json' });
await fetch(
`https://www.googleapis.com/upload/drive/v3/files/${configFileId}?uploadType=media`,
{
method: 'PATCH',
body: file,
headers: { Authorization: `Bearer ${token}` },
},
);
};
export const saveAppData = async (token: string, data: AppData): Promise<void> => {
const configFileId = await createConfigFile(token);
await uploadConfigFile(token, configFileId, data);
};
const getAppFiles = async (token: string) => {
const res = await fetch(
'https://www.googleapis.com/drive/v3/files?spaces=appDataFolder&fields=files(*)',
{
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
},
);
const json = await res.json();
return JSONtoFilesMetadata(json['files']);
};
const loadConfigFile = async (token: string, configFileId: string): Promise<AppData> => {
const res = await fetch(
`https://www.googleapis.com/drive/v3/files/${configFileId}?spaces=appDataFolder&alt=media`,
{
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
},
);
const json = await res.json();
return JSONtoAppData(json);
};
export const loadAppData = async (token: string): Promise<AppData | undefined> => {
const files = await getAppFiles(token);
const configFile = files.find((f) => f.name == CONFIG_FILE_NAME);
if (!configFile) {
// throw new Error(`Config file <${CONFIG_FILE_NAME}> not found`);
return;
}
return await loadConfigFile(token, configFile.id);
};
// only for debug
export const deleteAppFolder = async (token: string): Promise<void> => {
const files = await getAppFiles(token);
const promises = files.map(({ id: fileId }) => {
return fetch(`https://www.googleapis.com/drive/v3/files/${fileId}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` },
});
});
await Promise.all(promises);
};
export const getStorageQuota = async (token: string): Promise<StorageQuota> => {
const res = await fetch(
'https://www.googleapis.com/drive/v3/about?fields=storageQuota',
{
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
},
);
const json = await res.json();
return JSONtoStorageQuota(json['storageQuota']);
};
export const getUserFiles = async (token: string): Promise<FileMetadata[]> => {
const res = await fetch('https://www.googleapis.com/drive/v3/files?fields=*', {
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
});
const json = await res.json();
return JSONtoFilesMetadata(json['files']);
};
const uploadFileMetadata = async (token: string, name: string): Promise<string> => {
// https://developers.google.com/drive/api/guides/manage-uploads#http_2
const res = await fetch(
'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable',
{
method: 'POST',
body: JSON.stringify({
name: name,
originalFilename: name,
mimeType: 'application/octet-stream', // "text/plain"
description: 'From encryptly',
}),
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json; charset=UTF-8',
'X-Upload-Content-Type': 'application/octet-stream',
},
},
);
const location = res.headers.get('location');
if (!res.ok || !location) {
const error = new Error('Failed upload session resume.');
error.info = await res.json();
error.status = res.status;
throw error;
}
return location;
};
interface Chunk {
data: Blob;
ratio: number;
contentLength: string;
contentRange: string;
}
const generateChunks = (data: Blob): Chunk[] => {
/**
* Create chunks in multiples of 256 KB (256 x 1024 bytes) in size,
* except for the final chunk that completes the upload.
* Keep the chunk size as large as possible so that the upload is efficient.
*
* Add headers:
* - Content-Length. Set to the number of bytes in the current chunk.
* - Content-Range. Set to show which bytes in the file you upload.
* For example, Content-Range: bytes 0-524287/2000000 shows that you
* upload the first 524,288 bytes (256 x 1024 x 2) in a 2,000,000 byte file.
*/
const chunkSize = 256 * 1024 * 16;
const dataSize = data.size;
const chunks: Chunk[] = [];
let chunkCount = 0;
for (; (chunkCount + 1) * chunkSize < dataSize; chunkCount += 1) {
const start = chunkSize * chunkCount;
const end = chunkSize * (chunkCount + 1);
const chunk: Chunk = {
data: data.slice(start, end),
ratio: (end / dataSize) * 100,
contentLength: (end - start).toString(),
contentRange: `bytes ${start}-${end - 1}/${dataSize}`,
};
chunks.push(chunk);
}
const start = chunkSize * chunkCount;
const end = dataSize;
const lastChunk: Chunk = {
data: data.slice(start, end),
ratio: 100,
contentLength: (end - start).toString(),
contentRange: `bytes ${start}-${end - 1}/${dataSize}`,
};
chunks.push(lastChunk);
return chunks;
};
async function* uploadFileMedia(
token: string,
file: Blob,
session: string,
): AsyncGenerator<number, string, void> {
// https://developers.google.com/drive/api/guides/manage-uploads#http---multiple-requests
const chunks = generateChunks(file);
for (const { data, ratio, contentLength, contentRange } of chunks) {
await fetch(session, {
method: 'PUT',
body: data,
headers: {
Authorization: `Bearer ${token}`,
'Content-Length': contentLength,
'Content-Range': contentRange,
},
});
yield ratio;
}
return 'ok';
}
export const uploadFile = async (
token: string,
name: string,
data: Blob,
): Promise<AsyncGenerator<number, string, void>> => {
const uploadSession = await uploadFileMetadata(token, name);
return uploadFileMedia(token, data, uploadSession);
};
const downloadFileMedia = async (token: string, fileId: string): Promise<Blob> => {
const res = await fetch(
`https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`,
{
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
},
);
const data = await res.blob();
return data;
};
const downloadFileMetadata = async (
token: string,
fileId: string,
): Promise<FileMetadata> => {
const res = await fetch(
`https://www.googleapis.com/drive/v3/files/${fileId}?fields=*`,
{
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
},
);
const json = await res.json();
const metadata = JSONtoFileMetadata(json);
return metadata;
};
export const downloadFile = async (
token: string,
fileId: string,
): Promise<{
metadata: FileMetadata;
data: Blob;
}> => {
const data = await downloadFileMedia(token, fileId);
const metadata = await downloadFileMetadata(token, fileId);
return { metadata, data };
};
export const deleteFile = async (token: string, fileId: string): Promise<void> => {
await fetch(`https://www.googleapis.com/drive/v2/files/${fileId}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` },
});
};
| src/hooks/http.ts | 9OP-Encryptly-ef8661c | [
{
"filename": "src/components/FileTable.tsx",
"retrieved_chunk": " (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.7976022958755493
},
{
"filename": "src/lib/files.ts",
"retrieved_chunk": " break;\n }\n }\n return files;\n};\nconst getFile = async (fileEntry: FileSystemFileEntry): Promise<File> => {\n return new Promise((resolve, reject) => fileEntry.file(resolve, reject));\n};\nconst traverseFileTree = async (\n item: FileSystemFileEntry | FileSystemDirectoryEntry | FileSystemEntry,",
"score": 0.76140296459198
},
{
"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.7501552104949951
},
{
"filename": "src/lib/files.ts",
"retrieved_chunk": " }\n};\nconst readEntries = (reader: FileSystemDirectoryReader): Promise<FileSystemEntry[]> => {\n return new Promise((resolve, _) => {\n reader.readEntries((entries) => {\n resolve(entries);\n });\n });\n};\n/**",
"score": 0.7395404577255249
},
{
"filename": "src/lib/files.ts",
"retrieved_chunk": " path: string,\n acc: File[],\n) => {\n path = path || '';\n switch (true) {\n case item.isFile: {\n const file = await getFile(item as FileSystemFileEntry);\n acc.push(new File([file], path + file.name, { type: file.type }));\n return;\n }",
"score": 0.7394668459892273
}
] | 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/Pagination.tsx",
"retrieved_chunk": " alignItems=\"center\"\n marginTop=\"1rem\"\n color=\"gray.700\"\n >\n <HStack padding=\"0\" margin=\"0\" spacing=\"0.1rem\">\n <IconButton\n aria-label=\"previous\"\n icon={<ChevronLeftIcon boxSize=\"1.3rem\" />}\n onClick={onPrevious}\n size=\"xs\"",
"score": 0.8515761494636536
},
{
"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.8446683883666992
},
{
"filename": "src/components/PassphraseInput.tsx",
"retrieved_chunk": " <FormErrorMessage>Passphrases are different.</FormErrorMessage>\n )}\n </FormControl>\n <Button\n leftIcon={<SecretIcon />}\n size=\"md\"\n width=\"100%\"\n variant=\"solid\"\n isDisabled={!isValid}\n isLoading={loading}",
"score": 0.8444814085960388
},
{
"filename": "src/components/FileTable.tsx",
"retrieved_chunk": " setOrder: Dispatch<SetStateAction<SortOrder>>;\n }) => (\n <Th padding={0} textTransform=\"capitalize\">\n <HStack spacing={1} marginBottom=\"0.6rem\">\n <Text fontSize=\"md\" color=\"black\">\n {title}\n </Text>\n <IconButton\n color=\"black\"\n variant=\"none\"",
"score": 0.8232002258300781
},
{
"filename": "src/components/PassphraseInput.tsx",
"retrieved_chunk": " onChange={(e) => setPassphrase(e.target.value.trim())}\n />\n </FormControl>\n <Button\n leftIcon={<ShieldLockIcon />}\n size=\"lg\"\n width=\"100%\"\n onClick={handleClick}\n isDisabled={!passphrase}\n colorScheme=\"yellow\"",
"score": 0.8207924962043762
}
] | 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 { 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/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.9127155542373657
},
{
"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.9116418361663818
},
{
"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.8974390029907227
},
{
"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.8543862104415894
},
{
"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.8518638610839844
}
] | 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.9347255229949951
},
{
"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.9169492721557617
},
{
"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.894540011882782
},
{
"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.8892579078674316
},
{
"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.8892307281494141
}
] | 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/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.8230514526367188
},
{
"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.8033279180526733
},
{
"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.7944827675819397
},
{
"filename": "src/compiler/nodes/record.ts",
"retrieved_chunk": " })\n buffer.writeStatement(\n defineRecordLoop({\n variableName: this.field.variableName,\n loopCodeSnippet: recordElementsBuffer.toString(),\n })\n )\n recordElementsBuffer.flush()\n return buffer.toString()\n }",
"score": 0.7862992882728577
},
{
"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.7721040844917297
}
] | 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/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.7953730821609497
},
{
"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.7885476350784302
},
{
"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.7565145492553711
},
{
"filename": "src/scripts/object/move_unknown_properties.ts",
"retrieved_chunk": " */\nexport function defineMoveProperties({\n variableName,\n fieldsToIgnore,\n allowUnknownProperties,\n}: MovePropertiesOptions) {\n if (!allowUnknownProperties) {\n return ''\n }\n return `moveProperties(${variableName}.value, ${variableName}_out, ${inspect(fieldsToIgnore)});`",
"score": 0.7564899921417236
},
{
"filename": "src/scripts/union/parse.ts",
"retrieved_chunk": " variableName: string\n parseFnRefId?: RefIdentifier\n}\n/**\n * Returns JS fragment to call the parse function on the union conditional\n * schema.\n */\nexport function callParseFunction({ parseFnRefId, variableName }: FieldOptions) {\n if (parseFnRefId) {\n return `${variableName}.value = refs['${parseFnRefId}'](${variableName}.value);`",
"score": 0.7499912977218628
}
] | 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.7731183767318726
},
{
"filename": "src/types.ts",
"retrieved_chunk": "/**\n * Known tree nodes accepted by the compiler\n */\nexport type CompilerNodes =\n | LiteralNode\n | ObjectNode\n | ArrayNode\n | UnionNode\n | RecordNode\n | TupleNode",
"score": 0.7527858018875122
},
{
"filename": "src/types.ts",
"retrieved_chunk": "/**\n * Properties of a parent node as the compiler loops through the\n * rules tree and constructs JS code.\n */\nexport type CompilerParent = {\n type: 'array' | 'object' | 'tuple' | 'record' | 'root'\n /**\n * Wildcard path to the field\n */\n wildCardPath: string",
"score": 0.7526800632476807
},
{
"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.7519242763519287
},
{
"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.7507193088531494
}
] | 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 { 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.7731183767318726
},
{
"filename": "src/types.ts",
"retrieved_chunk": "/**\n * Known tree nodes accepted by the compiler\n */\nexport type CompilerNodes =\n | LiteralNode\n | ObjectNode\n | ArrayNode\n | UnionNode\n | RecordNode\n | TupleNode",
"score": 0.7527858018875122
},
{
"filename": "src/types.ts",
"retrieved_chunk": "/**\n * Properties of a parent node as the compiler loops through the\n * rules tree and constructs JS code.\n */\nexport type CompilerParent = {\n type: 'array' | 'object' | 'tuple' | 'record' | 'root'\n /**\n * Wildcard path to the field\n */\n wildCardPath: string",
"score": 0.7526800632476807
},
{
"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.7519242763519287
},
{
"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.7507193088531494
}
] | 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/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.9287117123603821
},
{
"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.9222730398178101
},
{
"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.9091532230377197
},
{
"filename": "src/compiler/nodes/array.ts",
"retrieved_chunk": " defineFieldExistenceValidations({\n allowNull: this.#node.allowNull,\n isOptional: this.#node.isOptional,\n variableName: this.field.variableName,\n })\n )\n /**\n * Wrapping initialization of output + array elements\n * validation inside `if array field is valid` block.\n *",
"score": 0.9054744243621826
},
{
"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.8845873475074768
}
] | typescript | const isValueAnObject = 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 { 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.935615062713623
},
{
"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.9279260039329529
},
{
"filename": "src/compiler/nodes/array.ts",
"retrieved_chunk": " defineFieldExistenceValidations({\n allowNull: this.#node.allowNull,\n isOptional: this.#node.isOptional,\n variableName: this.field.variableName,\n })\n )\n /**\n * Wrapping initialization of output + array elements\n * validation inside `if array field is valid` block.\n *",
"score": 0.8863561749458313
},
{
"filename": "src/compiler/nodes/object.ts",
"retrieved_chunk": " isOptional: this.#node.isOptional,\n variableName: this.field.variableName,\n })\n )\n /**\n * Wrapping initialization of output + object children validations\n * validation inside `if object field is valid` block.\n *\n * Pre step: 3\n */",
"score": 0.8816727995872498
},
{
"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.8788682222366333
}
] | 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/DropZone.tsx",
"retrieved_chunk": " display=\"flex\"\n position=\"absolute\"\n bg=\"blue.700\"\n opacity=\"0.2\"\n zIndex=\"10\"\n width=\"100%\"\n height=\"100vh\"\n ></Box>\n )}\n <>{children}</>",
"score": 0.8497831225395203
},
{
"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.8492992520332336
},
{
"filename": "src/components/Pagination.tsx",
"retrieved_chunk": " onClick={() => setSelected(range)}\n size=\"xs\"\n variant=\"ghost\"\n color={selected === range ? 'red.600' : ''}\n >\n {range}\n </Button>\n )}\n <IconButton\n aria-label=\"next\"",
"score": 0.8358417749404907
},
{
"filename": "src/pages/login.tsx",
"retrieved_chunk": " width={{ base: '100%', lg: '55%' }}\n padding=\"2rem\"\n backgroundColor=\"yellow.200\"\n height=\"100vh\"\n flexDirection=\"column\"\n alignItems=\"center\"\n justifyContent=\"center\"\n >\n <Heading marginBottom=\"3rem\">How it works ?</Heading>\n <Image",
"score": 0.8355871438980103
},
{
"filename": "src/components/UploadButton.tsx",
"retrieved_chunk": " <>\n <Button\n size=\"lg\"\n minH=\"3rem\"\n w=\"100%\"\n colorScheme=\"yellow\"\n backgroundColor=\"yellow.200\"\n onClick={handleClick}\n >\n Upload 🚀",
"score": 0.8345010876655579
}
] | typescript | <CheckIcon boxSize="1rem" color="white" />
))} |
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/hooks/index.ts",
"retrieved_chunk": " revalidateOnReconnect: false,\n });\n};\nexport const useSaveAppData = () => {\n const { accessToken } = useContext(AppContext);\n return async (passphrase: string) => {\n const encryptionKey = await generateEncryptionKey();\n const wrappedKey = await wrapEncryptionKey(encryptionKey, passphrase);\n await saveAppData(accessToken.value, { encryptionKey: wrappedKey });\n await mutate((key: string) => key == 'appData', undefined, {",
"score": 0.8726866245269775
},
{
"filename": "src/context/index.tsx",
"retrieved_chunk": " const [value, setValue] = useState<T>(initial);\n return {\n value,\n setValue,\n };\n}\nexport const AppContext = createContext<Context>(DEFAULT_CONTEXT);\nexport const ContextProvider = (props: { children: React.ReactNode }) => {\n const accessToken = useProvider('');\n const encryptionKey = useProvider('');",
"score": 0.8696153163909912
},
{
"filename": "src/pages/login.tsx",
"retrieved_chunk": " const url = getAuthorizationUrl();\n const [error, setError] = useState('');\n const { accessToken, encryptionKey } = useContext(AppContext);\n const recoverAccessToken = useRecoverAccessToken();\n useEffect(() => {\n recoverAccessToken();\n }, []);\n const setAccessToken = async (token: string) => {\n try {\n setError('');",
"score": 0.8672232627868652
},
{
"filename": "src/components/DeleteButton.tsx",
"retrieved_chunk": " file: FileMetadata;\n onClose: () => void;\n isOpen: boolean;\n}\nconst DeleteModal: FC<PropsModal> = (props: PropsModal) => {\n const { file, onDelete, onClose, isOpen } = props;\n const [deleting, setDeleting] = useState(false);\n const handleDelete = async () => {\n setDeleting(true);\n try {",
"score": 0.8587058782577515
},
{
"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.8580981492996216
}
] | 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/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.7572999000549316
},
{
"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.7560793161392212
},
{
"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.7514328360557556
},
{
"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.7495408058166504
},
{
"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.7442377805709839
}
] | 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.9534142017364502
},
{
"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.9119604825973511
},
{
"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.9026879668235779
},
{
"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.8821525573730469
},
{
"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.8699256181716919
}
] | typescript | this.#node.properties.forEach((child) => { |
/*
* @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/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.8744335174560547
},
{
"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.8741384744644165
},
{
"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.8682132959365845
},
{
"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.8650935888290405
},
{
"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.8634859323501587
}
] | typescript | .compileNode(this.#node.each, arrayElementsBuffer, { |
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.8593034744262695
},
{
"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.8246728181838989
},
{
"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.8147950768470764
},
{
"filename": "src/components/UserCard.tsx",
"retrieved_chunk": "import LogoutButton from './LogoutButton';\ninterface PropsModal {\n onDownload: () => void;\n onClose: () => void;\n isOpen: boolean;\n}\nconst InfoModal: FC<PropsModal> = (props: PropsModal) => {\n const { onDownload, onClose, isOpen } = props;\n const handleDownload = () => {\n onDownload();",
"score": 0.8123806118965149
},
{
"filename": "src/components/DownloadButton.tsx",
"retrieved_chunk": " setDecrypting(true);\n try {\n const fileData = await decryptFile(data);\n saveFile([fileData], metadata.name, metadata.mimeType, ref);\n } catch (err) {\n toast.closeAll();\n toast({\n position: 'bottom-right',\n duration: 5000,\n isClosable: true,",
"score": 0.8100652694702148
}
] | 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": " */\n #getGroupFieldNames(group: ObjectGroupNode): string[] {\n return group.conditions.flatMap((condition) => {\n return this.#getFieldNames(condition.schema)\n })\n }\n /**\n * Compiles object children to JS output\n */\n #compileObjectChildren() {",
"score": 0.8709550499916077
},
{
"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.8676055073738098
},
{
"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.8653430938720703
},
{
"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.8590491414070129
},
{
"filename": "src/compiler/nodes/literal.ts",
"retrieved_chunk": " this.#node = node\n this.#buffer = buffer\n }\n compile() {\n /**\n * Define 1: Define field variable\n */\n this.defineField(this.#buffer)\n /**\n * Step 2: Define block to validate the existence of field",
"score": 0.8466670513153076
}
] | 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/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.8778406381607056
},
{
"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.8727272152900696
},
{
"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.8642910718917847
},
{
"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.862832248210907
},
{
"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.860142171382904
}
] | 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 { 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/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.8763665556907654
},
{
"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.8750097751617432
},
{
"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.8726310133934021
},
{
"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.8690319061279297
},
{
"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.8677921295166016
}
] | 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/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.7395212054252625
},
{
"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.7306553721427917
},
{
"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.7285410165786743
},
{
"filename": "src/compiler/nodes/record.ts",
"retrieved_chunk": " })\n buffer.writeStatement(\n defineRecordLoop({\n variableName: this.field.variableName,\n loopCodeSnippet: recordElementsBuffer.toString(),\n })\n )\n recordElementsBuffer.flush()\n return buffer.toString()\n }",
"score": 0.7237519025802612
},
{
"filename": "src/compiler/nodes/array.ts",
"retrieved_chunk": " const buffer = this.#buffer.child()\n buffer.writeStatement(\n defineArrayLoop({\n variableName: this.field.variableName,\n startingIndex: 0,\n loopCodeSnippet: arrayElementsBuffer.toString(),\n })\n )\n arrayElementsBuffer.flush()\n return buffer.toString()",
"score": 0.7106364965438843
}
] | 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 { 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/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.8382745981216431
},
{
"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.8314312696456909
},
{
"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.8175262212753296
},
{
"filename": "src/scripts/array/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 array\n */\nexport function defineArrayInitialOutput({",
"score": 0.8139488697052002
},
{
"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.8127031922340393
}
] | 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 { 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/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.8277881145477295
},
{
"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.8077946305274963
},
{
"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.7934290766716003
},
{
"filename": "src/compiler/nodes/record.ts",
"retrieved_chunk": " })\n buffer.writeStatement(\n defineRecordLoop({\n variableName: this.field.variableName,\n loopCodeSnippet: recordElementsBuffer.toString(),\n })\n )\n recordElementsBuffer.flush()\n return buffer.toString()\n }",
"score": 0.7908607721328735
},
{
"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.7739482522010803
}
] | 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.9109535813331604
},
{
"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.9098424315452576
},
{
"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.8933906555175781
},
{
"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.8734984397888184
},
{
"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.8703933358192444
}
] | 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/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.760964035987854
},
{
"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.7576077580451965
},
{
"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.7542614936828613
},
{
"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.7536352872848511
},
{
"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.7484112977981567
}
] | 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/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.7902380228042603
},
{
"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.7828755378723145
},
{
"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.7549673318862915
},
{
"filename": "src/scripts/object/move_unknown_properties.ts",
"retrieved_chunk": " */\nexport function defineMoveProperties({\n variableName,\n fieldsToIgnore,\n allowUnknownProperties,\n}: MovePropertiesOptions) {\n if (!allowUnknownProperties) {\n return ''\n }\n return `moveProperties(${variableName}.value, ${variableName}_out, ${inspect(fieldsToIgnore)});`",
"score": 0.7546557784080505
},
{
"filename": "src/scripts/union/parse.ts",
"retrieved_chunk": " variableName: string\n parseFnRefId?: RefIdentifier\n}\n/**\n * Returns JS fragment to call the parse function on the union conditional\n * schema.\n */\nexport function callParseFunction({ parseFnRefId, variableName }: FieldOptions) {\n if (parseFnRefId) {\n return `${variableName}.value = refs['${parseFnRefId}'](${variableName}.value);`",
"score": 0.7441922426223755
}
] | 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 { 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": " 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.8653268814086914
},
{
"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.8520239591598511
},
{
"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.8358696103096008
},
{
"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.8355837464332581
},
{
"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.8297028541564941
}
] | 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/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.9610605835914612
},
{
"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.9349611401557922
},
{
"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.902001142501831
},
{
"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.8716874122619629
},
{
"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.8515278100967407
}
] | 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 { defineObjectGuard } from '../../scripts/object/guard.js'
import { defineElseCondition } from '../../scripts/define_else_conditon.js'
import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js'
import { defineFieldNullOutput } from '../../scripts/field/null_output.js'
import { defineFieldValidations } from '../../scripts/field/validations.js'
import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js'
import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js'
import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js'
import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js'
import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js'
/**
* Compiles an object schema node to JS string output.
*/
export class ObjectNodeCompiler extends BaseNode {
#node: ObjectNode
#buffer: CompilerBuffer
#compiler: Compiler
constructor(
node: ObjectNode,
buffer: CompilerBuffer,
compiler: Compiler,
parent: CompilerParent,
parentField?: CompilerField
) {
super(node, compiler, parent, parentField)
this.#node = node
this.#buffer = buffer
this.#compiler = compiler
}
/**
* Returns known field names for the object
*/
#getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] {
let fieldNames = node.properties.map((child) => child.fieldName)
const groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group))
return fieldNames.concat(groupsFieldNames)
}
/**
* Returns field names of a group.
*/
#getGroupFieldNames(group: ObjectGroupNode): string[] {
return group.conditions.flatMap((condition) => {
return this.#getFieldNames(condition.schema)
})
}
/**
* Compiles object children to JS output
*/
#compileObjectChildren() {
const buffer = this.#buffer.child()
const parent = {
type: 'object',
fieldPathExpression: this.field.fieldPathExpression,
outputExpression: this.field.outputExpression,
variableName: this.field.variableName,
wildCardPath: this.field.wildCardPath,
} as const
this.#node.properties.forEach(( | child) => this.#compiler.compileNode(child, buffer, parent))
return buffer.toString()
} |
/**
* Compiles object groups with conditions to JS output.
*/
#compileObjectGroups() {
const buffer = this.#buffer.child()
const parent = {
type: 'object',
fieldPathExpression: this.field.fieldPathExpression,
outputExpression: this.field.outputExpression,
variableName: this.field.variableName,
wildCardPath: this.field.wildCardPath,
} as const
this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent))
return buffer.toString()
}
/**
* Compiles an object groups recursively
*/
#compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) {
group.conditions.forEach((condition, index) => {
const guardBuffer = buffer.child()
condition.schema.properties.forEach((child) => {
this.#compiler.compileNode(child, guardBuffer, parent)
})
condition.schema.groups.forEach((child) => {
this.#compileObjectGroup(child, guardBuffer, parent)
})
buffer.writeStatement(
defineConditionalGuard({
variableName: this.field.variableName,
conditional: index === 0 ? 'if' : 'else if',
conditionalFnRefId: condition.conditionalFnRefId,
guardedCodeSnippet: guardBuffer.toString(),
})
)
})
/**
* Define else block
*/
if (group.elseConditionalFnRefId && group.conditions.length) {
buffer.writeStatement(
defineElseCondition({
variableName: this.field.variableName,
conditionalFnRefId: group.elseConditionalFnRefId,
})
)
}
}
compile() {
/**
* Define 1: Define field variable
*/
this.defineField(this.#buffer)
/**
* Step 2: Define code to validate the existence of field.
*/
this.#buffer.writeStatement(
defineFieldExistenceValidations({
allowNull: this.#node.allowNull,
isOptional: this.#node.isOptional,
variableName: this.field.variableName,
})
)
/**
* Wrapping initialization of output + object children validations
* validation inside `if object field is valid` block.
*
* Pre step: 3
*/
const isObjectValidBlock = defineIsValidGuard({
variableName: this.field.variableName,
bail: this.#node.bail,
guardedCodeSnippet: `${defineObjectInitialOutput({
variableName: this.field.variableName,
outputExpression: this.field.outputExpression,
outputValueExpression: '{}',
})}${this.#buffer.newLine}${this.#compileObjectChildren()}${
this.#buffer.newLine
}${this.#compileObjectGroups()}${this.#buffer.newLine}${defineMoveProperties({
variableName: this.field.variableName,
allowUnknownProperties: this.#node.allowUnknownProperties,
fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [],
})}`,
})
/**
* Wrapping field validations + "isObjectValidBlock" inside
* `if value is object` check.
*
* Pre step: 3
*/
const isValueAnObject = defineObjectGuard({
variableName: this.field.variableName,
guardedCodeSnippet: `${defineFieldValidations({
variableName: this.field.variableName,
validations: this.#node.validations,
bail: this.#node.bail,
dropMissingCheck: true,
})}${isObjectValidBlock}`,
})
/**
* Step 3: Define `if value is an object` block and `else if value is null`
* block.
*/
this.#buffer.writeStatement(
`${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({
variableName: this.field.variableName,
allowNull: this.#node.allowNull,
outputExpression: this.field.outputExpression,
conditional: 'else if',
})}`
)
}
}
| src/compiler/nodes/object.ts | vinejs-compiler-8909bb5 | [
{
"filename": "src/compiler/nodes/array.ts",
"retrieved_chunk": " */\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.9028937220573425
},
{
"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.8949861526489258
},
{
"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.8874474763870239
},
{
"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.8649737238883972
},
{
"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.8616840839385986
}
] | 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 { 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.948063850402832
},
{
"filename": "src/compiler/nodes/object.ts",
"retrieved_chunk": " isOptional: this.#node.isOptional,\n variableName: this.field.variableName,\n })\n )\n /**\n * Wrapping initialization of output + object children validations\n * validation inside `if object field is valid` block.\n *\n * Pre step: 3\n */",
"score": 0.9277889132499695
},
{
"filename": "src/compiler/nodes/array.ts",
"retrieved_chunk": " defineFieldExistenceValidations({\n allowNull: this.#node.allowNull,\n isOptional: this.#node.isOptional,\n variableName: this.field.variableName,\n })\n )\n /**\n * Wrapping initialization of output + array elements\n * validation inside `if array field is valid` block.\n *",
"score": 0.888041615486145
},
{
"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.8877374529838562
},
{
"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.8811906576156616
}
] | 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 { 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": " */\n #getGroupFieldNames(group: ObjectGroupNode): string[] {\n return group.conditions.flatMap((condition) => {\n return this.#getFieldNames(condition.schema)\n })\n }\n /**\n * Compiles object children to JS output\n */\n #compileObjectChildren() {",
"score": 0.8681718111038208
},
{
"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.8663020133972168
},
{
"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.8659789562225342
},
{
"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.8576730489730835
},
{
"filename": "src/compiler/nodes/literal.ts",
"retrieved_chunk": " this.#node = node\n this.#buffer = buffer\n }\n compile() {\n /**\n * Define 1: Define field variable\n */\n this.defineField(this.#buffer)\n /**\n * Step 2: Define block to validate the existence of field",
"score": 0.8446581959724426
}
] | 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 { 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/null_output.ts",
"retrieved_chunk": " * Returns JS fragment for writing the null value to the output.\n */\nexport function defineFieldNullOutput({\n allowNull,\n conditional,\n variableName,\n outputExpression,\n transformFnRefId,\n}: OutputOptions) {\n if (!allowNull) {",
"score": 0.8724353313446045
},
{
"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.8646442294120789
},
{
"filename": "src/types.ts",
"retrieved_chunk": " * Creates an instance of an exception to throw\n */\n createError(): Error\n /**\n * Report error for a field\n */\n report(message: string, rule: string, field: FieldContext, args?: Record<string, any>): any\n}\n/**\n * Messages provider is used to resolve validation error messages",
"score": 0.8602161407470703
},
{
"filename": "src/scripts/field/variables.ts",
"retrieved_chunk": " * value variable, context variable, and a boolean to know if the field\n * exists.\n */\nexport function defineFieldVariables({\n parseFnRefId,\n variableName,\n wildCardPath,\n isArrayMember,\n valueExpression,\n fieldNameExpression,",
"score": 0.8567993640899658
},
{
"filename": "src/scripts/field/existence_validations.ts",
"retrieved_chunk": " isOptional: boolean\n allowNull: boolean\n}\n/**\n * Returns JS fragment to validate a field's value for existence.\n */\nexport function defineFieldExistenceValidations({\n allowNull,\n isOptional,\n variableName,",
"score": 0.8523766994476318
}
] | 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": " 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.8553450107574463
},
{
"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.8441237807273865
},
{
"filename": "src/compiler/nodes/tuple.ts",
"retrieved_chunk": " * Step 2: Define code to validate the existence of field.\n */\n this.#buffer.writeStatement(\n defineFieldExistenceValidations({\n allowNull: this.#node.allowNull,\n isOptional: this.#node.isOptional,\n variableName: this.field.variableName,\n })\n )\n /**",
"score": 0.8342692852020264
},
{
"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.832669734954834
},
{
"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.8315141201019287
}
] | 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/null_output.ts",
"retrieved_chunk": " * Returns JS fragment for writing the null value to the output.\n */\nexport function defineFieldNullOutput({\n allowNull,\n conditional,\n variableName,\n outputExpression,\n transformFnRefId,\n}: OutputOptions) {\n if (!allowNull) {",
"score": 0.8753330707550049
},
{
"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.8722147941589355
},
{
"filename": "src/types.ts",
"retrieved_chunk": " * Creates an instance of an exception to throw\n */\n createError(): Error\n /**\n * Report error for a field\n */\n report(message: string, rule: string, field: FieldContext, args?: Record<string, any>): any\n}\n/**\n * Messages provider is used to resolve validation error messages",
"score": 0.8685885667800903
},
{
"filename": "src/scripts/field/existence_validations.ts",
"retrieved_chunk": " isOptional: boolean\n allowNull: boolean\n}\n/**\n * Returns JS fragment to validate a field's value for existence.\n */\nexport function defineFieldExistenceValidations({\n allowNull,\n isOptional,\n variableName,",
"score": 0.8604443669319153
},
{
"filename": "src/scripts/field/variables.ts",
"retrieved_chunk": " * value variable, context variable, and a boolean to know if the field\n * exists.\n */\nexport function defineFieldVariables({\n parseFnRefId,\n variableName,\n wildCardPath,\n isArrayMember,\n valueExpression,\n fieldNameExpression,",
"score": 0.8600097894668579
}
] | 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 { 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.9406232237815857
},
{
"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.895933985710144
},
{
"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.888032853603363
},
{
"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.8722538352012634
},
{
"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.8642368316650391
}
] | 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/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.8746830224990845
},
{
"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.8642475605010986
},
{
"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.859322190284729
},
{
"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.8480960726737976
},
{
"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.8473502397537231
}
] | 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 { defineObjectGuard } from '../../scripts/object/guard.js'
import { defineElseCondition } from '../../scripts/define_else_conditon.js'
import { defineIsValidGuard } from '../../scripts/field/is_valid_guard.js'
import { defineFieldNullOutput } from '../../scripts/field/null_output.js'
import { defineFieldValidations } from '../../scripts/field/validations.js'
import { defineConditionalGuard } from '../../scripts/define_conditional_guard.js'
import { defineObjectInitialOutput } from '../../scripts/object/initial_output.js'
import { defineMoveProperties } from '../../scripts/object/move_unknown_properties.js'
import { defineFieldExistenceValidations } from '../../scripts/field/existence_validations.js'
import type { CompilerField, CompilerParent, ObjectNode, ObjectGroupNode } from '../../types.js'
/**
* Compiles an object schema node to JS string output.
*/
export class ObjectNodeCompiler extends BaseNode {
#node: ObjectNode
#buffer: CompilerBuffer
#compiler: Compiler
constructor(
node: ObjectNode,
buffer: CompilerBuffer,
compiler: Compiler,
parent: CompilerParent,
parentField?: CompilerField
) {
super(node, compiler, parent, parentField)
this.#node = node
this.#buffer = buffer
this.#compiler = compiler
}
/**
* Returns known field names for the object
*/
#getFieldNames(node: Pick<ObjectNode, 'properties' | 'groups'>): string[] {
let fieldNames = node.properties.map((child) => child.fieldName)
const groupsFieldNames = node.groups.flatMap((group) => this.#getGroupFieldNames(group))
return fieldNames.concat(groupsFieldNames)
}
/**
* Returns field names of a group.
*/
#getGroupFieldNames(group: ObjectGroupNode): string[] {
return group.conditions.flatMap((condition) => {
return this.#getFieldNames(condition.schema)
})
}
/**
* Compiles object children to JS output
*/
#compileObjectChildren() {
const buffer = this.#buffer.child()
const parent = {
type: 'object',
fieldPathExpression: this.field.fieldPathExpression,
outputExpression: this.field.outputExpression,
variableName: this.field.variableName,
wildCardPath: this.field.wildCardPath,
} as const
this.#node.properties.forEach((child) => this.#compiler.compileNode(child, buffer, parent))
return buffer.toString()
}
/**
* Compiles object groups with conditions to JS output.
*/
#compileObjectGroups() {
const buffer = this.#buffer.child()
const parent = {
type: 'object',
fieldPathExpression: this.field.fieldPathExpression,
outputExpression: this.field.outputExpression,
variableName: this.field.variableName,
wildCardPath: this.field.wildCardPath,
} as const
this.#node.groups.forEach((group) => this.#compileObjectGroup(group, buffer, parent))
return buffer.toString()
}
/**
* Compiles an object groups recursively
*/
#compileObjectGroup(group: ObjectGroupNode, buffer: CompilerBuffer, parent: CompilerParent) {
group.conditions.forEach((condition, index) => {
const guardBuffer = buffer.child()
condition.schema.properties.forEach((child) => {
this.#compiler.compileNode(child, guardBuffer, parent)
})
condition.schema.groups.forEach((child) => {
this.#compileObjectGroup(child, guardBuffer, parent)
})
buffer.writeStatement(
defineConditionalGuard({
variableName: this.field.variableName,
conditional: index === 0 ? 'if' : 'else if',
conditionalFnRefId: condition.conditionalFnRefId,
guardedCodeSnippet: guardBuffer.toString(),
})
)
})
/**
* Define else block
*/
if (group.elseConditionalFnRefId && group.conditions.length) {
buffer.writeStatement(
defineElseCondition({
variableName: this.field.variableName,
conditionalFnRefId: group.elseConditionalFnRefId,
})
)
}
}
compile() {
/**
* Define 1: Define field variable
*/
this.defineField(this.#buffer)
/**
* Step 2: Define code to validate the existence of field.
*/
this.#buffer.writeStatement(
defineFieldExistenceValidations({
allowNull: this.#node.allowNull,
isOptional: this.#node.isOptional,
variableName: this.field.variableName,
})
)
/**
* Wrapping initialization of output + object children validations
* validation inside `if object field is valid` block.
*
* Pre step: 3
*/
const isObjectValidBlock = defineIsValidGuard({
variableName: this.field.variableName,
bail: this.#node.bail,
guardedCodeSnippet: `${defineObjectInitialOutput({
variableName: this.field.variableName,
outputExpression: this.field.outputExpression,
outputValueExpression: '{}',
})}${this.#buffer.newLine}${this.#compileObjectChildren()}${
this.#buffer.newLine
}${this.#compileObjectGroups()}${this.#buffer | .newLine}${defineMoveProperties({ |
variableName: this.field.variableName,
allowUnknownProperties: this.#node.allowUnknownProperties,
fieldsToIgnore: this.#node.allowUnknownProperties ? this.#getFieldNames(this.#node) : [],
})}`,
})
/**
* Wrapping field validations + "isObjectValidBlock" inside
* `if value is object` check.
*
* Pre step: 3
*/
const isValueAnObject = defineObjectGuard({
variableName: this.field.variableName,
guardedCodeSnippet: `${defineFieldValidations({
variableName: this.field.variableName,
validations: this.#node.validations,
bail: this.#node.bail,
dropMissingCheck: true,
})}${isObjectValidBlock}`,
})
/**
* Step 3: Define `if value is an object` block and `else if value is null`
* block.
*/
this.#buffer.writeStatement(
`${isValueAnObject}${this.#buffer.newLine}${defineFieldNullOutput({
variableName: this.field.variableName,
allowNull: this.#node.allowNull,
outputExpression: this.field.outputExpression,
conditional: 'else if',
})}`
)
}
}
| src/compiler/nodes/object.ts | vinejs-compiler-8909bb5 | [
{
"filename": "src/compiler/nodes/array.ts",
"retrieved_chunk": " 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.8473647236824036
},
{
"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.8430566787719727
},
{
"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.8404150605201721
},
{
"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.8398534059524536
},
{
"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.8312721252441406
}
] | typescript | .newLine}${defineMoveProperties({ |
/*
* @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/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.871720552444458
},
{
"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.8696682453155518
},
{
"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.8659120798110962
},
{
"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.8634512424468994
},
{
"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.8631553649902344
}
] | 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 { 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/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.8804320693016052
},
{
"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.8605934977531433
},
{
"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.8533068299293518
},
{
"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.8415300846099854
},
{
"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.8410094976425171
}
] | typescript | #node.each, recordElementsBuffer, { |
/*
* @vinejs/compiler
*
* (c) VineJS
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { BaseNode } from './base.js'
import type { Compiler } from '../main.js'
import type { CompilerBuffer } from '../buffer.js'
import { 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.9707549810409546
},
{
"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.9086120128631592
},
{
"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.898242712020874
},
{
"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.8754861354827881
},
{
"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.8446797132492065
}
] | typescript | .#node.properties.forEach((child) => { |
import * as vscode from "vscode";
import * as fs from "fs";
import {
Account,
ec,
json,
stark,
Provider,
hash,
CallData,
Signer,
} from "starknet";
import { logger } from "../lib";
import { IAccountQP, JSONAccountType } from "../types";
import { NETWORKS, getNetworkProvider } from "./network";
import { accountDeployStatus } from "../utils/functions";
export const createOZAccount = async (context: vscode.ExtensionContext) => {
try {
const privateKey = stark.randomAddress();
const publicKey = await new Signer(privateKey).getPubKey();
const OZaccountClassHash =
"0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb";
const OZaccountConstructorCallData = CallData.compile({
publicKey: publicKey,
});
const OZcontractAddress = hash.calculateContractAddressFromHash(
publicKey,
OZaccountClassHash,
OZaccountConstructorCallData,
0
);
if (fs.existsSync(`${context.extensionPath}/accounts.json`)) {
const filedata = fs.readFileSync(
`${context.extensionPath}/accounts.json`,
{
encoding: "utf-8",
}
);
const parsedFileData = JSON.parse(filedata);
const writeNewAccount: Array<JSONAccountType> = [
...parsedFileData,
{
accountHash: OZaccountClassHash,
constructorCallData: OZaccountConstructorCallData,
accountPubKey: publicKey,
accountAddress: OZcontractAddress,
privateKey: privateKey,
isDeployed: {
gAlpha: false,
gAlpha2: false,
mainnet: false,
},
},
];
fs.writeFileSync(
`${context.extensionPath}/accounts.json`,
JSON.stringify(writeNewAccount)
);
} else {
const writeNewAccount: Array<JSONAccountType> = [
{
accountHash: OZaccountClassHash,
constructorCallData: OZaccountConstructorCallData,
accountPubKey: publicKey,
accountAddress: OZcontractAddress,
privateKey: privateKey,
isDeployed: {
gAlpha: false,
gAlpha2: false,
mainnet: false,
},
},
];
fs.writeFileSync(
`${context.extensionPath}/accounts.json`,
JSON.stringify(writeNewAccount)
);
}
logger.log(`New account created: ${OZcontractAddress}`);
} catch (error) {
logger.error(`Error while creating new account: ${error}`);
}
};
export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => {
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
if (selectedNetwork === undefined) {
logger.log("Network not selected");
return;
}
if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) {
logger.log("No account exist.");
return;
}
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(
parsedFileData,
selectedNetwork,
false
);
if (accounts === undefined || accounts.length === 0) {
logger.log(`No undeployed account available on ${selectedNetwork}`);
return;
}
return accounts;
};
export const selectNotDeployedAccount = async (
context: vscode.ExtensionContext
) => {
const accounts: Array<JSONAccountType> | undefined =
await getNotDeployedAccounts(context);
if (accounts === undefined) return;
| const quickPick = vscode.window.createQuickPick<IAccountQP>(); |
quickPick.items = accounts.map((account: JSONAccountType) => ({
label: account.accountAddress,
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select account";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
void context.workspaceState.update("undeployedAccount", label);
logger.log(`${label} selected`);
quickPick.dispose();
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
};
export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => {
const presentAccounts: Array<JSONAccountType> | undefined =
await getNotDeployedAccounts(context);
const unDeployedAccount = await context.workspaceState.get(
"undeployedAccount"
);
if (presentAccounts === undefined) return;
const isAccountPresent: any = presentAccounts.filter(
(account) => account.accountAddress === unDeployedAccount
);
const selectedAccount: JSONAccountType = isAccountPresent[0];
const selectedNetwork = context.workspaceState.get("selectedNetwork");
const provider = getNetworkProvider(context);
console.log(`Account address: ${selectedAccount.accountAddress}`);
if (provider === undefined) return;
const account = new Account(
provider,
selectedAccount.accountAddress,
selectedAccount.privateKey,
"1"
);
logger.log(
`Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}`
);
const { contract_address, transaction_hash } = await account.deployAccount({
classHash: selectedAccount.accountHash,
constructorCalldata: selectedAccount.constructorCallData,
addressSalt: selectedAccount.accountPubKey,
});
logger.log(`Transaction hash: ${transaction_hash}`);
await provider.waitForTransaction(transaction_hash);
await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount);
logger.log(`Account deployed successfully at address: ${contract_address}`);
accountTreeDataProvider.refresh();
};
const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => {
const selectedNetwork = context.workspaceState.get("selectedNetwork");
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
const accounts = JSON.parse(data);
const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress);
if (indexToUpdate !== -1) {
accounts[indexToUpdate].isDeployed = {
gAlpha: selectedNetwork === NETWORKS[0] ? true : false,
gAlpha2: selectedNetwork === NETWORKS[1] ? true : false,
mainnet: selectedNetwork === NETWORKS[2] ? true : false,
};
fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('JSON file successfully updated.');
});
} else {
console.error('Element not found in JSON file.');
}
});
};
export const getDeployedAccounts = (context: vscode.ExtensionContext) => {
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
if (selectedNetwork === undefined){
// logger.log("Network not selected");
return;
}
if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) {
logger.log("No deployed account exist.");
return;
}
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(
parsedFileData,
selectedNetwork,
true
);
if (accounts === undefined || accounts.length === 0) {
logger.log(`No deployed account available on ${selectedNetwork}`);
return;
}
return accounts;
};
export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => {
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress);
fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2));
};
export const selectDeployedAccount = async (
context: vscode.ExtensionContext
) => {
const accounts: Array<JSONAccountType> | undefined =
await getDeployedAccounts(context);
if (accounts === undefined) return;
const quickPick = vscode.window.createQuickPick<IAccountQP>();
quickPick.items = accounts.map((account: JSONAccountType) => ({
label: account.accountAddress,
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select account";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
void context.workspaceState.update("account", label);
logger.log(`${label} selected`);
quickPick.dispose();
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
};
export const getAccountInfo = (
context: vscode.ExtensionContext,
accountAddress: string
) => {
const accounts = getDeployedAccounts(context) as JSONAccountType[];
const selectedAccountInfo = accounts.filter(
(account) => account.accountAddress === accountAddress
);
return selectedAccountInfo[0];
};
| src/config/account.ts | 7finney-starkode-2fba517 | [
{
"filename": "src/treeView/AccountTreeView/AccountTreeDataProvider.ts",
"retrieved_chunk": " return element;\n }\n async getChildren(element?: Account): Promise<Account[]> {\n const accounts: Array<JSONAccountType> | undefined = getDeployedAccounts(this.context);\n const undeployedAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(this.context);\n if ((accounts === undefined && undeployedAccounts === undefined)){\n return [];\n } else {\n const leaves = [];\n if (accounts !== undefined) {",
"score": 0.8620517253875732
},
{
"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.8372006416320801
},
{
"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.8291949033737183
},
{
"filename": "src/config/network.ts",
"retrieved_chunk": " }\n });\n quickPick.onDidHide(() => {\n quickPick.dispose();\n });\n quickPick.show();\n};\nexport const getNetworkProvider = (\n context: vscode.ExtensionContext\n): Provider | undefined => {",
"score": 0.8207761645317078
},
{
"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.8072876930236816
}
] | typescript | const quickPick = vscode.window.createQuickPick<IAccountQP>(); |
import * as vscode from "vscode";
import * as fs from "fs";
import {
Account,
ec,
json,
stark,
Provider,
hash,
CallData,
Signer,
} from "starknet";
import { logger } from "../lib";
import { IAccountQP, JSONAccountType } from "../types";
import { NETWORKS, getNetworkProvider } from "./network";
import { accountDeployStatus } from "../utils/functions";
export const createOZAccount = async (context: vscode.ExtensionContext) => {
try {
const privateKey = stark.randomAddress();
const publicKey = await new Signer(privateKey).getPubKey();
const OZaccountClassHash =
"0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb";
const OZaccountConstructorCallData = CallData.compile({
publicKey: publicKey,
});
const OZcontractAddress = hash.calculateContractAddressFromHash(
publicKey,
OZaccountClassHash,
OZaccountConstructorCallData,
0
);
if (fs.existsSync(`${context.extensionPath}/accounts.json`)) {
const filedata = fs.readFileSync(
`${context.extensionPath}/accounts.json`,
{
encoding: "utf-8",
}
);
const parsedFileData = JSON.parse(filedata);
const writeNewAccount: Array<JSONAccountType> = [
...parsedFileData,
{
accountHash: OZaccountClassHash,
constructorCallData: OZaccountConstructorCallData,
accountPubKey: publicKey,
accountAddress: OZcontractAddress,
privateKey: privateKey,
isDeployed: {
gAlpha: false,
gAlpha2: false,
mainnet: false,
},
},
];
fs.writeFileSync(
`${context.extensionPath}/accounts.json`,
JSON.stringify(writeNewAccount)
);
} else {
const writeNewAccount: Array<JSONAccountType> = [
{
accountHash: OZaccountClassHash,
constructorCallData: OZaccountConstructorCallData,
accountPubKey: publicKey,
accountAddress: OZcontractAddress,
privateKey: privateKey,
isDeployed: {
gAlpha: false,
gAlpha2: false,
mainnet: false,
},
},
];
fs.writeFileSync(
`${context.extensionPath}/accounts.json`,
JSON.stringify(writeNewAccount)
);
}
logger.log(`New account created: ${OZcontractAddress}`);
} catch (error) {
logger.error(`Error while creating new account: ${error}`);
}
};
export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => {
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
if (selectedNetwork === undefined) {
logger.log("Network not selected");
return;
}
if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) {
logger.log("No account exist.");
return;
}
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(
parsedFileData,
selectedNetwork,
false
);
if (accounts === undefined || accounts.length === 0) {
logger.log(`No undeployed account available on ${selectedNetwork}`);
return;
}
return accounts;
};
export const selectNotDeployedAccount = async (
context: vscode.ExtensionContext
) => {
const accounts: Array<JSONAccountType> | undefined =
await getNotDeployedAccounts(context);
if (accounts === undefined) return;
const quickPick = vscode.window.createQuickPick<IAccountQP>();
quickPick.items = accounts.map((account: JSONAccountType) => ({
label: account.accountAddress,
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select account";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
void context.workspaceState.update("undeployedAccount", label);
logger.log(`${label} selected`);
quickPick.dispose();
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
};
export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => {
const presentAccounts: Array<JSONAccountType> | undefined =
await getNotDeployedAccounts(context);
const unDeployedAccount = await context.workspaceState.get(
"undeployedAccount"
);
if (presentAccounts === undefined) return;
const isAccountPresent: any = presentAccounts.filter(
(account) => account.accountAddress === unDeployedAccount
);
const selectedAccount: JSONAccountType = isAccountPresent[0];
const selectedNetwork = context.workspaceState.get("selectedNetwork");
| const provider = getNetworkProvider(context); |
console.log(`Account address: ${selectedAccount.accountAddress}`);
if (provider === undefined) return;
const account = new Account(
provider,
selectedAccount.accountAddress,
selectedAccount.privateKey,
"1"
);
logger.log(
`Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}`
);
const { contract_address, transaction_hash } = await account.deployAccount({
classHash: selectedAccount.accountHash,
constructorCalldata: selectedAccount.constructorCallData,
addressSalt: selectedAccount.accountPubKey,
});
logger.log(`Transaction hash: ${transaction_hash}`);
await provider.waitForTransaction(transaction_hash);
await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount);
logger.log(`Account deployed successfully at address: ${contract_address}`);
accountTreeDataProvider.refresh();
};
const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => {
const selectedNetwork = context.workspaceState.get("selectedNetwork");
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
const accounts = JSON.parse(data);
const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress);
if (indexToUpdate !== -1) {
accounts[indexToUpdate].isDeployed = {
gAlpha: selectedNetwork === NETWORKS[0] ? true : false,
gAlpha2: selectedNetwork === NETWORKS[1] ? true : false,
mainnet: selectedNetwork === NETWORKS[2] ? true : false,
};
fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('JSON file successfully updated.');
});
} else {
console.error('Element not found in JSON file.');
}
});
};
export const getDeployedAccounts = (context: vscode.ExtensionContext) => {
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
if (selectedNetwork === undefined){
// logger.log("Network not selected");
return;
}
if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) {
logger.log("No deployed account exist.");
return;
}
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(
parsedFileData,
selectedNetwork,
true
);
if (accounts === undefined || accounts.length === 0) {
logger.log(`No deployed account available on ${selectedNetwork}`);
return;
}
return accounts;
};
export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => {
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress);
fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2));
};
export const selectDeployedAccount = async (
context: vscode.ExtensionContext
) => {
const accounts: Array<JSONAccountType> | undefined =
await getDeployedAccounts(context);
if (accounts === undefined) return;
const quickPick = vscode.window.createQuickPick<IAccountQP>();
quickPick.items = accounts.map((account: JSONAccountType) => ({
label: account.accountAddress,
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select account";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
void context.workspaceState.update("account", label);
logger.log(`${label} selected`);
quickPick.dispose();
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
};
export const getAccountInfo = (
context: vscode.ExtensionContext,
accountAddress: string
) => {
const accounts = getDeployedAccounts(context) as JSONAccountType[];
const selectedAccountInfo = accounts.filter(
(account) => account.accountAddress === accountAddress
);
return selectedAccountInfo[0];
};
| src/config/account.ts | 7finney-starkode-2fba517 | [
{
"filename": "src/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.9060665965080261
},
{
"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.8948432803153992
},
{
"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.8904448747634888
},
{
"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.8853789567947388
},
{
"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.8557213544845581
}
] | 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/utils/functions.ts",
"retrieved_chunk": " }\n};\nexport const createAddressFile = (file: string) => {\n try {\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const fileName = file.substring(0, file.length - 5);",
"score": 0.9352191686630249
},
{
"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.907738208770752
},
{
"filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts",
"retrieved_chunk": " getTreeItem(element: Abi): TreeItem {\n return element;\n }\n async getChildren(element?: Abi): Promise<Abi[] | undefined> {\n const leaves: Abi[] = [];\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return undefined;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;",
"score": 0.900249719619751
},
{
"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.8930318355560303
},
{
"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.883026123046875
}
] | typescript | = getNetworkProvider(context) as Provider; |
import * as vscode from "vscode";
import * as fs from "fs";
import path, { resolve } from "path";
import { logger } from "../lib";
import { ABIFragment, IContractQP, IFunctionQP } from "../types";
import { createABIFile, createAddressFile } from "../utils/functions";
import { getAccountInfo } from "./account";
import { Account, CairoAssembly, Contract, ec, Provider } from "starknet";
import { getNetworkProvider } from "./network";
export const loadAllCompiledContract = () => {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const compiledCairoContract = fs
.readdirSync(path_)
.filter((file) => exportPathOfJSONfiles(path_, file));
return compiledCairoContract;
};
const exportPathOfJSONfiles = (path_: string, file: string) => {
const filePath = path.join(path_, file);
if (path.extname(filePath) === ".json") {
const fileData = fs.readFileSync(filePath, {
encoding: "utf-8",
});
if (JSON.parse(fileData).program) return filePath;
if (JSON.parse(fileData).contract_class_version) {
return filePath;
}
}
};
export const setContract = async (context: vscode.ExtensionContext, label: string) => {
if (label === undefined) {
// logger.log("No Contract selected.");
return;
}
void context.workspaceState.update("selectedContract", `${label}.json`);
logger.log(`${label} contract selected`);
createABIFile(`${label}.json`);
createAddressFile(`${label}.json`);
};
export const selectCompiledContract = (context: vscode.ExtensionContext) => {
const contracts = loadAllCompiledContract();
if (contracts === undefined) {
logger.log("No Contract available.");
return;
}
const quickPick = vscode.window.createQuickPick | <IContractQP>(); |
quickPick.items = contracts.map((contract: string) => ({
label: contract.substring(0, contract.length - 5),
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select Contract";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
setContract(context, label);
quickPick.dispose();
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
};
export const getContractInfo = (path_: string, fileName: string) => {
try {
const file = fileName.substring(0, fileName.length - 5);
const fileData = fs.readFileSync(
path.join(path_, "starkode", file, `${file}_address.json`),
{ encoding: "utf-8" }
);
const parsedFileData = JSON.parse(fileData);
return parsedFileData;
} catch (error) {
// console.log(error);
return undefined;
}
};
export const getContractABI = (path_: string, fileName: string) => {
try {
const file = fileName.substring(0, fileName.length - 5);
const fileData = fs.readFileSync(
path.join(path_, "starkode", file, `${file}_abi.json`),
{ encoding: "utf-8" }
);
const parsedFileData = JSON.parse(fileData);
return parsedFileData;
} catch (error) {
// console.log(error);
return undefined;
}
};
export const isCairo1Contract = (fileName: string): boolean => {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return false;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const fileData = fs.readFileSync(
path.join(path_, fileName),
{ encoding: "utf-8" }
);
return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false;
};
export const declareContract = async (context: vscode.ExtensionContext) => {
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const fileName = selectedContract.substring(0, selectedContract.length - 5);
if (
!fs.existsSync(path.join(path_, selectedContract)) ||
!fs.existsSync(path.join(path_, `${fileName}.casm`))
) {
logger.log(`${fileName}.json or ${fileName}.casm must be present.`);
return;
}
const compiledContract = fs.readFileSync(
path.join(path_, selectedContract),
{
encoding: "ascii",
}
);
const casmFileData = fs
.readFileSync(path.join(path_, `${fileName}.casm`))
.toString("ascii");
const casmAssembly: CairoAssembly = JSON.parse(casmFileData);
logger.log("Declaring contract...");
const declareResponse = await account.declareAndDeploy({
contract: compiledContract,
casm: casmAssembly,
});
logger.log(
`declare transaction hash: ${declareResponse.deploy.transaction_hash}`
);
logger.log(`declare classHash: ${declareResponse.deploy.classHash}`);
logger.log("transaction successful");
} catch (error) {
logger.log(`Error while contract declaration: ${error}`);
}
};
export const deployContract = async (context: vscode.ExtensionContext) => {
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
logger.log("Deploying contract...");
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const contractInfo = getContractInfo(path_, selectedContract);
if (contractInfo.classHash === "") {
logger.log("No classHash available for selected contract.");
return;
}
const deployResponse = await account.deployContract({
classHash: contractInfo.classHash,
});
logger.log(`transaction hash: ${deployResponse.transaction_hash}`);
logger.log("waiting for transaction success...");
await provider.waitForTransaction(deployResponse.transaction_hash);
const { abi: testAbi } = await provider.getClassAt(
deployResponse.contract_address
);
if (testAbi === undefined) {
throw new Error("no abi.");
}
const myTestContract = new Contract(
testAbi,
deployResponse.contract_address,
provider
);
await provider.waitForTransaction(myTestContract.transaction_hash);
logger.log(`contract deployed successfully: ${myTestContract.address}`);
} catch (error) {
logger.log(`Error while contract deployment: ${error}`);
}
};
export const executeContractFunction = async (
context: vscode.ExtensionContext
) => {
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
const functionABI = await getSelectedFunction(path_, selectedContract);
const contractInfo = getContractInfo(path_, selectedContract);
const params_: Array<any> = functionABI.inputs.map((e) => {
return e.value;
});
const params: Array<any> = params_ !== undefined ? params_ : [];
if (
functionABI.stateMutability === "view" ||
functionABI.state_mutability === "view"
) {
const Abi = getContractABI(path_, selectedContract).abi;
const contract = new Contract(Abi, contractInfo.address, provider);
logger.log(`calling function: ${functionABI.name}`);
const functionCall: any = await contract.call(`${functionABI.name}`);
logger.log(`result: ${functionCall.res.toString()}`);
} else {
const Abi = getContractABI(path_, selectedContract).abi;
logger.log(`calling function: ${functionABI.name}`);
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const contract = new Contract(Abi, contractInfo.address, provider);
contract.connect(account);
const result = await contract.invoke(functionABI.name, params);
logger.log(`transaction hash: ${result.transaction_hash}`);
logger.log("waiting for transaction success...");
await provider.waitForTransaction(result.transaction_hash);
logger.log("transaction successfull");
}
} catch (error) {
logger.log(error);
}
};
export const executeContractFunctionFromTreeView = async (
context: vscode.ExtensionContext,
functionabi: ABIFragment
) => {
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
const functionABI = functionabi;
const contractInfo = getContractInfo(path_, selectedContract);
const params_: Array<any> = functionABI.inputs.map((e) => {
return e.value;
});
const params: Array<any> = params_ !== undefined ? params_ : [];
if (
functionABI.stateMutability === "view" ||
functionABI.state_mutability === "view"
) {
const Abi = getContractABI(path_, selectedContract).abi;
const contract = new Contract(Abi, contractInfo.address, provider);
logger.log(`calling function: ${functionABI.name}`);
const functionCall: any = await contract.call(`${functionABI.name}`);
logger.log(`result: ${functionCall.res.toString()}`);
} else {
const Abi = getContractABI(path_, selectedContract).abi;
logger.log(`calling function: ${functionABI.name}`);
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const contract = new Contract(Abi, contractInfo.address, provider);
contract.connect(account);
const result = await contract.invoke(functionABI.name, params);
logger.log(`transaction hash: ${result.transaction_hash}`);
logger.log("waiting for transaction success...");
await provider.waitForTransaction(result.transaction_hash);
logger.log("transaction successfull");
}
} catch (error) {
logger.log(error);
}
};
const getSelectedFunction = (
path_: string,
selectedContract: string
): Promise<ABIFragment> => {
return new Promise((resolve, reject) => {
try {
const contractInfo: Array<ABIFragment> = getContractABI(
path_,
selectedContract
).abi;
if (contractInfo === undefined) return;
const quickPick = vscode.window.createQuickPick<IFunctionQP>();
quickPick.items = contractInfo.map((account: ABIFragment) => ({
label: account.name,
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select Function";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
quickPick.dispose();
const functionItem = contractInfo.filter(
(i: ABIFragment) => i.name === label
);
if (functionItem.length === 0)
throw new Error("No function is selected");
resolve(functionItem[0]);
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
} catch (error) {
reject(error);
}
});
};
| src/config/contract.ts | 7finney-starkode-2fba517 | [
{
"filename": "src/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.8724565505981445
},
{
"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.8377495408058167
},
{
"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.8330422639846802
},
{
"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.8286124467849731
},
{
"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.828170657157898
}
] | typescript | <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/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.8418366312980652
},
{
"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.834672212600708
},
{
"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.8249828815460205
},
{
"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.8232862949371338
},
{
"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.8229678869247437
}
] | 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/config/contract.ts",
"retrieved_chunk": "};\nexport const getContractABI = (path_: string, fileName: string) => {\n try {\n const file = fileName.substring(0, fileName.length - 5);\n const fileData = fs.readFileSync(\n path.join(path_, \"starkode\", file, `${file}_abi.json`),\n { encoding: \"utf-8\" }\n );\n const parsedFileData = JSON.parse(fileData);\n return parsedFileData;",
"score": 0.8562488555908203
},
{
"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.8366690874099731
},
{
"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.8252155780792236
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": "const exportPathOfJSONfiles = (path_: string, file: string) => {\n const filePath = path.join(path_, file);\n if (path.extname(filePath) === \".json\") {\n const fileData = fs.readFileSync(filePath, {\n encoding: \"utf-8\",\n });\n if (JSON.parse(fileData).program) return filePath;\n if (JSON.parse(fileData).contract_class_version) {\n return filePath;\n }",
"score": 0.8127410411834717
},
{
"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.7984168529510498
}
] | typescript | const writeNewAccount: Array<JSONAccountType> = [
...parsedFileData,
{ |
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.8585983514785767
},
{
"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.8446608185768127
},
{
"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.8208872675895691
},
{
"filename": "src/extension.ts",
"retrieved_chunk": " accountTreeDataProvider.refresh();\n }),\n vscode.commands.registerCommand(\"starkode.editContractAddress\", async (node: ContractTreeItem) => {\n await editContractAddress(node, context);\n }),\n vscode.commands.registerCommand(\"starkode.editInput\", async (node: any) => {\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n await editInput(node, abiTreeDataProvider, selectedContract);",
"score": 0.7998559474945068
},
{
"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.7978575229644775
}
] | 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": " 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.7925410270690918
},
{
"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.7415142059326172
},
{
"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.7358000874519348
},
{
"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.7315970063209534
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " {\n encoding: \"ascii\",\n }\n );\n const casmFileData = fs\n .readFileSync(path.join(path_, `${fileName}.casm`))\n .toString(\"ascii\");\n const casmAssembly: CairoAssembly = JSON.parse(casmFileData);\n logger.log(\"Declaring contract...\");\n const declareResponse = await account.declareAndDeploy({",
"score": 0.7301449775695801
}
] | 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.8110442161560059
},
{
"filename": "src/config/account.ts",
"retrieved_chunk": " constructorCalldata: selectedAccount.constructorCallData,\n addressSalt: selectedAccount.accountPubKey,\n });\n logger.log(`Transaction hash: ${transaction_hash}`);\n await provider.waitForTransaction(transaction_hash);\n await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount);\n logger.log(`Account deployed successfully at address: ${contract_address}`);\n accountTreeDataProvider.refresh();\n};\nconst updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => {",
"score": 0.763553261756897
},
{
"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.7579373121261597
},
{
"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.7461577653884888
},
{
"filename": "src/config/network.ts",
"retrieved_chunk": "import * as vscode from \"vscode\";\nimport { logger } from \"../lib\";\nimport { INetworkQP } from \"../types\";\nimport { Provider, SequencerProviderOptions } from \"starknet\";\nimport { Account } from \"../treeView/AccountTreeView/AccountTreeDataProvider\";\nexport const NETWORKS = [\"goerli-alpha\", \"goerli-alpha-2\", \"mainnet-alpha\"];\nexport const updateSelectedNetwork = async (\n context: vscode.ExtensionContext,\n accountTreeView: vscode.TreeView<Account>,\n accountTreeDataProvider: any",
"score": 0.7432745099067688
}
] | typescript | await editContractAddress(node, 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": "};\nexport const getContractABI = (path_: string, fileName: string) => {\n try {\n const file = fileName.substring(0, fileName.length - 5);\n const fileData = fs.readFileSync(\n path.join(path_, \"starkode\", file, `${file}_abi.json`),\n { encoding: \"utf-8\" }\n );\n const parsedFileData = JSON.parse(fileData);\n return parsedFileData;",
"score": 0.851098358631134
},
{
"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.8261936902999878
},
{
"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.8207423686981201
},
{
"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.815548300743103
},
{
"filename": "src/treeView/AccountTreeView/AccountTreeDataProvider.ts",
"retrieved_chunk": " return element;\n }\n async getChildren(element?: Account): Promise<Account[]> {\n const accounts: Array<JSONAccountType> | undefined = getDeployedAccounts(this.context);\n const undeployedAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(this.context);\n if ((accounts === undefined && undeployedAccounts === undefined)){\n return [];\n } else {\n const leaves = [];\n if (accounts !== undefined) {",
"score": 0.8009347915649414
}
] | typescript | const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(
parsedFileData,
selectedNetwork,
false
); |
import * as vscode from "vscode";
import * as fs from "fs";
import path from "path";
import {
createOZAccount,
deleteAccount,
deployAccount,
selectDeployedAccount,
selectNotDeployedAccount,
} from "./config/account";
import {
declareContract,
deployContract,
executeContractFunction,
executeContractFunctionFromTreeView,
getContractInfo,
isCairo1Contract,
loadAllCompiledContract,
selectCompiledContract,
setContract,
} from "./config/contract";
import { updateSelectedNetwork } from "./config/network";
import { logger } from "./lib";
import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider";
import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function";
import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider";
import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider";
import { editInput } from "./treeView/ABITreeView/functions";
import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider";
export function activate(context: vscode.ExtensionContext) {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`);
watcher.onDidChange((event: vscode.Uri) => {
const contractName: string | undefined = context.workspaceState.get("selectedContract");
if (contractName === undefined) {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
} else {
abiTreeView.message = undefined;
const contractInfo = getContractInfo(path_, contractName);
abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;
}
abiTreeDataProvider.refresh();
});
// Contract Tree View
const contractTreeDataProvider = new ContractTreeDataProvider(
vscode.workspace.workspaceFolders?.[0].uri.fsPath
);
let contractTreeView = vscode.window.createTreeView("starkode.contracts", {
treeDataProvider: contractTreeDataProvider,
});
// if contract tree view is empty
const contracts = loadAllCompiledContract();
if (contracts === undefined || contracts.length === 0) {
contractTreeView.message = "No contract found. Please compile your contract.";
}
contractTreeView.onDidChangeSelection(event => {
const selectedNodes = event.selection;
if (selectedNodes && selectedNodes.length > 0) {
console.log('Selected nodes:', selectedNodes[0].label);
}
});
// Account Tree View
const accountTreeDataProvider = new AccountTreeDataProvider(
context
);
const accountTreeView = vscode.window.createTreeView("starkode.account", {
treeDataProvider: accountTreeDataProvider,
});
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
const selectedAccount: string | undefined = context.workspaceState.get("account") as string;
accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it";
// ABI Tree View
const abiTreeDataProvider = new AbiTreeDataProvider(
context
);
const abiTreeView = vscode.window.createTreeView("starkode.abis", {
treeDataProvider: abiTreeDataProvider,
});
const contractName: string | undefined = context.workspaceState.get("selectedContract");
if (!contractName || contractName === undefined) {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
}
else {
const contractInfo = getContractInfo(path_, contractName);
if (contractInfo !== undefined) {
abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;
} else {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
}
}
context.subscriptions.push(
vscode.commands.registerCommand("starkode.activate", () => {
try {
if (!fs.existsSync(path.join(path_, "starkode"))) {
fs.mkdirSync(path.join(path_, "starkode"));
}
vscode.window.showInformationMessage("Starkode activated.");
} catch (error) {
console.log(error);
}
}),
| vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { |
contractTreeView = await refreshContract(node, contractTreeDataProvider);
contractTreeView.message = undefined;
}),
vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => {
setContract(context, node.label);
abiTreeView.message = undefined;
const contractInfo = getContractInfo(path_, `${node.label}.json`);
if (contractInfo !== undefined) {
abiTreeView.description = `${node.label} @ ${contractInfo.address}`;
}
abiTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.useAccount", async (node: any) => {
console.log(node);
if (node.context === "deployedAccount") {
void context.workspaceState.update("account", node.account.accountAddress);
logger.log(`${node.account.accountAddress} selected`);
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount !== undefined) {
accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`;
}
abiTreeDataProvider.refresh();
} else {
vscode.window.showErrorMessage("Please deploy the account first.");
}
}),
vscode.commands.registerCommand("starkode.createAccountTreeView", async () => {
createOZAccount(context);
accountTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.selectNetwork", async () => {
await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => {
void context.workspaceState.update("undeployedAccount", node.account.accountAddress);
logger.log(`${node.account.accountAddress} selected`);
await deployAccount(context, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => {
vscode.env.clipboard.writeText(node.account.accountAddress);
}),
vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => {
await deleteAccount(context, node);
accountTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => {
await editContractAddress(node, context);
}),
vscode.commands.registerCommand("starkode.editInput", async (node: any) => {
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
await editInput(node, abiTreeDataProvider, selectedContract);
}),
vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => {
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
if (selectedContract === undefined) {
logger.log("No Contract selected");
return;
}
if (selectedContract.slice(0, -5) !== node.label) {
logger.log("Please select the contract first.");
} else {
if (isCairo1Contract(selectedContract)) {
await vscode.commands.executeCommand("starkode.declareContract");
} else {
await vscode.commands.executeCommand("starkode.deployContract");
}
}
}),
vscode.commands.registerCommand("starkode.selectnetwork", async () => {
await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.createaccount", async () => {
createOZAccount(context);
contractTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.unDeployedAccount", async () => {
selectNotDeployedAccount(context);
}),
vscode.commands.registerCommand("starkode.declareContract", async () => {
await declareContract(context);
}),
vscode.commands.registerCommand("starkode.deployaccount", async () => {
await deployAccount(context, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.selectaccount", async () => {
await selectDeployedAccount(context);
}),
vscode.commands.registerCommand("starkode.selectContract", async () => {
selectCompiledContract(context);
}),
vscode.commands.registerCommand("starkode.deployContract", async () => {
await deployContract(context);
}),
vscode.commands.registerCommand("starkode.callFunction", async () => {
await executeContractFunction(context);
}),
vscode.commands.registerCommand("starkode.callContract", async (node: any) => {
await executeContractFunctionFromTreeView(context, node.abi);
})
);
}
| src/extension.ts | 7finney-starkode-2fba517 | [
{
"filename": "src/utils/functions.ts",
"retrieved_chunk": " }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const fileName = file.substring(0, file.length - 5);\n if (!fs.existsSync(path.join(path_, \"starkode\", fileName))) {\n fs.mkdirSync(path.join(path_, \"starkode\", fileName),{recursive: true});\n }\n if (\n !fs.existsSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_abi.json`)\n )",
"score": 0.8123105764389038
},
{
"filename": "src/utils/functions.ts",
"retrieved_chunk": " if (\n !fs.existsSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_address.json`)\n )\n ) {\n fs.writeFileSync(\n path.join(path_, \"starkode\", fileName, `${fileName}_address.json`),\n JSON.stringify({\n name: fileName,\n address: \"\",",
"score": 0.7685415744781494
},
{
"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.7624504566192627
},
{
"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.7600658535957336
},
{
"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.749068021774292
}
] | typescript | vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => { |
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.899897038936615
},
{
"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.8561444282531738
},
{
"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.8537096381187439
},
{
"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.84832763671875
},
{
"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.8481196761131287
}
] | 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/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.7916883826255798
},
{
"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.7660318613052368
},
{
"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.7636311054229736
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;\n const compiledCairoContract = fs\n .readdirSync(path_)\n .filter((file) => exportPathOfJSONfiles(path_, file));\n return compiledCairoContract;\n};",
"score": 0.7561012506484985
},
{
"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.752987802028656
}
] | typescript | contractTreeView = await refreshContract(node, contractTreeDataProvider); |
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.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.7951894998550415
},
{
"filename": "src/config/account.ts",
"retrieved_chunk": " constructorCalldata: selectedAccount.constructorCallData,\n addressSalt: selectedAccount.accountPubKey,\n });\n logger.log(`Transaction hash: ${transaction_hash}`);\n await provider.waitForTransaction(transaction_hash);\n await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount);\n logger.log(`Account deployed successfully at address: ${contract_address}`);\n accountTreeDataProvider.refresh();\n};\nconst updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => {",
"score": 0.7928184866905212
},
{
"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.7914129495620728
},
{
"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.7878105044364929
},
{
"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.785524845123291
}
] | typescript | updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider); |
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": " }\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.8755820989608765
},
{
"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.8531570434570312
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " if (testAbi === undefined) {\n throw new Error(\"no abi.\");\n }\n const myTestContract = new Contract(\n testAbi,\n deployResponse.contract_address,\n provider\n );\n await provider.waitForTransaction(myTestContract.transaction_hash);\n logger.log(`contract deployed successfully: ${myTestContract.address}`);",
"score": 0.844180166721344
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " logger.log(`calling function: ${functionABI.name}`);\n const account = new Account(\n provider,\n accountInfo.accountAddress,\n accountInfo.privateKey,\n \"0\"\n );\n const contract = new Contract(Abi, contractInfo.address, provider);\n contract.connect(account);\n const result = await contract.invoke(functionABI.name, params);",
"score": 0.8336770534515381
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " const contract = new Contract(Abi, contractInfo.address, provider);\n logger.log(`calling function: ${functionABI.name}`);\n const functionCall: any = await contract.call(`${functionABI.name}`);\n logger.log(`result: ${functionCall.res.toString()}`);\n } else {\n const Abi = getContractABI(path_, selectedContract).abi;\n logger.log(`calling function: ${functionABI.name}`);\n const account = new Account(\n provider,\n accountInfo.accountAddress,",
"score": 0.8200591802597046
}
] | 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": " 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.8680009245872498
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " }\n } catch (error) {\n logger.log(error);\n }\n};\nconst getSelectedFunction = (\n path_: string,\n selectedContract: string\n): Promise<ABIFragment> => {\n return new Promise((resolve, reject) => {",
"score": 0.8595542907714844
},
{
"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.8549822568893433
},
{
"filename": "src/config/account.ts",
"retrieved_chunk": " false\n );\n if (accounts === undefined || accounts.length === 0) {\n logger.log(`No undeployed account available on ${selectedNetwork}`);\n return;\n }\n return accounts;\n};\nexport const selectNotDeployedAccount = async (\n context: vscode.ExtensionContext",
"score": 0.8545309901237488
},
{
"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.8531363606452942
}
] | 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/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.8398128747940063
},
{
"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.8293089866638184
},
{
"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.8288347721099854
},
{
"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.8178211450576782
},
{
"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.8133703470230103
}
] | typescript | editInput(node, abiTreeDataProvider, selectedContract); |
import * as vscode from "vscode";
import * as fs from "fs";
import path from "path";
import {
createOZAccount,
deleteAccount,
deployAccount,
selectDeployedAccount,
selectNotDeployedAccount,
} from "./config/account";
import {
declareContract,
deployContract,
executeContractFunction,
executeContractFunctionFromTreeView,
getContractInfo,
isCairo1Contract,
loadAllCompiledContract,
selectCompiledContract,
setContract,
} from "./config/contract";
import { updateSelectedNetwork } from "./config/network";
import { logger } from "./lib";
import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider";
import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function";
import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider";
import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider";
import { editInput } from "./treeView/ABITreeView/functions";
import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider";
export function activate(context: vscode.ExtensionContext) {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`);
watcher.onDidChange((event: vscode.Uri) => {
const contractName: string | undefined = context.workspaceState.get("selectedContract");
if (contractName === undefined) {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
} else {
abiTreeView.message = undefined;
const contractInfo = getContractInfo(path_, contractName);
abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;
}
abiTreeDataProvider.refresh();
});
// Contract Tree View
const contractTreeDataProvider = new ContractTreeDataProvider(
vscode.workspace.workspaceFolders?.[0].uri.fsPath
);
let contractTreeView = vscode.window.createTreeView("starkode.contracts", {
treeDataProvider: contractTreeDataProvider,
});
// if contract tree view is empty
const contracts = loadAllCompiledContract();
if (contracts === undefined || contracts.length === 0) {
contractTreeView.message = "No contract found. Please compile your contract.";
}
contractTreeView.onDidChangeSelection(event => {
const selectedNodes = event.selection;
if (selectedNodes && selectedNodes.length > 0) {
| console.log('Selected nodes:', selectedNodes[0].label); |
}
});
// Account Tree View
const accountTreeDataProvider = new AccountTreeDataProvider(
context
);
const accountTreeView = vscode.window.createTreeView("starkode.account", {
treeDataProvider: accountTreeDataProvider,
});
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
const selectedAccount: string | undefined = context.workspaceState.get("account") as string;
accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it";
// ABI Tree View
const abiTreeDataProvider = new AbiTreeDataProvider(
context
);
const abiTreeView = vscode.window.createTreeView("starkode.abis", {
treeDataProvider: abiTreeDataProvider,
});
const contractName: string | undefined = context.workspaceState.get("selectedContract");
if (!contractName || contractName === undefined) {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
}
else {
const contractInfo = getContractInfo(path_, contractName);
if (contractInfo !== undefined) {
abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;
} else {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
}
}
context.subscriptions.push(
vscode.commands.registerCommand("starkode.activate", () => {
try {
if (!fs.existsSync(path.join(path_, "starkode"))) {
fs.mkdirSync(path.join(path_, "starkode"));
}
vscode.window.showInformationMessage("Starkode activated.");
} catch (error) {
console.log(error);
}
}),
vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => {
contractTreeView = await refreshContract(node, contractTreeDataProvider);
contractTreeView.message = undefined;
}),
vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => {
setContract(context, node.label);
abiTreeView.message = undefined;
const contractInfo = getContractInfo(path_, `${node.label}.json`);
if (contractInfo !== undefined) {
abiTreeView.description = `${node.label} @ ${contractInfo.address}`;
}
abiTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.useAccount", async (node: any) => {
console.log(node);
if (node.context === "deployedAccount") {
void context.workspaceState.update("account", node.account.accountAddress);
logger.log(`${node.account.accountAddress} selected`);
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount !== undefined) {
accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`;
}
abiTreeDataProvider.refresh();
} else {
vscode.window.showErrorMessage("Please deploy the account first.");
}
}),
vscode.commands.registerCommand("starkode.createAccountTreeView", async () => {
createOZAccount(context);
accountTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.selectNetwork", async () => {
await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => {
void context.workspaceState.update("undeployedAccount", node.account.accountAddress);
logger.log(`${node.account.accountAddress} selected`);
await deployAccount(context, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => {
vscode.env.clipboard.writeText(node.account.accountAddress);
}),
vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => {
await deleteAccount(context, node);
accountTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => {
await editContractAddress(node, context);
}),
vscode.commands.registerCommand("starkode.editInput", async (node: any) => {
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
await editInput(node, abiTreeDataProvider, selectedContract);
}),
vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => {
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
if (selectedContract === undefined) {
logger.log("No Contract selected");
return;
}
if (selectedContract.slice(0, -5) !== node.label) {
logger.log("Please select the contract first.");
} else {
if (isCairo1Contract(selectedContract)) {
await vscode.commands.executeCommand("starkode.declareContract");
} else {
await vscode.commands.executeCommand("starkode.deployContract");
}
}
}),
vscode.commands.registerCommand("starkode.selectnetwork", async () => {
await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.createaccount", async () => {
createOZAccount(context);
contractTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.unDeployedAccount", async () => {
selectNotDeployedAccount(context);
}),
vscode.commands.registerCommand("starkode.declareContract", async () => {
await declareContract(context);
}),
vscode.commands.registerCommand("starkode.deployaccount", async () => {
await deployAccount(context, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.selectaccount", async () => {
await selectDeployedAccount(context);
}),
vscode.commands.registerCommand("starkode.selectContract", async () => {
selectCompiledContract(context);
}),
vscode.commands.registerCommand("starkode.deployContract", async () => {
await deployContract(context);
}),
vscode.commands.registerCommand("starkode.callFunction", async () => {
await executeContractFunction(context);
}),
vscode.commands.registerCommand("starkode.callContract", async (node: any) => {
await executeContractFunctionFromTreeView(context, node.abi);
})
);
}
| src/extension.ts | 7finney-starkode-2fba517 | [
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " createAddressFile(`${label}.json`);\n};\nexport const selectCompiledContract = (context: vscode.ExtensionContext) => {\n const contracts = loadAllCompiledContract();\n if (contracts === undefined) {\n logger.log(\"No Contract available.\");\n return;\n }\n const quickPick = vscode.window.createQuickPick<IContractQP>();\n quickPick.items = contracts.map((contract: string) => ({",
"score": 0.8470491766929626
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " quickPick.onDidChangeActive(() => {\n quickPick.placeholder = \"Select Function\";\n });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n quickPick.dispose();\n const functionItem = contractInfo.filter(\n (i: ABIFragment) => i.name === label\n );",
"score": 0.8240619897842407
},
{
"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.8225065469741821
},
{
"filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts",
"retrieved_chunk": " vscode.window.showInformationMessage(\"No Contracts in workspace\");\n return [];\n } else {\n const leaves = [];\n for (const file of contracts) {\n leaves.push(new Contract(\n file.slice(0, -5),\n vscode.TreeItemCollapsibleState.None,\n \"contract\",\n isCairo1Contract(file) ? \"file-code\" : \"file-text\"",
"score": 0.8148965835571289
},
{
"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.7999349236488342
}
] | typescript | console.log('Selected nodes:', selectedNodes[0].label); |
import * as vscode from "vscode";
import * as fs from "fs";
import path, { resolve } from "path";
import { logger } from "../lib";
import { ABIFragment, IContractQP, IFunctionQP } from "../types";
import { createABIFile, createAddressFile } from "../utils/functions";
import { getAccountInfo } from "./account";
import { Account, CairoAssembly, Contract, ec, Provider } from "starknet";
import { getNetworkProvider } from "./network";
export const loadAllCompiledContract = () => {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const compiledCairoContract = fs
.readdirSync(path_)
.filter((file) => exportPathOfJSONfiles(path_, file));
return compiledCairoContract;
};
const exportPathOfJSONfiles = (path_: string, file: string) => {
const filePath = path.join(path_, file);
if (path.extname(filePath) === ".json") {
const fileData = fs.readFileSync(filePath, {
encoding: "utf-8",
});
if (JSON.parse(fileData).program) return filePath;
if (JSON.parse(fileData).contract_class_version) {
return filePath;
}
}
};
export const setContract = async (context: vscode.ExtensionContext, label: string) => {
if (label === undefined) {
// logger.log("No Contract selected.");
return;
}
void context.workspaceState.update("selectedContract", `${label}.json`);
logger.log(`${label} contract selected`);
createABIFile(`${label}.json`);
createAddressFile(`${label}.json`);
};
export const selectCompiledContract = (context: vscode.ExtensionContext) => {
const contracts = loadAllCompiledContract();
if (contracts === undefined) {
logger.log("No Contract available.");
return;
}
const quickPick = vscode.window.createQuickPick<IContractQP>();
quickPick.items = contracts.map((contract: string) => ({
label: contract.substring(0, contract.length - 5),
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select Contract";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
setContract(context, label);
quickPick.dispose();
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
};
export const getContractInfo = (path_: string, fileName: string) => {
try {
const file = fileName.substring(0, fileName.length - 5);
const fileData = fs.readFileSync(
path.join(path_, "starkode", file, `${file}_address.json`),
{ encoding: "utf-8" }
);
const parsedFileData = JSON.parse(fileData);
return parsedFileData;
} catch (error) {
// console.log(error);
return undefined;
}
};
export const getContractABI = (path_: string, fileName: string) => {
try {
const file = fileName.substring(0, fileName.length - 5);
const fileData = fs.readFileSync(
path.join(path_, "starkode", file, `${file}_abi.json`),
{ encoding: "utf-8" }
);
const parsedFileData = JSON.parse(fileData);
return parsedFileData;
} catch (error) {
// console.log(error);
return undefined;
}
};
export const isCairo1Contract = (fileName: string): boolean => {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return false;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const fileData = fs.readFileSync(
path.join(path_, fileName),
{ encoding: "utf-8" }
);
return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false;
};
export const declareContract = async (context: vscode.ExtensionContext) => {
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const fileName = selectedContract.substring(0, selectedContract.length - 5);
if (
!fs.existsSync(path.join(path_, selectedContract)) ||
!fs.existsSync(path.join(path_, `${fileName}.casm`))
) {
logger.log(`${fileName}.json or ${fileName}.casm must be present.`);
return;
}
const compiledContract = fs.readFileSync(
path.join(path_, selectedContract),
{
encoding: "ascii",
}
);
const casmFileData = fs
.readFileSync(path.join(path_, `${fileName}.casm`))
.toString("ascii");
const casmAssembly: CairoAssembly = JSON.parse(casmFileData);
logger.log("Declaring contract...");
const declareResponse = await account.declareAndDeploy({
contract: compiledContract,
casm: casmAssembly,
});
logger.log(
`declare transaction hash: ${declareResponse.deploy.transaction_hash}`
);
logger.log(`declare classHash: ${declareResponse.deploy.classHash}`);
logger.log("transaction successful");
} catch (error) {
logger.log(`Error while contract declaration: ${error}`);
}
};
export const deployContract = async (context: vscode.ExtensionContext) => {
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
logger.log("Deploying contract...");
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const contractInfo = getContractInfo(path_, selectedContract);
if (contractInfo.classHash === "") {
logger.log("No classHash available for selected contract.");
return;
}
const deployResponse = await account.deployContract({
classHash: contractInfo.classHash,
});
logger.log(`transaction hash: ${deployResponse.transaction_hash}`);
logger.log("waiting for transaction success...");
await provider.waitForTransaction(deployResponse.transaction_hash);
const { abi: testAbi } = await provider.getClassAt(
deployResponse.contract_address
);
if (testAbi === undefined) {
throw new Error("no abi.");
}
const myTestContract = new Contract(
testAbi,
deployResponse.contract_address,
provider
);
await provider.waitForTransaction(myTestContract.transaction_hash);
logger.log(`contract deployed successfully: ${myTestContract.address}`);
} catch (error) {
logger.log(`Error while contract deployment: ${error}`);
}
};
export const executeContractFunction = async (
context: vscode.ExtensionContext
) => {
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
const functionABI = await getSelectedFunction(path_, selectedContract);
const contractInfo = getContractInfo(path_, selectedContract);
const params_: Array<any> = functionABI.inputs.map((e) => {
return e.value;
});
const params: Array<any> = params_ !== undefined ? params_ : [];
if (
functionABI.stateMutability === "view" ||
functionABI.state_mutability === "view"
) {
const Abi = getContractABI(path_, selectedContract).abi;
const contract = new Contract(Abi, contractInfo.address, provider);
logger.log(`calling function: ${functionABI.name}`);
const functionCall: any = await contract.call(`${functionABI.name}`);
logger.log(`result: ${functionCall.res.toString()}`);
} else {
const Abi = getContractABI(path_, selectedContract).abi;
logger.log(`calling function: ${functionABI.name}`);
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const contract = new Contract(Abi, contractInfo.address, provider);
contract.connect(account);
const result = await contract.invoke(functionABI.name, params);
logger.log(`transaction hash: ${result.transaction_hash}`);
logger.log("waiting for transaction success...");
await provider.waitForTransaction(result.transaction_hash);
logger.log("transaction successfull");
}
} catch (error) {
logger.log(error);
}
};
export const executeContractFunctionFromTreeView = async (
context: vscode.ExtensionContext,
functionabi | : ABIFragment
) => { |
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
const functionABI = functionabi;
const contractInfo = getContractInfo(path_, selectedContract);
const params_: Array<any> = functionABI.inputs.map((e) => {
return e.value;
});
const params: Array<any> = params_ !== undefined ? params_ : [];
if (
functionABI.stateMutability === "view" ||
functionABI.state_mutability === "view"
) {
const Abi = getContractABI(path_, selectedContract).abi;
const contract = new Contract(Abi, contractInfo.address, provider);
logger.log(`calling function: ${functionABI.name}`);
const functionCall: any = await contract.call(`${functionABI.name}`);
logger.log(`result: ${functionCall.res.toString()}`);
} else {
const Abi = getContractABI(path_, selectedContract).abi;
logger.log(`calling function: ${functionABI.name}`);
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const contract = new Contract(Abi, contractInfo.address, provider);
contract.connect(account);
const result = await contract.invoke(functionABI.name, params);
logger.log(`transaction hash: ${result.transaction_hash}`);
logger.log("waiting for transaction success...");
await provider.waitForTransaction(result.transaction_hash);
logger.log("transaction successfull");
}
} catch (error) {
logger.log(error);
}
};
const getSelectedFunction = (
path_: string,
selectedContract: string
): Promise<ABIFragment> => {
return new Promise((resolve, reject) => {
try {
const contractInfo: Array<ABIFragment> = getContractABI(
path_,
selectedContract
).abi;
if (contractInfo === undefined) return;
const quickPick = vscode.window.createQuickPick<IFunctionQP>();
quickPick.items = contractInfo.map((account: ABIFragment) => ({
label: account.name,
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select Function";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
quickPick.dispose();
const functionItem = contractInfo.filter(
(i: ABIFragment) => i.name === label
);
if (functionItem.length === 0)
throw new Error("No function is selected");
resolve(functionItem[0]);
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
} catch (error) {
reject(error);
}
});
};
| src/config/contract.ts | 7finney-starkode-2fba517 | [
{
"filename": "src/config/account.ts",
"retrieved_chunk": " 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.8428522348403931
},
{
"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.8255652189254761
},
{
"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.8032211065292358
},
{
"filename": "src/config/network.ts",
"retrieved_chunk": " }\n });\n quickPick.onDidHide(() => {\n quickPick.dispose();\n });\n quickPick.show();\n};\nexport const getNetworkProvider = (\n context: vscode.ExtensionContext\n): Provider | undefined => {",
"score": 0.800276517868042
},
{
"filename": "src/config/account.ts",
"retrieved_chunk": " false\n );\n if (accounts === undefined || accounts.length === 0) {\n logger.log(`No undeployed account available on ${selectedNetwork}`);\n return;\n }\n return accounts;\n};\nexport const selectNotDeployedAccount = async (\n context: vscode.ExtensionContext",
"score": 0.7963124513626099
}
] | 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/account.ts",
"retrieved_chunk": " constructorCalldata: selectedAccount.constructorCallData,\n addressSalt: selectedAccount.accountPubKey,\n });\n logger.log(`Transaction hash: ${transaction_hash}`);\n await provider.waitForTransaction(transaction_hash);\n await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount);\n logger.log(`Account deployed successfully at address: ${contract_address}`);\n accountTreeDataProvider.refresh();\n};\nconst updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => {",
"score": 0.8105394840240479
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " const contract = new Contract(Abi, contractInfo.address, provider);\n logger.log(`calling function: ${functionABI.name}`);\n const functionCall: any = await contract.call(`${functionABI.name}`);\n logger.log(`result: ${functionCall.res.toString()}`);\n } else {\n const Abi = getContractABI(path_, selectedContract).abi;\n logger.log(`calling function: ${functionABI.name}`);\n const account = new Account(\n provider,\n accountInfo.accountAddress,",
"score": 0.8022803068161011
},
{
"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.7930382490158081
},
{
"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.7851297855377197
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " functionABI.stateMutability === \"view\" ||\n functionABI.state_mutability === \"view\"\n ) {\n const Abi = getContractABI(path_, selectedContract).abi;\n const contract = new Contract(Abi, contractInfo.address, provider);\n logger.log(`calling function: ${functionABI.name}`);\n const functionCall: any = await contract.call(`${functionABI.name}`);\n logger.log(`result: ${functionCall.res.toString()}`);\n } else {\n const Abi = getContractABI(path_, selectedContract).abi;",
"score": 0.7823446989059448
}
] | typescript | contractTreeDataProvider = new ContractTreeDataProvider(
vscode.workspace.workspaceFolders?.[0].uri.fsPath
); |
import * as vscode from "vscode";
import * as fs from "fs";
import path, { resolve } from "path";
import { logger } from "../lib";
import { ABIFragment, IContractQP, IFunctionQP } from "../types";
import { createABIFile, createAddressFile } from "../utils/functions";
import { getAccountInfo } from "./account";
import { Account, CairoAssembly, Contract, ec, Provider } from "starknet";
import { getNetworkProvider } from "./network";
export const loadAllCompiledContract = () => {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const compiledCairoContract = fs
.readdirSync(path_)
.filter((file) => exportPathOfJSONfiles(path_, file));
return compiledCairoContract;
};
const exportPathOfJSONfiles = (path_: string, file: string) => {
const filePath = path.join(path_, file);
if (path.extname(filePath) === ".json") {
const fileData = fs.readFileSync(filePath, {
encoding: "utf-8",
});
if (JSON.parse(fileData).program) return filePath;
if (JSON.parse(fileData).contract_class_version) {
return filePath;
}
}
};
export const setContract = async (context: vscode.ExtensionContext, label: string) => {
if (label === undefined) {
// logger.log("No Contract selected.");
return;
}
void context.workspaceState.update("selectedContract", `${label}.json`);
logger.log(`${label} contract selected`);
createABIFile(`${label}.json`);
createAddressFile(`${label}.json`);
};
export const selectCompiledContract = (context: vscode.ExtensionContext) => {
const contracts = loadAllCompiledContract();
if (contracts === undefined) {
logger.log("No Contract available.");
return;
}
const quickPick = vscode.window.createQuickPick<IContractQP>();
quickPick.items = contracts.map((contract: string) => ({
label: contract.substring(0, contract.length - 5),
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select Contract";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
setContract(context, label);
quickPick.dispose();
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
};
export const getContractInfo = (path_: string, fileName: string) => {
try {
const file = fileName.substring(0, fileName.length - 5);
const fileData = fs.readFileSync(
path.join(path_, "starkode", file, `${file}_address.json`),
{ encoding: "utf-8" }
);
const parsedFileData = JSON.parse(fileData);
return parsedFileData;
} catch (error) {
// console.log(error);
return undefined;
}
};
export const getContractABI = (path_: string, fileName: string) => {
try {
const file = fileName.substring(0, fileName.length - 5);
const fileData = fs.readFileSync(
path.join(path_, "starkode", file, `${file}_abi.json`),
{ encoding: "utf-8" }
);
const parsedFileData = JSON.parse(fileData);
return parsedFileData;
} catch (error) {
// console.log(error);
return undefined;
}
};
export const isCairo1Contract = (fileName: string): boolean => {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return false;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const fileData = fs.readFileSync(
path.join(path_, fileName),
{ encoding: "utf-8" }
);
return JSON.parse(fileData).contract_class_version === "0.1.0" ? true : false;
};
export const declareContract = async (context: vscode.ExtensionContext) => {
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const fileName = selectedContract.substring(0, selectedContract.length - 5);
if (
!fs.existsSync(path.join(path_, selectedContract)) ||
!fs.existsSync(path.join(path_, `${fileName}.casm`))
) {
logger.log(`${fileName}.json or ${fileName}.casm must be present.`);
return;
}
const compiledContract = fs.readFileSync(
path.join(path_, selectedContract),
{
encoding: "ascii",
}
);
const casmFileData = fs
.readFileSync(path.join(path_, `${fileName}.casm`))
.toString("ascii");
const casmAssembly: CairoAssembly = JSON.parse(casmFileData);
logger.log("Declaring contract...");
const declareResponse = await account.declareAndDeploy({
contract: compiledContract,
casm: casmAssembly,
});
logger.log(
`declare transaction hash: ${declareResponse.deploy.transaction_hash}`
);
logger.log(`declare classHash: ${declareResponse.deploy.classHash}`);
logger.log("transaction successful");
} catch (error) {
logger.log(`Error while contract declaration: ${error}`);
}
};
export const deployContract = async (context: vscode.ExtensionContext) => {
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
logger.log("Deploying contract...");
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const contractInfo = getContractInfo(path_, selectedContract);
if (contractInfo.classHash === "") {
logger.log("No classHash available for selected contract.");
return;
}
const deployResponse = await account.deployContract({
classHash: contractInfo.classHash,
});
logger.log(`transaction hash: ${deployResponse.transaction_hash}`);
logger.log("waiting for transaction success...");
await provider.waitForTransaction(deployResponse.transaction_hash);
const { abi: testAbi } = await provider.getClassAt(
deployResponse.contract_address
);
if (testAbi === undefined) {
throw new Error("no abi.");
}
const myTestContract = new Contract(
testAbi,
deployResponse.contract_address,
provider
);
await provider.waitForTransaction(myTestContract.transaction_hash);
logger.log(`contract deployed successfully: ${myTestContract.address}`);
} catch (error) {
logger.log(`Error while contract deployment: ${error}`);
}
};
export const executeContractFunction = async (
context: vscode.ExtensionContext
) => {
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
const functionABI = await getSelectedFunction(path_, selectedContract);
const contractInfo = getContractInfo(path_, selectedContract);
const params_: Array<any> = | functionABI.inputs.map((e) => { |
return e.value;
});
const params: Array<any> = params_ !== undefined ? params_ : [];
if (
functionABI.stateMutability === "view" ||
functionABI.state_mutability === "view"
) {
const Abi = getContractABI(path_, selectedContract).abi;
const contract = new Contract(Abi, contractInfo.address, provider);
logger.log(`calling function: ${functionABI.name}`);
const functionCall: any = await contract.call(`${functionABI.name}`);
logger.log(`result: ${functionCall.res.toString()}`);
} else {
const Abi = getContractABI(path_, selectedContract).abi;
logger.log(`calling function: ${functionABI.name}`);
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const contract = new Contract(Abi, contractInfo.address, provider);
contract.connect(account);
const result = await contract.invoke(functionABI.name, params);
logger.log(`transaction hash: ${result.transaction_hash}`);
logger.log("waiting for transaction success...");
await provider.waitForTransaction(result.transaction_hash);
logger.log("transaction successfull");
}
} catch (error) {
logger.log(error);
}
};
export const executeContractFunctionFromTreeView = async (
context: vscode.ExtensionContext,
functionabi: ABIFragment
) => {
try {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const provider = getNetworkProvider(context) as Provider;
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount === undefined) {
logger.log("No account selected.");
return;
}
const accountInfo = getAccountInfo(context, selectedAccount);
const functionABI = functionabi;
const contractInfo = getContractInfo(path_, selectedContract);
const params_: Array<any> = functionABI.inputs.map((e) => {
return e.value;
});
const params: Array<any> = params_ !== undefined ? params_ : [];
if (
functionABI.stateMutability === "view" ||
functionABI.state_mutability === "view"
) {
const Abi = getContractABI(path_, selectedContract).abi;
const contract = new Contract(Abi, contractInfo.address, provider);
logger.log(`calling function: ${functionABI.name}`);
const functionCall: any = await contract.call(`${functionABI.name}`);
logger.log(`result: ${functionCall.res.toString()}`);
} else {
const Abi = getContractABI(path_, selectedContract).abi;
logger.log(`calling function: ${functionABI.name}`);
const account = new Account(
provider,
accountInfo.accountAddress,
accountInfo.privateKey,
"0"
);
const contract = new Contract(Abi, contractInfo.address, provider);
contract.connect(account);
const result = await contract.invoke(functionABI.name, params);
logger.log(`transaction hash: ${result.transaction_hash}`);
logger.log("waiting for transaction success...");
await provider.waitForTransaction(result.transaction_hash);
logger.log("transaction successfull");
}
} catch (error) {
logger.log(error);
}
};
const getSelectedFunction = (
path_: string,
selectedContract: string
): Promise<ABIFragment> => {
return new Promise((resolve, reject) => {
try {
const contractInfo: Array<ABIFragment> = getContractABI(
path_,
selectedContract
).abi;
if (contractInfo === undefined) return;
const quickPick = vscode.window.createQuickPick<IFunctionQP>();
quickPick.items = contractInfo.map((account: ABIFragment) => ({
label: account.name,
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select Function";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
quickPick.dispose();
const functionItem = contractInfo.filter(
(i: ABIFragment) => i.name === label
);
if (functionItem.length === 0)
throw new Error("No function is selected");
resolve(functionItem[0]);
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
} catch (error) {
reject(error);
}
});
};
| src/config/contract.ts | 7finney-starkode-2fba517 | [
{
"filename": "src/extension.ts",
"retrieved_chunk": " 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.8915322422981262
},
{
"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.8834569454193115
},
{
"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.8754735589027405
},
{
"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.8502358198165894
},
{
"filename": "src/config/account.ts",
"retrieved_chunk": " provider,\n selectedAccount.accountAddress,\n selectedAccount.privateKey,\n \"1\"\n );\n logger.log(\n `Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}`\n );\n const { contract_address, transaction_hash } = await account.deployAccount({\n classHash: selectedAccount.accountHash,",
"score": 0.8444135189056396
}
] | 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": " );\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.8594861030578613
},
{
"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.8314310312271118
},
{
"filename": "src/extension.ts",
"retrieved_chunk": " accountTreeDataProvider.refresh();\n }),\n vscode.commands.registerCommand(\"starkode.editContractAddress\", async (node: ContractTreeItem) => {\n await editContractAddress(node, context);\n }),\n vscode.commands.registerCommand(\"starkode.editInput\", async (node: any) => {\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n await editInput(node, abiTreeDataProvider, selectedContract);",
"score": 0.8241475820541382
},
{
"filename": "src/extension.ts",
"retrieved_chunk": " setContract(context, node.label);\n abiTreeView.message = undefined;\n const contractInfo = getContractInfo(path_, `${node.label}.json`);\n if (contractInfo !== undefined) {\n abiTreeView.description = `${node.label} @ ${contractInfo.address}`;\n }\n abiTreeDataProvider.refresh();\n }),\n vscode.commands.registerCommand(\"starkode.useAccount\", async (node: any) => {\n console.log(node);",
"score": 0.8225783109664917
},
{
"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.8201573491096497
}
] | 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/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.8875036239624023
},
{
"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.8861972689628601
},
{
"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.8810064792633057
},
{
"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.8806385397911072
},
{
"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.8684165477752686
}
] | 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": " }\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.8690088987350464
},
{
"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.861162006855011
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " if (testAbi === undefined) {\n throw new Error(\"no abi.\");\n }\n const myTestContract = new Contract(\n testAbi,\n deployResponse.contract_address,\n provider\n );\n await provider.waitForTransaction(myTestContract.transaction_hash);\n logger.log(`contract deployed successfully: ${myTestContract.address}`);",
"score": 0.8423271775245667
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " logger.log(`calling function: ${functionABI.name}`);\n const account = new Account(\n provider,\n accountInfo.accountAddress,\n accountInfo.privateKey,\n \"0\"\n );\n const contract = new Contract(Abi, contractInfo.address, provider);\n contract.connect(account);\n const result = await contract.invoke(functionABI.name, params);",
"score": 0.8396480083465576
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " return;\n }\n const accountInfo = getAccountInfo(context, selectedAccount);\n const functionABI = await getSelectedFunction(path_, selectedContract);\n 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 (",
"score": 0.8183732628822327
}
] | typescript | .constructorCallData,
addressSalt: selectedAccount.accountPubKey,
}); |
import * as vscode from "vscode";
import * as fs from "fs";
import {
Account,
ec,
json,
stark,
Provider,
hash,
CallData,
Signer,
} from "starknet";
import { logger } from "../lib";
import { IAccountQP, JSONAccountType } from "../types";
import { NETWORKS, getNetworkProvider } from "./network";
import { accountDeployStatus } from "../utils/functions";
export const createOZAccount = async (context: vscode.ExtensionContext) => {
try {
const privateKey = stark.randomAddress();
const publicKey = await new Signer(privateKey).getPubKey();
const OZaccountClassHash =
"0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb";
const OZaccountConstructorCallData = CallData.compile({
publicKey: publicKey,
});
const OZcontractAddress = hash.calculateContractAddressFromHash(
publicKey,
OZaccountClassHash,
OZaccountConstructorCallData,
0
);
if (fs.existsSync(`${context.extensionPath}/accounts.json`)) {
const filedata = fs.readFileSync(
`${context.extensionPath}/accounts.json`,
{
encoding: "utf-8",
}
);
const parsedFileData = JSON.parse(filedata);
const writeNewAccount: Array<JSONAccountType> = [
...parsedFileData,
{
accountHash: OZaccountClassHash,
constructorCallData: OZaccountConstructorCallData,
accountPubKey: publicKey,
accountAddress: OZcontractAddress,
privateKey: privateKey,
isDeployed: {
gAlpha: false,
gAlpha2: false,
mainnet: false,
},
},
];
fs.writeFileSync(
`${context.extensionPath}/accounts.json`,
JSON.stringify(writeNewAccount)
);
} else {
const writeNewAccount: Array<JSONAccountType> = [
{
accountHash: OZaccountClassHash,
constructorCallData: OZaccountConstructorCallData,
accountPubKey: publicKey,
accountAddress: OZcontractAddress,
privateKey: privateKey,
isDeployed: {
gAlpha: false,
gAlpha2: false,
mainnet: false,
},
},
];
fs.writeFileSync(
`${context.extensionPath}/accounts.json`,
JSON.stringify(writeNewAccount)
);
}
logger.log(`New account created: ${OZcontractAddress}`);
} catch (error) {
logger.error(`Error while creating new account: ${error}`);
}
};
export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => {
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
if (selectedNetwork === undefined) {
logger.log("Network not selected");
return;
}
if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) {
logger.log("No account exist.");
return;
}
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(
parsedFileData,
selectedNetwork,
false
);
if (accounts === undefined || accounts.length === 0) {
logger.log(`No undeployed account available on ${selectedNetwork}`);
return;
}
return accounts;
};
export const selectNotDeployedAccount = async (
context: vscode.ExtensionContext
) => {
const accounts: Array<JSONAccountType> | undefined =
await getNotDeployedAccounts(context);
if (accounts === undefined) return;
const quickPick = vscode.window.createQuickPick<IAccountQP>();
quickPick.items = accounts.map((account: JSONAccountType) => ({
| label: account.accountAddress,
})); |
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select account";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
void context.workspaceState.update("undeployedAccount", label);
logger.log(`${label} selected`);
quickPick.dispose();
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
};
export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => {
const presentAccounts: Array<JSONAccountType> | undefined =
await getNotDeployedAccounts(context);
const unDeployedAccount = await context.workspaceState.get(
"undeployedAccount"
);
if (presentAccounts === undefined) return;
const isAccountPresent: any = presentAccounts.filter(
(account) => account.accountAddress === unDeployedAccount
);
const selectedAccount: JSONAccountType = isAccountPresent[0];
const selectedNetwork = context.workspaceState.get("selectedNetwork");
const provider = getNetworkProvider(context);
console.log(`Account address: ${selectedAccount.accountAddress}`);
if (provider === undefined) return;
const account = new Account(
provider,
selectedAccount.accountAddress,
selectedAccount.privateKey,
"1"
);
logger.log(
`Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}`
);
const { contract_address, transaction_hash } = await account.deployAccount({
classHash: selectedAccount.accountHash,
constructorCalldata: selectedAccount.constructorCallData,
addressSalt: selectedAccount.accountPubKey,
});
logger.log(`Transaction hash: ${transaction_hash}`);
await provider.waitForTransaction(transaction_hash);
await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount);
logger.log(`Account deployed successfully at address: ${contract_address}`);
accountTreeDataProvider.refresh();
};
const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => {
const selectedNetwork = context.workspaceState.get("selectedNetwork");
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
const accounts = JSON.parse(data);
const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress);
if (indexToUpdate !== -1) {
accounts[indexToUpdate].isDeployed = {
gAlpha: selectedNetwork === NETWORKS[0] ? true : false,
gAlpha2: selectedNetwork === NETWORKS[1] ? true : false,
mainnet: selectedNetwork === NETWORKS[2] ? true : false,
};
fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('JSON file successfully updated.');
});
} else {
console.error('Element not found in JSON file.');
}
});
};
export const getDeployedAccounts = (context: vscode.ExtensionContext) => {
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
if (selectedNetwork === undefined){
// logger.log("Network not selected");
return;
}
if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) {
logger.log("No deployed account exist.");
return;
}
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(
parsedFileData,
selectedNetwork,
true
);
if (accounts === undefined || accounts.length === 0) {
logger.log(`No deployed account available on ${selectedNetwork}`);
return;
}
return accounts;
};
export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => {
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress);
fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2));
};
export const selectDeployedAccount = async (
context: vscode.ExtensionContext
) => {
const accounts: Array<JSONAccountType> | undefined =
await getDeployedAccounts(context);
if (accounts === undefined) return;
const quickPick = vscode.window.createQuickPick<IAccountQP>();
quickPick.items = accounts.map((account: JSONAccountType) => ({
label: account.accountAddress,
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select account";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
void context.workspaceState.update("account", label);
logger.log(`${label} selected`);
quickPick.dispose();
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
};
export const getAccountInfo = (
context: vscode.ExtensionContext,
accountAddress: string
) => {
const accounts = getDeployedAccounts(context) as JSONAccountType[];
const selectedAccountInfo = accounts.filter(
(account) => account.accountAddress === accountAddress
);
return selectedAccountInfo[0];
};
| src/config/account.ts | 7finney-starkode-2fba517 | [
{
"filename": "src/treeView/AccountTreeView/AccountTreeDataProvider.ts",
"retrieved_chunk": " return element;\n }\n async getChildren(element?: Account): Promise<Account[]> {\n const accounts: Array<JSONAccountType> | undefined = getDeployedAccounts(this.context);\n const undeployedAccounts: Array<JSONAccountType> | undefined = await getNotDeployedAccounts(this.context);\n if ((accounts === undefined && undeployedAccounts === undefined)){\n return [];\n } else {\n const leaves = [];\n if (accounts !== undefined) {",
"score": 0.8645382523536682
},
{
"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.857295572757721
},
{
"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.8381009697914124
},
{
"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.8337687253952026
},
{
"filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts",
"retrieved_chunk": " getTreeItem(element: Abi): TreeItem {\n return element;\n }\n async getChildren(element?: Abi): Promise<Abi[] | undefined> {\n const leaves: Abi[] = [];\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return undefined;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;",
"score": 0.8177029490470886
}
] | 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.9097781181335449
},
{
"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.9065490365028381
},
{
"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.8946267366409302
},
{
"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.8883395195007324
},
{
"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.8843104839324951
}
] | 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": " 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.8626773953437805
},
{
"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.8358665704727173
},
{
"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.8118207454681396
},
{
"filename": "src/config/network.ts",
"retrieved_chunk": " const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n let networkBaseUrl: string | undefined = undefined;\n switch (selectedNetwork) {\n case NETWORKS[0]: {\n networkBaseUrl = \"https://alpha4.starknet.io\";\n break;\n }\n case NETWORKS[1]: {\n networkBaseUrl = \"https://alpha4-2.starknet.io\";\n break;",
"score": 0.8101599216461182
},
{
"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.8045967817306519
}
] | typescript | gAlpha2: selectedNetwork === NETWORKS[1] ? true : false,
mainnet: selectedNetwork === NETWORKS[2] ? true : false,
}; |
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.8518587350845337
},
{
"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.8169037103652954
},
{
"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.7995120882987976
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " contract: compiledContract,\n casm: casmAssembly,\n });\n logger.log(\n `declare transaction hash: ${declareResponse.deploy.transaction_hash}`\n );\n logger.log(`declare classHash: ${declareResponse.deploy.classHash}`);\n logger.log(\"transaction successful\");\n } catch (error) {\n logger.log(`Error while contract declaration: ${error}`);",
"score": 0.776308536529541
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": "};\nexport const getContractABI = (path_: string, fileName: string) => {\n try {\n const file = fileName.substring(0, fileName.length - 5);\n const fileData = fs.readFileSync(\n path.join(path_, \"starkode\", file, `${file}_abi.json`),\n { encoding: \"utf-8\" }\n );\n const parsedFileData = JSON.parse(fileData);\n return parsedFileData;",
"score": 0.7594394683837891
}
] | typescript | logger.error(`Error while creating new account: ${error}`); |
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": " 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.8348192572593689
},
{
"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.834308385848999
},
{
"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.8289188146591187
},
{
"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.8221375942230225
},
{
"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.8188794255256653
}
] | typescript | await editInput(node, abiTreeDataProvider, selectedContract); |
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": " 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.8927214741706848
},
{
"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.8854321241378784
},
{
"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.8787941336631775
},
{
"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.8565034866333008
},
{
"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.835910439491272
}
] | typescript | const params_: Array<any> = functionABI.inputs.map((e) => { |
import * as vscode from "vscode";
import * as fs from "fs";
import {
Account,
ec,
json,
stark,
Provider,
hash,
CallData,
Signer,
} from "starknet";
import { logger } from "../lib";
import { IAccountQP, JSONAccountType } from "../types";
import { NETWORKS, getNetworkProvider } from "./network";
import { accountDeployStatus } from "../utils/functions";
export const createOZAccount = async (context: vscode.ExtensionContext) => {
try {
const privateKey = stark.randomAddress();
const publicKey = await new Signer(privateKey).getPubKey();
const OZaccountClassHash =
"0x06f3ec04229f8f9663ee7d5bb9d2e06f213ba8c20eb34c58c25a54ef8fc591cb";
const OZaccountConstructorCallData = CallData.compile({
publicKey: publicKey,
});
const OZcontractAddress = hash.calculateContractAddressFromHash(
publicKey,
OZaccountClassHash,
OZaccountConstructorCallData,
0
);
if (fs.existsSync(`${context.extensionPath}/accounts.json`)) {
const filedata = fs.readFileSync(
`${context.extensionPath}/accounts.json`,
{
encoding: "utf-8",
}
);
const parsedFileData = JSON.parse(filedata);
const writeNewAccount: Array<JSONAccountType> = [
...parsedFileData,
{
accountHash: OZaccountClassHash,
constructorCallData: OZaccountConstructorCallData,
accountPubKey: publicKey,
accountAddress: OZcontractAddress,
privateKey: privateKey,
isDeployed: {
gAlpha: false,
gAlpha2: false,
mainnet: false,
},
},
];
fs.writeFileSync(
`${context.extensionPath}/accounts.json`,
JSON.stringify(writeNewAccount)
);
} else {
const writeNewAccount: Array<JSONAccountType> = [
{
accountHash: OZaccountClassHash,
constructorCallData: OZaccountConstructorCallData,
accountPubKey: publicKey,
accountAddress: OZcontractAddress,
privateKey: privateKey,
isDeployed: {
gAlpha: false,
gAlpha2: false,
mainnet: false,
},
},
];
fs.writeFileSync(
`${context.extensionPath}/accounts.json`,
JSON.stringify(writeNewAccount)
);
}
logger.log(`New account created: ${OZcontractAddress}`);
} catch (error) {
logger.error(`Error while creating new account: ${error}`);
}
};
export const getNotDeployedAccounts = async (context: vscode.ExtensionContext) => {
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
if (selectedNetwork === undefined) {
logger.log("Network not selected");
return;
}
if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) {
logger.log("No account exist.");
return;
}
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(
parsedFileData,
selectedNetwork,
false
);
if (accounts === undefined || accounts.length === 0) {
logger.log(`No undeployed account available on ${selectedNetwork}`);
return;
}
return accounts;
};
export const selectNotDeployedAccount = async (
context: vscode.ExtensionContext
) => {
const accounts: Array<JSONAccountType> | undefined =
await getNotDeployedAccounts(context);
if (accounts === undefined) return;
const quickPick = vscode.window.createQuickPick<IAccountQP>();
quickPick.items = accounts.map((account: JSONAccountType) => ({
label: account.accountAddress,
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select account";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
void context.workspaceState.update("undeployedAccount", label);
logger.log(`${label} selected`);
quickPick.dispose();
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
};
export const deployAccount = async (context: vscode.ExtensionContext , accountTreeDataProvider: any) => {
const presentAccounts: Array<JSONAccountType> | undefined =
await getNotDeployedAccounts(context);
const unDeployedAccount = await context.workspaceState.get(
"undeployedAccount"
);
if (presentAccounts === undefined) return;
const isAccountPresent: any = presentAccounts.filter(
(account) => account.accountAddress === unDeployedAccount
);
const selectedAccount: JSONAccountType = isAccountPresent[0];
const selectedNetwork = context.workspaceState.get("selectedNetwork");
const provider = getNetworkProvider(context);
console.log(`Account address: ${selectedAccount.accountAddress}`);
if (provider === undefined) return;
const account = new Account(
provider,
selectedAccount.accountAddress,
selectedAccount.privateKey,
"1"
);
logger.log(
`Deploying account ${selectedAccount.accountAddress} on ${selectedNetwork}`
);
const { contract_address, transaction_hash } = await account.deployAccount({
classHash: selectedAccount.accountHash,
constructorCalldata: selectedAccount.constructorCallData,
addressSalt: selectedAccount.accountPubKey,
});
logger.log(`Transaction hash: ${transaction_hash}`);
await provider.waitForTransaction(transaction_hash);
await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount);
logger.log(`Account deployed successfully at address: ${contract_address}`);
accountTreeDataProvider.refresh();
};
const updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => {
const selectedNetwork = context.workspaceState.get("selectedNetwork");
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
const accounts = JSON.parse(data);
const indexToUpdate = accounts.findIndex((account: { accountAddress: string; }) => account.accountAddress === selectedAccount.accountAddress);
if (indexToUpdate !== -1) {
accounts[indexToUpdate].isDeployed = {
gAlpha: selectedNetwork === NETWORKS[0] ? true : false,
gAlpha2: selectedNetwork === NETWORKS[1] ? true : false,
mainnet: selectedNetwork | === NETWORKS[2] ? true : false,
}; |
fs.writeFile(path, JSON.stringify(accounts, null, 2), 'utf8', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('JSON file successfully updated.');
});
} else {
console.error('Element not found in JSON file.');
}
});
};
export const getDeployedAccounts = (context: vscode.ExtensionContext) => {
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
if (selectedNetwork === undefined){
// logger.log("Network not selected");
return;
}
if (!fs.existsSync(`${context.extensionPath}/accounts.json`)) {
logger.log("No deployed account exist.");
return;
}
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const accounts: Array<JSONAccountType> | undefined = accountDeployStatus(
parsedFileData,
selectedNetwork,
true
);
if (accounts === undefined || accounts.length === 0) {
logger.log(`No deployed account available on ${selectedNetwork}`);
return;
}
return accounts;
};
export const deleteAccount = async (context: vscode.ExtensionContext,node: any) => {
const fileData = fs.readFileSync(`${context.extensionPath}/accounts.json`, {
encoding: "utf-8",
});
const parsedFileData: Array<JSONAccountType> = JSON.parse(fileData);
const filteredData = parsedFileData.filter(obj => obj.accountAddress !== node.account.accountAddress);
fs.writeFileSync(`${context.extensionPath}/accounts.json`, JSON.stringify(filteredData, null, 2));
};
export const selectDeployedAccount = async (
context: vscode.ExtensionContext
) => {
const accounts: Array<JSONAccountType> | undefined =
await getDeployedAccounts(context);
if (accounts === undefined) return;
const quickPick = vscode.window.createQuickPick<IAccountQP>();
quickPick.items = accounts.map((account: JSONAccountType) => ({
label: account.accountAddress,
}));
quickPick.onDidChangeActive(() => {
quickPick.placeholder = "Select account";
});
quickPick.onDidChangeSelection((selection: any) => {
if (selection[0] != null) {
const { label } = selection[0];
void context.workspaceState.update("account", label);
logger.log(`${label} selected`);
quickPick.dispose();
}
});
quickPick.onDidHide(() => {
quickPick.dispose();
});
quickPick.show();
};
export const getAccountInfo = (
context: vscode.ExtensionContext,
accountAddress: string
) => {
const accounts = getDeployedAccounts(context) as JSONAccountType[];
const selectedAccountInfo = accounts.filter(
(account) => account.accountAddress === accountAddress
);
return selectedAccountInfo[0];
};
| src/config/account.ts | 7finney-starkode-2fba517 | [
{
"filename": "src/utils/functions.ts",
"retrieved_chunk": " result = accounts.filter((e) => e.isDeployed.gAlpha === status);\n break;\n }\n case networks[1]: {\n result = accounts.filter((e) => e.isDeployed.gAlpha2 === status);\n break;\n }\n case networks[2]: {\n result = accounts.filter((e) => e.isDeployed.mainnet === status);\n break;",
"score": 0.8615221381187439
},
{
"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.8363929986953735
},
{
"filename": "src/config/network.ts",
"retrieved_chunk": " const selectedNetwork: any = context.workspaceState.get(\"selectedNetwork\");\n let networkBaseUrl: string | undefined = undefined;\n switch (selectedNetwork) {\n case NETWORKS[0]: {\n networkBaseUrl = \"https://alpha4.starknet.io\";\n break;\n }\n case NETWORKS[1]: {\n networkBaseUrl = \"https://alpha4-2.starknet.io\";\n break;",
"score": 0.8111941814422607
},
{
"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.805507481098175
},
{
"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.8037378787994385
}
] | 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.8545132875442505
},
{
"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.8421032428741455
},
{
"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.8182795643806458
},
{
"filename": "src/extension.ts",
"retrieved_chunk": " accountTreeDataProvider.refresh();\n }),\n vscode.commands.registerCommand(\"starkode.editContractAddress\", async (node: ContractTreeItem) => {\n await editContractAddress(node, context);\n }),\n vscode.commands.registerCommand(\"starkode.editInput\", async (node: any) => {\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n await editInput(node, abiTreeDataProvider, selectedContract);",
"score": 0.8029943704605103
},
{
"filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts",
"retrieved_chunk": " getTreeItem(element: Abi): TreeItem {\n return element;\n }\n async getChildren(element?: Abi): Promise<Abi[] | undefined> {\n const leaves: Abi[] = [];\n if (vscode.workspace.workspaceFolders === undefined) {\n logger.error(\"Error: Please open your solidity project to vscode\");\n return undefined;\n }\n const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;",
"score": 0.7986981868743896
}
] | typescript | const quickPick = vscode.window.createQuickPick<IFunctionQP>(); |
import * as vscode from "vscode";
import * as fs from "fs";
import path from "path";
import {
createOZAccount,
deleteAccount,
deployAccount,
selectDeployedAccount,
selectNotDeployedAccount,
} from "./config/account";
import {
declareContract,
deployContract,
executeContractFunction,
executeContractFunctionFromTreeView,
getContractInfo,
isCairo1Contract,
loadAllCompiledContract,
selectCompiledContract,
setContract,
} from "./config/contract";
import { updateSelectedNetwork } from "./config/network";
import { logger } from "./lib";
import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider";
import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function";
import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider";
import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider";
import { editInput } from "./treeView/ABITreeView/functions";
import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider";
export function activate(context: vscode.ExtensionContext) {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`);
watcher.onDidChange((event: vscode.Uri) => {
const contractName: string | undefined = context.workspaceState.get("selectedContract");
if (contractName === undefined) {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
} else {
abiTreeView.message = undefined;
const contractInfo = getContractInfo(path_, contractName);
abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;
}
abiTreeDataProvider.refresh();
});
// Contract Tree View
const contractTreeDataProvider = new ContractTreeDataProvider(
vscode.workspace.workspaceFolders?.[0].uri.fsPath
);
let contractTreeView = vscode.window.createTreeView("starkode.contracts", {
treeDataProvider: contractTreeDataProvider,
});
// if contract tree view is empty
const contracts = loadAllCompiledContract();
if (contracts === undefined || contracts.length === 0) {
contractTreeView.message = "No contract found. Please compile your contract.";
}
contractTreeView.onDidChangeSelection(event => {
const selectedNodes = event.selection;
if (selectedNodes && selectedNodes.length > 0) {
console.log('Selected nodes:', selectedNodes[0].label);
}
});
// Account Tree View
const accountTreeDataProvider = new AccountTreeDataProvider(
context
);
const accountTreeView = vscode.window.createTreeView("starkode.account", {
treeDataProvider: accountTreeDataProvider,
});
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
const selectedAccount: string | undefined = context.workspaceState.get("account") as string;
accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it";
// ABI Tree View
const abiTreeDataProvider = new AbiTreeDataProvider(
context
);
const abiTreeView = vscode.window.createTreeView("starkode.abis", {
treeDataProvider: abiTreeDataProvider,
});
const contractName: string | undefined = context.workspaceState.get("selectedContract");
if (!contractName || contractName === undefined) {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
}
else {
const contractInfo = getContractInfo(path_, contractName);
if (contractInfo !== undefined) {
abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;
} else {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
}
}
context.subscriptions.push(
vscode.commands.registerCommand("starkode.activate", () => {
try {
if (!fs.existsSync(path.join(path_, "starkode"))) {
fs.mkdirSync(path.join(path_, "starkode"));
}
vscode.window.showInformationMessage("Starkode activated.");
} catch (error) {
console.log(error);
}
}),
vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => {
contractTreeView = await refreshContract(node, contractTreeDataProvider);
contractTreeView.message = undefined;
}),
vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => {
setContract(context, node.label);
abiTreeView.message = undefined;
const contractInfo = getContractInfo(path_, `${node.label}.json`);
if (contractInfo !== undefined) {
abiTreeView.description = `${node.label} @ ${contractInfo.address}`;
}
abiTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.useAccount", async (node: any) => {
console.log(node);
if (node.context === "deployedAccount") {
void context.workspaceState.update("account", node.account.accountAddress);
logger. | log(`${node.account.accountAddress} selected`); |
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount !== undefined) {
accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`;
}
abiTreeDataProvider.refresh();
} else {
vscode.window.showErrorMessage("Please deploy the account first.");
}
}),
vscode.commands.registerCommand("starkode.createAccountTreeView", async () => {
createOZAccount(context);
accountTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.selectNetwork", async () => {
await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => {
void context.workspaceState.update("undeployedAccount", node.account.accountAddress);
logger.log(`${node.account.accountAddress} selected`);
await deployAccount(context, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => {
vscode.env.clipboard.writeText(node.account.accountAddress);
}),
vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => {
await deleteAccount(context, node);
accountTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => {
await editContractAddress(node, context);
}),
vscode.commands.registerCommand("starkode.editInput", async (node: any) => {
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
await editInput(node, abiTreeDataProvider, selectedContract);
}),
vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => {
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
if (selectedContract === undefined) {
logger.log("No Contract selected");
return;
}
if (selectedContract.slice(0, -5) !== node.label) {
logger.log("Please select the contract first.");
} else {
if (isCairo1Contract(selectedContract)) {
await vscode.commands.executeCommand("starkode.declareContract");
} else {
await vscode.commands.executeCommand("starkode.deployContract");
}
}
}),
vscode.commands.registerCommand("starkode.selectnetwork", async () => {
await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.createaccount", async () => {
createOZAccount(context);
contractTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.unDeployedAccount", async () => {
selectNotDeployedAccount(context);
}),
vscode.commands.registerCommand("starkode.declareContract", async () => {
await declareContract(context);
}),
vscode.commands.registerCommand("starkode.deployaccount", async () => {
await deployAccount(context, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.selectaccount", async () => {
await selectDeployedAccount(context);
}),
vscode.commands.registerCommand("starkode.selectContract", async () => {
selectCompiledContract(context);
}),
vscode.commands.registerCommand("starkode.deployContract", async () => {
await deployContract(context);
}),
vscode.commands.registerCommand("starkode.callFunction", async () => {
await executeContractFunction(context);
}),
vscode.commands.registerCommand("starkode.callContract", async (node: any) => {
await executeContractFunctionFromTreeView(context, node.abi);
})
);
}
| src/extension.ts | 7finney-starkode-2fba517 | [
{
"filename": "src/config/account.ts",
"retrieved_chunk": " constructorCalldata: selectedAccount.constructorCallData,\n addressSalt: selectedAccount.accountPubKey,\n });\n logger.log(`Transaction hash: ${transaction_hash}`);\n await provider.waitForTransaction(transaction_hash);\n await updateAccountJSON( context, `${context.extensionPath}/accounts.json`, selectedAccount);\n logger.log(`Account deployed successfully at address: ${contract_address}`);\n accountTreeDataProvider.refresh();\n};\nconst updateAccountJSON = async ( context: vscode.ExtensionContext , path: string, selectedAccount:JSONAccountType ) => {",
"score": 0.8268827795982361
},
{
"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.8227620124816895
},
{
"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.8091458678245544
},
{
"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.8014883995056152
},
{
"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.7920929193496704
}
] | typescript | log(`${node.account.accountAddress} selected`); |
import * as vscode from "vscode";
import * as fs from "fs";
import path from "path";
import {
createOZAccount,
deleteAccount,
deployAccount,
selectDeployedAccount,
selectNotDeployedAccount,
} from "./config/account";
import {
declareContract,
deployContract,
executeContractFunction,
executeContractFunctionFromTreeView,
getContractInfo,
isCairo1Contract,
loadAllCompiledContract,
selectCompiledContract,
setContract,
} from "./config/contract";
import { updateSelectedNetwork } from "./config/network";
import { logger } from "./lib";
import { ContractTreeDataProvider } from "./treeView/ContractTreeView/ContractTreeDataProvider";
import { editContractAddress, refreshContract } from "./treeView/ContractTreeView/function";
import { Contract as ContractTreeItem } from "./treeView/ContractTreeView/ContractTreeDataProvider";
import { AbiTreeDataProvider } from "./treeView/ABITreeView/AbiTreeDataProvider";
import { editInput } from "./treeView/ABITreeView/functions";
import { AccountTreeDataProvider } from "./treeView/AccountTreeView/AccountTreeDataProvider";
export function activate(context: vscode.ExtensionContext) {
if (vscode.workspace.workspaceFolders === undefined) {
logger.error("Error: Please open your solidity project to vscode");
return;
}
const path_ = vscode.workspace.workspaceFolders[0].uri.fsPath;
const watcher = vscode.workspace.createFileSystemWatcher(`${path_}/starkode/**`);
watcher.onDidChange((event: vscode.Uri) => {
const contractName: string | undefined = context.workspaceState.get("selectedContract");
if (contractName === undefined) {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
} else {
abiTreeView.message = undefined;
const contractInfo = getContractInfo(path_, contractName);
abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;
}
abiTreeDataProvider.refresh();
});
// Contract Tree View
const contractTreeDataProvider = new ContractTreeDataProvider(
vscode.workspace.workspaceFolders?.[0].uri.fsPath
);
let contractTreeView = vscode.window.createTreeView("starkode.contracts", {
treeDataProvider: contractTreeDataProvider,
});
// if contract tree view is empty
const contracts = loadAllCompiledContract();
if (contracts === undefined || contracts.length === 0) {
contractTreeView.message = "No contract found. Please compile your contract.";
}
contractTreeView.onDidChangeSelection(event => {
const selectedNodes = event.selection;
if (selectedNodes && selectedNodes.length > 0) {
console | .log('Selected nodes:', selectedNodes[0].label); |
}
});
// Account Tree View
const accountTreeDataProvider = new AccountTreeDataProvider(
context
);
const accountTreeView = vscode.window.createTreeView("starkode.account", {
treeDataProvider: accountTreeDataProvider,
});
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
const selectedAccount: string | undefined = context.workspaceState.get("account") as string;
accountTreeView.message = selectedAccount ? `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}` : "Select a deployed account , or create an account and deploy it";
// ABI Tree View
const abiTreeDataProvider = new AbiTreeDataProvider(
context
);
const abiTreeView = vscode.window.createTreeView("starkode.abis", {
treeDataProvider: abiTreeDataProvider,
});
const contractName: string | undefined = context.workspaceState.get("selectedContract");
if (!contractName || contractName === undefined) {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
}
else {
const contractInfo = getContractInfo(path_, contractName);
if (contractInfo !== undefined) {
abiTreeView.description = `${contractName.slice(0, -5)} @ ${contractInfo.address}`;
} else {
abiTreeView.message = "Select a contract and its ABI functions will appear here.";
}
}
context.subscriptions.push(
vscode.commands.registerCommand("starkode.activate", () => {
try {
if (!fs.existsSync(path.join(path_, "starkode"))) {
fs.mkdirSync(path.join(path_, "starkode"));
}
vscode.window.showInformationMessage("Starkode activated.");
} catch (error) {
console.log(error);
}
}),
vscode.commands.registerCommand("starkode.refreshContracts", async (node: ContractTreeItem) => {
contractTreeView = await refreshContract(node, contractTreeDataProvider);
contractTreeView.message = undefined;
}),
vscode.commands.registerCommand("starkode.useContract", async (node: ContractTreeItem) => {
setContract(context, node.label);
abiTreeView.message = undefined;
const contractInfo = getContractInfo(path_, `${node.label}.json`);
if (contractInfo !== undefined) {
abiTreeView.description = `${node.label} @ ${contractInfo.address}`;
}
abiTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.useAccount", async (node: any) => {
console.log(node);
if (node.context === "deployedAccount") {
void context.workspaceState.update("account", node.account.accountAddress);
logger.log(`${node.account.accountAddress} selected`);
const selectedNetwork: any = context.workspaceState.get("selectedNetwork");
const selectedAccount = context.workspaceState.get("account") as string;
if (selectedAccount !== undefined) {
accountTreeView.message = `Account : ${selectedAccount.slice(0, 5) + "..." + selectedAccount.slice(-5)} | ${selectedNetwork}`;
}
abiTreeDataProvider.refresh();
} else {
vscode.window.showErrorMessage("Please deploy the account first.");
}
}),
vscode.commands.registerCommand("starkode.createAccountTreeView", async () => {
createOZAccount(context);
accountTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.selectNetwork", async () => {
await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.deployAccountTreeView", async (node: any) => {
void context.workspaceState.update("undeployedAccount", node.account.accountAddress);
logger.log(`${node.account.accountAddress} selected`);
await deployAccount(context, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.copyAccountAddress", async (node: any) => {
vscode.env.clipboard.writeText(node.account.accountAddress);
}),
vscode.commands.registerCommand("starkode.deleteAccount", async (node: any) => {
await deleteAccount(context, node);
accountTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.editContractAddress", async (node: ContractTreeItem) => {
await editContractAddress(node, context);
}),
vscode.commands.registerCommand("starkode.editInput", async (node: any) => {
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
await editInput(node, abiTreeDataProvider, selectedContract);
}),
vscode.commands.registerCommand("starkode.deploycontract", async (node: any) => {
const selectedContract: string = context.workspaceState.get(
"selectedContract"
) as string;
if (selectedContract === undefined) {
logger.log("No Contract selected");
return;
}
if (selectedContract.slice(0, -5) !== node.label) {
logger.log("Please select the contract first.");
} else {
if (isCairo1Contract(selectedContract)) {
await vscode.commands.executeCommand("starkode.declareContract");
} else {
await vscode.commands.executeCommand("starkode.deployContract");
}
}
}),
vscode.commands.registerCommand("starkode.selectnetwork", async () => {
await updateSelectedNetwork(context, accountTreeView, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.createaccount", async () => {
createOZAccount(context);
contractTreeDataProvider.refresh();
}),
vscode.commands.registerCommand("starkode.unDeployedAccount", async () => {
selectNotDeployedAccount(context);
}),
vscode.commands.registerCommand("starkode.declareContract", async () => {
await declareContract(context);
}),
vscode.commands.registerCommand("starkode.deployaccount", async () => {
await deployAccount(context, accountTreeDataProvider);
}),
vscode.commands.registerCommand("starkode.selectaccount", async () => {
await selectDeployedAccount(context);
}),
vscode.commands.registerCommand("starkode.selectContract", async () => {
selectCompiledContract(context);
}),
vscode.commands.registerCommand("starkode.deployContract", async () => {
await deployContract(context);
}),
vscode.commands.registerCommand("starkode.callFunction", async () => {
await executeContractFunction(context);
}),
vscode.commands.registerCommand("starkode.callContract", async (node: any) => {
await executeContractFunctionFromTreeView(context, node.abi);
})
);
}
| src/extension.ts | 7finney-starkode-2fba517 | [
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " createAddressFile(`${label}.json`);\n};\nexport const selectCompiledContract = (context: vscode.ExtensionContext) => {\n const contracts = loadAllCompiledContract();\n if (contracts === undefined) {\n logger.log(\"No Contract available.\");\n return;\n }\n const quickPick = vscode.window.createQuickPick<IContractQP>();\n quickPick.items = contracts.map((contract: string) => ({",
"score": 0.8503067493438721
},
{
"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.8260036706924438
},
{
"filename": "src/config/contract.ts",
"retrieved_chunk": " quickPick.onDidChangeActive(() => {\n quickPick.placeholder = \"Select Function\";\n });\n quickPick.onDidChangeSelection((selection: any) => {\n if (selection[0] != null) {\n const { label } = selection[0];\n quickPick.dispose();\n const functionItem = contractInfo.filter(\n (i: ABIFragment) => i.name === label\n );",
"score": 0.824486255645752
},
{
"filename": "src/treeView/ContractTreeView/ContractTreeDataProvider.ts",
"retrieved_chunk": " vscode.window.showInformationMessage(\"No Contracts in workspace\");\n return [];\n } else {\n const leaves = [];\n for (const file of contracts) {\n leaves.push(new Contract(\n file.slice(0, -5),\n vscode.TreeItemCollapsibleState.None,\n \"contract\",\n isCairo1Contract(file) ? \"file-code\" : \"file-text\"",
"score": 0.8135106563568115
},
{
"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.8010962009429932
}
] | typescript | .log('Selected nodes:', selectedNodes[0].label); |
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": " }\n } catch (error) {\n logger.log(error);\n }\n};\nconst getSelectedFunction = (\n path_: string,\n selectedContract: string\n): Promise<ABIFragment> => {\n return new Promise((resolve, reject) => {",
"score": 0.871172308921814
},
{
"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.8645359873771667
},
{
"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.8634569644927979
},
{
"filename": "src/config/account.ts",
"retrieved_chunk": " false\n );\n if (accounts === undefined || accounts.length === 0) {\n logger.log(`No undeployed account available on ${selectedNetwork}`);\n return;\n }\n return accounts;\n};\nexport const selectNotDeployedAccount = async (\n context: vscode.ExtensionContext",
"score": 0.85792475938797
},
{
"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.8572245240211487
}
] | 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": "\t\t\t() => this._value,\n\t\t\t( newValue: ValueType ) => this._onChange?.( newValue, this._parentForm )\n\t\t);\n\t}\n\tprivate get failedValidationResult() {\n\t\treturn this.validationResults.find( result => !result.isValid );\n\t}\n\tprivate get validationResults() {\n\t\treturn this._validators.map(\n\t\t\tvalidator => validator( this._value, this._parentForm, this.label )",
"score": 0.8170057535171509
},
{
"filename": "src/utils/FieldState/index.ts",
"retrieved_chunk": "\t\treturn this._parentForm;\n\t}\n\tsetValue( newValue: ValueType ) {\n\t\tthis._value = newValue;\n\t}\n\tsetIsDisabled( isDisabled: boolean ) {\n\t\tthis._isDisabled = isDisabled;\n\t}\n\tclear() {\n\t\tthis._value = this._defaultValue;",
"score": 0.7959339022636414
},
{
"filename": "src/utils/FieldState/index.ts",
"retrieved_chunk": "\t\tthis._isDisabled = disabled;\n\t\tmakeAutoObservable( this );\n\t\tthis.setUpOnChangeReaction();\n\t}\n\tget value() {\n\t\treturn this._value;\n\t}\n\tget isValid() {\n\t\treturn !this.failedValidationResult;\n\t}",
"score": 0.7892898917198181
},
{
"filename": "src/Input/index.ts",
"retrieved_chunk": "\t\treaction(\n\t\t\t() => this.isFocused,\n\t\t\t( isFocused ) => {\n\t\t\t\tconst callback = isFocused ? this.onFocus : this.onBlur;\n\t\t\t\tcallback?.( this.parentForm );\n\t\t\t}\n\t\t);\n\t}\n\tprotected get parentForm() {\n\t\treturn this._state.parentForm;",
"score": 0.782880425453186
},
{
"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.7813358306884766
}
] | typescript | <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": "\t\t\t() => this._value,\n\t\t\t( newValue: ValueType ) => this._onChange?.( newValue, this._parentForm )\n\t\t);\n\t}\n\tprivate get failedValidationResult() {\n\t\treturn this.validationResults.find( result => !result.isValid );\n\t}\n\tprivate get validationResults() {\n\t\treturn this._validators.map(\n\t\t\tvalidator => validator( this._value, this._parentForm, this.label )",
"score": 0.8135659694671631
},
{
"filename": "src/utils/FieldState/index.ts",
"retrieved_chunk": "\t\tthis._isDisabled = disabled;\n\t\tmakeAutoObservable( this );\n\t\tthis.setUpOnChangeReaction();\n\t}\n\tget value() {\n\t\treturn this._value;\n\t}\n\tget isValid() {\n\t\treturn !this.failedValidationResult;\n\t}",
"score": 0.7907769680023193
},
{
"filename": "src/utils/FieldState/index.ts",
"retrieved_chunk": "\t\treturn this._parentForm;\n\t}\n\tsetValue( newValue: ValueType ) {\n\t\tthis._value = newValue;\n\t}\n\tsetIsDisabled( isDisabled: boolean ) {\n\t\tthis._isDisabled = isDisabled;\n\t}\n\tclear() {\n\t\tthis._value = this._defaultValue;",
"score": 0.7891262769699097
},
{
"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.7820874452590942
},
{
"filename": "src/Input/index.ts",
"retrieved_chunk": "\t\treaction(\n\t\t\t() => this.isFocused,\n\t\t\t( isFocused ) => {\n\t\t\t\tconst callback = isFocused ? this.onFocus : this.onBlur;\n\t\t\t\tcallback?.( this.parentForm );\n\t\t\t}\n\t\t);\n\t}\n\tprotected get parentForm() {\n\t\treturn this._state.parentForm;",
"score": 0.7783221006393433
}
] | 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/utils/FieldState/index.ts",
"retrieved_chunk": "\t\t\t() => this._value,\n\t\t\t( newValue: ValueType ) => this._onChange?.( newValue, this._parentForm )\n\t\t);\n\t}\n\tprivate get failedValidationResult() {\n\t\treturn this.validationResults.find( result => !result.isValid );\n\t}\n\tprivate get validationResults() {\n\t\treturn this._validators.map(\n\t\t\tvalidator => validator( this._value, this._parentForm, this.label )",
"score": 0.8158053159713745
},
{
"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.8145670890808105
},
{
"filename": "src/utils/FieldState/index.ts",
"retrieved_chunk": "\t\tthis._isDisabled = disabled;\n\t\tmakeAutoObservable( this );\n\t\tthis.setUpOnChangeReaction();\n\t}\n\tget value() {\n\t\treturn this._value;\n\t}\n\tget isValid() {\n\t\treturn !this.failedValidationResult;\n\t}",
"score": 0.8059258460998535
},
{
"filename": "src/utils/FieldState/index.ts",
"retrieved_chunk": "\t\treturn this._parentForm;\n\t}\n\tsetValue( newValue: ValueType ) {\n\t\tthis._value = newValue;\n\t}\n\tsetIsDisabled( isDisabled: boolean ) {\n\t\tthis._isDisabled = isDisabled;\n\t}\n\tclear() {\n\t\tthis._value = this._defaultValue;",
"score": 0.7993214130401611
},
{
"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.7863527536392212
}
] | typescript | field<FieldType extends Field<ValueType<FieldType>> = Field<unknown>>( fieldKey: string ) { |
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.8636404871940613
},
{
"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.8481820821762085
},
{
"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.801438570022583
},
{
"filename": "src/extension.ts",
"retrieved_chunk": " accountTreeDataProvider.refresh();\n }),\n vscode.commands.registerCommand(\"starkode.editContractAddress\", async (node: ContractTreeItem) => {\n await editContractAddress(node, context);\n }),\n vscode.commands.registerCommand(\"starkode.editInput\", async (node: any) => {\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n await editInput(node, abiTreeDataProvider, selectedContract);",
"score": 0.7969236373901367
},
{
"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.7958394289016724
}
] | typescript | functionABI.state_mutability === "view"
) { |
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": " });\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.8229482173919678
},
{
"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.8215407729148865
},
{
"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.813811182975769
},
{
"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.8100177049636841
},
{
"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.8093958497047424
}
] | typescript | = new AccountTreeDataProvider(
context
); |
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/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.7784576416015625
},
{
"filename": "src/Field/index.ts",
"retrieved_chunk": "\tconstructor( {\n\t\thint = '',\n\t\t...fieldStateParams\n\t}: FieldParams<ValueType> ) {\n\t\tthis.hint = hint;\n\t\tthis._state = new FieldState( fieldStateParams );\n\t\tthis._presentedError = '';\n\t\tmakeObservable<Field<ValueType>, AnnotatedPrivateFieldProps>( this, {\n\t\t\t_state: observable,\n\t\t\t_presentedError: observable,",
"score": 0.7637044191360474
},
{
"filename": "src/multiSelect/index.ts",
"retrieved_chunk": "import ManualField from '../ManualField';\nimport type { FieldParams } from '../Field';\nimport type { WithOptionalDefaultValue } from '../utils/types';\nexport type MultiSelect<ValueType> = ManualField<ValueType[]>;\nexport type MultiSelectParams<ValueType> = WithOptionalDefaultValue<FieldParams<ValueType[]>>;\nexport default function multiSelect<ValueType = string>( params: MultiSelectParams<ValueType> ) {\n\treturn new ManualField<ValueType[]>( { defaultValue: [], ...params } );\n}",
"score": 0.7593530416488647
},
{
"filename": "src/select/index.ts",
"retrieved_chunk": "import ManualField from '../ManualField';\nimport type { FieldParams } from '../Field';\nimport type { WithOptionalDefaultValue } from '../utils/types';\nexport type Select<ValueType> = ManualField<ValueType | null>;\nexport type SelectParams<ValueType> = WithOptionalDefaultValue<FieldParams<ValueType | null>>;\nexport default function select<ValueType = string>( params: SelectParams<ValueType> ) {\n\treturn new ManualField<ValueType | null>( { defaultValue: null, ...params } );\n}",
"score": 0.7586353421211243
},
{
"filename": "src/validators/utils.ts",
"retrieved_chunk": "import { invalid, valid } from './results';\nimport type { FieldValidator, MakeValidatorParams } from './types';\nexport function makeValidator<ValueType>( {\n\tpredicate, message\n}: MakeValidatorParams<ValueType> ): FieldValidator<ValueType> {\n\treturn ( value, form, label ) => (\n\t\tpredicate( value, form )\n\t\t\t? valid()\n\t\t\t: invalid( message.replace( ':label', label || 'Field' ) )\n\t);",
"score": 0.7388471961021423
}
] | typescript | eachField( actionOnField: ( field: Field<unknown> ) => void ) { |
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.7882707118988037
},
{
"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.7768734693527222
},
{
"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.769878625869751
},
{
"filename": "src/treeView/ABITreeView/AbiTreeDataProvider.ts",
"retrieved_chunk": " new Abi(\n input.name,\n input,\n \"abiInput\",\n element,\n [],\n TreeItemCollapsibleState.None\n )\n );\n }",
"score": 0.7551898956298828
},
{
"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.7512328624725342
}
] | 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/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.8579375147819519
},
{
"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.8415169715881348
},
{
"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.8104543089866638
},
{
"filename": "src/extension.ts",
"retrieved_chunk": " setContract(context, node.label);\n abiTreeView.message = undefined;\n const contractInfo = getContractInfo(path_, `${node.label}.json`);\n if (contractInfo !== undefined) {\n abiTreeView.description = `${node.label} @ ${contractInfo.address}`;\n }\n abiTreeDataProvider.refresh();\n }),\n vscode.commands.registerCommand(\"starkode.useAccount\", async (node: any) => {\n console.log(node);",
"score": 0.8088049292564392
},
{
"filename": "src/extension.ts",
"retrieved_chunk": " accountTreeDataProvider.refresh();\n }),\n vscode.commands.registerCommand(\"starkode.editContractAddress\", async (node: ContractTreeItem) => {\n await editContractAddress(node, context);\n }),\n vscode.commands.registerCommand(\"starkode.editInput\", async (node: any) => {\n const selectedContract: string = context.workspaceState.get(\n \"selectedContract\"\n ) as string;\n await editInput(node, abiTreeDataProvider, selectedContract);",
"score": 0.8062110543251038
}
] | typescript | logger.log(`calling function: ${functionABI.name}`); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.