Compare commits

..

5 Commits

Author SHA1 Message Date
Shreerang Kale
d93afb564b Use deployer LRN instead of ID in rollback deployment
All checks were successful
Lint / lint (20.x) (pull_request) Successful in 2m6s
2025-02-07 10:31:51 +05:30
Shreerang Kale
285d0e86bf Add custom domain support for auctions flow 2025-02-06 10:01:39 +05:30
Shreerang Kale
13cc0f8b9b Add UI to show multiple domains 2025-02-06 10:01:39 +05:30
Shreerang Kale
93b74074a3 Handle auction deployment when changing to production 2025-02-06 10:01:39 +05:30
Shreerang Kale
b0d3c0593a Enable add domain button for auctions 2025-02-06 10:01:39 +05:30
49 changed files with 2040 additions and 1404 deletions

View File

@ -47,11 +47,11 @@ jobs:
cat > packages/deployer/config.yml <<EOF cat > packages/deployer/config.yml <<EOF
services: services:
registry: registry:
rpcEndpoint: https://laconicd-mainnet-1.laconic.com rpcEndpoint: https://laconicd-sapo.laconic.com
gqlEndpoint: https://laconicd-mainnet-1.laconic.com/api gqlEndpoint: https://laconicd-sapo.laconic.com/api
userKey: $REGISTRY_USER_KEY userKey: $REGISTRY_USER_KEY
bondId: $REGISTRY_BOND_ID bondId: $REGISTRY_BOND_ID
chainId: laconic-mainnet chainId: laconic-testnet-2
gasPrice: 0.001alnt gasPrice: 0.001alnt
EOF EOF

View File

@ -15,6 +15,8 @@ VITE_GITHUB_CLIENT_ID = 'LACONIC_HOSTED_CONFIG_github_clientid'
VITE_GITHUB_PWA_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_pwa_templaterepo' VITE_GITHUB_PWA_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_pwa_templaterepo'
VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_image_upload_templaterepo' VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_image_upload_templaterepo'
VITE_GITHUB_NEXT_APP_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_next_app_templaterepo' VITE_GITHUB_NEXT_APP_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_next_app_templaterepo'
VITE_WALLET_CONNECT_ID = 'LACONIC_HOSTED_CONFIG_wallet_connect_id'
VITE_LACONICD_CHAIN_ID = 'LACONIC_HOSTED_CONFIG_laconicd_chain_id'
VITE_WALLET_IFRAME_URL = 'LACONIC_HOSTED_CONFIG_wallet_iframe_url' VITE_WALLET_IFRAME_URL = 'LACONIC_HOSTED_CONFIG_wallet_iframe_url'
VITE_LIT_RELAY_API_KEY = 'LACONIC_HOSTED_CONFIG_lit_relay_api_key' VITE_LIT_RELAY_API_KEY = 'LACONIC_HOSTED_CONFIG_lit_relay_api_key'
VITE_BUGSNAG_API_KEY = 'LACONIC_HOSTED_CONFIG_bugsnag_api_key' VITE_BUGSNAG_API_KEY = 'LACONIC_HOSTED_CONFIG_bugsnag_api_key'

View File

@ -14,6 +14,5 @@
"prepare": "husky install", "prepare": "husky install",
"build": "lerna run build --stream", "build": "lerna run build --stream",
"lint": "lerna run lint --stream" "lint": "lerna run lint --stream"
}, }
"packageManager": "yarn@1.22.19+sha1.4ba7fc5c6e704fce2066ecbfb0b0d8976fe62447" }
}

View File

@ -5,7 +5,7 @@ import {
FindOneOptions, FindOneOptions,
FindOptionsWhere, FindOptionsWhere,
IsNull, IsNull,
Not, Not
} from 'typeorm'; } from 'typeorm';
import path from 'path'; import path from 'path';
import debug from 'debug'; import debug from 'debug';
@ -16,7 +16,7 @@ import { lowercase, numbers } from 'nanoid-dictionary';
import { DatabaseConfig } from './config'; import { DatabaseConfig } from './config';
import { User } from './entity/User'; import { User } from './entity/User';
import { Organization } from './entity/Organization'; import { Organization } from './entity/Organization';
import { AuctionStatus, Project } from './entity/Project'; import { Project } from './entity/Project';
import { Deployment, DeploymentStatus } from './entity/Deployment'; import { Deployment, DeploymentStatus } from './entity/Deployment';
import { ProjectMember } from './entity/ProjectMember'; import { ProjectMember } from './entity/ProjectMember';
import { EnvironmentVariable } from './entity/EnvironmentVariable'; import { EnvironmentVariable } from './entity/EnvironmentVariable';
@ -42,7 +42,7 @@ export class Database {
database: dbPath, database: dbPath,
entities: [path.join(__dirname, '/entity/*')], entities: [path.join(__dirname, '/entity/*')],
synchronize: true, synchronize: true,
logging: false, logging: false
}); });
} }
@ -54,24 +54,21 @@ export class Database {
// Load an organization if none exist // Load an organization if none exist
if (!organizations.length) { if (!organizations.length) {
const orgEntities = await getEntities( const orgEntities = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH));
path.resolve(__dirname, ORGANIZATION_DATA_PATH), organizations = await loadAndSaveData(Organization, this.dataSource, [orgEntities[0]]);
);
organizations = await loadAndSaveData(Organization, this.dataSource, [
orgEntities[0],
]);
} }
// Hotfix for updating old DB data // Hotfix for updating old DB data
if (organizations[0].slug === 'snowball-tools-1') { if (organizations[0].slug === 'snowball-tools-1') {
const [orgEntity] = await getEntities( const [orgEntity] = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH));
path.resolve(__dirname, ORGANIZATION_DATA_PATH),
);
await this.updateOrganization(organizations[0].id, { await this.updateOrganization(
slug: orgEntity.slug as string, organizations[0].id,
name: orgEntity.name as string, {
}); slug: orgEntity.slug as string,
name: orgEntity.name as string
}
)
} }
} }
@ -98,7 +95,7 @@ export class Database {
} }
async getOrganizations( async getOrganizations(
options: FindManyOptions<Organization>, options: FindManyOptions<Organization>
): Promise<Organization[]> { ): Promise<Organization[]> {
const organizationRepository = this.dataSource.getRepository(Organization); const organizationRepository = this.dataSource.getRepository(Organization);
const organizations = await organizationRepository.find(options); const organizations = await organizationRepository.find(options);
@ -107,7 +104,7 @@ export class Database {
} }
async getOrganization( async getOrganization(
options: FindOneOptions<Organization>, options: FindOneOptions<Organization>
): Promise<Organization | null> { ): Promise<Organization | null> {
const organizationRepository = this.dataSource.getRepository(Organization); const organizationRepository = this.dataSource.getRepository(Organization);
const organization = await organizationRepository.findOne(options); const organization = await organizationRepository.findOne(options);
@ -122,34 +119,25 @@ export class Database {
where: { where: {
userOrganizations: { userOrganizations: {
member: { member: {
id: userId, id: userId
}, }
}, }
}, }
}); });
return userOrgs; return userOrgs;
} }
async addUserOrganization( async addUserOrganization(data: DeepPartial<UserOrganization>): Promise<UserOrganization> {
data: DeepPartial<UserOrganization>, const userOrganizationRepository = this.dataSource.getRepository(UserOrganization);
): Promise<UserOrganization> {
const userOrganizationRepository =
this.dataSource.getRepository(UserOrganization);
const newUserOrganization = await userOrganizationRepository.save(data); const newUserOrganization = await userOrganizationRepository.save(data);
return newUserOrganization; return newUserOrganization;
} }
async updateOrganization( async updateOrganization(organizationId: string, data: DeepPartial<Organization>): Promise<boolean> {
organizationId: string,
data: DeepPartial<Organization>,
): Promise<boolean> {
const organizationRepository = this.dataSource.getRepository(Organization); const organizationRepository = this.dataSource.getRepository(Organization);
const updateResult = await organizationRepository.update( const updateResult = await organizationRepository.update({ id: organizationId }, data);
{ id: organizationId },
data,
);
assert(updateResult.affected); assert(updateResult.affected);
return updateResult.affected > 0; return updateResult.affected > 0;
@ -170,7 +158,7 @@ export class Database {
.leftJoinAndSelect( .leftJoinAndSelect(
'project.deployments', 'project.deployments',
'deployments', 'deployments',
'deployments.isCurrent = true AND deployments.isCanonical = true', 'deployments.isCurrent = true AND deployments.isCanonical = true'
) )
.leftJoinAndSelect('deployments.createdBy', 'user') .leftJoinAndSelect('deployments.createdBy', 'user')
.leftJoinAndSelect('deployments.deployer', 'deployer') .leftJoinAndSelect('deployments.deployer', 'deployer')
@ -178,7 +166,7 @@ export class Database {
.leftJoinAndSelect('project.deployers', 'deployers') .leftJoinAndSelect('project.deployers', 'deployers')
.leftJoinAndSelect('project.organization', 'organization') .leftJoinAndSelect('project.organization', 'organization')
.where('project.id = :projectId', { .where('project.id = :projectId', {
projectId, projectId
}) })
.getOne(); .getOne();
@ -186,28 +174,26 @@ export class Database {
} }
async allProjectsWithoutDeployments(): Promise<Project[]> { async allProjectsWithoutDeployments(): Promise<Project[]> {
// Fetch all projects with auction not completed and wihout any deployments
const allProjects = await this.getProjects({ const allProjects = await this.getProjects({
where: { where: {
auctionId: Not(IsNull()), auctionId: Not(IsNull()),
auctionStatus: Not(AuctionStatus.Completed),
}, },
relations: ['deployments'], relations: ['deployments'],
withDeleted: true, withDeleted: true,
}); });
const activeProjectsWithoutDeployments = allProjects.filter((project) => { const projects = allProjects.filter(project => {
if (project.deletedAt !== null) return false; if (project.deletedAt !== null) return false;
return project.deployments.length === 0; return project.deployments.length === 0;
}); });
return activeProjectsWithoutDeployments; return projects;
} }
async getProjectsInOrganization( async getProjectsInOrganization(
userId: string, userId: string,
organizationSlug: string, organizationSlug: string
): Promise<Project[]> { ): Promise<Project[]> {
const projectRepository = this.dataSource.getRepository(Project); const projectRepository = this.dataSource.getRepository(Project);
@ -216,7 +202,7 @@ export class Database {
.leftJoinAndSelect( .leftJoinAndSelect(
'project.deployments', 'project.deployments',
'deployments', 'deployments',
'deployments.isCurrent = true AND deployments.isCanonical = true', 'deployments.isCurrent = true AND deployments.isCanonical = true'
) )
.leftJoin('project.projectMembers', 'projectMembers') .leftJoin('project.projectMembers', 'projectMembers')
.leftJoin('project.organization', 'organization') .leftJoin('project.organization', 'organization')
@ -224,8 +210,8 @@ export class Database {
'(project.ownerId = :userId OR projectMembers.userId = :userId) AND organization.slug = :organizationSlug', '(project.ownerId = :userId OR projectMembers.userId = :userId) AND organization.slug = :organizationSlug',
{ {
userId, userId,
organizationSlug, organizationSlug
}, }
) )
.getMany(); .getMany();
@ -236,7 +222,7 @@ export class Database {
* Get deployments with specified filter * Get deployments with specified filter
*/ */
async getDeployments( async getDeployments(
options: FindManyOptions<Deployment>, options: FindManyOptions<Deployment>
): Promise<Deployment[]> { ): Promise<Deployment[]> {
const deploymentRepository = this.dataSource.getRepository(Deployment); const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployments = await deploymentRepository.find(options); const deployments = await deploymentRepository.find(options);
@ -253,18 +239,16 @@ export class Database {
}, },
where: { where: {
project: { project: {
id: projectId, id: projectId
}, }
}, },
order: { order: {
createdAt: 'DESC', createdAt: 'DESC'
}, }
}); });
} }
async getNonCanonicalDeploymentsByProjectId( async getNonCanonicalDeploymentsByProjectId(projectId: string): Promise<Deployment[]> {
projectId: string,
): Promise<Deployment[]> {
return this.getDeployments({ return this.getDeployments({
relations: { relations: {
project: true, project: true,
@ -273,18 +257,18 @@ export class Database {
}, },
where: { where: {
project: { project: {
id: projectId, id: projectId
}, },
isCanonical: false, isCanonical: false
}, },
order: { order: {
createdAt: 'DESC', createdAt: 'DESC'
}, }
}); });
} }
async getDeployment( async getDeployment(
options: FindOneOptions<Deployment>, options: FindOneOptions<Deployment>
): Promise<Deployment | null> { ): Promise<Deployment | null> {
const deploymentRepository = this.dataSource.getRepository(Deployment); const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployment = await deploymentRepository.findOne(options); const deployment = await deploymentRepository.findOne(options);
@ -306,7 +290,7 @@ export class Database {
const updatedData = { const updatedData = {
...data, ...data,
id, id
}; };
const deployment = await deploymentRepository.save(updatedData); const deployment = await deploymentRepository.save(updatedData);
@ -314,7 +298,7 @@ export class Database {
} }
async getProjectMembersByProjectId( async getProjectMembersByProjectId(
projectId: string, projectId: string
): Promise<ProjectMember[]> { ): Promise<ProjectMember[]> {
const projectMemberRepository = const projectMemberRepository =
this.dataSource.getRepository(ProjectMember); this.dataSource.getRepository(ProjectMember);
@ -322,13 +306,13 @@ export class Database {
const projectMembers = await projectMemberRepository.find({ const projectMembers = await projectMemberRepository.find({
relations: { relations: {
project: true, project: true,
member: true, member: true
}, },
where: { where: {
project: { project: {
id: projectId, id: projectId
}, }
}, }
}); });
return projectMembers; return projectMembers;
@ -336,7 +320,7 @@ export class Database {
async getEnvironmentVariablesByProjectId( async getEnvironmentVariablesByProjectId(
projectId: string, projectId: string,
filter?: FindOptionsWhere<EnvironmentVariable>, filter?: FindOptionsWhere<EnvironmentVariable>
): Promise<EnvironmentVariable[]> { ): Promise<EnvironmentVariable[]> {
const environmentVariableRepository = const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable); this.dataSource.getRepository(EnvironmentVariable);
@ -344,10 +328,10 @@ export class Database {
const environmentVariables = await environmentVariableRepository.find({ const environmentVariables = await environmentVariableRepository.find({
where: { where: {
project: { project: {
id: projectId, id: projectId
}, },
...filter, ...filter
}, }
}); });
return environmentVariables; return environmentVariables;
@ -358,7 +342,7 @@ export class Database {
this.dataSource.getRepository(ProjectMember); this.dataSource.getRepository(ProjectMember);
const deleteResult = await projectMemberRepository.delete({ const deleteResult = await projectMemberRepository.delete({
id: projectMemberId, id: projectMemberId
}); });
if (deleteResult.affected) { if (deleteResult.affected) {
@ -370,20 +354,20 @@ export class Database {
async updateProjectMemberById( async updateProjectMemberById(
projectMemberId: string, projectMemberId: string,
data: DeepPartial<ProjectMember>, data: DeepPartial<ProjectMember>
): Promise<boolean> { ): Promise<boolean> {
const projectMemberRepository = const projectMemberRepository =
this.dataSource.getRepository(ProjectMember); this.dataSource.getRepository(ProjectMember);
const updateResult = await projectMemberRepository.update( const updateResult = await projectMemberRepository.update(
{ id: projectMemberId }, { id: projectMemberId },
data, data
); );
return Boolean(updateResult.affected); return Boolean(updateResult.affected);
} }
async addProjectMember( async addProjectMember(
data: DeepPartial<ProjectMember>, data: DeepPartial<ProjectMember>
): Promise<ProjectMember> { ): Promise<ProjectMember> {
const projectMemberRepository = const projectMemberRepository =
this.dataSource.getRepository(ProjectMember); this.dataSource.getRepository(ProjectMember);
@ -393,7 +377,7 @@ export class Database {
} }
async addEnvironmentVariables( async addEnvironmentVariables(
data: DeepPartial<EnvironmentVariable>[], data: DeepPartial<EnvironmentVariable>[]
): Promise<EnvironmentVariable[]> { ): Promise<EnvironmentVariable[]> {
const environmentVariableRepository = const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable); this.dataSource.getRepository(EnvironmentVariable);
@ -405,25 +389,25 @@ export class Database {
async updateEnvironmentVariable( async updateEnvironmentVariable(
environmentVariableId: string, environmentVariableId: string,
data: DeepPartial<EnvironmentVariable>, data: DeepPartial<EnvironmentVariable>
): Promise<boolean> { ): Promise<boolean> {
const environmentVariableRepository = const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable); this.dataSource.getRepository(EnvironmentVariable);
const updateResult = await environmentVariableRepository.update( const updateResult = await environmentVariableRepository.update(
{ id: environmentVariableId }, { id: environmentVariableId },
data, data
); );
return Boolean(updateResult.affected); return Boolean(updateResult.affected);
} }
async deleteEnvironmentVariable( async deleteEnvironmentVariable(
environmentVariableId: string, environmentVariableId: string
): Promise<boolean> { ): Promise<boolean> {
const environmentVariableRepository = const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable); this.dataSource.getRepository(EnvironmentVariable);
const deleteResult = await environmentVariableRepository.delete({ const deleteResult = await environmentVariableRepository.delete({
id: environmentVariableId, id: environmentVariableId
}); });
if (deleteResult.affected) { if (deleteResult.affected) {
@ -440,13 +424,13 @@ export class Database {
const projectMemberWithProject = await projectMemberRepository.find({ const projectMemberWithProject = await projectMemberRepository.find({
relations: { relations: {
project: { project: {
owner: true, owner: true
}, },
member: true, member: true
}, },
where: { where: {
id: projectMemberId, id: projectMemberId
}, }
}); });
if (projectMemberWithProject.length === 0) { if (projectMemberWithProject.length === 0) {
@ -458,7 +442,7 @@ export class Database {
async getProjectsBySearchText( async getProjectsBySearchText(
userId: string, userId: string,
searchText: string, searchText: string
): Promise<Project[]> { ): Promise<Project[]> {
const projectRepository = this.dataSource.getRepository(Project); const projectRepository = this.dataSource.getRepository(Project);
@ -470,8 +454,8 @@ export class Database {
'(project.owner = :userId OR projectMembers.member.id = :userId) AND project.name LIKE :searchText', '(project.owner = :userId OR projectMembers.member.id = :userId) AND project.name LIKE :searchText',
{ {
userId, userId,
searchText: `%${searchText}%`, searchText: `%${searchText}%`
}, }
) )
.getMany(); .getMany();
@ -480,14 +464,14 @@ export class Database {
async updateDeploymentById( async updateDeploymentById(
deploymentId: string, deploymentId: string,
data: DeepPartial<Deployment>, data: DeepPartial<Deployment>
): Promise<boolean> { ): Promise<boolean> {
return this.updateDeployment({ id: deploymentId }, data); return this.updateDeployment({ id: deploymentId }, data);
} }
async updateDeployment( async updateDeployment(
criteria: FindOptionsWhere<Deployment>, criteria: FindOptionsWhere<Deployment>,
data: DeepPartial<Deployment>, data: DeepPartial<Deployment>
): Promise<boolean> { ): Promise<boolean> {
const deploymentRepository = this.dataSource.getRepository(Deployment); const deploymentRepository = this.dataSource.getRepository(Deployment);
const updateResult = await deploymentRepository.update(criteria, data); const updateResult = await deploymentRepository.update(criteria, data);
@ -497,7 +481,7 @@ export class Database {
async updateDeploymentsByProjectIds( async updateDeploymentsByProjectIds(
projectIds: string[], projectIds: string[],
data: DeepPartial<Deployment>, data: DeepPartial<Deployment>
): Promise<boolean> { ): Promise<boolean> {
const deploymentRepository = this.dataSource.getRepository(Deployment); const deploymentRepository = this.dataSource.getRepository(Deployment);
@ -515,8 +499,8 @@ export class Database {
const deploymentRepository = this.dataSource.getRepository(Deployment); const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployment = await deploymentRepository.findOneOrFail({ const deployment = await deploymentRepository.findOneOrFail({
where: { where: {
id: deploymentId, id: deploymentId
}, }
}); });
const deleteResult = await deploymentRepository.softRemove(deployment); const deleteResult = await deploymentRepository.softRemove(deployment);
@ -524,11 +508,7 @@ export class Database {
return Boolean(deleteResult); return Boolean(deleteResult);
} }
async addProject( async addProject(user: User, organizationId: string, data: DeepPartial<Project>): Promise<Project> {
user: User,
organizationId: string,
data: DeepPartial<Project>,
): Promise<Project> {
const projectRepository = this.dataSource.getRepository(Project); const projectRepository = this.dataSource.getRepository(Project);
// TODO: Check if organization exists // TODO: Check if organization exists
@ -541,7 +521,7 @@ export class Database {
newProject.owner = user; newProject.owner = user;
newProject.organization = Object.assign(new Organization(), { newProject.organization = Object.assign(new Organization(), {
id: organizationId, id: organizationId
}); });
return projectRepository.save(newProject); return projectRepository.save(newProject);
@ -555,12 +535,12 @@ export class Database {
async updateProjectById( async updateProjectById(
projectId: string, projectId: string,
data: DeepPartial<Project>, data: DeepPartial<Project>
): Promise<boolean> { ): Promise<boolean> {
const projectRepository = this.dataSource.getRepository(Project); const projectRepository = this.dataSource.getRepository(Project);
const updateResult = await projectRepository.update( const updateResult = await projectRepository.update(
{ id: projectId }, { id: projectId },
data, data
); );
return Boolean(updateResult.affected); return Boolean(updateResult.affected);
@ -570,11 +550,11 @@ export class Database {
const projectRepository = this.dataSource.getRepository(Project); const projectRepository = this.dataSource.getRepository(Project);
const project = await projectRepository.findOneOrFail({ const project = await projectRepository.findOneOrFail({
where: { where: {
id: projectId, id: projectId
}, },
relations: { relations: {
projectMembers: true, projectMembers: true
}, }
}); });
const deleteResult = await projectRepository.softRemove(project); const deleteResult = await projectRepository.softRemove(project);
@ -610,7 +590,7 @@ export class Database {
async updateDomainById( async updateDomainById(
domainId: string, domainId: string,
data: DeepPartial<Domain>, data: DeepPartial<Domain>
): Promise<boolean> { ): Promise<boolean> {
const domainRepository = this.dataSource.getRepository(Domain); const domainRepository = this.dataSource.getRepository(Domain);
const updateResult = await domainRepository.update({ id: domainId }, data); const updateResult = await domainRepository.update({ id: domainId }, data);
@ -620,37 +600,39 @@ export class Database {
async getDomainsByProjectId( async getDomainsByProjectId(
projectId: string, projectId: string,
filter?: FindOptionsWhere<Domain>, filter?: FindOptionsWhere<Domain>
): Promise<Domain[]> { ): Promise<Domain[]> {
const domainRepository = this.dataSource.getRepository(Domain); const domainRepository = this.dataSource.getRepository(Domain);
const domains = await domainRepository.find({ const domains = await domainRepository.find({
relations: { relations: {
redirectTo: true, redirectTo: true
}, },
where: { where: {
project: { project: {
id: projectId, id: projectId
}, },
...filter, ...filter
}, }
}); });
return domains; return domains;
} }
async getOldestDomainByProjectId(projectId: string): Promise<Domain | null> { async getOldestDomainByProjectId(
projectId: string,
): Promise<Domain | null> {
const domainRepository = this.dataSource.getRepository(Domain); const domainRepository = this.dataSource.getRepository(Domain);
const domain = await domainRepository.findOne({ const domain = await domainRepository.findOne({
where: { where: {
project: { project: {
id: projectId, id: projectId
}, },
}, },
order: { order: {
createdAt: 'ASC', createdAt: 'ASC'
}, }
}); });
return domain; return domain;
@ -669,8 +651,8 @@ export class Database {
status: DeploymentStatus.Ready, status: DeploymentStatus.Ready,
}, },
order: { order: {
createdAt: 'DESC', createdAt: 'DESC'
}, }
}); });
if (deployment === null) { if (deployment === null) {
@ -695,9 +677,7 @@ export class Database {
async getDeployerByLRN(deployerLrn: string): Promise<Deployer | null> { async getDeployerByLRN(deployerLrn: string): Promise<Deployer | null> {
const deployerRepository = this.dataSource.getRepository(Deployer); const deployerRepository = this.dataSource.getRepository(Deployer);
const deployer = await deployerRepository.findOne({ const deployer = await deployerRepository.findOne({ where: { deployerLrn } });
where: { deployerLrn },
});
return deployer; return deployer;
} }

View File

@ -9,7 +9,7 @@ import {
OneToMany, OneToMany,
DeleteDateColumn, DeleteDateColumn,
JoinTable, JoinTable,
ManyToMany, ManyToMany
} from 'typeorm'; } from 'typeorm';
import { User } from './User'; import { User } from './User';
@ -18,12 +18,6 @@ import { ProjectMember } from './ProjectMember';
import { Deployment } from './Deployment'; import { Deployment } from './Deployment';
import { Deployer } from './Deployer'; import { Deployer } from './Deployer';
export enum AuctionStatus {
Commit = 'commit',
Reveal = 'reveal',
Completed = 'completed',
}
@Entity() @Entity()
export class Project { export class Project {
@PrimaryGeneratedColumn('uuid') @PrimaryGeneratedColumn('uuid')
@ -55,23 +49,16 @@ export class Project {
@Column('text', { default: '' }) @Column('text', { default: '' })
description!: string; description!: string;
@Column('varchar', { nullable: true })
auctionId!: string | null;
// Tx hash for sending coins from snowball to deployer // Tx hash for sending coins from snowball to deployer
@Column('varchar', { nullable: true }) @Column('varchar', { nullable: true })
txHash!: string | null; txHash!: string | null;
@ManyToMany(() => Deployer, (deployer) => deployer.projects) @ManyToMany(() => Deployer, (deployer) => (deployer.projects))
@JoinTable() @JoinTable()
deployers!: Deployer[]; deployers!: Deployer[]
@Column('varchar', { nullable: true })
auctionId!: string | null;
@Column({
enum: AuctionStatus,
// TODO: Remove later after all projects auction status have been set
default: AuctionStatus.Completed,
})
auctionStatus!: AuctionStatus;
@Column('boolean', { default: false, nullable: true }) @Column('boolean', { default: false, nullable: true })
fundsReleased!: boolean; fundsReleased!: boolean;

View File

@ -6,13 +6,7 @@ import { inc as semverInc } from 'semver';
import { DeepPartial } from 'typeorm'; import { DeepPartial } from 'typeorm';
import * as openpgp from 'openpgp'; import * as openpgp from 'openpgp';
import { import { Account, DEFAULT_GAS_ESTIMATION_MULTIPLIER, Registry as LaconicRegistry, getGasPrice, parseGasAndFees } from '@cerc-io/registry-sdk';
Account,
DEFAULT_GAS_ESTIMATION_MULTIPLIER,
Registry as LaconicRegistry,
getGasPrice,
parseGasAndFees,
} from '@cerc-io/registry-sdk';
import { DeliverTxResponse, IndexedTx } from '@cosmjs/stargate'; import { DeliverTxResponse, IndexedTx } from '@cosmjs/stargate';
import { RegistryConfig } from './config'; import { RegistryConfig } from './config';
@ -20,30 +14,17 @@ import {
ApplicationRecord, ApplicationRecord,
Deployment, Deployment,
ApplicationDeploymentRequest, ApplicationDeploymentRequest,
ApplicationDeploymentRemovalRequest, ApplicationDeploymentRemovalRequest
} from './entity/Deployment'; } from './entity/Deployment';
import { import { AppDeploymentRecord, AppDeploymentRemovalRecord, AuctionParams, DeployerRecord, RegistryRecord } from './types';
AppDeploymentRecord, import { getConfig, getRepoDetails, registryTransactionWithRetry, sleep } from './utils';
AppDeploymentRemovalRecord,
AuctionParams,
DeployerRecord,
RegistryRecord,
} from './types';
import {
getConfig,
getRepoDetails,
registryTransactionWithRetry,
sleep,
} from './utils';
import { MsgCreateAuctionResponse } from '@cerc-io/registry-sdk/dist/proto/cerc/auction/v1/tx';
const log = debug('snowball:registry'); const log = debug('snowball:registry');
const APP_RECORD_TYPE = 'ApplicationRecord'; const APP_RECORD_TYPE = 'ApplicationRecord';
const APP_DEPLOYMENT_AUCTION_RECORD_TYPE = 'ApplicationDeploymentAuction'; const APP_DEPLOYMENT_AUCTION_RECORD_TYPE = 'ApplicationDeploymentAuction';
const APP_DEPLOYMENT_REQUEST_TYPE = 'ApplicationDeploymentRequest'; const APP_DEPLOYMENT_REQUEST_TYPE = 'ApplicationDeploymentRequest';
const APP_DEPLOYMENT_REMOVAL_REQUEST_TYPE = const APP_DEPLOYMENT_REMOVAL_REQUEST_TYPE = 'ApplicationDeploymentRemovalRequest';
'ApplicationDeploymentRemovalRequest';
const APP_DEPLOYMENT_RECORD_TYPE = 'ApplicationDeploymentRecord'; const APP_DEPLOYMENT_RECORD_TYPE = 'ApplicationDeploymentRecord';
const APP_DEPLOYMENT_REMOVAL_RECORD_TYPE = 'ApplicationDeploymentRemovalRecord'; const APP_DEPLOYMENT_REMOVAL_RECORD_TYPE = 'ApplicationDeploymentRemovalRecord';
const WEBAPP_DEPLOYER_RECORD_TYPE = 'WebappDeployer'; const WEBAPP_DEPLOYER_RECORD_TYPE = 'WebappDeployer';
@ -62,7 +43,7 @@ export class Registry {
this.registry = new LaconicRegistry( this.registry = new LaconicRegistry(
registryConfig.gqlEndpoint, registryConfig.gqlEndpoint,
registryConfig.restEndpoint, registryConfig.restEndpoint,
{ chainId: registryConfig.chainId, gasPrice }, { chainId: registryConfig.chainId, gasPrice }
); );
} }
@ -72,7 +53,7 @@ export class Registry {
commitHash, commitHash,
appType, appType,
}: { }: {
octokit: Octokit; octokit: Octokit
repository: string; repository: string;
commitHash: string; commitHash: string;
appType: string; appType: string;
@ -80,33 +61,29 @@ export class Registry {
applicationRecordId: string; applicationRecordId: string;
applicationRecordData: ApplicationRecord; applicationRecordData: ApplicationRecord;
}> { }> {
const { repo, repoUrl, packageJSON } = await getRepoDetails( const { repo, repoUrl, packageJSON } = await getRepoDetails(octokit, repository, commitHash)
octokit,
repository,
commitHash,
);
// Use registry-sdk to publish record // Use registry-sdk to publish record
// Reference: https://git.vdb.to/cerc-io/test-progressive-web-app/src/branch/main/scripts/publish-app-record.sh // Reference: https://git.vdb.to/cerc-io/test-progressive-web-app/src/branch/main/scripts/publish-app-record.sh
// Fetch previous records // Fetch previous records
const records = await this.registry.queryRecords( const records = await this.registry.queryRecords(
{ {
type: APP_RECORD_TYPE, type: APP_RECORD_TYPE,
name: packageJSON.name, name: packageJSON.name
}, },
true, true
); );
// Get next version of record // Get next version of record
const bondRecords = records.filter( const bondRecords = records.filter(
(record: any) => record.bondId === this.registryConfig.bondId, (record: any) => record.bondId === this.registryConfig.bondId
); );
const [latestBondRecord] = bondRecords.sort( const [latestBondRecord] = bondRecords.sort(
(a: any, b: any) => (a: any, b: any) =>
new Date(b.createTime).getTime() - new Date(a.createTime).getTime(), new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
); );
const nextVersion = semverInc( const nextVersion = semverInc(
latestBondRecord?.attributes.version ?? '0.0.0', latestBondRecord?.attributes.version ?? '0.0.0',
'patch', 'patch'
); );
assert(nextVersion, 'Application record version not valid'); assert(nextVersion, 'Application record version not valid');
@ -126,9 +103,9 @@ export class Registry {
author: author:
typeof packageJSON.author === 'object' typeof packageJSON.author === 'object'
? JSON.stringify(packageJSON.author) ? JSON.stringify(packageJSON.author)
: packageJSON.author, : packageJSON.author
}), }),
...(packageJSON.version && { app_version: packageJSON.version }), ...(packageJSON.version && { app_version: packageJSON.version })
}; };
const result = await this.publishRecord(applicationRecord); const result = await this.publishRecord(applicationRecord);
@ -140,9 +117,18 @@ export class Registry {
const lrn = this.getLrn(repo); const lrn = this.getLrn(repo);
log(`Setting name: ${lrn} for record ID: ${result.id}`); log(`Setting name: ${lrn} for record ID: ${result.id}`);
const fee = parseGasAndFees( const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
this.registryConfig.fee.gas,
this.registryConfig.fee.fees, await sleep(SLEEP_DURATION);
await registryTransactionWithRetry(() =>
this.registry.setName(
{
cid: result.id,
lrn
},
this.registryConfig.privateKey,
fee
)
); );
await sleep(SLEEP_DURATION); await sleep(SLEEP_DURATION);
@ -150,11 +136,11 @@ export class Registry {
this.registry.setName( this.registry.setName(
{ {
cid: result.id, cid: result.id,
lrn, lrn: `${lrn}@${applicationRecord.app_version}`
}, },
this.registryConfig.privateKey, this.registryConfig.privateKey,
fee, fee
), )
); );
await sleep(SLEEP_DURATION); await sleep(SLEEP_DURATION);
@ -162,28 +148,16 @@ export class Registry {
this.registry.setName( this.registry.setName(
{ {
cid: result.id, cid: result.id,
lrn: `${lrn}@${applicationRecord.app_version}`, lrn: `${lrn}@${applicationRecord.repository_ref}`
}, },
this.registryConfig.privateKey, this.registryConfig.privateKey,
fee, fee
), )
);
await sleep(SLEEP_DURATION);
await registryTransactionWithRetry(() =>
this.registry.setName(
{
cid: result.id,
lrn: `${lrn}@${applicationRecord.repository_ref}`,
},
this.registryConfig.privateKey,
fee,
),
); );
return { return {
applicationRecordId: result.id, applicationRecordId: result.id,
applicationRecordData: applicationRecord, applicationRecordData: applicationRecord
}; };
} }
@ -193,7 +167,7 @@ export class Registry {
auctionParams: AuctionParams, auctionParams: AuctionParams,
data: DeepPartial<Deployment>, data: DeepPartial<Deployment>,
): Promise<{ ): Promise<{
applicationDeploymentAuction: MsgCreateAuctionResponse['auction']; applicationDeploymentAuctionId: string;
}> { }> {
assert(data.project?.repository, 'Project repository not found'); assert(data.project?.repository, 'Project repository not found');
@ -208,11 +182,8 @@ export class Registry {
const config = await getConfig(); const config = await getConfig();
const auctionConfig = config.auction; const auctionConfig = config.auction;
const fee = parseGasAndFees( const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
this.registryConfig.fee.gas, const auctionResult = await registryTransactionWithRetry(() =>
this.registryConfig.fee.fees,
);
const auctionResult = (await registryTransactionWithRetry(() =>
this.registry.createProviderAuction( this.registry.createProviderAuction(
{ {
commitFee: auctionConfig.commitFee, commitFee: auctionConfig.commitFee,
@ -224,9 +195,9 @@ export class Registry {
numProviders: auctionParams.numProviders, numProviders: auctionParams.numProviders,
}, },
this.registryConfig.privateKey, this.registryConfig.privateKey,
fee, fee
), )
)) as MsgCreateAuctionResponse; );
if (!auctionResult.auction) { if (!auctionResult.auction) {
throw new Error('Error creating auction'); throw new Error('Error creating auction');
@ -246,22 +217,22 @@ export class Registry {
log('Application deployment auction data:', applicationDeploymentAuction); log('Application deployment auction data:', applicationDeploymentAuction);
return { return {
applicationDeploymentAuction: auctionResult.auction!, applicationDeploymentAuctionId: auctionResult.auction.id,
}; };
} }
async createApplicationDeploymentRequest(data: { async createApplicationDeploymentRequest(data: {
deployment: Deployment; deployment: Deployment,
appName: string; appName: string,
repository: string; repository: string,
auctionId?: string | null; auctionId?: string | null,
lrn: string; lrn: string,
apiUrl: string; apiUrl: string,
environmentVariables: { [key: string]: string }; environmentVariables: { [key: string]: string },
dns: string; dns: string,
requesterAddress: string; requesterAddress: string,
publicKey: string; publicKey: string,
payment?: string | null; payment?: string | null
}): Promise<{ }): Promise<{
applicationDeploymentRequestId: string; applicationDeploymentRequestId: string;
applicationDeploymentRequestData: ApplicationDeploymentRequest; applicationDeploymentRequestData: ApplicationDeploymentRequest;
@ -296,10 +267,10 @@ export class Registry {
config: JSON.stringify(hash ? { ref: hash } : {}), config: JSON.stringify(hash ? { ref: hash } : {}),
meta: JSON.stringify({ meta: JSON.stringify({
note: `Added by Snowball @ ${DateTime.utc().toFormat( note: `Added by Snowball @ ${DateTime.utc().toFormat(
"EEE LLL dd HH:mm:ss 'UTC' yyyy", "EEE LLL dd HH:mm:ss 'UTC' yyyy"
)}`, )}`,
repository: data.repository, repository: data.repository,
repository_ref: data.deployment.commitHash, repository_ref: data.deployment.commitHash
}), }),
deployer: data.lrn, deployer: data.lrn,
...(data.auctionId && { auction: data.auctionId }), ...(data.auctionId && { auction: data.auctionId }),
@ -315,12 +286,12 @@ export class Registry {
return { return {
applicationDeploymentRequestId: result.id, applicationDeploymentRequestId: result.id,
applicationDeploymentRequestData: applicationDeploymentRequest, applicationDeploymentRequestData: applicationDeploymentRequest
}; };
} }
async getAuctionWinningDeployerRecords( async getAuctionWinningDeployerRecords(
auctionId: string, auctionId: string
): Promise<DeployerRecord[]> { ): Promise<DeployerRecord[]> {
const records = await this.registry.getAuctionsByIds([auctionId]); const records = await this.registry.getAuctionsByIds([auctionId]);
const auctionResult = records[0]; const auctionResult = records[0];
@ -333,7 +304,7 @@ export class Registry {
paymentAddress: auctionWinner, paymentAddress: auctionWinner,
}); });
const newRecords = records.filter((record) => { const newRecords = records.filter(record => {
return record.names !== null && record.names.length > 0; return record.names !== null && record.names.length > 0;
}); });
@ -348,19 +319,18 @@ export class Registry {
return deployerRecords; return deployerRecords;
} }
async releaseDeployerFunds(auctionId: string): Promise<any> { async releaseDeployerFunds(
const fee = parseGasAndFees( auctionId: string
this.registryConfig.fee.gas, ): Promise<any> {
this.registryConfig.fee.fees, const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
);
const auction = await registryTransactionWithRetry(() => const auction = await registryTransactionWithRetry(() =>
this.registry.releaseFunds( this.registry.releaseFunds(
{ {
auctionId, auctionId
}, },
this.registryConfig.privateKey, this.registryConfig.privateKey,
fee, fee
), )
); );
return auction; return auction;
@ -370,54 +340,49 @@ export class Registry {
* Fetch ApplicationDeploymentRecords for deployments * Fetch ApplicationDeploymentRecords for deployments
*/ */
async getDeploymentRecords( async getDeploymentRecords(
deployments: Deployment[], deployments: Deployment[]
): Promise<AppDeploymentRecord[]> { ): Promise<AppDeploymentRecord[]> {
// Fetch ApplicationDeploymentRecords for corresponding ApplicationRecord set in deployments // Fetch ApplicationDeploymentRecords for corresponding ApplicationRecord set in deployments
// TODO: Implement Laconicd GQL query to filter records by multiple values for an attribute // TODO: Implement Laconicd GQL query to filter records by multiple values for an attribute
const records = await this.registry.queryRecords( const records = await this.registry.queryRecords(
{ {
type: APP_DEPLOYMENT_RECORD_TYPE, type: APP_DEPLOYMENT_RECORD_TYPE
}, },
true, true
); );
// Filter records with ApplicationDeploymentRequestId ID // Filter records with ApplicationDeploymentRequestId ID
return records.filter((record: AppDeploymentRecord) => return records.filter((record: AppDeploymentRecord) =>
deployments.some( deployments.some(
(deployment) => (deployment) =>
deployment.applicationDeploymentRequestId === deployment.applicationDeploymentRequestId === record.attributes.request
record.attributes.request, )
),
); );
} }
/** /**
* Fetch WebappDeployer Records by filter * Fetch WebappDeployer Records by filter
*/ */
async getDeployerRecordsByFilter(filter: { async getDeployerRecordsByFilter(filter: { [key: string]: any }): Promise<DeployerRecord[]> {
[key: string]: any;
}): Promise<DeployerRecord[]> {
return this.registry.queryRecords( return this.registry.queryRecords(
{ {
type: WEBAPP_DEPLOYER_RECORD_TYPE, type: WEBAPP_DEPLOYER_RECORD_TYPE,
...filter, ...filter
}, },
true, true
); );
} }
/** /**
* Fetch ApplicationDeploymentRecords by filter * Fetch ApplicationDeploymentRecords by filter
*/ */
async getDeploymentRecordsByFilter(filter: { async getDeploymentRecordsByFilter(filter: { [key: string]: any }): Promise<AppDeploymentRecord[]> {
[key: string]: any;
}): Promise<AppDeploymentRecord[]> {
return this.registry.queryRecords( return this.registry.queryRecords(
{ {
type: APP_DEPLOYMENT_RECORD_TYPE, type: APP_DEPLOYMENT_RECORD_TYPE,
...filter, ...filter
}, },
true, true
); );
} }
@ -425,31 +390,29 @@ export class Registry {
* Fetch ApplicationDeploymentRemovalRecords for deployments * Fetch ApplicationDeploymentRemovalRecords for deployments
*/ */
async getDeploymentRemovalRecords( async getDeploymentRemovalRecords(
deployments: Deployment[], deployments: Deployment[]
): Promise<AppDeploymentRemovalRecord[]> { ): Promise<AppDeploymentRemovalRecord[]> {
// Fetch ApplicationDeploymentRemovalRecords for corresponding ApplicationDeploymentRecord set in deployments // Fetch ApplicationDeploymentRemovalRecords for corresponding ApplicationDeploymentRecord set in deployments
const records = await this.registry.queryRecords( const records = await this.registry.queryRecords(
{ {
type: APP_DEPLOYMENT_REMOVAL_RECORD_TYPE, type: APP_DEPLOYMENT_REMOVAL_RECORD_TYPE
}, },
true, true
); );
// Filter records with ApplicationDeploymentRecord and ApplicationDeploymentRemovalRequest IDs // Filter records with ApplicationDeploymentRecord and ApplicationDeploymentRemovalRequest IDs
return records.filter((record: AppDeploymentRemovalRecord) => return records.filter((record: AppDeploymentRemovalRecord) =>
deployments.some( deployments.some(
(deployment) => (deployment) =>
deployment.applicationDeploymentRemovalRequestId === deployment.applicationDeploymentRemovalRequestId === record.attributes.request &&
record.attributes.request && deployment.applicationDeploymentRecordId === record.attributes.deployment
deployment.applicationDeploymentRecordId === )
record.attributes.deployment,
),
); );
} }
/** /**
* Fetch record by Id * Fetch record by Id
*/ */
async getRecordById(id: string): Promise<RegistryRecord | null> { async getRecordById(id: string): Promise<RegistryRecord | null> {
const [record] = await this.registry.getRecordsByIds([id]); const [record] = await this.registry.getRecordsByIds([id]);
return record ?? null; return record ?? null;
@ -477,18 +440,12 @@ export class Registry {
applicationDeploymentRemovalRequest, applicationDeploymentRemovalRequest,
); );
log( log(`Application deployment removal request record published: ${result.id}`);
`Application deployment removal request record published: ${result.id}`, log('Application deployment removal request data:', applicationDeploymentRemovalRequest);
);
log(
'Application deployment removal request data:',
applicationDeploymentRemovalRequest,
);
return { return {
applicationDeploymentRemovalRequestId: result.id, applicationDeploymentRemovalRequestId: result.id,
applicationDeploymentRemovalRequestData: applicationDeploymentRemovalRequestData: applicationDeploymentRemovalRequest
applicationDeploymentRemovalRequest,
}; };
} }
@ -500,11 +457,8 @@ export class Registry {
const auctions = await this.registry.getAuctionsByIds(auctionIds); const auctions = await this.registry.getAuctionsByIds(auctionIds);
const completedAuctions = auctions const completedAuctions = auctions
.filter( .filter((auction: { id: string, status: string }) => auction.status === 'completed')
(auction: { id: string; status: string }) => .map((auction: { id: string, status: string }) => auction.id);
auction.status === 'completed',
)
.map((auction: { id: string; status: string }) => auction.id);
return completedAuctions; return completedAuctions;
} }
@ -538,38 +492,27 @@ export class Registry {
return this.registry.getAuctionsByIds([auctionId]); return this.registry.getAuctionsByIds([auctionId]);
} }
async sendTokensToAccount( async sendTokensToAccount(receiverAddress: string, amount: string): Promise<DeliverTxResponse> {
receiverAddress: string, const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
amount: string,
): Promise<DeliverTxResponse> {
const fee = parseGasAndFees(
this.registryConfig.fee.gas,
this.registryConfig.fee.fees,
);
const account = await this.getAccount(); const account = await this.getAccount();
const laconicClient = await this.registry.getLaconicClient(account); const laconicClient = await this.registry.getLaconicClient(account);
const txResponse: DeliverTxResponse = await registryTransactionWithRetry( const txResponse: DeliverTxResponse =
() => await registryTransactionWithRetry(() =>
laconicClient.sendTokens( laconicClient.sendTokens(account.address, receiverAddress,
account.address,
receiverAddress,
[ [
{ {
denom: 'alnt', denom: 'alnt',
amount, amount
}, }
], ],
fee || DEFAULT_GAS_ESTIMATION_MULTIPLIER, fee || DEFAULT_GAS_ESTIMATION_MULTIPLIER)
), );
);
return txResponse; return txResponse;
} }
async getAccount(): Promise<Account> { async getAccount(): Promise<Account> {
const account = new Account( const account = new Account(Buffer.from(this.registryConfig.privateKey, 'hex'));
Buffer.from(this.registryConfig.privateKey, 'hex'),
);
await account.init(); await account.init();
return account; return account;

View File

@ -345,10 +345,11 @@ export const createResolvers = async (service: Service): Promise<any> => {
{ {
projectId, projectId,
deploymentId, deploymentId,
}: { deploymentId: string; projectId: string }, deployerLrn,
}: { deploymentId: string; projectId: string, deployerLrn: string },
) => { ) => {
try { try {
return await service.rollbackDeployment(projectId, deploymentId); return await service.rollbackDeployment(projectId, deploymentId, deployerLrn);
} catch (err) { } catch (err) {
log(err); log(err);
return false; return false;

View File

@ -94,4 +94,13 @@ router.get('/session', (req, res) => {
} }
}); });
router.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
return res.send({ success: false });
}
res.send({ success: true });
});
});
export default router; export default router;

View File

@ -111,6 +111,7 @@ type Deployment {
isCurrent: Boolean! isCurrent: Boolean!
baseDomain: String baseDomain: String
status: DeploymentStatus! status: DeploymentStatus!
dnsRecordData: DNSRecordAttributes
createdAt: String! createdAt: String!
updatedAt: String! updatedAt: String!
createdBy: User! createdBy: User!

View File

@ -7,16 +7,11 @@ import { DateTime } from 'luxon';
import { OAuthApp } from '@octokit/oauth-app'; import { OAuthApp } from '@octokit/oauth-app';
import { Database } from './database'; import { Database } from './database';
import { import { ApplicationRecord, Deployment, DeploymentStatus, Environment } from './entity/Deployment';
ApplicationRecord,
Deployment,
DeploymentStatus,
Environment,
} from './entity/Deployment';
import { Domain } from './entity/Domain'; import { Domain } from './entity/Domain';
import { EnvironmentVariable } from './entity/EnvironmentVariable'; import { EnvironmentVariable } from './entity/EnvironmentVariable';
import { Organization } from './entity/Organization'; import { Organization } from './entity/Organization';
import { AuctionStatus, Project } from './entity/Project'; import { Project } from './entity/Project';
import { Permission, ProjectMember } from './entity/ProjectMember'; import { Permission, ProjectMember } from './entity/ProjectMember';
import { User } from './entity/User'; import { User } from './entity/User';
import { Registry } from './registry'; import { Registry } from './registry';
@ -124,8 +119,7 @@ export class Service {
} }
// Fetch ApplicationDeploymentRecord for deployments // Fetch ApplicationDeploymentRecord for deployments
const records = const records = await this.laconicRegistry.getDeploymentRecords(deployments);
await this.laconicRegistry.getDeploymentRecords(deployments);
log(`Found ${records.length} ApplicationDeploymentRecords`); log(`Found ${records.length} ApplicationDeploymentRecords`);
// Update deployments for which ApplicationDeploymentRecords were returned // Update deployments for which ApplicationDeploymentRecords were returned
@ -210,9 +204,7 @@ export class Service {
return; return;
} }
const registryRecord = await this.laconicRegistry.getRecordById( const registryRecord = await this.laconicRegistry.getRecordById(record.attributes.dns);
record.attributes.dns,
);
if (!registryRecord) { if (!registryRecord) {
log(`DNS record not found for deployment ${deployment.id}`); log(`DNS record not found for deployment ${deployment.id}`);
@ -227,7 +219,7 @@ export class Service {
resourceType: dnsRecord.attributes.resource_type, resourceType: dnsRecord.attributes.resource_type,
value: dnsRecord.attributes.value, value: dnsRecord.attributes.value,
version: dnsRecord.attributes.version, version: dnsRecord.attributes.version,
}; }
deployment.applicationDeploymentRecordId = record.id; deployment.applicationDeploymentRecordId = record.id;
deployment.applicationDeploymentRecordData = record.attributes; deployment.applicationDeploymentRecordData = record.attributes;
@ -247,21 +239,18 @@ export class Service {
relations: { relations: {
project: true, project: true,
deployer: true, deployer: true,
}, }
}); });
if (previousCanonicalDeployment) { if (previousCanonicalDeployment) {
// Send removal request for the previous canonical deployment and delete DB entry // Send removal request for the previous canonical deployment and delete DB entry
if (previousCanonicalDeployment.url !== deployment.url) { if (previousCanonicalDeployment.url !== deployment.url) {
await this.laconicRegistry.createApplicationDeploymentRemovalRequest( await this.laconicRegistry.createApplicationDeploymentRemovalRequest({
{ deploymentId: previousCanonicalDeployment.applicationDeploymentRecordId!,
deploymentId: deployerLrn: previousCanonicalDeployment.deployer.deployerLrn,
previousCanonicalDeployment.applicationDeploymentRecordId!, auctionId: previousCanonicalDeployment.project.auctionId,
deployerLrn: previousCanonicalDeployment.deployer.deployerLrn, payment: previousCanonicalDeployment.project.txHash
auctionId: previousCanonicalDeployment.project.auctionId, });
payment: previousCanonicalDeployment.project.txHash,
},
);
} }
await this.db.deleteDeploymentById(previousCanonicalDeployment.id); await this.db.deleteDeploymentById(previousCanonicalDeployment.id);
@ -272,9 +261,7 @@ export class Service {
// Release deployer funds on successful deployment // Release deployer funds on successful deployment
if (!deployment.project.fundsReleased) { if (!deployment.project.fundsReleased) {
const fundsReleased = await this.releaseDeployerFundsByProjectId( const fundsReleased = await this.releaseDeployerFundsByProjectId(deployment.projectId);
deployment.projectId,
);
// Return remaining amount to owner // Return remaining amount to owner
await this.returnUserFundsByProjectId(deployment.projectId, true); await this.returnUserFundsByProjectId(deployment.projectId, true);
@ -304,7 +291,7 @@ export class Service {
const oldDeployments = projectDeployments.filter( const oldDeployments = projectDeployments.filter(
(projectDeployment) => (projectDeployment) =>
projectDeployment.deployer.deployerLrn === projectDeployment.deployer.deployerLrn ===
deployment.deployer.deployerLrn && deployment.deployer.deployerLrn &&
projectDeployment.id !== deployment.id && projectDeployment.id !== deployment.id &&
projectDeployment.isCanonical == deployment.isCanonical, projectDeployment.isCanonical == deployment.isCanonical,
); );
@ -369,30 +356,24 @@ export class Service {
async checkAuctionStatus(): Promise<void> { async checkAuctionStatus(): Promise<void> {
const projects = await this.db.allProjectsWithoutDeployments(); const projects = await this.db.allProjectsWithoutDeployments();
const validAuctionIds = projects const validAuctionIds = projects.map((project) => project.auctionId)
.map((project) => project.auctionId)
.filter((id): id is string => Boolean(id)); .filter((id): id is string => Boolean(id));
const completedAuctionIds = const completedAuctionIds = await this.laconicRegistry.getCompletedAuctionIds(validAuctionIds);
await this.laconicRegistry.getCompletedAuctionIds(validAuctionIds);
const projectsToBedeployed = projects.filter((project) => const projectsToBedeployed = projects.filter((project) =>
completedAuctionIds.includes(project.auctionId!), completedAuctionIds.includes(project.auctionId!)
); );
for (const project of projectsToBedeployed) { for (const project of projectsToBedeployed) {
const deployerRecords = const deployerRecords = await this.laconicRegistry.getAuctionWinningDeployerRecords(project!.auctionId!);
await this.laconicRegistry.getAuctionWinningDeployerRecords(
project!.auctionId!,
);
if (!deployerRecords) { if (!deployerRecords) {
log(`No winning deployer for auction ${project!.auctionId}`); log(`No winning deployer for auction ${project!.auctionId}`);
// Return all funds to the owner // Return all funds to the owner
await this.returnUserFundsByProjectId(project.id, false); await this.returnUserFundsByProjectId(project.id, false)
} else { } else {
const deployers = const deployers = await this.saveDeployersByDeployerRecords(deployerRecords);
await this.saveDeployersByDeployerRecords(deployerRecords);
for (const deployer of deployers) { for (const deployer of deployers) {
log(`Creating deployment for deployer ${deployer.deployerLrn}`); log(`Creating deployment for deployer ${deployer.deployerLrn}`);
await this.createDeploymentFromAuction(project, deployer); await this.createDeploymentFromAuction(project, deployer);
@ -400,10 +381,6 @@ export class Service {
await this.updateProjectWithDeployer(project.id, deployer); await this.updateProjectWithDeployer(project.id, deployer);
} }
} }
await this.updateProject(project.id, {
auctionStatus: AuctionStatus.Completed,
});
} }
this.auctionStatusCheckTimeout = setTimeout(() => { this.auctionStatusCheckTimeout = setTimeout(() => {
@ -508,17 +485,12 @@ export class Service {
return dbProjects; return dbProjects;
} }
async getNonCanonicalDeploymentsByProjectId( async getNonCanonicalDeploymentsByProjectId(projectId: string): Promise<Deployment[]> {
projectId: string, const nonCanonicalDeployments = await this.db.getNonCanonicalDeploymentsByProjectId(projectId);
): Promise<Deployment[]> {
const nonCanonicalDeployments =
await this.db.getNonCanonicalDeploymentsByProjectId(projectId);
return nonCanonicalDeployments; return nonCanonicalDeployments;
} }
async getLatestDNSRecordByProjectId( async getLatestDNSRecordByProjectId(projectId: string): Promise<DNSRecordAttributes | null> {
projectId: string,
): Promise<DNSRecordAttributes | null> {
const dnsRecord = await this.db.getLatestDNSRecordByProjectId(projectId); const dnsRecord = await this.db.getLatestDNSRecordByProjectId(projectId);
return dnsRecord; return dnsRecord;
} }
@ -672,15 +644,20 @@ export class Service {
const octokit = await this.getOctokit(user.id); const octokit = await this.getOctokit(user.id);
const newDeployment = await this.createDeployment(user.id, octokit, { let newDeployment: Deployment;
project: oldDeployment.project,
branch: oldDeployment.branch,
environment: Environment.Production,
commitHash: oldDeployment.commitHash,
commitMessage: oldDeployment.commitMessage,
deployer: oldDeployment.deployer,
});
if (oldDeployment.project.auctionId) {
newDeployment = await this.createDeploymentFromAuction(oldDeployment.project, oldDeployment.deployer);
} else {
newDeployment = await this.createDeployment(user.id, octokit, {
project: oldDeployment.project,
branch: oldDeployment.branch,
environment: Environment.Production,
commitHash: oldDeployment.commitHash,
commitMessage: oldDeployment.commitMessage,
deployer: oldDeployment.deployer
});
}
return newDeployment; return newDeployment;
} }
@ -688,7 +665,7 @@ export class Service {
userId: string, userId: string,
octokit: Octokit, octokit: Octokit,
data: DeepPartial<Deployment>, data: DeepPartial<Deployment>,
deployerLrn?: string, deployerLrn?: string
): Promise<Deployment> { ): Promise<Deployment> {
assert(data.project?.repository, 'Project repository not found'); assert(data.project?.repository, 'Project repository not found');
log( log(
@ -711,58 +688,34 @@ export class Service {
deployer = data.deployer; deployer = data.deployer;
} }
const deployment = await this.createDeploymentFromData( const deployment = await this.createDeploymentFromData(userId, data, deployer!.deployerLrn!, applicationRecordId, applicationRecordData, false);
userId,
data,
deployer!.deployerLrn!,
applicationRecordId,
applicationRecordData,
false,
);
const address = await this.getAddress(); const address = await this.getAddress();
const { repo, repoUrl } = await getRepoDetails( const { repo, repoUrl } = await getRepoDetails(octokit, data.project.repository, data.commitHash);
octokit, const environmentVariablesObj = await this.getEnvVariables(data.project!.id!);
data.project.repository,
data.commitHash,
);
const environmentVariablesObj = await this.getEnvVariables(
data.project!.id!,
);
// To set project DNS // To set project DNS
if (data.environment === Environment.Production) { if (data.environment === Environment.Production) {
const canonicalDeployment = await this.createDeploymentFromData( const canonicalDeployment = await this.createDeploymentFromData(userId, data, deployer!.deployerLrn!, applicationRecordId, applicationRecordData, true);
userId,
data,
deployer!.deployerLrn!,
applicationRecordId,
applicationRecordData,
true,
);
// If a custom domain is present then use that as the DNS in the deployment request // If a custom domain is present then use that as the DNS in the deployment request
const customDomain = await this.db.getOldestDomainByProjectId( const customDomain = await this.db.getOldestDomainByProjectId(data.project!.id!);
data.project!.id!,
);
// On deleting deployment later, project canonical deployment is also deleted // On deleting deployment later, project canonical deployment is also deleted
// So publish project canonical deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later // So publish project canonical deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later
const { const { applicationDeploymentRequestData, applicationDeploymentRequestId } =
applicationDeploymentRequestData, await this.laconicRegistry.createApplicationDeploymentRequest({
applicationDeploymentRequestId, deployment: canonicalDeployment,
} = await this.laconicRegistry.createApplicationDeploymentRequest({ appName: repo,
deployment: canonicalDeployment, repository: repoUrl,
appName: repo, environmentVariables: environmentVariablesObj,
repository: repoUrl, dns: customDomain?.name ?? `${canonicalDeployment.project.name}`,
environmentVariables: environmentVariablesObj, lrn: deployer!.deployerLrn!,
dns: customDomain?.name ?? `${canonicalDeployment.project.name}`, apiUrl: deployer!.deployerApiUrl!,
lrn: deployer!.deployerLrn!, payment: data.project.txHash,
apiUrl: deployer!.deployerApiUrl!, auctionId: data.project.auctionId,
payment: data.project.txHash, requesterAddress: address,
auctionId: data.project.auctionId, publicKey: deployer!.publicKey!
requesterAddress: address, });
publicKey: deployer!.publicKey!,
});
await this.db.updateDeploymentById(canonicalDeployment.id, { await this.db.updateDeploymentById(canonicalDeployment.id, {
applicationDeploymentRequestId, applicationDeploymentRequestId,
@ -782,7 +735,7 @@ export class Service {
payment: data.project.txHash, payment: data.project.txHash,
auctionId: data.project.auctionId, auctionId: data.project.auctionId,
requesterAddress: address, requesterAddress: address,
publicKey: deployer!.publicKey!, publicKey: deployer!.publicKey!
}); });
await this.db.updateDeploymentById(deployment.id, { await this.db.updateDeploymentById(deployment.id, {
@ -795,7 +748,7 @@ export class Service {
async createDeploymentFromAuction( async createDeploymentFromAuction(
project: DeepPartial<Project>, project: DeepPartial<Project>,
deployer: Deployer, deployer: Deployer
): Promise<Deployment> { ): Promise<Deployment> {
const octokit = await this.getOctokit(project.ownerId!); const octokit = await this.getOctokit(project.ownerId!);
const [owner, repo] = project.repository!.split('/'); const [owner, repo] = project.repository!.split('/');
@ -821,7 +774,7 @@ export class Service {
const applicationRecordId = record.id; const applicationRecordId = record.id;
const applicationRecordData = record.attributes; const applicationRecordData = record.attributes;
const deployerLrn = deployer!.deployerLrn; const deployerLrn = deployer!.deployerLrn
// Create deployment with prod branch and latest commit // Create deployment with prod branch and latest commit
const deploymentData = { const deploymentData = {
@ -833,49 +786,31 @@ export class Service {
commitMessage: latestCommit.commit.message, commitMessage: latestCommit.commit.message,
}; };
const deployment = await this.createDeploymentFromData( const deployment = await this.createDeploymentFromData(project.ownerId!, deploymentData, deployerLrn, applicationRecordId, applicationRecordData, false);
project.ownerId!,
deploymentData,
deployerLrn,
applicationRecordId,
applicationRecordData,
false,
);
const address = await this.getAddress(); const address = await this.getAddress();
const environmentVariablesObj = await this.getEnvVariables(project!.id!); const environmentVariablesObj = await this.getEnvVariables(project!.id!);
// To set project DNS // To set project DNS
if (deploymentData.environment === Environment.Production) { if (deploymentData.environment === Environment.Production) {
const canonicalDeployment = await this.createDeploymentFromData( const canonicalDeployment = await this.createDeploymentFromData(project.ownerId!, deploymentData, deployerLrn, applicationRecordId, applicationRecordData, true);
project.ownerId!,
deploymentData,
deployerLrn,
applicationRecordId,
applicationRecordData,
true,
);
// If a custom domain is present then use that as the DNS in the deployment request // If a custom domain is present then use that as the DNS in the deployment request
const customDomain = await this.db.getOldestDomainByProjectId( const customDomain = await this.db.getOldestDomainByProjectId(project!.id!);
project!.id!,
);
// On deleting deployment later, project canonical deployment is also deleted // On deleting deployment later, project canonical deployment is also deleted
// So publish project canonical deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later // So publish project canonical deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later
const { const { applicationDeploymentRequestId, applicationDeploymentRequestData } =
applicationDeploymentRequestId, await this.laconicRegistry.createApplicationDeploymentRequest({
applicationDeploymentRequestData, deployment: canonicalDeployment,
} = await this.laconicRegistry.createApplicationDeploymentRequest({ appName: repo,
deployment: canonicalDeployment, repository: repoUrl,
appName: repo, environmentVariables: environmentVariablesObj,
repository: repoUrl, dns: customDomain?.name ?? `${canonicalDeployment.project.name}`,
environmentVariables: environmentVariablesObj, auctionId: project.auctionId!,
dns: customDomain?.name ?? `${canonicalDeployment.project.name}`, lrn: deployerLrn,
auctionId: project.auctionId!, apiUrl: deployer!.deployerApiUrl!,
lrn: deployerLrn, requesterAddress: address,
apiUrl: deployer!.deployerApiUrl!, publicKey: deployer!.publicKey!
requesterAddress: address, });
publicKey: deployer!.publicKey!,
});
await this.db.updateDeploymentById(canonicalDeployment.id, { await this.db.updateDeploymentById(canonicalDeployment.id, {
applicationDeploymentRequestId, applicationDeploymentRequestId,
@ -895,7 +830,7 @@ export class Service {
environmentVariables: environmentVariablesObj, environmentVariables: environmentVariablesObj,
dns: `${deployment.project.name}-${deployment.id}`, dns: `${deployment.project.name}-${deployment.id}`,
requesterAddress: address, requesterAddress: address,
publicKey: deployer!.publicKey!, publicKey: deployer!.publicKey!
}); });
await this.db.updateDeploymentById(deployment.id, { await this.db.updateDeploymentById(deployment.id, {
@ -929,7 +864,7 @@ export class Service {
deployer: Object.assign(new Deployer(), { deployer: Object.assign(new Deployer(), {
deployerLrn, deployerLrn,
}), }),
isCanonical, isCanonical
}); });
log(`Created deployment ${newDeployment.id}`); log(`Created deployment ${newDeployment.id}`);
@ -939,11 +874,11 @@ export class Service {
async updateProjectWithDeployer( async updateProjectWithDeployer(
projectId: string, projectId: string,
deployer: Deployer, deployer: Deployer
): Promise<Deployer> { ): Promise<Deployer> {
const deploymentProject = await this.db.getProjects({ const deploymentProject = await this.db.getProjects({
where: { id: projectId }, where: { id: projectId },
relations: ['deployers'], relations: ['deployers']
}); });
if (!deploymentProject[0].deployers) { if (!deploymentProject[0].deployers) {
@ -988,22 +923,15 @@ export class Service {
const prodBranch = createdTemplateRepo.data.default_branch ?? 'main'; const prodBranch = createdTemplateRepo.data.default_branch ?? 'main';
const project = await this.addProject( const project = await this.addProject(user, organizationSlug, {
user, name: `${gitRepo.data.owner!.login}-${gitRepo.data.name}`,
organizationSlug, prodBranch,
{ repository: gitRepo.data.full_name,
name: `${gitRepo.data.owner!.login}-${gitRepo.data.name}`, // TODO: Set selected template
prodBranch, template: 'webapp',
repository: gitRepo.data.full_name, paymentAddress: data.paymentAddress,
// TODO: Set selected template txHash: data.txHash
template: 'webapp', }, lrn, auctionParams, environmentVariables);
paymentAddress: data.paymentAddress,
txHash: data.txHash,
},
lrn,
auctionParams,
environmentVariables,
);
if (!project || !project.id) { if (!project || !project.id) {
throw new Error('Failed to create project from template'); throw new Error('Failed to create project from template');
@ -1062,19 +990,8 @@ export class Service {
commitHash: latestCommit.sha, commitHash: latestCommit.sha,
commitMessage: latestCommit.commit.message, commitMessage: latestCommit.commit.message,
}; };
const { applicationDeploymentAuctionId } = await this.laconicRegistry.createApplicationDeploymentAuction(repo, octokit, auctionParams!, deploymentData);
const { applicationDeploymentAuction } = await this.updateProject(project.id, { auctionId: applicationDeploymentAuctionId });
await this.laconicRegistry.createApplicationDeploymentAuction(
repo,
octokit,
auctionParams!,
deploymentData,
);
await this.updateProject(project.id, {
auctionId: applicationDeploymentAuction!.id,
auctionStatus: applicationDeploymentAuction!.status as AuctionStatus,
});
} else { } else {
const deployer = await this.db.getDeployerByLRN(lrn!); const deployer = await this.db.getDeployerByLRN(lrn!);
@ -1084,13 +1001,11 @@ export class Service {
} }
if (deployer.minimumPayment && project.txHash) { if (deployer.minimumPayment && project.txHash) {
const amountToBePaid = deployer?.minimumPayment const amountToBePaid = deployer?.minimumPayment.replace(/\D/g, '').toString();
.replace(/\D/g, '')
.toString();
const txResponse = await this.laconicRegistry.sendTokensToAccount( const txResponse = await this.laconicRegistry.sendTokensToAccount(
deployer?.paymentAddress!, deployer?.paymentAddress!,
amountToBePaid, amountToBePaid
); );
const txHash = txResponse.transactionHash; const txHash = txResponse.transactionHash;
@ -1108,19 +1023,12 @@ export class Service {
domain: null, domain: null,
commitHash: latestCommit.sha, commitHash: latestCommit.sha,
commitMessage: latestCommit.commit.message, commitMessage: latestCommit.commit.message,
deployer, deployer
}; };
const newDeployment = await this.createDeployment( const newDeployment = await this.createDeployment(user.id, octokit, deploymentData);
user.id,
octokit,
deploymentData,
);
// Update project with deployer // Update project with deployer
await this.updateProjectWithDeployer( await this.updateProjectWithDeployer(newDeployment.projectId, newDeployment.deployer);
newDeployment.projectId,
newDeployment.deployer,
);
} }
await this.createRepoHook(octokit, project); await this.createRepoHook(octokit, project);
@ -1176,7 +1084,7 @@ export class Service {
where: { repository: repository.full_name }, where: { repository: repository.full_name },
relations: { relations: {
deployers: true, deployers: true,
}, }
}); });
if (!projects.length) { if (!projects.length) {
@ -1192,23 +1100,25 @@ export class Service {
const deployers = project.deployers; const deployers = project.deployers;
if (!deployers) { if (!deployers) {
log(`No deployer present for project ${project.id}`); log(`No deployer present for project ${project.id}`)
return; return;
} }
for (const deployer of deployers) { for (const deployer of deployers) {
// Create deployment with branch and latest commit in GitHub data // Create deployment with branch and latest commit in GitHub data
await this.createDeployment(project.ownerId, octokit, { await this.createDeployment(project.ownerId, octokit,
project, {
branch, project,
environment: branch,
project.prodBranch === branch environment:
? Environment.Production project.prodBranch === branch
: Environment.Preview, ? Environment.Production
commitHash: headCommit.id, : Environment.Preview,
commitMessage: headCommit.message, commitHash: headCommit.id,
deployer: deployer, commitMessage: headCommit.message,
}); deployer: deployer
},
);
} }
} }
} }
@ -1262,20 +1172,19 @@ export class Service {
let newDeployment: Deployment; let newDeployment: Deployment;
if (oldDeployment.project.auctionId) { if (oldDeployment.project.auctionId) {
newDeployment = await this.createDeploymentFromAuction( newDeployment = await this.createDeploymentFromAuction(oldDeployment.project, oldDeployment.deployer);
oldDeployment.project,
oldDeployment.deployer,
);
} else { } else {
newDeployment = await this.createDeployment(user.id, octokit, { newDeployment = await this.createDeployment(user.id, octokit,
project: oldDeployment.project, {
// TODO: Put isCurrent field in project project: oldDeployment.project,
branch: oldDeployment.branch, // TODO: Put isCurrent field in project
environment: Environment.Production, branch: oldDeployment.branch,
commitHash: oldDeployment.commitHash, environment: Environment.Production,
commitMessage: oldDeployment.commitMessage, commitHash: oldDeployment.commitHash,
deployer: oldDeployment.deployer, commitMessage: oldDeployment.commitMessage,
}); deployer: oldDeployment.deployer
}
);
} }
return newDeployment; return newDeployment;
@ -1284,6 +1193,7 @@ export class Service {
async rollbackDeployment( async rollbackDeployment(
projectId: string, projectId: string,
deploymentId: string, deploymentId: string,
deployerLrn: string,
): Promise<boolean> { ): Promise<boolean> {
// TODO: Implement transactions // TODO: Implement transactions
const oldCurrentDeployment = await this.db.getDeployment({ const oldCurrentDeployment = await this.db.getDeployment({
@ -1295,6 +1205,9 @@ export class Service {
project: { project: {
id: projectId, id: projectId,
}, },
deployer: {
deployerLrn
},
isCurrent: true, isCurrent: true,
isCanonical: false, isCanonical: false,
}, },
@ -1314,26 +1227,22 @@ export class Service {
{ isCurrent: true }, { isCurrent: true },
); );
if (!newCurrentDeploymentUpdate || !oldCurrentDeploymentUpdate) { if (!newCurrentDeploymentUpdate || !oldCurrentDeploymentUpdate){
return false; return false;
} }
const newCurrentDeployment = await this.db.getDeployment({ const newCurrentDeployment = await this.db.getDeployment({ where: { id: deploymentId }, relations: { project: true, deployer: true } });
where: { id: deploymentId },
relations: { project: true, deployer: true },
});
if (!newCurrentDeployment) { if (!newCurrentDeployment) {
throw new Error(`Deployment with Id ${deploymentId} not found`); throw new Error(`Deployment with Id ${deploymentId} not found`);
} }
const applicationDeploymentRequestData = const applicationDeploymentRequestData = newCurrentDeployment.applicationDeploymentRequestData;
newCurrentDeployment.applicationDeploymentRequestData;
const customDomain = await this.db.getOldestDomainByProjectId(projectId); const customDomain = await this.db.getOldestDomainByProjectId(projectId);
if (customDomain && applicationDeploymentRequestData) { if (customDomain && applicationDeploymentRequestData) {
applicationDeploymentRequestData.dns = customDomain.name; applicationDeploymentRequestData.dns = customDomain.name
} }
// Create a canonical deployment for the new current deployment // Create a canonical deployment for the new current deployment
@ -1349,23 +1258,20 @@ export class Service {
applicationDeploymentRequestData!.meta = JSON.stringify({ applicationDeploymentRequestData!.meta = JSON.stringify({
...JSON.parse(applicationDeploymentRequestData!.meta), ...JSON.parse(applicationDeploymentRequestData!.meta),
note: `Updated by Snowball @ ${DateTime.utc().toFormat( note: `Updated by Snowball @ ${DateTime.utc().toFormat(
"EEE LLL dd HH:mm:ss 'UTC' yyyy", "EEE LLL dd HH:mm:ss 'UTC' yyyy"
)}`, )}`
}); });
const result = await this.laconicRegistry.publishRecord( const result = await this.laconicRegistry.publishRecord(
applicationDeploymentRequestData, applicationDeploymentRequestData,
); );
log(`Application deployment request record published: ${result.id}`); log(`Application deployment request record published: ${result.id}`)
const updateResult = await this.db.updateDeploymentById( const updateResult = await this.db.updateDeploymentById(canonicalDeployment.id, {
canonicalDeployment.id, applicationDeploymentRequestId: result.id,
{ applicationDeploymentRequestData,
applicationDeploymentRequestId: result.id, });
applicationDeploymentRequestData,
},
);
return updateResult; return updateResult;
} }
@ -1388,20 +1294,18 @@ export class Service {
where: { where: {
projectId: deployment.project.id, projectId: deployment.project.id,
deployer: deployment.deployer, deployer: deployment.deployer,
isCanonical: true, isCanonical: true
}, },
relations: { relations: {
project: true, project: true,
deployer: true, deployer: true,
}, },
}); })
// If the canonical deployment is not present then query the chain for the deployment record for backward compatibility // If the canonical deployment is not present then query the chain for the deployment record for backward compatibility
if (!canonicalDeployment) { if (!canonicalDeployment) {
log( log(`Canonical deployment for deployment with id ${deployment.id} not found, querying the chain..`);
`Canonical deployment for deployment with id ${deployment.id} not found, querying the chain..`, const currentDeploymentURL = `https://${(deployment.project.name).toLowerCase()}.${deployment.deployer.baseDomain}`;
);
const currentDeploymentURL = `https://${deployment.project.name.toLowerCase()}.${deployment.deployer.baseDomain}`;
const deploymentRecords = const deploymentRecords =
await this.laconicRegistry.getDeploymentRecordsByFilter({ await this.laconicRegistry.getDeploymentRecordsByFilter({
@ -1418,30 +1322,24 @@ export class Service {
} }
// Multiple records are fetched, take the latest record // Multiple records are fetched, take the latest record
const latestRecord = deploymentRecords.sort( const latestRecord = deploymentRecords
(a, b) => .sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())[0];
new Date(b.createTime).getTime() -
new Date(a.createTime).getTime(),
)[0];
await this.laconicRegistry.createApplicationDeploymentRemovalRequest({ await this.laconicRegistry.createApplicationDeploymentRemovalRequest({
deploymentId: latestRecord.id, deploymentId: latestRecord.id,
deployerLrn: deployment.deployer.deployerLrn, deployerLrn: deployment.deployer.deployerLrn,
auctionId: deployment.project.auctionId, auctionId: deployment.project.auctionId,
payment: deployment.project.txHash, payment: deployment.project.txHash
}); });
} else { } else {
// If canonical deployment is found in the DB, then send the removal request with that deployment record Id // If canonical deployment is found in the DB, then send the removal request with that deployment record Id
const result = const result =
await this.laconicRegistry.createApplicationDeploymentRemovalRequest( await this.laconicRegistry.createApplicationDeploymentRemovalRequest({
{ deploymentId: canonicalDeployment.applicationDeploymentRecordId!,
deploymentId: deployerLrn: canonicalDeployment.deployer.deployerLrn,
canonicalDeployment.applicationDeploymentRecordId!, auctionId: canonicalDeployment.project.auctionId,
deployerLrn: canonicalDeployment.deployer.deployerLrn, payment: canonicalDeployment.project.txHash
auctionId: canonicalDeployment.project.auctionId, });
payment: canonicalDeployment.project.txHash,
},
);
await this.db.updateDeploymentById(canonicalDeployment.id, { await this.db.updateDeploymentById(canonicalDeployment.id, {
status: DeploymentStatus.Deleting, status: DeploymentStatus.Deleting,
@ -1458,7 +1356,7 @@ export class Service {
deploymentId: deployment.applicationDeploymentRecordId, deploymentId: deployment.applicationDeploymentRecordId,
deployerLrn: deployment.deployer.deployerLrn, deployerLrn: deployment.deployer.deployerLrn,
auctionId: deployment.project.auctionId, auctionId: deployment.project.auctionId,
payment: deployment.project.txHash, payment: deployment.project.txHash
}); });
await this.db.updateDeploymentById(deployment.id, { await this.db.updateDeploymentById(deployment.id, {
@ -1594,11 +1492,12 @@ export class Service {
return this.db.updateUser(user, data); return this.db.updateUser(user, data);
} }
async getEnvVariables(projectId: string): Promise<{ [key: string]: string }> { async getEnvVariables(
const environmentVariables = projectId: string,
await this.db.getEnvironmentVariablesByProjectId(projectId, { ): Promise<{ [key: string]: string }> {
environment: Environment.Production, const environmentVariables = await this.db.getEnvironmentVariablesByProjectId(projectId, {
}); environment: Environment.Production,
});
const environmentVariablesObj = environmentVariables.reduce( const environmentVariablesObj = environmentVariables.reduce(
(acc, env) => { (acc, env) => {
@ -1611,7 +1510,9 @@ export class Service {
return environmentVariablesObj; return environmentVariablesObj;
} }
async getAuctionData(auctionId: string): Promise<any> { async getAuctionData(
auctionId: string
): Promise<any> {
const auctions = await this.laconicRegistry.getAuctionData(auctionId); const auctions = await this.laconicRegistry.getAuctionData(auctionId);
return auctions[0]; return auctions[0];
} }
@ -1620,19 +1521,16 @@ export class Service {
const project = await this.db.getProjectById(projectId); const project = await this.db.getProjectById(projectId);
if (!project || !project.auctionId) { if (!project || !project.auctionId) {
log( log(`Project ${projectId} ${!project ? 'not found' : 'does not have an auction'}`);
`Project ${projectId} ${!project ? 'not found' : 'does not have an auction'}`,
);
return false; return false;
} }
const auction = await this.laconicRegistry.releaseDeployerFunds( const auction = await this.laconicRegistry.releaseDeployerFunds(project.auctionId);
project.auctionId,
);
if (auction.auction.fundsReleased) { if (auction.auction.fundsReleased) {
log(`Funds released for auction ${project.auctionId}`); log(`Funds released for auction ${project.auctionId}`);
await this.db.updateProjectById(projectId, { fundsReleased: true });
return true; return true;
} }
@ -1642,29 +1540,21 @@ export class Service {
return false; return false;
} }
async returnUserFundsByProjectId( async returnUserFundsByProjectId(projectId: string, winningDeployersPresent: boolean) {
projectId: string,
winningDeployersPresent: boolean,
) {
const project = await this.db.getProjectById(projectId); const project = await this.db.getProjectById(projectId);
if (!project || !project.auctionId) { if (!project || !project.auctionId) {
log( log(`Project ${projectId} ${!project ? 'not found' : 'does not have an auction'}`);
`Project ${projectId} ${!project ? 'not found' : 'does not have an auction'}`,
);
return false; return false;
} }
const auction = await this.getAuctionData(project.auctionId); const auction = await this.getAuctionData(project.auctionId);
const totalAuctionPrice = const totalAuctionPrice = Number(auction.maxPrice.quantity) * auction.numProviders;
Number(auction.maxPrice.quantity) * auction.numProviders;
let amountToBeReturned; let amountToBeReturned;
if (winningDeployersPresent) { if (winningDeployersPresent) {
amountToBeReturned = amountToBeReturned = totalAuctionPrice - auction.winnerAddresses.length * Number(auction.winnerPrice.quantity);
totalAuctionPrice -
auction.winnerAddresses.length * Number(auction.winnerPrice.quantity);
} else { } else {
amountToBeReturned = totalAuctionPrice; amountToBeReturned = totalAuctionPrice;
} }
@ -1672,7 +1562,7 @@ export class Service {
if (amountToBeReturned !== 0) { if (amountToBeReturned !== 0) {
await this.laconicRegistry.sendTokensToAccount( await this.laconicRegistry.sendTokensToAccount(
project.paymentAddress, project.paymentAddress,
amountToBeReturned.toString(), amountToBeReturned.toString()
); );
} }
} }
@ -1691,16 +1581,13 @@ export class Service {
} }
async updateDeployersFromRegistry(): Promise<Deployer[]> { async updateDeployersFromRegistry(): Promise<Deployer[]> {
const deployerRecords = const deployerRecords = await this.laconicRegistry.getDeployerRecordsByFilter({});
await this.laconicRegistry.getDeployerRecordsByFilter({});
await this.saveDeployersByDeployerRecords(deployerRecords); await this.saveDeployersByDeployerRecords(deployerRecords);
return await this.db.getDeployers(); return await this.db.getDeployers();
} }
async saveDeployersByDeployerRecords( async saveDeployersByDeployerRecords(deployerRecords: DeployerRecord[]): Promise<Deployer[]> {
deployerRecords: DeployerRecord[],
): Promise<Deployer[]> {
const deployers: Deployer[] = []; const deployers: Deployer[] = [];
for (const record of deployerRecords) { for (const record of deployerRecords) {
@ -1711,9 +1598,7 @@ export class Service {
const minimumPayment = record.attributes.minimumPayment; const minimumPayment = record.attributes.minimumPayment;
const paymentAddress = record.attributes.paymentAddress; const paymentAddress = record.attributes.paymentAddress;
const publicKey = record.attributes.publicKey; const publicKey = record.attributes.publicKey;
const baseDomain = deployerApiUrl.substring( const baseDomain = deployerApiUrl.substring(deployerApiUrl.indexOf('.') + 1);
deployerApiUrl.indexOf('.') + 1,
);
const deployerData = { const deployerData = {
deployerLrn, deployerLrn,
@ -1722,7 +1607,7 @@ export class Service {
baseDomain, baseDomain,
minimumPayment, minimumPayment,
paymentAddress, paymentAddress,
publicKey, publicKey
}; };
// TODO: Update deployers table in a separate job // TODO: Update deployers table in a separate job
@ -1740,39 +1625,25 @@ export class Service {
return account.address; return account.address;
} }
async verifyTx( async verifyTx(txHash: string, amountSent: string, senderAddress: string): Promise<boolean> {
txHash: string,
amountSent: string,
senderAddress: string,
): Promise<boolean> {
const txResponse = await this.laconicRegistry.getTxResponse(txHash); const txResponse = await this.laconicRegistry.getTxResponse(txHash);
if (!txResponse) { if (!txResponse) {
log('Transaction response not found'); log('Transaction response not found');
return false; return false;
} }
const transfer = txResponse.events.find( const transfer = txResponse.events.find(e => e.type === 'transfer' && e.attributes.some(a => a.key === 'msg_index'));
(e) =>
e.type === 'transfer' &&
e.attributes.some((a) => a.key === 'msg_index'),
);
if (!transfer) { if (!transfer) {
log('No transfer event found'); log('No transfer event found');
return false; return false;
} }
const sender = transfer.attributes.find((a) => a.key === 'sender')?.value; const sender = transfer.attributes.find(a => a.key === 'sender')?.value;
const recipient = transfer.attributes.find( const recipient = transfer.attributes.find(a => a.key === 'recipient')?.value;
(a) => a.key === 'recipient', const amount = transfer.attributes.find(a => a.key === 'amount')?.value;
)?.value;
const amount = transfer.attributes.find((a) => a.key === 'amount')?.value;
const recipientAddress = await this.getAddress(); const recipientAddress = await this.getAddress();
return ( return amount === amountSent && sender === senderAddress && recipient === recipientAddress;
amount === amountSent &&
sender === senderAddress &&
recipient === recipientAddress
);
} }
} }

View File

@ -1,8 +1,8 @@
services: services:
registry: registry:
rpcEndpoint: https://laconicd-mainnet-1.laconic.com rpcEndpoint: https://laconicd-sapo.laconic.com
gqlEndpoint: https://laconicd-mainnet-1.laconic.com/api gqlEndpoint: https://laconicd-sapo.laconic.com/api
userKey: userKey:
bondId: bondId:
chainId: laconic-mainnet chainId: laconic-testnet-2
gasPrice: 0.001alnt gasPrice: 0.001alnt

View File

@ -133,6 +133,8 @@ record:
LACONIC_HOSTED_CONFIG_github_pwa_templaterepo: laconic-templates/test-progressive-web-app LACONIC_HOSTED_CONFIG_github_pwa_templaterepo: laconic-templates/test-progressive-web-app
LACONIC_HOSTED_CONFIG_github_image_upload_templaterepo: laconic-templates/image-upload-pwa-example LACONIC_HOSTED_CONFIG_github_image_upload_templaterepo: laconic-templates/image-upload-pwa-example
LACONIC_HOSTED_CONFIG_github_next_app_templaterepo: laconic-templates/starter.nextjs-react-tailwind LACONIC_HOSTED_CONFIG_github_next_app_templaterepo: laconic-templates/starter.nextjs-react-tailwind
LACONIC_HOSTED_CONFIG_wallet_connect_id: 63cad7ba97391f63652161f484670e15
LACONIC_HOSTED_CONFIG_laconicd_chain_id: laconic-testnet-2
LACONIC_HOSTED_CONFIG_wallet_iframe_url: https://wallet.laconic.com LACONIC_HOSTED_CONFIG_wallet_iframe_url: https://wallet.laconic.com
meta: meta:
note: Added @ $CURRENT_DATE_TIME note: Added @ $CURRENT_DATE_TIME

View File

@ -127,6 +127,7 @@ record:
LACONIC_HOSTED_CONFIG_github_pwa_templaterepo: laconic-templates/test-progressive-web-app LACONIC_HOSTED_CONFIG_github_pwa_templaterepo: laconic-templates/test-progressive-web-app
LACONIC_HOSTED_CONFIG_github_image_upload_templaterepo: laconic-templates/image-upload-pwa-example LACONIC_HOSTED_CONFIG_github_image_upload_templaterepo: laconic-templates/image-upload-pwa-example
LACONIC_HOSTED_CONFIG_github_next_app_templaterepo: laconic-templates/starter.nextjs-react-tailwind LACONIC_HOSTED_CONFIG_github_next_app_templaterepo: laconic-templates/starter.nextjs-react-tailwind
LACONIC_HOSTED_CONFIG_wallet_connect_id: 63cad7ba97391f63652161f484670e15
LACONIC_HOSTED_CONFIG_laconicd_chain_id: laconic-testnet-2 LACONIC_HOSTED_CONFIG_laconicd_chain_id: laconic-testnet-2
meta: meta:
note: Added by Snowball @ $CURRENT_DATE_TIME note: Added by Snowball @ $CURRENT_DATE_TIME

View File

@ -5,6 +5,8 @@ VITE_GITHUB_PWA_TEMPLATE_REPO="snowball-tools/test-progressive-web-app"
VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO="snowball-tools/image-upload-pwa-example" VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO="snowball-tools/image-upload-pwa-example"
VITE_GITHUB_NEXT_APP_TEMPLATE_REPO="snowball-tools/starter.nextjs-react-tailwind" VITE_GITHUB_NEXT_APP_TEMPLATE_REPO="snowball-tools/starter.nextjs-react-tailwind"
VITE_WALLET_CONNECT_ID=
VITE_LIT_RELAY_API_KEY= VITE_LIT_RELAY_API_KEY=
VITE_BUGSNAG_API_KEY= VITE_BUGSNAG_API_KEY=
@ -12,4 +14,5 @@ VITE_BUGSNAG_API_KEY=
VITE_PASSKEY_WALLET_RPID= VITE_PASSKEY_WALLET_RPID=
VITE_TURNKEY_API_BASE_URL= VITE_TURNKEY_API_BASE_URL=
VITE_LACONICD_CHAIN_ID=
VITE_WALLET_IFRAME_URL= VITE_WALLET_IFRAME_URL=

View File

@ -41,12 +41,13 @@
"@turnkey/http": "^2.10.0", "@turnkey/http": "^2.10.0",
"@turnkey/sdk-react": "^0.1.0", "@turnkey/sdk-react": "^0.1.0",
"@turnkey/webauthn-stamper": "^0.5.0", "@turnkey/webauthn-stamper": "^0.5.0",
"@walletconnect/ethereum-provider": "^2.16.1",
"@web3modal/siwe": "4.0.5", "@web3modal/siwe": "4.0.5",
"@web3modal/wagmi": "4.0.5",
"assert": "^2.1.0", "assert": "^2.1.0",
"axios": "^1.6.7", "axios": "^1.6.7",
"clsx": "^2.1.0", "clsx": "^2.1.0",
"date-fns": "^3.3.1", "date-fns": "^3.3.1",
"ethers": "^5.6.2",
"downshift": "^8.3.2", "downshift": "^8.3.2",
"framer-motion": "^11.0.8", "framer-motion": "^11.0.8",
"gql-client": "^1.0.0", "gql-client": "^1.0.0",
@ -68,6 +69,7 @@
"usehooks-ts": "^2.15.1", "usehooks-ts": "^2.15.1",
"uuid": "^9.0.1", "uuid": "^9.0.1",
"viem": "^2.7.11", "viem": "^2.7.11",
"wagmi": "2.5.7",
"web-vitals": "^2.1.4" "web-vitals": "^2.1.4"
}, },
"devDependencies": { "devDependencies": {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -1,11 +0,0 @@
{
"chainId": "laconic-mainnet",
"networkName": "laconicd mainnet",
"namespace": "cosmos",
"rpcUrl": "https://laconicd-mainnet-1.laconic.com",
"blockExplorerUrl": "",
"nativeDenom": "alnt",
"addressPrefix": "laconic",
"coinType": 118,
"gasPrice": 0.001
}

View File

@ -11,8 +11,8 @@ import ProjectSearchLayout from './layouts/ProjectSearch';
import Index from './pages'; import Index from './pages';
import AuthPage from './pages/AuthPage'; import AuthPage from './pages/AuthPage';
import { DashboardLayout } from './pages/org-slug/layout'; import { DashboardLayout } from './pages/org-slug/layout';
import Web3Provider from 'context/Web3Provider';
import { BASE_URL } from 'utils/constants'; import { BASE_URL } from 'utils/constants';
import BuyPrepaidService from './pages/BuyPrepaidService';
const router = createBrowserRouter([ const router = createBrowserRouter([
{ {
@ -50,10 +50,6 @@ const router = createBrowserRouter([
path: '/login', path: '/login',
element: <AuthPage />, element: <AuthPage />,
}, },
{
path: '/buy-prepaid-service',
element: <BuyPrepaidService />,
},
]); ]);
function App() { function App() {
@ -79,7 +75,9 @@ function App() {
}, []); }, []);
return ( return (
<RouterProvider router={router} /> <Web3Provider>
<RouterProvider router={router} />
</Web3Provider>
); );
} }

View File

@ -0,0 +1,60 @@
import {
Select,
Option,
Spinner,
} from '@snowballtools/material-tailwind-react-fork';
const AccountsDropdown = ({
accounts,
isDataReceived,
onAccountChange,
}: {
accounts: string[];
isDataReceived: boolean;
onAccountChange: (selectedAccount: string) => void;
}) => {
return (
<div className="p-6 bg-slate-100 dark:bg-overlay3 rounded-lg mb-6 shadow-md">
{isDataReceived ? (
!accounts.length ? (
<div className="text-center">
<p className="text-gray-700 dark:text-gray-300 mb-4">
No accounts found. Please visit{' '}
<a
href="https://store.laconic.com"
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 underline dark:text-blue-400"
>
store.laconic.com
</a>{' '}
to create a wallet.
</p>
</div>
) : (
<div>
<Select
label="Select Account"
defaultValue={accounts[0]}
onChange={(value) => value && onAccountChange(value)}
className="dark:bg-overlay2 dark:text-foreground"
aria-label="Wallet Account Selector"
>
{accounts.map((account, index) => (
<Option key={index} value={account}>
{account}
</Option>
))}
</Select>
</div>
)
) : (
<div className="flex items-center justify-center h-12">
<Spinner className="h-6 w-6" />
</div>
)}
</div>
);
};
export default AccountsDropdown;

View File

@ -1,67 +0,0 @@
import { useEffect } from 'react';
import { Modal } from '@mui/material';
import { VITE_WALLET_IFRAME_URL } from 'utils/constants';
import useCheckBalance from '../../../hooks/useCheckBalance';
import { useAddNetwork } from '../../../hooks/useAddNetwork';
const CHECK_BALANCE_INTERVAL = 5000;
const IFRAME_ID = 'checkBalanceIframe';
const CheckBalanceIframe = ({
onBalanceChange,
isPollingEnabled,
amount,
}: {
onBalanceChange: (value: boolean | undefined) => void;
isPollingEnabled: boolean;
amount: string;
}) => {
const { isBalanceSufficient, checkBalance } = useCheckBalance(
amount,
IFRAME_ID,
);
const { isNetworkAvailable, setIframe } = useAddNetwork();
useEffect(() => {
if (!isNetworkAvailable || isBalanceSufficient) {
return;
}
checkBalance();
if (!isPollingEnabled) {
return;
}
const interval = setInterval(() => {
checkBalance();
}, CHECK_BALANCE_INTERVAL);
return () => {
clearInterval(interval);
};
}, [isBalanceSufficient, isPollingEnabled, checkBalance, isNetworkAvailable]);
useEffect(() => {
onBalanceChange(isBalanceSufficient);
}, [isBalanceSufficient]);
return (
<Modal open={false} disableEscapeKeyDown keepMounted>
<iframe
onLoad={(event) => setIframe(event.target as HTMLIFrameElement)}
id={IFRAME_ID}
src={VITE_WALLET_IFRAME_URL}
width="100%"
height="100%"
sandbox="allow-scripts allow-same-origin"
className="border rounded-md shadow-sm"
/>
</Modal>
);
};
export default CheckBalanceIframe;

View File

@ -1,4 +1,4 @@
import { useCallback, useState, useEffect, useMemo } from 'react'; import { useCallback, useState, useEffect } from 'react';
import { useForm, Controller } from 'react-hook-form'; import { useForm, Controller } from 'react-hook-form';
import { FormProvider, FieldValues } from 'react-hook-form'; import { FormProvider, FieldValues } from 'react-hook-form';
import { useNavigate, useSearchParams } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
@ -8,7 +8,6 @@ import {
AuctionParams, AuctionParams,
Deployer, Deployer,
} from 'gql-client'; } from 'gql-client';
import { BigNumber } from 'ethers';
import { Select, MenuItem, FormControl, FormHelperText } from '@mui/material'; import { Select, MenuItem, FormControl, FormHelperText } from '@mui/material';
@ -21,19 +20,19 @@ import { Button } from '../../shared/Button';
import { Input } from 'components/shared/Input'; import { Input } from 'components/shared/Input';
import { useToast } from 'components/shared/Toast'; import { useToast } from 'components/shared/Toast';
import { useGQLClient } from '../../../context/GQLClientContext'; import { useGQLClient } from '../../../context/GQLClientContext';
import ApproveTransactionModal from './ApproveTransactionModal'; import IFrameModal from './IFrameModal';
import EnvironmentVariablesForm from 'pages/org-slug/projects/id/settings/EnvironmentVariablesForm'; import EnvironmentVariablesForm from 'pages/org-slug/projects/id/settings/EnvironmentVariablesForm';
import { EnvironmentVariablesFormValues } from 'types/types'; import { EnvironmentVariablesFormValues } from 'types/types';
import { import {
VITE_LACONICD_CHAIN_ID,
VITE_WALLET_IFRAME_URL, VITE_WALLET_IFRAME_URL,
} from 'utils/constants'; } from 'utils/constants';
import CheckBalanceIframe from './CheckBalanceIframe'; import AccountsDropdown from './AccountsDropdown';
import { useAddNetwork } from '../../../hooks/useAddNetwork';
type ConfigureDeploymentFormValues = { type ConfigureDeploymentFormValues = {
option: string; option: string;
lrn?: string; lrn?: string;
numProviders?: string; numProviders?: number;
maxPrice?: string; maxPrice?: string;
}; };
@ -47,13 +46,12 @@ const Configure = () => {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [deployers, setDeployers] = useState<Deployer[]>([]); const [deployers, setDeployers] = useState<Deployer[]>([]);
const [selectedAccount, setSelectedAccount] = useState<string>(); const [selectedAccount, setSelectedAccount] = useState<string>();
const [accounts, setAccounts] = useState<string[]>([]);
const [selectedDeployer, setSelectedDeployer] = useState<Deployer>(); const [selectedDeployer, setSelectedDeployer] = useState<Deployer>();
const [isPaymentLoading, setIsPaymentLoading] = useState(false); const [isPaymentLoading, setIsPaymentLoading] = useState(false);
const [isPaymentDone, setIsPaymentDone] = useState(false); const [isPaymentDone, setIsPaymentDone] = useState(false);
const [isFrameVisible, setIsFrameVisible] = useState(false); const [isFrameVisible, setIsFrameVisible] = useState(false);
const [isAccountsDataReceived, setIsAccountsDataReceived] = useState(false); const [isAccountsDataReceived, setIsAccountsDataReceived] = useState(false);
const [balanceMessage, setBalanceMessage] = useState<string>();
const [isBalanceSufficient, setIsBalanceSufficient] = useState<boolean>();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const templateId = searchParams.get('templateId'); const templateId = searchParams.get('templateId');
@ -71,47 +69,22 @@ const Configure = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const { toast, dismiss } = useToast(); const { toast, dismiss } = useToast();
const client = useGQLClient(); const client = useGQLClient();
const { networkData } = useAddNetwork()
const methods = useForm<ConfigureFormValues>({ const methods = useForm<ConfigureFormValues>({
defaultValues: { defaultValues: {
option: 'Auction', option: 'Auction',
maxPrice: DEFAULT_MAX_PRICE, maxPrice: DEFAULT_MAX_PRICE,
lrn: '', lrn: '',
numProviders: '1', numProviders: 1,
variables: [], variables: [],
}, },
}); });
const selectedOption = methods.watch('option'); const selectedOption = methods.watch('option');
const selectedNumProviders = methods.watch('numProviders') ?? '1';
const selectedMaxPrice = methods.watch('maxPrice') ?? DEFAULT_MAX_PRICE;
const isTabletView = useMediaQuery('(min-width: 720px)'); // md: const isTabletView = useMediaQuery('(min-width: 720px)'); // md:
const buttonSize = isTabletView ? { size: 'lg' as const } : {}; const buttonSize = isTabletView ? { size: 'lg' as const } : {};
const amountToBePaid = useMemo(() => {
let amount: string;
if (selectedOption === 'LRN') {
amount = selectedDeployer?.minimumPayment?.replace(/\D/g, '') ?? '0';
} else {
if (!selectedNumProviders || !selectedMaxPrice) {
return '';
}
const bigMaxPrice = BigNumber.from(selectedMaxPrice);
amount = bigMaxPrice.mul(selectedNumProviders).toString();
}
return amount;
}, [
selectedOption,
selectedDeployer?.minimumPayment,
selectedMaxPrice,
selectedNumProviders,
]);
const createProject = async ( const createProject = async (
data: FieldValues, data: FieldValues,
envVariables: AddEnvironmentVariableInput[], envVariables: AddEnvironmentVariableInput[],
@ -213,6 +186,7 @@ const Configure = () => {
(deployer) => deployer.deployerLrn === deployerLrn, (deployer) => deployer.deployerLrn === deployerLrn,
); );
let amount: string;
let senderAddress: string; let senderAddress: string;
let txHash: string | null = null; let txHash: string | null = null;
if (createFormData.option === 'LRN' && !deployer?.minimumPayment) { if (createFormData.option === 'LRN' && !deployer?.minimumPayment) {
@ -230,6 +204,16 @@ const Configure = () => {
senderAddress = selectedAccount; senderAddress = selectedAccount;
if (createFormData.option === 'LRN') {
amount = deployer?.minimumPayment!;
} else {
amount = (
createFormData.numProviders * createFormData.maxPrice
).toString();
}
const amountToBePaid = amount.replace(/\D/g, '').toString();
txHash = await cosmosSendTokensHandler(senderAddress, amountToBePaid); txHash = await cosmosSendTokensHandler(senderAddress, amountToBePaid);
if (!txHash) { if (!txHash) {
@ -319,7 +303,7 @@ const Configure = () => {
throw new Error(error); throw new Error(error);
} }
}, },
[client, createProject, dismiss, toast, amountToBePaid], [client, createProject, dismiss, toast],
); );
const fetchDeployers = useCallback(async () => { const fetchDeployers = useCallback(async () => {
@ -327,6 +311,10 @@ const Configure = () => {
setDeployers(res.deployers); setDeployers(res.deployers);
}, [client]); }, [client]);
const onAccountChange = useCallback((account: string) => {
setSelectedAccount(account);
}, []);
const onDeployerChange = useCallback( const onDeployerChange = useCallback(
(selectedLrn: string) => { (selectedLrn: string) => {
const deployer = deployers.find((d) => d.deployerLrn === selectedLrn); const deployer = deployers.find((d) => d.deployerLrn === selectedLrn);
@ -352,20 +340,12 @@ const Configure = () => {
await requestTx(senderAddress, snowballAddress, amount); await requestTx(senderAddress, snowballAddress, amount);
const txHash = await new Promise<string | null>((resolve, reject) => { const txHash = await new Promise<string | null>((resolve, reject) => {
// Call cleanup method only if appropriate event type is recieved
const cleanup = () => {
setIsFrameVisible(false);
window.removeEventListener('message', handleTxStatus);
};
const handleTxStatus = async (event: MessageEvent) => { const handleTxStatus = async (event: MessageEvent) => {
if (event.origin !== VITE_WALLET_IFRAME_URL) return; if (event.origin !== VITE_WALLET_IFRAME_URL) return;
if (event.data.type === 'TRANSACTION_RESPONSE') { if (event.data.type === 'TRANSACTION_RESPONSE') {
const txResponse = event.data.data; const txResponse = event.data.data;
resolve(txResponse); resolve(txResponse);
cleanup();
} else if (event.data.type === 'ERROR') { } else if (event.data.type === 'ERROR') {
console.error('Error from wallet:', event.data.message); console.error('Error from wallet:', event.data.message);
reject(new Error('Transaction failed')); reject(new Error('Transaction failed'));
@ -375,9 +355,10 @@ const Configure = () => {
variant: 'error', variant: 'error',
onDismiss: dismiss, onDismiss: dismiss,
}); });
cleanup();
} }
setIsFrameVisible(false);
window.removeEventListener('message', handleTxStatus);
}; };
window.addEventListener('message', handleTxStatus); window.addEventListener('message', handleTxStatus);
@ -422,7 +403,7 @@ const Configure = () => {
iframe.contentWindow.postMessage( iframe.contentWindow.postMessage(
{ {
type: 'REQUEST_TX', type: 'REQUEST_TX',
chainId: networkData?.chainId, chainId: VITE_LACONICD_CHAIN_ID,
fromAddress: sender, fromAddress: sender,
toAddress: recipient, toAddress: recipient,
amount, amount,
@ -437,12 +418,6 @@ const Configure = () => {
fetchDeployers(); fetchDeployers();
}, []); }, []);
useEffect(() => {
if (isBalanceSufficient) {
setBalanceMessage(undefined);
}
}, [isBalanceSufficient]);
return ( return (
<div className="space-y-7 px-4 py-6"> <div className="space-y-7 px-4 py-6">
<div className="flex justify-between mb-6"> <div className="flex justify-between mb-6">
@ -559,7 +534,6 @@ const Configure = () => {
type="number" type="number"
value={value} value={value}
onChange={(e) => onChange(e)} onChange={(e) => onChange(e)}
min={1}
/> />
)} )}
/> />
@ -573,7 +547,7 @@ const Configure = () => {
control={methods.control} control={methods.control}
rules={{ required: true }} rules={{ required: true }}
render={({ field: { value, onChange } }) => ( render={({ field: { value, onChange } }) => (
<Input type="number" value={value} onChange={onChange} min={1} /> <Input type="number" value={value} onChange={onChange} />
)} )}
/> />
</div> </div>
@ -605,83 +579,49 @@ const Configure = () => {
</Button> </Button>
</div> </div>
) : ( ) : (
<div className="flex gap-4"> <>
<Button <AccountsDropdown
{...buttonSize} accounts={accounts}
type="submit" onAccountChange={onAccountChange}
shape="default" isDataReceived={isAccountsDataReceived}
disabled={ />
isLoading || {accounts.length > 0 && (
isPaymentLoading || <div>
!selectedAccount || <Button
!isBalanceSufficient || {...buttonSize}
amountToBePaid === '' || type="submit"
selectedNumProviders === '' shape="default"
} disabled={
rightIcon={ isLoading || isPaymentLoading || !selectedAccount
isLoading || isPaymentLoading ? ( }
<LoadingIcon className="animate-spin" /> rightIcon={
) : ( isLoading || isPaymentLoading ? (
<ArrowRightCircleFilledIcon /> <LoadingIcon className="animate-spin" />
)
}
>
{!isPaymentDone
? isPaymentLoading
? 'Transaction Requested'
: 'Pay and Deploy'
: isLoading
? 'Deploying'
: 'Deploy'}
</Button>
{isAccountsDataReceived && isBalanceSufficient !== undefined ? (
!selectedAccount || !isBalanceSufficient ? (
<div className="flex items-center gap-4">
<Button
{...buttonSize}
shape="default"
onClick={(e: any) => {
e.preventDefault();
setBalanceMessage('Waiting for payment');
window.open(
'https://store.laconic.com',
'_blank',
'noopener,noreferrer',
);
}}
>
Buy prepaid service
</Button>
<p className="text-gray-700 dark:text-gray-300">
{balanceMessage !== undefined ? (
<div className="flex items-center gap-2 text-white">
<LoadingIcon className="animate-spin w-5 h-5" />
<p>{balanceMessage}</p>
</div>
) : !selectedAccount ? (
'No accounts found. Create a wallet.'
) : ( ) : (
'Insufficient funds.' <ArrowRightCircleFilledIcon />
)} )
</p> }
</div> >
) : null {!isPaymentDone
) : null} ? isPaymentLoading
</div> ? 'Transaction Requested'
: 'Pay and Deploy'
: isLoading
? 'Deploying'
: 'Deploy'}
</Button>
</div>
)}
</>
)} )}
</form> </form>
</FormProvider> </FormProvider>
<ApproveTransactionModal <IFrameModal
setAccount={setSelectedAccount} setAccounts={setAccounts}
setIsDataReceived={setIsAccountsDataReceived} setIsDataReceived={setIsAccountsDataReceived}
isVisible={isFrameVisible} isVisible={isFrameVisible}
/> />
<CheckBalanceIframe
onBalanceChange={setIsBalanceSufficient}
amount={amountToBePaid}
isPollingEnabled={true}
/>
</div> </div>
</div> </div>
); );

View File

@ -3,38 +3,27 @@ import { useCallback, useEffect } from 'react';
import { Box, Modal } from '@mui/material'; import { Box, Modal } from '@mui/material';
import { import {
VITE_LACONICD_CHAIN_ID,
VITE_WALLET_IFRAME_URL, VITE_WALLET_IFRAME_URL,
} from 'utils/constants'; } from 'utils/constants';
import { REQUEST_WALLET_ACCOUNTS, WALLET_ACCOUNTS_DATA } from '../../../constants';
import { useAddNetwork } from '../../../hooks/useAddNetwork';
const ApproveTransactionModal = ({ const IFrameModal = ({
setAccount, setAccounts,
setIsDataReceived, setIsDataReceived,
isVisible, isVisible,
}: { }: {
setAccount: (account: string) => void; setAccounts: (accounts: string[]) => void;
setIsDataReceived: (isReceived: boolean) => void; setIsDataReceived: (isReceived: boolean) => void;
isVisible: boolean; isVisible: boolean;
}) => { }) => {
const { setIframe, isNetworkAvailable, networkData } = useAddNetwork();
useEffect(() => { useEffect(() => {
const handleMessage = (event: MessageEvent) => { const handleMessage = (event: MessageEvent) => {
if (event.origin !== VITE_WALLET_IFRAME_URL) return; if (event.origin !== VITE_WALLET_IFRAME_URL) return;
if (event.data.type === WALLET_ACCOUNTS_DATA) { setIsDataReceived(true);
setIsDataReceived(true); if (event.data.type === 'WALLET_ACCOUNTS_DATA') {
setAccounts(event.data.data);
if (event.data.data.length === 0) { } else if (event.data.type === 'ERROR') {
console.error(`Accounts not present for chainId: ${networkData?.chainId}`);
return;
}
setAccount(event.data.data[0]);
}
if (event.data.type === 'ERROR') {
console.error('Error from wallet:', event.data.message); console.error('Error from wallet:', event.data.message);
} }
}; };
@ -44,14 +33,9 @@ const ApproveTransactionModal = ({
return () => { return () => {
window.removeEventListener('message', handleMessage); window.removeEventListener('message', handleMessage);
}; };
}, [networkData]); }, []);
const getDataFromWallet = useCallback(() => { const getDataFromWallet = useCallback(() => {
if (!networkData) {
console.error('networkData should not be empty');
return;
}
const iframe = document.getElementById('walletIframe') as HTMLIFrameElement; const iframe = document.getElementById('walletIframe') as HTMLIFrameElement;
if (!iframe.contentWindow) { if (!iframe.contentWindow) {
@ -61,18 +45,12 @@ const ApproveTransactionModal = ({
iframe.contentWindow.postMessage( iframe.contentWindow.postMessage(
{ {
type: REQUEST_WALLET_ACCOUNTS, type: 'REQUEST_WALLET_ACCOUNTS',
chainId: networkData.chainId, chainId: VITE_LACONICD_CHAIN_ID,
}, },
VITE_WALLET_IFRAME_URL, VITE_WALLET_IFRAME_URL,
); );
}, [networkData]); }, []);
useEffect(() => {
if (isNetworkAvailable) {
getDataFromWallet();
}
}, [isNetworkAvailable, getDataFromWallet])
return ( return (
<Modal open={isVisible} disableEscapeKeyDown keepMounted> <Modal open={isVisible} disableEscapeKeyDown keepMounted>
@ -94,7 +72,7 @@ const ApproveTransactionModal = ({
}} }}
> >
<iframe <iframe
onLoad={(event) => setIframe(event.target as HTMLIFrameElement)} onLoad={getDataFromWallet}
id="walletIframe" id="walletIframe"
src={`${VITE_WALLET_IFRAME_URL}/wallet-embed`} src={`${VITE_WALLET_IFRAME_URL}/wallet-embed`}
width="100%" width="100%"
@ -107,4 +85,4 @@ const ApproveTransactionModal = ({
); );
}; };
export default ApproveTransactionModal; export default IFrameModal;

View File

@ -99,6 +99,7 @@ export const DeploymentMenu = ({
const isRollbacked = await client.rollbackDeployment( const isRollbacked = await client.rollbackDeployment(
project.id, project.id,
deployment.id, deployment.id,
deployment.deployer.deployerLrn
); );
if (isRollbacked.rollbackDeployment) { if (isRollbacked.rollbackDeployment) {
await onUpdate(); await onUpdate();

View File

@ -43,11 +43,6 @@ export const AuctionCard = ({ project }: { project: Project }) => {
const checkAuctionStatus = useCallback(async () => { const checkAuctionStatus = useCallback(async () => {
const result = await client.getAuctionData(project.auctionId); const result = await client.getAuctionData(project.auctionId);
if (!result) {
return
}
setAuctionStatus(result.status); setAuctionStatus(result.status);
setAuctionDetails(result); setAuctionDetails(result);
}, [project.auctionId, project.deployers, project.fundsReleased]); }, [project.auctionId, project.deployers, project.fundsReleased]);

View File

@ -8,13 +8,14 @@ import {
MenuList, MenuList,
MenuItem, MenuItem,
Card, Card,
Tooltip,
} from '@snowballtools/material-tailwind-react-fork'; } from '@snowballtools/material-tailwind-react-fork';
import EditDomainDialog from './EditDomainDialog'; import EditDomainDialog from './EditDomainDialog';
import { useGQLClient } from 'context/GQLClientContext'; import { useGQLClient } from 'context/GQLClientContext';
import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog'; import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog';
import { useToast } from 'components/shared/Toast'; import { useToast } from 'components/shared/Toast';
import { GearIcon } from 'components/shared/CustomIcon'; import { GearIcon, InfoRoundFilledIcon } from 'components/shared/CustomIcon';
import { Heading } from 'components/shared/Heading'; import { Heading } from 'components/shared/Heading';
import { Button } from 'components/shared/Button'; import { Button } from 'components/shared/Button';
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
@ -44,7 +45,6 @@ interface DomainCardProps {
onUpdate: () => Promise<void>; onUpdate: () => Promise<void>;
} }
const DomainCard = ({ const DomainCard = ({
domains, domains,
domain, domain,
@ -56,7 +56,9 @@ const DomainCard = ({
const { id } = useParams(); const { id } = useParams();
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [editDialogOpen, setEditDialogOpen] = useState(false); const [editDialogOpen, setEditDialogOpen] = useState(false);
const [dnsRecord, setDnsRecord] = useState<DNSRecordAttributes | null>(null); const [dnsRecordsWithLRN, setDnsRecordsWithLRN] = useState<
{ dnsRecord: DNSRecordAttributes; deployerLRN: string }[]
>([]);
// const [refreshStatus, SetRefreshStatus] = useState(RefreshStatus.IDLE); // const [refreshStatus, SetRefreshStatus] = useState(RefreshStatus.IDLE);
const client = useGQLClient(); const client = useGQLClient();
@ -94,9 +96,26 @@ const DomainCard = ({
return; return;
} }
const dnsRecordResponse = await client.getLatestDNSRecordByProjectId(id); const dnsRecordResponse = await client.getProject(id);
setDnsRecord(dnsRecordResponse.latestDNSRecord); if (!dnsRecordResponse.project) {
return;
}
const tempDNSRecords: {
dnsRecord: DNSRecordAttributes;
deployerLRN: string;
}[] = [];
for (const deployment of dnsRecordResponse.project.deployments) {
if (deployment.dnsRecordData.value) {
tempDNSRecords.push({
dnsRecord: deployment.dnsRecordData,
deployerLRN: deployment.deployer.deployerLrn,
});
}
}
setDnsRecordsWithLRN(tempDNSRecords);
}; };
fetchDNSData(); fetchDNSData();
@ -182,11 +201,16 @@ const DomainCard = ({
<Typography variant="small">Production</Typography> <Typography variant="small">Production</Typography>
{domain.status === DomainStatus.Pending && ( {domain.status === DomainStatus.Pending && (
<Card className="bg-slate-100 p-4 text-sm"> <Card className="bg-slate-100 p-4 text-sm">
{/* {refreshStatus === RefreshStatus.IDLE ? ( */} {dnsRecordsWithLRN.length ? (
<Heading> <>
^ Add these records to your domain {/* and refresh to check */} {/* {refreshStatus === RefreshStatus.IDLE ? ( */}
</Heading> <Heading>
{/* ) : refreshStatus === RefreshStatus.CHECKING ? ( <p className="text-blue-gray-500 pb-3">
^ Add these records to your domain{' '}
{/* and refresh to check */}
</p>
</Heading>
{/* ) : refreshStatus === RefreshStatus.CHECKING ? (
<Heading className="text-blue-500"> <Heading className="text-blue-500">
^ Checking records for {domain.name} ^ Checking records for {domain.name}
</Heading> </Heading>
@ -199,26 +223,49 @@ const DomainCard = ({
</div> </div>
)} */} )} */}
<table> <table>
<thead> <thead>
<tr> <tr>
<th className="text-left">Type</th> <th></th>
<th className="text-left">Name</th> <th className="text-left">Type</th>
<th className="text-left">Value</th> <th className="text-left">Name</th>
</tr> <th className="text-left">Value</th>
</thead> </tr>
<tbody> </thead>
{dnsRecord ? ( {dnsRecordsWithLRN.map((record) => {
<tr> return (
<td>{dnsRecord.resourceType}</td> <>
<td>@</td> <tbody>
<td>{dnsRecord.value ?? 'Not Configured'}</td> <tr>
</tr> <Tooltip
) : ( content={
<p className={'text-red-500'}>DNS record data not available</p> <div>
)} <p className="inline text-white">
</tbody> Service Provider:
</table> </p>
<p className="text-blue-gray-300 pl-2 inline">
{record.deployerLRN}
</p>
</div>
}
>
<td>
<InfoRoundFilledIcon />
</td>
</Tooltip>
<td>{record.dnsRecord.resourceType}</td>
<td>@</td>
<td>{record.dnsRecord.value}</td>
</tr>
</tbody>
</>
);
})}
</table>
</>
) : (
<p className="text-red-500">DNS record data not available</p>
)}
</Card> </Card>
)} )}

View File

@ -1,11 +1,14 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom'; import { useNavigate, useParams } from 'react-router-dom';
import { User } from 'gql-client'; import { User } from 'gql-client';
import { motion } from 'framer-motion'; import { motion } from 'framer-motion';
import { useDisconnect } from 'wagmi';
import { useGQLClient } from 'context/GQLClientContext'; import { useGQLClient } from 'context/GQLClientContext';
import { import {
GlobeIcon,
LifeBuoyIcon, LifeBuoyIcon,
LogoutIcon,
QuestionMarkRoundIcon, QuestionMarkRoundIcon,
} from 'components/shared/CustomIcon'; } from 'components/shared/CustomIcon';
import { Tabs } from 'components/shared/Tabs'; import { Tabs } from 'components/shared/Tabs';
@ -13,9 +16,10 @@ import { Logo } from 'components/Logo';
import { Avatar } from 'components/shared/Avatar'; import { Avatar } from 'components/shared/Avatar';
import { formatAddress } from 'utils/format'; import { formatAddress } from 'utils/format';
import { getInitials } from 'utils/geInitials'; import { getInitials } from 'utils/geInitials';
import { Button } from 'components/shared/Button';
import { cn } from 'utils/classnames'; import { cn } from 'utils/classnames';
import { useMediaQuery } from 'usehooks-ts'; import { useMediaQuery } from 'usehooks-ts';
import { SHOPIFY_APP_URL } from '../../../constants'; import { BASE_URL } from 'utils/constants';
interface SidebarProps { interface SidebarProps {
mobileOpen?: boolean; mobileOpen?: boolean;
@ -23,10 +27,12 @@ interface SidebarProps {
export const Sidebar = ({ mobileOpen }: SidebarProps) => { export const Sidebar = ({ mobileOpen }: SidebarProps) => {
const { orgSlug } = useParams(); const { orgSlug } = useParams();
const navigate = useNavigate();
const client = useGQLClient(); const client = useGQLClient();
const isDesktop = useMediaQuery('(min-width: 960px)'); const isDesktop = useMediaQuery('(min-width: 960px)');
const [user, setUser] = useState<User>(); const [user, setUser] = useState<User>();
const { disconnect } = useDisconnect();
const fetchUser = useCallback(async () => { const fetchUser = useCallback(async () => {
const { user } = await client.getUser(); const { user } = await client.getUser();
@ -37,6 +43,16 @@ export const Sidebar = ({ mobileOpen }: SidebarProps) => {
fetchUser(); fetchUser();
}, []); }, []);
const handleLogOut = useCallback(async () => {
await fetch(`${BASE_URL}/auth/logout`, {
method: 'POST',
credentials: 'include',
});
localStorage.clear();
disconnect();
navigate('/login');
}, [disconnect, navigate]);
return ( return (
<motion.nav <motion.nav
initial={{ x: -320 }} initial={{ x: -320 }}
@ -66,10 +82,19 @@ export const Sidebar = ({ mobileOpen }: SidebarProps) => {
<Tabs defaultValue="Projects" orientation="vertical"> <Tabs defaultValue="Projects" orientation="vertical">
{/* // TODO: use proper link buttons */} {/* // TODO: use proper link buttons */}
<Tabs.List> <Tabs.List>
<Tabs.Trigger
icon={<GlobeIcon />}
value=""
className="hidden lg:flex"
>
<a className="cursor-pointer font-mono" onClick={handleLogOut}>
LOG OUT
</a>
</Tabs.Trigger>
<Tabs.Trigger icon={<QuestionMarkRoundIcon />} value=""> <Tabs.Trigger icon={<QuestionMarkRoundIcon />} value="">
<a <a
className="cursor-pointer font-mono" className="cursor-pointer font-mono"
href={`${SHOPIFY_APP_URL}/pages/instruction-faq`} href="https://store.laconic.com/pages/instruction-faq"
> >
DOCUMENTATION DOCUMENTATION
</a> </a>
@ -100,6 +125,14 @@ export const Sidebar = ({ mobileOpen }: SidebarProps) => {
</p> </p>
</div> </div>
)} )}
<Button
iconOnly
variant="ghost"
className="text-elements-low-em"
onClick={handleLogOut}
>
<LogoutIcon />
</Button>
</div> </div>
</motion.nav> </motion.nav>
); );

View File

@ -1,155 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
import { generateNonce, SiweMessage } from 'siwe';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { Box, Modal } from '@mui/material';
import { BASE_URL, VITE_WALLET_IFRAME_URL } from 'utils/constants';
import { REQUEST_CREATE_OR_GET_ACCOUNTS, WALLET_ACCOUNTS_DATA } from '../../../constants';
const axiosInstance = axios.create({
baseURL: BASE_URL,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
withCredentials: true,
});
const AutoSignInIFrameModal = () => {
const navigate = useNavigate();
const [accountAddress, setAccountAddress] = useState();
useEffect(() => {
const handleSignInResponse = async (event: MessageEvent) => {
if (event.origin !== VITE_WALLET_IFRAME_URL) return;
if (event.data.type === 'SIGN_IN_RESPONSE') {
try {
const { success } = (
await axiosInstance.post('/auth/validate', {
message: event.data.data.message,
signature: event.data.data.signature,
})
).data;
if (success === true) {
navigate('/');
}
} catch (error) {
console.error('Error signing in:', error);
}
}
};
window.addEventListener('message', handleSignInResponse);
return () => {
window.removeEventListener('message', handleSignInResponse);
};
}, []);
useEffect(() => {
const initiateAutoSignIn = async () => {
if (!accountAddress) return;
const iframe = document.getElementById(
'autoSignInFrame',
) as HTMLIFrameElement;
if (!iframe.contentWindow) {
console.error('Iframe not found or not loaded');
return;
}
const message = new SiweMessage({
version: '1',
domain: window.location.host,
uri: window.location.origin,
chainId: 1,
address: accountAddress,
nonce: generateNonce(),
// Human-readable ASCII assertion that the user will sign, and it must not contain `\n`.
statement: 'Sign in With Ethereum.',
}).prepareMessage();
iframe.contentWindow.postMessage(
{
type: 'AUTO_SIGN_IN',
chainId: '1',
message,
},
VITE_WALLET_IFRAME_URL,
);
};
initiateAutoSignIn();
}, [accountAddress]);
useEffect(() => {
const handleAccountsDataResponse = async (event: MessageEvent) => {
if (event.origin !== VITE_WALLET_IFRAME_URL) return;
if (event.data.type === WALLET_ACCOUNTS_DATA) {
setAccountAddress(event.data.data[0]);
}
};
window.addEventListener('message', handleAccountsDataResponse);
return () => {
window.removeEventListener('message', handleAccountsDataResponse);
};
}, []);
const getAddressFromWallet = useCallback(() => {
const iframe = document.getElementById(
'autoSignInFrame',
) as HTMLIFrameElement;
if (!iframe.contentWindow) {
console.error('Iframe not found or not loaded');
return;
}
iframe.contentWindow.postMessage(
{
type: REQUEST_CREATE_OR_GET_ACCOUNTS,
chainId: '1',
},
VITE_WALLET_IFRAME_URL,
);
}, []);
return (
<Modal open={true} disableEscapeKeyDown keepMounted>
<Box
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: '90%',
maxWidth: '1200px',
height: '600px',
maxHeight: '80vh',
overflow: 'auto',
outline: 'none',
}}
>
<iframe
onLoad={getAddressFromWallet}
id="autoSignInFrame"
src={`${VITE_WALLET_IFRAME_URL}/auto-sign-in`}
width="100%"
height="100%"
sandbox="allow-scripts allow-same-origin"
></iframe>
</Box>
</Modal>
);
};
export default AutoSignInIFrameModal;

View File

@ -1,16 +1,3 @@
export const SHORT_COMMIT_HASH_LENGTH = 8; export const SHORT_COMMIT_HASH_LENGTH = 8;
export const SERVER_GQL_PATH = 'graphql'; export const SERVER_GQL_PATH = 'graphql';
export const SHOPIFY_APP_URL = 'https://store.laconic.com';
// iframe request types
export const REQUEST_CREATE_OR_GET_ACCOUNTS = 'REQUEST_CREATE_OR_GET_ACCOUNTS';
export const REQUEST_ADD_NETWORK = 'REQUEST_ADD_NETWORK';
export const REQUEST_WALLET_ACCOUNTS = 'REQUEST_WALLET_ACCOUNTS';
// iframe response types
export const WALLET_ACCOUNTS_DATA = 'WALLET_ACCOUNTS_DATA';
export const NETWORK_ADDED_RESPONSE = "NETWORK_ADDED_RESPONSE";
export const NETWORK_ALREADY_EXISTS_RESPONSE = "NETWORK_ALREADY_EXISTS_RESPONSE";
export const NETWORK_ADD_FAILED_RESPONSE = "NETWORK_ADD_FAILED_RESPONSE";

View File

@ -0,0 +1,116 @@
import { ReactNode } from 'react';
import assert from 'assert';
import { SiweMessage, generateNonce } from 'siwe';
import { WagmiProvider } from 'wagmi';
import { mainnet } from 'wagmi/chains';
import axios from 'axios';
import { createWeb3Modal } from '@web3modal/wagmi/react';
import { defaultWagmiConfig } from '@web3modal/wagmi/react/config';
import { createSIWEConfig } from '@web3modal/siwe';
import type {
SIWECreateMessageArgs,
SIWEVerifyMessageArgs,
} from '@web3modal/core';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { VITE_WALLET_CONNECT_ID, BASE_URL } from 'utils/constants';
if (!VITE_WALLET_CONNECT_ID) {
throw new Error('Error: VITE_WALLET_CONNECT_ID env config is not set');
}
assert(BASE_URL, 'VITE_SERVER_URL is not set in env');
const queryClient = new QueryClient();
const axiosInstance = axios.create({
baseURL: BASE_URL,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
withCredentials: true,
});
const metadata = {
name: 'Deploy App Auth',
description: '',
url: window.location.origin,
icons: ['https://avatars.githubusercontent.com/u/37784886'],
};
const chains = [mainnet] as const;
const config = defaultWagmiConfig({
chains,
projectId: VITE_WALLET_CONNECT_ID,
metadata,
});
const siweConfig = createSIWEConfig({
createMessage: ({ nonce, address, chainId }: SIWECreateMessageArgs) =>
new SiweMessage({
version: '1',
domain: window.location.host,
uri: window.location.origin,
address,
chainId,
nonce,
// Human-readable ASCII assertion that the user will sign, and it must not contain `\n`.
statement: 'Sign in With Ethereum.',
}).prepareMessage(),
getNonce: async () => {
return generateNonce();
},
getSession: async () => {
try {
const session = (await axiosInstance.get('/auth/session')).data;
const { address, chainId } = session;
return { address, chainId };
} catch (err) {
if (window.location.pathname !== '/login') {
window.location.href = '/login';
}
throw new Error('Failed to get session!');
}
},
verifyMessage: async ({ message, signature }: SIWEVerifyMessageArgs) => {
try {
const { success } = (
await axiosInstance.post('/auth/validate', {
message,
signature,
})
).data;
return success;
} catch (error) {
return false;
}
},
signOut: async () => {
try {
const { success } = (await axiosInstance.post('/auth/logout')).data;
return success;
} catch (error) {
return false;
}
},
onSignOut: () => {
window.location.href = '/login';
},
onSignIn: () => {
window.location.href = '/';
},
});
createWeb3Modal({
siweConfig,
wagmiConfig: config,
projectId: VITE_WALLET_CONNECT_ID,
});
export default function Web3ModalProvider({
children,
}: {
children: ReactNode;
}) {
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</WagmiProvider>
);
}

View File

@ -1,92 +0,0 @@
import { useState, useEffect } from 'react';
import { VITE_WALLET_IFRAME_URL } from 'utils/constants';
import { NETWORK_ADD_FAILED_RESPONSE, NETWORK_ADDED_RESPONSE, NETWORK_ALREADY_EXISTS_RESPONSE, REQUEST_ADD_NETWORK } from '../constants';
interface NetworkData {
chainId: string;
namespace: string;
networkName: string;
rpcUrl: string;
coinType: string;
addressPrefix?: string;
blockExplorerUrl?: string;
nativeDenom?: string;
gasPrice?: string;
}
export const useAddNetwork = () => {
const [networkData, setNetworkData] = useState<NetworkData | null>(null);
const [iframe, setIframe] = useState<HTMLIFrameElement | null>(null);
const [isNetworkAvailable, setIsNetworkAvailable] = useState(false);
// useEffect to add network in embedded wallet
useEffect(() => {
if (!networkData) {
return;
}
if (!iframe?.contentWindow) {
return;
}
iframe.contentWindow.postMessage(
{
type: REQUEST_ADD_NETWORK,
chainId: networkData.chainId,
networkData,
},
VITE_WALLET_IFRAME_URL,
);
}, [networkData, iframe]);
// useEffect to listen for network add reponses
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
if (event.origin !== VITE_WALLET_IFRAME_URL) return;
switch (event.data.type) {
case NETWORK_ADDED_RESPONSE:
case NETWORK_ALREADY_EXISTS_RESPONSE:
// Once network is available, set state
setIsNetworkAvailable(true);
break;
case NETWORK_ADD_FAILED_RESPONSE:
setIsNetworkAvailable(false);
console.error("Network could not be added:", event.data.message);
break;
default:
break;
}
};
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, []);
useEffect(() => {
const loadNetworkData = async () => {
try {
const res = await fetch('/network.json');
const json = await res.json();
setNetworkData(json);
} catch (err) {
console.error('Failed to load network data:', err);
}
};
loadNetworkData();
}, []);
return {
networkData,
isNetworkAvailable,
iframe,
setIframe
};
};

View File

@ -1,50 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import { useAddNetwork } from './useAddNetwork';
const useCheckBalance = (amount: string, iframeId: string) => {
const [isBalanceSufficient, setIsBalanceSufficient] = useState<boolean>();
const { networkData } = useAddNetwork()
const checkBalance = useCallback(() => {
if (!networkData) {
return;
}
const iframe = document.getElementById(iframeId) as HTMLIFrameElement;
if (!iframe || !iframe.contentWindow) {
console.error(`Iframe with ID "${iframeId}" not found or not loaded`);
return;
}
iframe.contentWindow.postMessage(
{
type: 'CHECK_BALANCE',
chainId: networkData.chainId,
amount,
},
import.meta.env.VITE_WALLET_IFRAME_URL
);
}, [iframeId, amount, networkData]);
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
if (event.origin !== import.meta.env.VITE_WALLET_IFRAME_URL) return;
if (event.data.type !== 'IS_SUFFICIENT') return;
setIsBalanceSufficient(event.data.data);
};
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, []);
return { isBalanceSufficient, checkBalance };
};
export default useCheckBalance;

View File

@ -14,6 +14,7 @@ import { SERVER_GQL_PATH } from './constants';
import { Toaster } from 'components/shared/Toast'; import { Toaster } from 'components/shared/Toast';
import { LogErrorBoundary } from 'utils/log-error'; import { LogErrorBoundary } from 'utils/log-error';
import { BASE_URL } from 'utils/constants'; import { BASE_URL } from 'utils/constants';
import Web3ModalProvider from './context/Web3Provider';
import './index.css'; import './index.css';
console.log(`v-0.0.9`); console.log(`v-0.0.9`);
@ -31,10 +32,12 @@ root.render(
<LogErrorBoundary> <LogErrorBoundary>
<React.StrictMode> <React.StrictMode>
<ThemeProvider> <ThemeProvider>
<GQLClientProvider client={gqlClient}> <Web3ModalProvider>
<App /> <GQLClientProvider client={gqlClient}>
<Toaster /> <App />
</GQLClientProvider> <Toaster />
</GQLClientProvider>
</Web3ModalProvider>
</ThemeProvider> </ThemeProvider>
</React.StrictMode> </React.StrictMode>
</LogErrorBoundary>, </LogErrorBoundary>,

View File

@ -1,4 +1,4 @@
import AutoSignInIFrameModal from 'components/shared/auth/AutoSignInIFrameModal'; import { Login } from './auth/Login';
const AuthPage = () => { const AuthPage = () => {
return ( return (
@ -13,7 +13,9 @@ const AuthPage = () => {
</div> </div>
</div> </div>
<div className="pb-12 relative z-10 flex-1 flex-center"> <div className="pb-12 relative z-10 flex-1 flex-center">
<AutoSignInIFrameModal /> <div className="max-w-[520px] w-full dark:bg-overlay bg-white rounded-xl shadow">
<Login />
</div>
</div> </div>
</div> </div>
); );

View File

@ -1,38 +0,0 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useMediaQuery } from 'usehooks-ts';
import { Button } from 'components/shared';
import CheckBalanceIframe from 'components/projects/create/CheckBalanceIframe';
import { SHOPIFY_APP_URL } from '../constants';
const BuyPrepaidService = () => {
const navigate = useNavigate();
const [isBalanceSufficient, setIsBalanceSufficient] = useState<boolean>();
const isTabletView = useMediaQuery('(min-width: 720px)'); // md:
const buttonSize = isTabletView ? { size: 'lg' as const } : {};
useEffect(() => {
if (isBalanceSufficient === true) {
navigate('/');
}
}, [isBalanceSufficient]);
return (
<div className="dark:bg-background flex flex-col min-h-screen">
<div className="pb-12 relative z-10 flex-1 flex-center">
<Button {...buttonSize} shape={'default'}>
<a href={SHOPIFY_APP_URL} target="_blank">
Buy prepaid service
</a>
</Button>
</div>
<CheckBalanceIframe onBalanceChange={setIsBalanceSufficient} isPollingEnabled={true} amount='1'/>
</div>
);
};
export default BuyPrepaidService;

View File

@ -9,6 +9,12 @@ export const Login = () => {
</div> </div>
</div> </div>
<WavyBorder className="self-stretch" variant="stroke" /> <WavyBorder className="self-stretch" variant="stroke" />
<div className="self-stretch p-4 xs:p-6 flex-col justify-center items-center gap-8 flex">
<div className="self-stretch flex-col justify-center items-center gap-3 flex">
<w3m-button />
</div>
</div>
</div> </div>
); );
}; };

View File

@ -13,6 +13,7 @@ import {
AppDeploymentRecordAttributes, AppDeploymentRecordAttributes,
Deployment, Deployment,
DeploymentStatus, DeploymentStatus,
DNSRecordAttributes,
Domain, Domain,
DomainStatus, DomainStatus,
Environment, Environment,
@ -50,6 +51,7 @@ const deployment: Deployment = {
applicationDeploymentRequestId: applicationDeploymentRequestId:
'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize', 'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize',
applicationDeploymentRecordData: {} as AppDeploymentRecordAttributes, applicationDeploymentRecordData: {} as AppDeploymentRecordAttributes,
dnsRecordData: {} as DNSRecordAttributes,
}; };
const domains: Domain[] = [ const domains: Domain[] = [

View File

@ -1,20 +1,16 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom'; import { Link, useParams } from 'react-router-dom';
import { ProjectCard } from 'components/projects/ProjectCard'; import { ProjectCard } from 'components/projects/ProjectCard';
import { Heading, Badge, Button } from 'components/shared'; import { Heading, Badge, Button } from 'components/shared';
import { PlusIcon } from 'components/shared/CustomIcon'; import { PlusIcon } from 'components/shared/CustomIcon';
import { useGQLClient } from 'context/GQLClientContext'; import { useGQLClient } from 'context/GQLClientContext';
import { Project } from 'gql-client'; import { Project } from 'gql-client';
import CheckBalanceIframe from 'components/projects/create/CheckBalanceIframe';
const Projects = () => { const Projects = () => {
const [isBalanceSufficient, setIsBalanceSufficient] = useState<boolean>();
const [projects, setProjects] = useState<Project[]>([]);
const navigate = useNavigate();
const client = useGQLClient(); const client = useGQLClient();
const { orgSlug } = useParams(); const { orgSlug } = useParams();
const [projects, setProjects] = useState<Project[]>([]);
const fetchProjects = useCallback(async () => { const fetchProjects = useCallback(async () => {
const { projectsInOrganization } = await client.getProjectsInOrganization( const { projectsInOrganization } = await client.getProjectsInOrganization(
@ -27,12 +23,6 @@ const Projects = () => {
fetchProjects(); fetchProjects();
}, [orgSlug]); }, [orgSlug]);
useEffect(() => {
if (isBalanceSufficient === false) {
navigate('/buy-prepaid-service');
}
}, [isBalanceSufficient]);
return ( return (
<section className="px-4 md:px-6 py-6 flex flex-col gap-6"> <section className="px-4 md:px-6 py-6 flex flex-col gap-6">
{/* Header */} {/* Header */}
@ -59,8 +49,6 @@ const Projects = () => {
return <ProjectCard project={project} key={key} />; return <ProjectCard project={project} key={key} />;
})} })}
</div> </div>
<CheckBalanceIframe onBalanceChange={setIsBalanceSufficient} isPollingEnabled={false} amount='1' />
</section> </section>
); );
}; };

View File

@ -204,7 +204,7 @@ const OverviewTabPanel = () => {
{project.deployments && {project.deployments &&
project.deployments.length > 0 && project.deployments.length > 0 &&
project.deployments.map((deployment) => ( project.deployments.map((deployment) => (
<div key={deployment.id} className="flex gap-2 items-center"> <div className="flex gap-2 items-center">
<Link to={deployment.applicationDeploymentRecordData.url}> <Link to={deployment.applicationDeploymentRecordData.url}>
<span className="text-controls-primary dark:text-foreground group hover:border-controls-primary transition-colors border-b border-b-transparent flex gap-2 items-center text-sm tracking-tight"> <span className="text-controls-primary dark:text-foreground group hover:border-controls-primary transition-colors border-b border-b-transparent flex gap-2 items-center text-sm tracking-tight">
{deployment.applicationDeploymentRecordData.url} {deployment.applicationDeploymentRecordData.url}

View File

@ -60,39 +60,31 @@ const Domains = () => {
return ( return (
<ProjectSettingContainer <ProjectSettingContainer
headingText="Domains" headingText="Domains"
{...(!project.auctionId && { button={
button: ( <Button
<Button as="a"
as="a" href="add"
href="add" variant="secondary"
variant="secondary" leftIcon={<PlusIcon />}
leftIcon={<PlusIcon />} size="md"
size="md" >
> Add domain
Add domain </Button>
</Button> }
),
})}
> >
{project.auctionId ? ( {domains.map((domain) => {
<p className="text-gray-500"> return (
Custom domains not supported for auction driven deployments. <DomainCard
</p> domains={domains}
) : ( domain={domain}
domains.map((domain) => { key={domain.id}
return ( // TODO: Use github API for getting linked repository
<DomainCard branches={branches}
domains={domains} project={project}
domain={domain} onUpdate={fetchDomains}
key={domain.id} />
// TODO: Use github API for getting linked repository );
branches={branches} })}
project={project}
onUpdate={fetchDomains}
/>
);
})
)}
</ProjectSettingContainer> </ProjectSettingContainer>
); );
}; };

View File

@ -18,7 +18,9 @@ const Config = () => {
const primaryDomainName = searchParams.get('name'); const primaryDomainName = searchParams.get('name');
const { toast, dismiss } = useToast(); const { toast, dismiss } = useToast();
const [dnsRecord, setDnsRecord] = useState<DNSRecordAttributes | null>(null); const [dnsRecordsWithLRN, setDnsRecordsWithLRN] = useState<
{ dnsRecord: DNSRecordAttributes; deployerLRN: string }[]
>([]);
const handleSubmitDomain = async () => { const handleSubmitDomain = async () => {
if (primaryDomainName === null) { if (primaryDomainName === null) {
@ -75,9 +77,26 @@ const Config = () => {
return; return;
} }
const dnsRecordResponse = await client.getLatestDNSRecordByProjectId(id); const dnsRecordResponse = await client.getProject(id);
setDnsRecord(dnsRecordResponse.latestDNSRecord); if (!dnsRecordResponse.project) {
return;
}
const tempDNSRecords: {
dnsRecord: DNSRecordAttributes;
deployerLRN: string;
}[] = [];
for (const deployment of dnsRecordResponse.project.deployments) {
if (deployment.dnsRecordData.value) {
tempDNSRecords.push({
dnsRecord: deployment.dnsRecordData,
deployerLRN: deployment.deployer.deployerLrn,
});
}
}
setDnsRecordsWithLRN(tempDNSRecords);
}; };
fetchDNSData(); fetchDNSData();
@ -86,57 +105,66 @@ const Config = () => {
// TODO: Figure out DNS Provider if possible and update appropriatly // TODO: Figure out DNS Provider if possible and update appropriatly
return ( return (
<ProjectSettingContainer headingText="Setup domain name"> <ProjectSettingContainer headingText="Setup domain name">
{dnsRecord ? ( {dnsRecordsWithLRN.length ? (
<> <>
<p className="text-blue-gray-500"> <p className="text-blue-gray-500">
Add the following records to your domain. Add the following records to your domain.
</p> </p>
{dnsRecordsWithLRN.map((record) => {
<Table> if (record.dnsRecord.value) {
<Table.Header> return (
<Table.Row> <>
<Table.ColumnHeaderCell>Type</Table.ColumnHeaderCell> <div className="pt-6">
<Table.ColumnHeaderCell>Host</Table.ColumnHeaderCell> <p className="text-gray-100 inline">Service Provider:</p>
<Table.ColumnHeaderCell>Value</Table.ColumnHeaderCell> <p className="text-blue-gray-500 pl-2 inline">
</Table.Row> {record.deployerLRN}
</Table.Header> </p>
</div>
<Table.Body> <Table>
<Table.Row> <Table.Header>
<Table.RowHeaderCell> <Table.Row>
{dnsRecord.resourceType} <Table.ColumnHeaderCell>Type</Table.ColumnHeaderCell>
</Table.RowHeaderCell> <Table.ColumnHeaderCell>Host</Table.ColumnHeaderCell>
<Table.Cell>@</Table.Cell> <Table.ColumnHeaderCell>Value</Table.ColumnHeaderCell>
<Table.Cell> </Table.Row>
<p className={!dnsRecord.value ? 'text-red-500' : ''}> </Table.Header>
{dnsRecord.value ?? 'Not available'} <Table.Body>
</p> <Table.Row>
</Table.Cell> <Table.RowHeaderCell>
</Table.Row> {record.dnsRecord.resourceType}
</Table.Body> </Table.RowHeaderCell>
</Table> <Table.Cell>@</Table.Cell>
<Table.Cell>
{dnsRecord?.value && ( <p>{record.dnsRecord.value}</p>
<InlineNotification </Table.Cell>
variant="info" </Table.Row>
title={`It can take up to 48 hours for these updates to reflect </Table.Body>
globally.`} </Table>
/> </>
)} );
<Button }
className="w-fit" })}
disabled={!dnsRecord?.value}
onClick={handleSubmitDomain}
variant="primary"
shape="default"
rightIcon={<ArrowRightCircleIcon />}
>
FINISH
</Button>
</> </>
) : ( ) : (
<p className={'text-red-500'}>DNS record data not available</p> <p className={'text-red-500'}>DNS record data not available</p>
)} )}
{dnsRecordsWithLRN.length && (
<InlineNotification
variant="info"
title={`It can take up to 48 hours for these updates to reflect
globally.`}
/>
)}
<Button
className="w-fit"
disabled={!dnsRecordsWithLRN.length}
onClick={handleSubmitDomain}
variant="primary"
shape="default"
rightIcon={<ArrowRightCircleIcon />}
>
FINISH
</Button>
</ProjectSettingContainer> </ProjectSettingContainer>
); );
}; };

View File

@ -13,6 +13,7 @@ import {
Environment, Environment,
Permission, Permission,
AppDeploymentRecordAttributes, AppDeploymentRecordAttributes,
DNSRecordAttributes,
} from 'gql-client'; } from 'gql-client';
export const user: User = { export const user: User = {
@ -112,6 +113,7 @@ export const deployment0: Deployment = {
applicationDeploymentRequestId: applicationDeploymentRequestId:
'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize', 'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize',
applicationDeploymentRecordData: {} as AppDeploymentRecordAttributes, applicationDeploymentRecordData: {} as AppDeploymentRecordAttributes,
dnsRecordData: {} as DNSRecordAttributes,
}; };
export const project: Project = { export const project: Project = {

View File

@ -8,6 +8,8 @@ export const VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO = import.meta.env
export const VITE_GITHUB_NEXT_APP_TEMPLATE_REPO = import.meta.env export const VITE_GITHUB_NEXT_APP_TEMPLATE_REPO = import.meta.env
.VITE_GITHUB_NEXT_APP_TEMPLATE_REPO; .VITE_GITHUB_NEXT_APP_TEMPLATE_REPO;
export const VITE_GITHUB_CLIENT_ID = import.meta.env.VITE_GITHUB_CLIENT_ID; export const VITE_GITHUB_CLIENT_ID = import.meta.env.VITE_GITHUB_CLIENT_ID;
export const VITE_WALLET_CONNECT_ID = import.meta.env.VITE_WALLET_CONNECT_ID;
export const VITE_BUGSNAG_API_KEY = import.meta.env.VITE_BUGSNAG_API_KEY; export const VITE_BUGSNAG_API_KEY = import.meta.env.VITE_BUGSNAG_API_KEY;
export const VITE_LIT_RELAY_API_KEY = import.meta.env.VITE_LIT_RELAY_API_KEY; export const VITE_LIT_RELAY_API_KEY = import.meta.env.VITE_LIT_RELAY_API_KEY;
export const VITE_LACONICD_CHAIN_ID = import.meta.env.VITE_LACONICD_CHAIN_ID;
export const VITE_WALLET_IFRAME_URL = import.meta.env.VITE_WALLET_IFRAME_URL; export const VITE_WALLET_IFRAME_URL = import.meta.env.VITE_WALLET_IFRAME_URL;

View File

@ -0,0 +1,8 @@
import { WalletConnectModal } from '@walletconnect/modal';
import { VITE_WALLET_CONNECT_ID } from 'utils/constants';
export const walletConnectModal = new WalletConnectModal({
projectId: VITE_WALLET_CONNECT_ID,
chains: [],
});

View File

@ -337,13 +337,15 @@ export class GQLClient {
async rollbackDeployment( async rollbackDeployment(
projectId: string, projectId: string,
deploymentId: string deploymentId: string,
deployerLrn: string,
): Promise<types.RollbackDeploymentResponse> { ): Promise<types.RollbackDeploymentResponse> {
const { data } = await this.client.mutate({ const { data } = await this.client.mutate({
mutation: mutations.rollbackDeployment, mutation: mutations.rollbackDeployment,
variables: { variables: {
projectId, projectId,
deploymentId, deploymentId,
deployerLrn,
}, },
}); });
@ -414,25 +416,14 @@ export class GQLClient {
return data; return data;
} }
async getAuctionData(auctionId: string): Promise<types.Auction | null> { async getAuctionData(auctionId: string): Promise<types.Auction> {
const { data, errors } = await this.client.query({ const { data } = await this.client.query({
query: queries.getAuctionData, query: queries.getAuctionData,
variables: { variables: {
auctionId, auctionId,
}, },
}); });
if (errors && errors.length) {
const isAuctionNotFound = errors.some((error) =>
error.message?.includes('Auction not found')
);
if (isAuctionNotFound) {
return data;
}
}
return data.getAuctionData; return data.getAuctionData;
} }

View File

@ -95,8 +95,8 @@ export const deleteDomain = gql`
`; `;
export const rollbackDeployment = gql` export const rollbackDeployment = gql`
mutation ($projectId: String!, $deploymentId: String!) { mutation ($projectId: String!, $deployerLrn: String!) {
rollbackDeployment(projectId: $projectId, deploymentId: $deploymentId) rollbackDeployment(projectId: $projectId, deployerLrn: $deployerLrn)
} }
`; `;

View File

@ -62,11 +62,19 @@ query ($projectId: String!) {
} }
deployer { deployer {
baseDomain baseDomain
deployerLrn
} }
createdBy { createdBy {
id id
name name
} }
dnsRecordData {
name
value
request
resourceType
version
}
} }
} }
} }

View File

@ -112,6 +112,7 @@ export type Deployment = {
createdBy: User; createdBy: User;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
dnsRecordData: DNSRecordAttributes;
applicationDeploymentRequestId: string; applicationDeploymentRequestId: string;
}; };

View File

@ -1,7 +0,0 @@
# Initial Commit for QWRK UX Changes
This is the first commit for QWRK UX changes to a fork of the `snowballtools-base` repository in Gitea. This commit sets the foundation for the upcoming user experience improvements and modifications.
- Repository: `snowballtools-base`
- Platform: Gitea
- Purpose: QWRK UX changes

1157
yarn.lock

File diff suppressed because it is too large Load Diff