Compare commits

..
32 Commits
Author SHA1 Message Date
IshaVenikar a17386eb68 Update method name to get record by Id
Lint / lint (20.x) (pull_request) Successful in 4m40s
2025-02-03 09:23:03 +05:30
Shreerang Kale f318a95641 Fix custom domain not showing up in UI 2025-02-03 09:23:03 +05:30
Shreerang Kale e9f746cd8b Revert removing order while getting latest DNS data 2025-02-03 09:23:03 +05:30
IshaVenikar e59c14440c Fix check for setting isCurrent 2025-02-03 09:23:03 +05:30
IshaVenikar 22f8a8c943 Update method to return single DNS record by ID 2025-02-03 09:23:03 +05:30
IshaVenikar df5062c75f Remove ununsed imports 2025-02-03 09:23:03 +05:30
Shreerang Kale 22e814840e Fix method to get latest DNS data 2025-02-03 09:23:03 +05:30
IshaVenikar 9d27dd568a Update isCurrent status for commit deployments 2025-02-03 09:23:03 +05:30
Shreerang Kale fc62392c83 Update methods for using stored DNS deployments in UI 2025-02-03 09:23:03 +05:30
IshaVenikar 2ee65b8fd8 Remove ununsed variables 2025-02-03 09:23:03 +05:30
IshaVenikar d0302d0153 Store domain for DNS deployments after previous deployment is deleted 2025-02-03 09:23:03 +05:30
Shreerang Kale 90e9260eb6 Update UI when IP address is unavailable and project is created via auctions 2025-02-03 09:23:03 +05:30
IshaVenikar 6dcee29487 Update flow for deleting deployments 2025-02-03 09:23:03 +05:30
IshaVenikar 5be10b6b0a Implement functionality to store DNS deployment 2025-02-03 09:23:01 +05:30
Shreerang Kale 6e8af82dc2 Make service provider domains non clickable 2025-02-03 09:18:14 +05:30
Shreerang Kale 1a5ab4d47e Remove showing domain status in overview pannel 2025-02-03 09:18:14 +05:30
Shreerang Kale 6df685831f Populate domainId while creating deployment 2025-02-03 09:18:14 +05:30
IshaVenikar 13892015a5 Store DNS deployment records data in Deployment entity 2025-02-03 09:18:14 +05:30
Shreerang Kale 55500b5914 Display custom domain in project card 2025-02-03 09:18:14 +05:30
Shreerang Kale a7190ed804 Show custom domain in overview tabs panel 2025-02-03 09:18:14 +05:30
Shreerang Kale 6a79ee5c47 Remove UI elements for domain verification 2025-02-03 09:18:14 +05:30
Shreerang Kale f2ba931961 Update method to show IP address 2025-02-03 09:18:14 +05:30
IshaVenikar 85b4265fbe Query DNS records by Id 2025-02-03 09:18:14 +05:30
Shreerang Kale 63223a4807 Get DNS records for all completed deployments 2025-02-03 09:18:14 +05:30
Shreerang Kale 9784eb4f4a Fix DNS records data not getting stored in the DB 2025-02-03 09:18:14 +05:30
Shreerang Kale 624f36155a Fix deploy button disabled for deployers with no min payment 2025-02-03 09:18:14 +05:30
IshaVenikar 82c4b71694 Use oldest custom domain in deployment requests 2025-02-03 09:18:14 +05:30
Shreerang Kale 5d9c965f54 Show service provider IP address while creating custom domain 2025-02-03 09:18:14 +05:30
IshaVenikar 56eccb48b3 Add method to fetch DNS data for latest deployment 2025-02-03 09:18:14 +05:30
Shreerang Kale b5762432e6 Remove redirect domain from edit domain form 2025-02-03 09:18:14 +05:30
Shreerang Kale 4ae4670dca Remove redirect domain creation while adding custom domain 2025-02-03 09:18:14 +05:30
IshaVenikar c202554002 Store DNS record data for deployments 2025-02-03 09:18:14 +05:30
54 changed files with 2221 additions and 1649 deletions
+3 -3
View File
@@ -47,11 +47,11 @@ jobs:
cat > packages/deployer/config.yml <<EOF
services:
registry:
rpcEndpoint: https://laconicd-mainnet-1.laconic.com
gqlEndpoint: https://laconicd-mainnet-1.laconic.com/api
rpcEndpoint: https://laconicd-sapo.laconic.com
gqlEndpoint: https://laconicd-sapo.laconic.com/api
userKey: $REGISTRY_USER_KEY
bondId: $REGISTRY_BOND_ID
chainId: laconic-mainnet
chainId: laconic-testnet-2
gasPrice: 0.001alnt
EOF
+2
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_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_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_LIT_RELAY_API_KEY = 'LACONIC_HOSTED_CONFIG_lit_relay_api_key'
VITE_BUGSNAG_API_KEY = 'LACONIC_HOSTED_CONFIG_bugsnag_api_key'
+2 -3
View File
@@ -14,6 +14,5 @@
"prepare": "husky install",
"build": "lerna run build --stream",
"lint": "lerna run lint --stream"
},
"packageManager": "yarn@1.22.19+sha1.4ba7fc5c6e704fce2066ecbfb0b0d8976fe62447"
}
}
}
+102 -117
View File
@@ -5,7 +5,7 @@ import {
FindOneOptions,
FindOptionsWhere,
IsNull,
Not,
Not
} from 'typeorm';
import path from 'path';
import debug from 'debug';
@@ -16,7 +16,7 @@ import { lowercase, numbers } from 'nanoid-dictionary';
import { DatabaseConfig } from './config';
import { User } from './entity/User';
import { Organization } from './entity/Organization';
import { AuctionStatus, Project } from './entity/Project';
import { Project } from './entity/Project';
import { Deployment, DeploymentStatus } from './entity/Deployment';
import { ProjectMember } from './entity/ProjectMember';
import { EnvironmentVariable } from './entity/EnvironmentVariable';
@@ -42,7 +42,7 @@ export class Database {
database: dbPath,
entities: [path.join(__dirname, '/entity/*')],
synchronize: true,
logging: false,
logging: false
});
}
@@ -54,24 +54,21 @@ export class Database {
// Load an organization if none exist
if (!organizations.length) {
const orgEntities = await getEntities(
path.resolve(__dirname, ORGANIZATION_DATA_PATH),
);
organizations = await loadAndSaveData(Organization, this.dataSource, [
orgEntities[0],
]);
const orgEntities = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH));
organizations = await loadAndSaveData(Organization, this.dataSource, [orgEntities[0]]);
}
// Hotfix for updating old DB data
if (organizations[0].slug === 'snowball-tools-1') {
const [orgEntity] = await getEntities(
path.resolve(__dirname, ORGANIZATION_DATA_PATH),
);
const [orgEntity] = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH));
await this.updateOrganization(organizations[0].id, {
slug: orgEntity.slug as string,
name: orgEntity.name as string,
});
await this.updateOrganization(
organizations[0].id,
{
slug: orgEntity.slug as string,
name: orgEntity.name as string
}
)
}
}
@@ -98,7 +95,7 @@ export class Database {
}
async getOrganizations(
options: FindManyOptions<Organization>,
options: FindManyOptions<Organization>
): Promise<Organization[]> {
const organizationRepository = this.dataSource.getRepository(Organization);
const organizations = await organizationRepository.find(options);
@@ -107,7 +104,7 @@ export class Database {
}
async getOrganization(
options: FindOneOptions<Organization>,
options: FindOneOptions<Organization>
): Promise<Organization | null> {
const organizationRepository = this.dataSource.getRepository(Organization);
const organization = await organizationRepository.findOne(options);
@@ -122,34 +119,25 @@ export class Database {
where: {
userOrganizations: {
member: {
id: userId,
},
},
},
id: userId
}
}
}
});
return userOrgs;
}
async addUserOrganization(
data: DeepPartial<UserOrganization>,
): Promise<UserOrganization> {
const userOrganizationRepository =
this.dataSource.getRepository(UserOrganization);
async addUserOrganization(data: DeepPartial<UserOrganization>): Promise<UserOrganization> {
const userOrganizationRepository = this.dataSource.getRepository(UserOrganization);
const newUserOrganization = await userOrganizationRepository.save(data);
return newUserOrganization;
}
async updateOrganization(
organizationId: string,
data: DeepPartial<Organization>,
): Promise<boolean> {
async updateOrganization(organizationId: string, data: DeepPartial<Organization>): Promise<boolean> {
const organizationRepository = this.dataSource.getRepository(Organization);
const updateResult = await organizationRepository.update(
{ id: organizationId },
data,
);
const updateResult = await organizationRepository.update({ id: organizationId }, data);
assert(updateResult.affected);
return updateResult.affected > 0;
@@ -170,15 +158,16 @@ export class Database {
.leftJoinAndSelect(
'project.deployments',
'deployments',
'deployments.isCurrent = true AND deployments.isCanonical = true',
'deployments.isCurrent = true AND deployments.isDNS = true'
)
.leftJoinAndSelect('deployments.createdBy', 'user')
.leftJoinAndSelect('deployments.domain', 'domain')
.leftJoinAndSelect('deployments.deployer', 'deployer')
.leftJoinAndSelect('project.owner', 'owner')
.leftJoinAndSelect('project.deployers', 'deployers')
.leftJoinAndSelect('project.organization', 'organization')
.where('project.id = :projectId', {
projectId,
projectId
})
.getOne();
@@ -186,28 +175,26 @@ export class Database {
}
async allProjectsWithoutDeployments(): Promise<Project[]> {
// Fetch all projects with auction not completed and wihout any deployments
const allProjects = await this.getProjects({
where: {
auctionId: Not(IsNull()),
auctionStatus: Not(AuctionStatus.Completed),
},
relations: ['deployments'],
withDeleted: true,
});
const activeProjectsWithoutDeployments = allProjects.filter((project) => {
const projects = allProjects.filter(project => {
if (project.deletedAt !== null) return false;
return project.deployments.length === 0;
});
return activeProjectsWithoutDeployments;
return projects;
}
async getProjectsInOrganization(
userId: string,
organizationSlug: string,
organizationSlug: string
): Promise<Project[]> {
const projectRepository = this.dataSource.getRepository(Project);
@@ -216,16 +203,17 @@ export class Database {
.leftJoinAndSelect(
'project.deployments',
'deployments',
'deployments.isCurrent = true AND deployments.isCanonical = true',
'deployments.isCurrent = true AND deployments.isDNS = true'
)
.leftJoinAndSelect('deployments.domain', 'domain')
.leftJoin('project.projectMembers', 'projectMembers')
.leftJoin('project.organization', 'organization')
.where(
'(project.ownerId = :userId OR projectMembers.userId = :userId) AND organization.slug = :organizationSlug',
{
userId,
organizationSlug,
},
organizationSlug
}
)
.getMany();
@@ -236,7 +224,7 @@ export class Database {
* Get deployments with specified filter
*/
async getDeployments(
options: FindManyOptions<Deployment>,
options: FindManyOptions<Deployment>
): Promise<Deployment[]> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployments = await deploymentRepository.find(options);
@@ -248,43 +236,43 @@ export class Database {
return this.getDeployments({
relations: {
project: true,
domain: true,
createdBy: true,
deployer: true,
},
where: {
project: {
id: projectId,
},
id: projectId
}
},
order: {
createdAt: 'DESC',
},
createdAt: 'DESC'
}
});
}
async getNonCanonicalDeploymentsByProjectId(
projectId: string,
): Promise<Deployment[]> {
async getCommitDeploymentsByProjectId(projectId: string): Promise<Deployment[]> {
return this.getDeployments({
relations: {
project: true,
domain: true,
createdBy: true,
deployer: true,
},
where: {
project: {
id: projectId,
id: projectId
},
isCanonical: false,
isDNS: false
},
order: {
createdAt: 'DESC',
},
createdAt: 'DESC'
}
});
}
async getDeployment(
options: FindOneOptions<Deployment>,
options: FindOneOptions<Deployment>
): Promise<Deployment | null> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployment = await deploymentRepository.findOne(options);
@@ -306,7 +294,7 @@ export class Database {
const updatedData = {
...data,
id,
id
};
const deployment = await deploymentRepository.save(updatedData);
@@ -314,7 +302,7 @@ export class Database {
}
async getProjectMembersByProjectId(
projectId: string,
projectId: string
): Promise<ProjectMember[]> {
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
@@ -322,13 +310,13 @@ export class Database {
const projectMembers = await projectMemberRepository.find({
relations: {
project: true,
member: true,
member: true
},
where: {
project: {
id: projectId,
},
},
id: projectId
}
}
});
return projectMembers;
@@ -336,7 +324,7 @@ export class Database {
async getEnvironmentVariablesByProjectId(
projectId: string,
filter?: FindOptionsWhere<EnvironmentVariable>,
filter?: FindOptionsWhere<EnvironmentVariable>
): Promise<EnvironmentVariable[]> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
@@ -344,10 +332,10 @@ export class Database {
const environmentVariables = await environmentVariableRepository.find({
where: {
project: {
id: projectId,
id: projectId
},
...filter,
},
...filter
}
});
return environmentVariables;
@@ -358,7 +346,7 @@ export class Database {
this.dataSource.getRepository(ProjectMember);
const deleteResult = await projectMemberRepository.delete({
id: projectMemberId,
id: projectMemberId
});
if (deleteResult.affected) {
@@ -370,20 +358,20 @@ export class Database {
async updateProjectMemberById(
projectMemberId: string,
data: DeepPartial<ProjectMember>,
data: DeepPartial<ProjectMember>
): Promise<boolean> {
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
const updateResult = await projectMemberRepository.update(
{ id: projectMemberId },
data,
data
);
return Boolean(updateResult.affected);
}
async addProjectMember(
data: DeepPartial<ProjectMember>,
data: DeepPartial<ProjectMember>
): Promise<ProjectMember> {
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
@@ -393,7 +381,7 @@ export class Database {
}
async addEnvironmentVariables(
data: DeepPartial<EnvironmentVariable>[],
data: DeepPartial<EnvironmentVariable>[]
): Promise<EnvironmentVariable[]> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
@@ -405,25 +393,25 @@ export class Database {
async updateEnvironmentVariable(
environmentVariableId: string,
data: DeepPartial<EnvironmentVariable>,
data: DeepPartial<EnvironmentVariable>
): Promise<boolean> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
const updateResult = await environmentVariableRepository.update(
{ id: environmentVariableId },
data,
data
);
return Boolean(updateResult.affected);
}
async deleteEnvironmentVariable(
environmentVariableId: string,
environmentVariableId: string
): Promise<boolean> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
const deleteResult = await environmentVariableRepository.delete({
id: environmentVariableId,
id: environmentVariableId
});
if (deleteResult.affected) {
@@ -440,13 +428,13 @@ export class Database {
const projectMemberWithProject = await projectMemberRepository.find({
relations: {
project: {
owner: true,
owner: true
},
member: true,
member: true
},
where: {
id: projectMemberId,
},
id: projectMemberId
}
});
if (projectMemberWithProject.length === 0) {
@@ -458,7 +446,7 @@ export class Database {
async getProjectsBySearchText(
userId: string,
searchText: string,
searchText: string
): Promise<Project[]> {
const projectRepository = this.dataSource.getRepository(Project);
@@ -470,8 +458,8 @@ export class Database {
'(project.owner = :userId OR projectMembers.member.id = :userId) AND project.name LIKE :searchText',
{
userId,
searchText: `%${searchText}%`,
},
searchText: `%${searchText}%`
}
)
.getMany();
@@ -480,14 +468,14 @@ export class Database {
async updateDeploymentById(
deploymentId: string,
data: DeepPartial<Deployment>,
data: DeepPartial<Deployment>
): Promise<boolean> {
return this.updateDeployment({ id: deploymentId }, data);
}
async updateDeployment(
criteria: FindOptionsWhere<Deployment>,
data: DeepPartial<Deployment>,
data: DeepPartial<Deployment>
): Promise<boolean> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const updateResult = await deploymentRepository.update(criteria, data);
@@ -497,7 +485,7 @@ export class Database {
async updateDeploymentsByProjectIds(
projectIds: string[],
data: DeepPartial<Deployment>,
data: DeepPartial<Deployment>
): Promise<boolean> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
@@ -515,8 +503,8 @@ export class Database {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployment = await deploymentRepository.findOneOrFail({
where: {
id: deploymentId,
},
id: deploymentId
}
});
const deleteResult = await deploymentRepository.softRemove(deployment);
@@ -524,11 +512,7 @@ export class Database {
return Boolean(deleteResult);
}
async addProject(
user: User,
organizationId: string,
data: DeepPartial<Project>,
): Promise<Project> {
async addProject(user: User, organizationId: string, data: DeepPartial<Project>): Promise<Project> {
const projectRepository = this.dataSource.getRepository(Project);
// TODO: Check if organization exists
@@ -541,7 +525,7 @@ export class Database {
newProject.owner = user;
newProject.organization = Object.assign(new Organization(), {
id: organizationId,
id: organizationId
});
return projectRepository.save(newProject);
@@ -555,12 +539,12 @@ export class Database {
async updateProjectById(
projectId: string,
data: DeepPartial<Project>,
data: DeepPartial<Project>
): Promise<boolean> {
const projectRepository = this.dataSource.getRepository(Project);
const updateResult = await projectRepository.update(
{ id: projectId },
data,
data
);
return Boolean(updateResult.affected);
@@ -570,11 +554,11 @@ export class Database {
const projectRepository = this.dataSource.getRepository(Project);
const project = await projectRepository.findOneOrFail({
where: {
id: projectId,
id: projectId
},
relations: {
projectMembers: true,
},
projectMembers: true
}
});
const deleteResult = await projectRepository.softRemove(project);
@@ -610,7 +594,7 @@ export class Database {
async updateDomainById(
domainId: string,
data: DeepPartial<Domain>,
data: DeepPartial<Domain>
): Promise<boolean> {
const domainRepository = this.dataSource.getRepository(Domain);
const updateResult = await domainRepository.update({ id: domainId }, data);
@@ -620,43 +604,45 @@ export class Database {
async getDomainsByProjectId(
projectId: string,
filter?: FindOptionsWhere<Domain>,
filter?: FindOptionsWhere<Domain>
): Promise<Domain[]> {
const domainRepository = this.dataSource.getRepository(Domain);
const domains = await domainRepository.find({
relations: {
redirectTo: true,
redirectTo: true
},
where: {
project: {
id: projectId,
id: projectId
},
...filter,
},
...filter
}
});
return domains;
}
async getOldestDomainByProjectId(projectId: string): Promise<Domain | null> {
async getOldestDomainByProjectId(
projectId: string,
): Promise<Domain | null> {
const domainRepository = this.dataSource.getRepository(Domain);
const domain = await domainRepository.findOne({
where: {
project: {
id: projectId,
id: projectId
},
},
order: {
createdAt: 'ASC',
},
createdAt: 'ASC'
}
});
return domain;
}
async getLatestDNSRecordByProjectId(
async getLatestDNSDataByProjectId(
projectId: string,
): Promise<DNSRecordAttributes | null> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
@@ -667,14 +653,15 @@ export class Database {
id: projectId,
},
status: DeploymentStatus.Ready,
isDNS: true
},
order: {
createdAt: 'DESC',
},
createdAt: 'DESC'
}
});
if (deployment === null) {
throw new Error(`No deployment found for project ${projectId}`);
throw new Error(`Error finding DNS data for project with id ${projectId}`);
}
return deployment.dnsRecordData;
@@ -695,9 +682,7 @@ export class Database {
async getDeployerByLRN(deployerLrn: string): Promise<Deployer | null> {
const deployerRepository = this.dataSource.getRepository(Deployer);
const deployer = await deployerRepository.findOne({
where: { deployerLrn },
});
const deployer = await deployerRepository.findOne({ where: { deployerLrn } });
return deployer;
}
+10 -2
View File
@@ -39,7 +39,6 @@ export interface ApplicationDeploymentRequest {
config: string;
meta: string;
payment?: string;
dns?: string;
}
export interface ApplicationDeploymentRemovalRequest {
@@ -78,6 +77,13 @@ export class Deployment {
@JoinColumn({ name: 'projectId' })
project!: Project;
@Column({ nullable: true })
domainId!: string | null;
@OneToOne(() => Domain)
@JoinColumn({ name: 'domainId' })
domain!: Domain | null;
@Column('varchar')
branch!: string;
@@ -135,8 +141,10 @@ export class Deployment {
@Column('boolean', { default: false })
isCurrent!: boolean;
// TODO: Rename field
@Column('boolean', { default: false })
isCanonical!: boolean;
isDNS!: boolean;
@Column({
enum: DeploymentStatus
+6 -19
View File
@@ -9,7 +9,7 @@ import {
OneToMany,
DeleteDateColumn,
JoinTable,
ManyToMany,
ManyToMany
} from 'typeorm';
import { User } from './User';
@@ -18,12 +18,6 @@ import { ProjectMember } from './ProjectMember';
import { Deployment } from './Deployment';
import { Deployer } from './Deployer';
export enum AuctionStatus {
Commit = 'commit',
Reveal = 'reveal',
Completed = 'completed',
}
@Entity()
export class Project {
@PrimaryGeneratedColumn('uuid')
@@ -55,23 +49,16 @@ export class Project {
@Column('text', { default: '' })
description!: string;
@Column('varchar', { nullable: true })
auctionId!: string | null;
// Tx hash for sending coins from snowball to deployer
@Column('varchar', { nullable: true })
txHash!: string | null;
@ManyToMany(() => Deployer, (deployer) => deployer.projects)
@ManyToMany(() => Deployer, (deployer) => (deployer.projects))
@JoinTable()
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;
deployers!: Deployer[]
@Column('boolean', { default: false, nullable: true })
fundsReleased!: boolean;
+157 -195
View File
@@ -6,13 +6,7 @@ import { inc as semverInc } from 'semver';
import { DeepPartial } from 'typeorm';
import * as openpgp from 'openpgp';
import {
Account,
DEFAULT_GAS_ESTIMATION_MULTIPLIER,
Registry as LaconicRegistry,
getGasPrice,
parseGasAndFees,
} from '@cerc-io/registry-sdk';
import { Account, DEFAULT_GAS_ESTIMATION_MULTIPLIER, Registry as LaconicRegistry, getGasPrice, parseGasAndFees } from '@cerc-io/registry-sdk';
import { DeliverTxResponse, IndexedTx } from '@cosmjs/stargate';
import { RegistryConfig } from './config';
@@ -20,30 +14,17 @@ import {
ApplicationRecord,
Deployment,
ApplicationDeploymentRequest,
ApplicationDeploymentRemovalRequest,
ApplicationDeploymentRemovalRequest
} from './entity/Deployment';
import {
AppDeploymentRecord,
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';
import { AppDeploymentRecord, AppDeploymentRemovalRecord, AuctionParams, DeployerRecord, DNSRecord } from './types';
import { getConfig, getRepoDetails, registryTransactionWithRetry, sleep } from './utils';
const log = debug('snowball:registry');
const APP_RECORD_TYPE = 'ApplicationRecord';
const APP_DEPLOYMENT_AUCTION_RECORD_TYPE = 'ApplicationDeploymentAuction';
const APP_DEPLOYMENT_REQUEST_TYPE = 'ApplicationDeploymentRequest';
const APP_DEPLOYMENT_REMOVAL_REQUEST_TYPE =
'ApplicationDeploymentRemovalRequest';
const APP_DEPLOYMENT_REMOVAL_REQUEST_TYPE = 'ApplicationDeploymentRemovalRequest';
const APP_DEPLOYMENT_RECORD_TYPE = 'ApplicationDeploymentRecord';
const APP_DEPLOYMENT_REMOVAL_RECORD_TYPE = 'ApplicationDeploymentRemovalRecord';
const WEBAPP_DEPLOYER_RECORD_TYPE = 'WebappDeployer';
@@ -62,7 +43,7 @@ export class Registry {
this.registry = new LaconicRegistry(
registryConfig.gqlEndpoint,
registryConfig.restEndpoint,
{ chainId: registryConfig.chainId, gasPrice },
{ chainId: registryConfig.chainId, gasPrice }
);
}
@@ -72,7 +53,7 @@ export class Registry {
commitHash,
appType,
}: {
octokit: Octokit;
octokit: Octokit
repository: string;
commitHash: string;
appType: string;
@@ -80,33 +61,29 @@ export class Registry {
applicationRecordId: string;
applicationRecordData: ApplicationRecord;
}> {
const { repo, repoUrl, packageJSON } = await getRepoDetails(
octokit,
repository,
commitHash,
);
const { repo, repoUrl, packageJSON } = await getRepoDetails(octokit, repository, commitHash)
// 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
// Fetch previous records
const records = await this.registry.queryRecords(
{
type: APP_RECORD_TYPE,
name: packageJSON.name,
name: packageJSON.name
},
true,
true
);
// Get next version of record
const bondRecords = records.filter(
(record: any) => record.bondId === this.registryConfig.bondId,
(record: any) => record.bondId === this.registryConfig.bondId
);
const [latestBondRecord] = bondRecords.sort(
(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(
latestBondRecord?.attributes.version ?? '0.0.0',
'patch',
'patch'
);
assert(nextVersion, 'Application record version not valid');
@@ -126,12 +103,24 @@ export class Registry {
author:
typeof packageJSON.author === 'object'
? 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 fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
const result = await registryTransactionWithRetry(() =>
this.registry.setRecord(
{
privateKey: this.registryConfig.privateKey,
record: applicationRecord,
bondId: this.registryConfig.bondId
},
this.registryConfig.privateKey,
fee
)
);
log(`Published application record ${result.id}`);
log('Application record data:', applicationRecord);
@@ -140,9 +129,16 @@ export class Registry {
const lrn = this.getLrn(repo);
log(`Setting name: ${lrn} for record ID: ${result.id}`);
const fee = parseGasAndFees(
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);
@@ -150,11 +146,11 @@ export class Registry {
this.registry.setName(
{
cid: result.id,
lrn,
lrn: `${lrn}@${applicationRecord.app_version}`
},
this.registryConfig.privateKey,
fee,
),
fee
)
);
await sleep(SLEEP_DURATION);
@@ -162,28 +158,16 @@ export class Registry {
this.registry.setName(
{
cid: result.id,
lrn: `${lrn}@${applicationRecord.app_version}`,
lrn: `${lrn}@${applicationRecord.repository_ref}`
},
this.registryConfig.privateKey,
fee,
),
);
await sleep(SLEEP_DURATION);
await registryTransactionWithRetry(() =>
this.registry.setName(
{
cid: result.id,
lrn: `${lrn}@${applicationRecord.repository_ref}`,
},
this.registryConfig.privateKey,
fee,
),
fee
)
);
return {
applicationRecordId: result.id,
applicationRecordData: applicationRecord,
applicationRecordData: applicationRecord
};
}
@@ -193,7 +177,7 @@ export class Registry {
auctionParams: AuctionParams,
data: DeepPartial<Deployment>,
): Promise<{
applicationDeploymentAuction: MsgCreateAuctionResponse['auction'];
applicationDeploymentAuctionId: string;
}> {
assert(data.project?.repository, 'Project repository not found');
@@ -208,11 +192,8 @@ export class Registry {
const config = await getConfig();
const auctionConfig = config.auction;
const fee = parseGasAndFees(
this.registryConfig.fee.gas,
this.registryConfig.fee.fees,
);
const auctionResult = (await registryTransactionWithRetry(() =>
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
const auctionResult = await registryTransactionWithRetry(() =>
this.registry.createProviderAuction(
{
commitFee: auctionConfig.commitFee,
@@ -224,9 +205,9 @@ export class Registry {
numProviders: auctionParams.numProviders,
},
this.registryConfig.privateKey,
fee,
),
)) as MsgCreateAuctionResponse;
fee
)
);
if (!auctionResult.auction) {
throw new Error('Error creating auction');
@@ -239,29 +220,39 @@ export class Registry {
type: APP_DEPLOYMENT_AUCTION_RECORD_TYPE,
};
const result = await this.publishRecord(applicationDeploymentAuction);
const result = await registryTransactionWithRetry(() =>
this.registry.setRecord(
{
privateKey: this.registryConfig.privateKey,
record: applicationDeploymentAuction,
bondId: this.registryConfig.bondId
},
this.registryConfig.privateKey,
fee
)
);
log(`Application deployment auction created: ${auctionResult.auction.id}`);
log(`Application deployment auction record published: ${result.id}`);
log('Application deployment auction data:', applicationDeploymentAuction);
return {
applicationDeploymentAuction: auctionResult.auction!,
applicationDeploymentAuctionId: auctionResult.auction.id,
};
}
async createApplicationDeploymentRequest(data: {
deployment: Deployment;
appName: string;
repository: string;
auctionId?: string | null;
lrn: string;
apiUrl: string;
environmentVariables: { [key: string]: string };
dns: string;
requesterAddress: string;
publicKey: string;
payment?: string | null;
deployment: Deployment,
appName: string,
repository: string,
auctionId?: string | null,
lrn: string,
apiUrl: string,
environmentVariables: { [key: string]: string },
dns: string,
requesterAddress: string,
publicKey: string,
payment?: string | null
}): Promise<{
applicationDeploymentRequestId: string;
applicationDeploymentRequestData: ApplicationDeploymentRequest;
@@ -274,15 +265,12 @@ export class Registry {
throw new Error(`No record found for ${lrn}`);
}
let hash;
if (Object.keys(data.environmentVariables).length !== 0) {
hash = await this.generateConfigHash(
data.environmentVariables,
data.requesterAddress,
data.publicKey,
data.apiUrl,
);
}
const hash = await this.generateConfigHash(
data.environmentVariables,
data.requesterAddress,
data.publicKey,
data.apiUrl,
);
// Create record of type ApplicationDeploymentRequest and publish
const applicationDeploymentRequest = {
@@ -293,13 +281,15 @@ export class Registry {
dns: data.dns,
// https://git.vdb.to/cerc-io/laconic-registry-cli/commit/129019105dfb93bebcea02fde0ed64d0f8e5983b
config: JSON.stringify(hash ? { ref: hash } : {}),
config: JSON.stringify({
ref: hash,
}),
meta: JSON.stringify({
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_ref: data.deployment.commitHash,
repository_ref: data.deployment.commitHash
}),
deployer: data.lrn,
...(data.auctionId && { auction: data.auctionId }),
@@ -308,19 +298,31 @@ export class Registry {
await sleep(SLEEP_DURATION);
const result = await this.publishRecord(applicationDeploymentRequest);
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
const result = await registryTransactionWithRetry(() =>
this.registry.setRecord(
{
privateKey: this.registryConfig.privateKey,
record: applicationDeploymentRequest,
bondId: this.registryConfig.bondId
},
this.registryConfig.privateKey,
fee
)
);
log(`Application deployment request record published: ${result.id}`);
log('Application deployment request data:', applicationDeploymentRequest);
return {
applicationDeploymentRequestId: result.id,
applicationDeploymentRequestData: applicationDeploymentRequest,
applicationDeploymentRequestData: applicationDeploymentRequest
};
}
async getAuctionWinningDeployerRecords(
auctionId: string,
auctionId: string
): Promise<DeployerRecord[]> {
const records = await this.registry.getAuctionsByIds([auctionId]);
const auctionResult = records[0];
@@ -333,7 +335,7 @@ export class Registry {
paymentAddress: auctionWinner,
});
const newRecords = records.filter((record) => {
const newRecords = records.filter(record => {
return record.names !== null && record.names.length > 0;
});
@@ -348,19 +350,18 @@ export class Registry {
return deployerRecords;
}
async releaseDeployerFunds(auctionId: string): Promise<any> {
const fee = parseGasAndFees(
this.registryConfig.fee.gas,
this.registryConfig.fee.fees,
);
async releaseDeployerFunds(
auctionId: string
): Promise<any> {
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
const auction = await registryTransactionWithRetry(() =>
this.registry.releaseFunds(
{
auctionId,
auctionId
},
this.registryConfig.privateKey,
fee,
),
fee
)
);
return auction;
@@ -370,54 +371,49 @@ export class Registry {
* Fetch ApplicationDeploymentRecords for deployments
*/
async getDeploymentRecords(
deployments: Deployment[],
deployments: Deployment[]
): Promise<AppDeploymentRecord[]> {
// Fetch ApplicationDeploymentRecords for corresponding ApplicationRecord set in deployments
// TODO: Implement Laconicd GQL query to filter records by multiple values for an attribute
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 and Deployment specific URL
return records.filter((record: AppDeploymentRecord) =>
deployments.some(
(deployment) =>
deployment.applicationDeploymentRequestId ===
record.attributes.request,
),
deployment.applicationDeploymentRequestId === record.attributes.request
)
);
}
/**
* Fetch WebappDeployer Records by filter
*/
async getDeployerRecordsByFilter(filter: {
[key: string]: any;
}): Promise<DeployerRecord[]> {
async getDeployerRecordsByFilter(filter: { [key: string]: any }): Promise<DeployerRecord[]> {
return this.registry.queryRecords(
{
type: WEBAPP_DEPLOYER_RECORD_TYPE,
...filter,
...filter
},
true,
true
);
}
/**
* Fetch ApplicationDeploymentRecords by filter
*/
async getDeploymentRecordsByFilter(filter: {
[key: string]: any;
}): Promise<AppDeploymentRecord[]> {
async getDeploymentRecordsByFilter(filter: { [key: string]: any }): Promise<AppDeploymentRecord[]> {
return this.registry.queryRecords(
{
type: APP_DEPLOYMENT_RECORD_TYPE,
...filter,
...filter
},
true,
true
);
}
@@ -425,34 +421,31 @@ export class Registry {
* Fetch ApplicationDeploymentRemovalRecords for deployments
*/
async getDeploymentRemovalRecords(
deployments: Deployment[],
deployments: Deployment[]
): Promise<AppDeploymentRemovalRecord[]> {
// Fetch ApplicationDeploymentRemovalRecords for corresponding ApplicationDeploymentRecord set in deployments
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
return records.filter((record: AppDeploymentRemovalRecord) =>
deployments.some(
(deployment) =>
deployment.applicationDeploymentRemovalRequestId ===
record.attributes.request &&
deployment.applicationDeploymentRecordId ===
record.attributes.deployment,
),
deployment.applicationDeploymentRemovalRequestId === record.attributes.request &&
deployment.applicationDeploymentRecordId === record.attributes.deployment
)
);
}
/**
* Fetch record by Id
*/
async getRecordById(id: string): Promise<RegistryRecord | null> {
const [record] = await this.registry.getRecordsByIds([id]);
return record ?? null;
* Fetch record by Id
*/
async getRecordById(id: string): Promise<any[]> {
return this.registry.getRecordsByIds([id]);
}
async createApplicationDeploymentRemovalRequest(data: {
@@ -473,22 +466,26 @@ export class Registry {
...(data.payment && { payment: data.payment }),
};
const result = await this.publishRecord(
applicationDeploymentRemovalRequest,
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
const result = await registryTransactionWithRetry(() =>
this.registry.setRecord(
{
privateKey: this.registryConfig.privateKey,
record: applicationDeploymentRemovalRequest,
bondId: this.registryConfig.bondId
},
this.registryConfig.privateKey,
fee
)
);
log(
`Application deployment removal request record published: ${result.id}`,
);
log(
'Application deployment removal request data:',
applicationDeploymentRemovalRequest,
);
log(`Application deployment removal request record published: ${result.id}`);
log('Application deployment removal request data:', applicationDeploymentRemovalRequest);
return {
applicationDeploymentRemovalRequestId: result.id,
applicationDeploymentRemovalRequestData:
applicationDeploymentRemovalRequest,
applicationDeploymentRemovalRequestData: applicationDeploymentRemovalRequest
};
}
@@ -500,36 +497,12 @@ export class Registry {
const auctions = await this.registry.getAuctionsByIds(auctionIds);
const completedAuctions = auctions
.filter(
(auction: { id: string; status: string }) =>
auction.status === 'completed',
)
.map((auction: { id: string; status: string }) => auction.id);
.filter((auction: { id: string, status: string }) => auction.status === 'completed')
.map((auction: { id: string, status: string }) => auction.id);
return completedAuctions;
}
async publishRecord(recordData: any): Promise<any> {
const fee = parseGasAndFees(
this.registryConfig.fee.gas,
this.registryConfig.fee.fees,
);
const result = await registryTransactionWithRetry(() =>
this.registry.setRecord(
{
privateKey: this.registryConfig.privateKey,
record: recordData,
bondId: this.registryConfig.bondId,
},
this.registryConfig.privateKey,
fee,
),
);
return result;
}
async getRecordsByName(name: string): Promise<any> {
return this.registry.resolveNames([name]);
}
@@ -538,38 +511,27 @@ export class Registry {
return this.registry.getAuctionsByIds([auctionId]);
}
async sendTokensToAccount(
receiverAddress: string,
amount: string,
): Promise<DeliverTxResponse> {
const fee = parseGasAndFees(
this.registryConfig.fee.gas,
this.registryConfig.fee.fees,
);
async sendTokensToAccount(receiverAddress: string, amount: string): Promise<DeliverTxResponse> {
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
const account = await this.getAccount();
const laconicClient = await this.registry.getLaconicClient(account);
const txResponse: DeliverTxResponse = await registryTransactionWithRetry(
() =>
laconicClient.sendTokens(
account.address,
receiverAddress,
const txResponse: DeliverTxResponse =
await registryTransactionWithRetry(() =>
laconicClient.sendTokens(account.address, receiverAddress,
[
{
denom: 'alnt',
amount,
},
amount
}
],
fee || DEFAULT_GAS_ESTIMATION_MULTIPLIER,
),
);
fee || DEFAULT_GAS_ESTIMATION_MULTIPLIER)
);
return txResponse;
}
async getAccount(): Promise<Account> {
const account = new Account(
Buffer.from(this.registryConfig.privateKey, 'hex'),
);
const account = new Account(Buffer.from(this.registryConfig.privateKey, 'hex'));
await account.init();
return account;
+15 -3
View File
@@ -38,7 +38,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
},
deployments: async (_: any, { projectId }: { projectId: string }) => {
return service.getNonCanonicalDeploymentsByProjectId(projectId);
return service.getDeploymentsByProjectId(projectId);
},
environmentVariables: async (
@@ -70,6 +70,18 @@ export const createResolvers = async (service: Service): Promise<any> => {
return service.getDomainsByProjectId(projectId, filter);
},
oldestDomain: async (
_: any,
{ projectId }: { projectId: string },
) => {
try {
return await service.getOldestDomainByProjectId(projectId);
} catch (err) {
log(err);
return false;
}
},
getAuctionData: async (
_: any,
{ auctionId }: { auctionId: string },
@@ -96,11 +108,11 @@ export const createResolvers = async (service: Service): Promise<any> => {
return service.verifyTx(txHash, amount, senderAddress);
},
latestDNSRecord: async (
getLatestDNSDataByProjectId: async (
_: any,
{ projectId }: { projectId: string },
) => {
return service.getLatestDNSRecordByProjectId(projectId);
return service.getLatestDNSDataByProjectId(projectId);
},
},
+9
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;
+3 -15
View File
@@ -100,6 +100,7 @@ type ProjectMember {
type Deployment {
id: String!
domain: Domain
branch: String!
commitHash: String!
commitMessage: String!
@@ -107,7 +108,6 @@ type Deployment {
environment: Environment!
deployer: Deployer
applicationDeploymentRequestId: String
applicationDeploymentRecordData: AppDeploymentRecordAttributes
isCurrent: Boolean!
baseDomain: String
status: DeploymentStatus!
@@ -257,19 +257,6 @@ type DNSRecordAttributes {
version: String
}
type AppDeploymentRecordAttributes {
application: String
auction: String
deployer: String
dns: String
meta: String
name: String
request: String
type: String
url: String
version: String
}
input AuctionParams {
maxPrice: String,
numProviders: Int,
@@ -286,7 +273,8 @@ type Query {
projectMembers(projectId: String!): [ProjectMember!]
searchProjects(searchText: String!): [Project!]
getAuctionData(auctionId: String!): Auction!
latestDNSRecord(projectId: String!): DNSRecordAttributes
getLatestDNSDataByProjectId(projectId: String!): DNSRecordAttributes
oldestDomain(projectId: String!): Domain
domains(projectId: String!, filter: FilterDomainsInput): [Domain]
deployers: [Deployer]
address: String!
File diff suppressed because it is too large Load Diff
+2 -10
View File
@@ -48,14 +48,6 @@ export interface DNSRecordAttributes {
version: string;
}
export interface RegistryDNSRecordAttributes {
name: string;
value: string;
request: string;
resource_type: string;
version: string;
}
export interface AppDeploymentRemovalRecordAttributes {
deployment: string;
request: string;
@@ -63,7 +55,7 @@ export interface AppDeploymentRemovalRecordAttributes {
version: string;
}
export interface RegistryRecord {
interface RegistryRecord {
id: string;
names: string[] | null;
owners: string[];
@@ -81,7 +73,7 @@ export interface AppDeploymentRemovalRecord extends RegistryRecord {
}
export interface DNSRecord extends RegistryRecord {
attributes: RegistryDNSRecordAttributes
attributes: DNSRecordAttributes
}
export interface AddProjectFromTemplateInput {
+3 -3
View File
@@ -1,8 +1,8 @@
services:
registry:
rpcEndpoint: https://laconicd-mainnet-1.laconic.com
gqlEndpoint: https://laconicd-mainnet-1.laconic.com/api
rpcEndpoint: https://laconicd-sapo.laconic.com
gqlEndpoint: https://laconicd-sapo.laconic.com/api
userKey:
bondId:
chainId: laconic-mainnet
chainId: laconic-testnet-2
gasPrice: 0.001alnt
+2
View File
@@ -133,6 +133,8 @@ record:
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_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
meta:
note: Added @ $CURRENT_DATE_TIME
@@ -127,6 +127,7 @@ record:
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_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
meta:
note: Added by Snowball @ $CURRENT_DATE_TIME
+3
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_NEXT_APP_TEMPLATE_REPO="snowball-tools/starter.nextjs-react-tailwind"
VITE_WALLET_CONNECT_ID=
VITE_LIT_RELAY_API_KEY=
VITE_BUGSNAG_API_KEY=
@@ -12,4 +14,5 @@ VITE_BUGSNAG_API_KEY=
VITE_PASSKEY_WALLET_RPID=
VITE_TURNKEY_API_BASE_URL=
VITE_LACONICD_CHAIN_ID=
VITE_WALLET_IFRAME_URL=
+3 -1
View File
@@ -41,12 +41,13 @@
"@turnkey/http": "^2.10.0",
"@turnkey/sdk-react": "^0.1.0",
"@turnkey/webauthn-stamper": "^0.5.0",
"@walletconnect/ethereum-provider": "^2.16.1",
"@web3modal/siwe": "4.0.5",
"@web3modal/wagmi": "4.0.5",
"assert": "^2.1.0",
"axios": "^1.6.7",
"clsx": "^2.1.0",
"date-fns": "^3.3.1",
"ethers": "^5.6.2",
"downshift": "^8.3.2",
"framer-motion": "^11.0.8",
"gql-client": "^1.0.0",
@@ -68,6 +69,7 @@
"usehooks-ts": "^2.15.1",
"uuid": "^9.0.1",
"viem": "^2.7.11",
"wagmi": "2.5.7",
"web-vitals": "^2.1.4"
},
"devDependencies": {
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

-11
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
}
+4 -6
View File
@@ -11,8 +11,8 @@ import ProjectSearchLayout from './layouts/ProjectSearch';
import Index from './pages';
import AuthPage from './pages/AuthPage';
import { DashboardLayout } from './pages/org-slug/layout';
import Web3Provider from 'context/Web3Provider';
import { BASE_URL } from 'utils/constants';
import BuyPrepaidService from './pages/BuyPrepaidService';
const router = createBrowserRouter([
{
@@ -50,10 +50,6 @@ const router = createBrowserRouter([
path: '/login',
element: <AuthPage />,
},
{
path: '/buy-prepaid-service',
element: <BuyPrepaidService />,
},
]);
function App() {
@@ -79,7 +75,9 @@ function App() {
}, []);
return (
<RouterProvider router={router} />
<Web3Provider>
<RouterProvider router={router} />
</Web3Provider>
);
}
@@ -87,7 +87,7 @@ export const ProjectCard = ({
<p className={theme.title()}>{project.name}</p>
</Tooltip>
<p className={theme.description()}>
{project.deployments[0]?.applicationDeploymentRecordData?.url ?? 'No domain'}
{project.deployments[0]?.domain?.name ?? 'No domain'}
</p>
</div>
{/* Icons */}
@@ -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;
@@ -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;
@@ -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 { FormProvider, FieldValues } from 'react-hook-form';
import { useNavigate, useSearchParams } from 'react-router-dom';
@@ -8,7 +8,6 @@ import {
AuctionParams,
Deployer,
} from 'gql-client';
import { BigNumber } from 'ethers';
import { Select, MenuItem, FormControl, FormHelperText } from '@mui/material';
@@ -21,19 +20,19 @@ import { Button } from '../../shared/Button';
import { Input } from 'components/shared/Input';
import { useToast } from 'components/shared/Toast';
import { useGQLClient } from '../../../context/GQLClientContext';
import ApproveTransactionModal from './ApproveTransactionModal';
import IFrameModal from './IFrameModal';
import EnvironmentVariablesForm from 'pages/org-slug/projects/id/settings/EnvironmentVariablesForm';
import { EnvironmentVariablesFormValues } from 'types/types';
import {
VITE_LACONICD_CHAIN_ID,
VITE_WALLET_IFRAME_URL,
} from 'utils/constants';
import CheckBalanceIframe from './CheckBalanceIframe';
import { useAddNetwork } from '../../../hooks/useAddNetwork';
import AccountsDropdown from './AccountsDropdown';
type ConfigureDeploymentFormValues = {
option: string;
lrn?: string;
numProviders?: string;
numProviders?: number;
maxPrice?: string;
};
@@ -47,13 +46,12 @@ const Configure = () => {
const [isLoading, setIsLoading] = useState(false);
const [deployers, setDeployers] = useState<Deployer[]>([]);
const [selectedAccount, setSelectedAccount] = useState<string>();
const [accounts, setAccounts] = useState<string[]>([]);
const [selectedDeployer, setSelectedDeployer] = useState<Deployer>();
const [isPaymentLoading, setIsPaymentLoading] = useState(false);
const [isPaymentDone, setIsPaymentDone] = useState(false);
const [isFrameVisible, setIsFrameVisible] = useState(false);
const [isAccountsDataReceived, setIsAccountsDataReceived] = useState(false);
const [balanceMessage, setBalanceMessage] = useState<string>();
const [isBalanceSufficient, setIsBalanceSufficient] = useState<boolean>();
const [searchParams] = useSearchParams();
const templateId = searchParams.get('templateId');
@@ -71,47 +69,22 @@ const Configure = () => {
const navigate = useNavigate();
const { toast, dismiss } = useToast();
const client = useGQLClient();
const { networkData } = useAddNetwork()
const methods = useForm<ConfigureFormValues>({
defaultValues: {
option: 'Auction',
maxPrice: DEFAULT_MAX_PRICE,
lrn: '',
numProviders: '1',
numProviders: 1,
variables: [],
},
});
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 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 (
data: FieldValues,
envVariables: AddEnvironmentVariableInput[],
@@ -213,6 +186,7 @@ const Configure = () => {
(deployer) => deployer.deployerLrn === deployerLrn,
);
let amount: string;
let senderAddress: string;
let txHash: string | null = null;
if (createFormData.option === 'LRN' && !deployer?.minimumPayment) {
@@ -230,6 +204,16 @@ const Configure = () => {
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);
if (!txHash) {
@@ -319,7 +303,7 @@ const Configure = () => {
throw new Error(error);
}
},
[client, createProject, dismiss, toast, amountToBePaid],
[client, createProject, dismiss, toast],
);
const fetchDeployers = useCallback(async () => {
@@ -327,6 +311,10 @@ const Configure = () => {
setDeployers(res.deployers);
}, [client]);
const onAccountChange = useCallback((account: string) => {
setSelectedAccount(account);
}, []);
const onDeployerChange = useCallback(
(selectedLrn: string) => {
const deployer = deployers.find((d) => d.deployerLrn === selectedLrn);
@@ -352,20 +340,12 @@ const Configure = () => {
await requestTx(senderAddress, snowballAddress, amount);
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) => {
if (event.origin !== VITE_WALLET_IFRAME_URL) return;
if (event.data.type === 'TRANSACTION_RESPONSE') {
const txResponse = event.data.data;
resolve(txResponse);
cleanup();
} else if (event.data.type === 'ERROR') {
console.error('Error from wallet:', event.data.message);
reject(new Error('Transaction failed'));
@@ -375,9 +355,10 @@ const Configure = () => {
variant: 'error',
onDismiss: dismiss,
});
cleanup();
}
setIsFrameVisible(false);
window.removeEventListener('message', handleTxStatus);
};
window.addEventListener('message', handleTxStatus);
@@ -422,7 +403,7 @@ const Configure = () => {
iframe.contentWindow.postMessage(
{
type: 'REQUEST_TX',
chainId: networkData?.chainId,
chainId: VITE_LACONICD_CHAIN_ID,
fromAddress: sender,
toAddress: recipient,
amount,
@@ -437,12 +418,6 @@ const Configure = () => {
fetchDeployers();
}, []);
useEffect(() => {
if (isBalanceSufficient) {
setBalanceMessage(undefined);
}
}, [isBalanceSufficient]);
return (
<div className="space-y-7 px-4 py-6">
<div className="flex justify-between mb-6">
@@ -559,7 +534,6 @@ const Configure = () => {
type="number"
value={value}
onChange={(e) => onChange(e)}
min={1}
/>
)}
/>
@@ -573,7 +547,7 @@ const Configure = () => {
control={methods.control}
rules={{ required: true }}
render={({ field: { value, onChange } }) => (
<Input type="number" value={value} onChange={onChange} min={1} />
<Input type="number" value={value} onChange={onChange} />
)}
/>
</div>
@@ -605,83 +579,49 @@ const Configure = () => {
</Button>
</div>
) : (
<div className="flex gap-4">
<Button
{...buttonSize}
type="submit"
shape="default"
disabled={
isLoading ||
isPaymentLoading ||
!selectedAccount ||
!isBalanceSufficient ||
amountToBePaid === '' ||
selectedNumProviders === ''
}
rightIcon={
isLoading || isPaymentLoading ? (
<LoadingIcon className="animate-spin" />
) : (
<ArrowRightCircleFilledIcon />
)
}
>
{!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.'
<>
<AccountsDropdown
accounts={accounts}
onAccountChange={onAccountChange}
isDataReceived={isAccountsDataReceived}
/>
{accounts.length > 0 && (
<div>
<Button
{...buttonSize}
type="submit"
shape="default"
disabled={
isLoading || isPaymentLoading || !selectedAccount
}
rightIcon={
isLoading || isPaymentLoading ? (
<LoadingIcon className="animate-spin" />
) : (
'Insufficient funds.'
)}
</p>
</div>
) : null
) : null}
</div>
<ArrowRightCircleFilledIcon />
)
}
>
{!isPaymentDone
? isPaymentLoading
? 'Transaction Requested'
: 'Pay and Deploy'
: isLoading
? 'Deploying'
: 'Deploy'}
</Button>
</div>
)}
</>
)}
</form>
</FormProvider>
<ApproveTransactionModal
setAccount={setSelectedAccount}
<IFrameModal
setAccounts={setAccounts}
setIsDataReceived={setIsAccountsDataReceived}
isVisible={isFrameVisible}
/>
<CheckBalanceIframe
onBalanceChange={setIsBalanceSufficient}
amount={amountToBePaid}
isPollingEnabled={true}
/>
</div>
</div>
);
@@ -3,38 +3,27 @@ import { useCallback, useEffect } from 'react';
import { Box, Modal } from '@mui/material';
import {
VITE_LACONICD_CHAIN_ID,
VITE_WALLET_IFRAME_URL,
} from 'utils/constants';
import { REQUEST_WALLET_ACCOUNTS, WALLET_ACCOUNTS_DATA } from '../../../constants';
import { useAddNetwork } from '../../../hooks/useAddNetwork';
const ApproveTransactionModal = ({
setAccount,
const IFrameModal = ({
setAccounts,
setIsDataReceived,
isVisible,
}: {
setAccount: (account: string) => void;
setAccounts: (accounts: string[]) => void;
setIsDataReceived: (isReceived: boolean) => void;
isVisible: boolean;
}) => {
const { setIframe, isNetworkAvailable, networkData } = useAddNetwork();
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
if (event.origin !== VITE_WALLET_IFRAME_URL) return;
if (event.data.type === WALLET_ACCOUNTS_DATA) {
setIsDataReceived(true);
if (event.data.data.length === 0) {
console.error(`Accounts not present for chainId: ${networkData?.chainId}`);
return;
}
setAccount(event.data.data[0]);
}
if (event.data.type === 'ERROR') {
setIsDataReceived(true);
if (event.data.type === 'WALLET_ACCOUNTS_DATA') {
setAccounts(event.data.data);
} else if (event.data.type === 'ERROR') {
console.error('Error from wallet:', event.data.message);
}
};
@@ -44,14 +33,9 @@ const ApproveTransactionModal = ({
return () => {
window.removeEventListener('message', handleMessage);
};
}, [networkData]);
}, []);
const getDataFromWallet = useCallback(() => {
if (!networkData) {
console.error('networkData should not be empty');
return;
}
const iframe = document.getElementById('walletIframe') as HTMLIFrameElement;
if (!iframe.contentWindow) {
@@ -61,18 +45,12 @@ const ApproveTransactionModal = ({
iframe.contentWindow.postMessage(
{
type: REQUEST_WALLET_ACCOUNTS,
chainId: networkData.chainId,
type: 'REQUEST_WALLET_ACCOUNTS',
chainId: VITE_LACONICD_CHAIN_ID,
},
VITE_WALLET_IFRAME_URL,
);
}, [networkData]);
useEffect(() => {
if (isNetworkAvailable) {
getDataFromWallet();
}
}, [isNetworkAvailable, getDataFromWallet])
}, []);
return (
<Modal open={isVisible} disableEscapeKeyDown keepMounted>
@@ -94,7 +72,7 @@ const ApproveTransactionModal = ({
}}
>
<iframe
onLoad={(event) => setIframe(event.target as HTMLIFrameElement)}
onLoad={getDataFromWallet}
id="walletIframe"
src={`${VITE_WALLET_IFRAME_URL}/wallet-embed`}
width="100%"
@@ -107,4 +85,4 @@ const ApproveTransactionModal = ({
);
};
export default ApproveTransactionModal;
export default IFrameModal;
@@ -0,0 +1,42 @@
import { CopyBlock, atomOneLight } from 'react-code-blocks';
import { Link } from 'react-router-dom';
import { Modal } from 'components/shared/Modal';
import { Button } from 'components/shared/Button';
interface AssignDomainProps {
open: boolean;
handleOpen: () => void;
}
const AssignDomainDialog = ({ open, handleOpen }: AssignDomainProps) => {
return (
<Modal open={open} onOpenChange={handleOpen}>
<Modal.Content>
<Modal.Header>Assign Domain</Modal.Header>
<Modal.Body>
In order to assign a domain to your production deployments, configure
it in the{' '}
{/* TODO: Fix selection of project settings tab on navigation to domains */}
<Link to="../settings/domains" className="text-light-blue-800 inline">
project settings{' '}
</Link>
(recommended). If you want to assign to this specific deployment,
however, you can do so using our command-line interface:
{/* https://github.com/rajinwonderland/react-code-blocks/issues/138 */}
<CopyBlock
text="snowball alias <deployment> <domain>"
language=""
showLineNumbers={false}
theme={atomOneLight}
/>
</Modal.Body>
<Modal.Footer className="flex justify-start">
<Button onClick={handleOpen}>Okay</Button>
</Modal.Footer>
</Modal.Content>
</Modal>
);
};
export default AssignDomainDialog;
@@ -10,6 +10,7 @@ import {
import { Deployment, Domain, Environment, Project } from 'gql-client';
import { Button } from 'components/shared/Button';
import {
GlobeIcon,
HorizontalDotIcon,
LinkIcon,
RefreshIcon,
@@ -17,6 +18,7 @@ import {
UndoIcon,
CrossCircleIcon,
} from 'components/shared/CustomIcon';
import AssignDomainDialog from './AssignDomainDialog';
import { useGQLClient } from 'context/GQLClientContext';
import { cn } from 'utils/classnames';
import { ChangeStateToProductionDialog } from 'components/projects/Dialog/ChangeStateToProductionDialog';
@@ -47,8 +49,8 @@ export const DeploymentMenu = ({
const [redeployToProduction, setRedeployToProduction] = useState(false);
const [deleteDeploymentDialog, setDeleteDeploymentDialog] = useState(false);
const [isConfirmDeleteLoading, setIsConfirmDeleteLoading] = useState(false);
const [isConfirmUpdateLoading, setIsConfirmUpdateLoading] = useState(false);
const [rollbackDeployment, setRollbackDeployment] = useState(false);
const [assignDomainDialog, setAssignDomainDialog] = useState(false);
const [isConfirmButtonLoading, setConfirmButtonLoadingLoading] =
useState(false);
@@ -56,8 +58,6 @@ export const DeploymentMenu = ({
const isUpdated = await client.updateDeploymentToProd(deployment.id);
if (isUpdated.updateDeploymentToProd) {
await onUpdate();
setIsConfirmUpdateLoading(false);
toast({
id: 'deployment_changed_to_production',
title: 'Deployment changed to production',
@@ -102,8 +102,6 @@ export const DeploymentMenu = ({
);
if (isRollbacked.rollbackDeployment) {
await onUpdate();
setIsConfirmUpdateLoading(false);
toast({
id: 'deployment_rolled_back',
title: 'Deployment rolled back',
@@ -175,6 +173,12 @@ export const DeploymentMenu = ({
<LinkIcon /> Visit
</a>
</MenuItem>
<MenuItem
className="hover:bg-base-bg-emphasized flex items-center gap-3"
onClick={() => setAssignDomainDialog(!assignDomainDialog)}
>
<GlobeIcon /> Assign domain
</MenuItem>
<MenuItem
className="hover:bg-base-bg-emphasized flex items-center gap-3"
onClick={() => setChangeToProduction(!changeToProduction)}
@@ -222,11 +226,9 @@ export const DeploymentMenu = ({
handleCancel={() => setChangeToProduction((preVal) => !preVal)}
open={changeToProduction}
handleConfirm={async () => {
setIsConfirmUpdateLoading(true);
await updateDeployment();
setChangeToProduction((preVal) => !preVal);
}}
isConfirmButtonLoading={isConfirmUpdateLoading}
deployment={deployment}
domains={prodBranchDomains}
/>
@@ -241,7 +243,7 @@ export const DeploymentMenu = ({
setRedeployToProduction((preVal) => !preVal);
}}
deployment={deployment}
domains={prodBranchDomains}
domains={deployment.domain ? [deployment.domain] : []}
isConfirmButtonLoading={isConfirmButtonLoading}
/>
{Boolean(currentDeployment) && (
@@ -251,16 +253,18 @@ export const DeploymentMenu = ({
open={rollbackDeployment}
confirmButtonTitle="Rollback"
handleConfirm={async () => {
setIsConfirmUpdateLoading(true);
await rollbackDeploymentHandler();
setRollbackDeployment((preVal) => !preVal);
}}
deployment={currentDeployment}
newDeployment={deployment}
domains={prodBranchDomains}
isConfirmButtonLoading={isConfirmUpdateLoading}
domains={currentDeployment.domain ? [currentDeployment.domain] : []}
/>
)}
<AssignDomainDialog
open={assignDomainDialog}
handleOpen={() => setAssignDomainDialog(!assignDomainDialog)}
/>
<DeleteDeploymentDialog
open={deleteDeploymentDialog}
handleConfirm={async () => {
@@ -43,11 +43,6 @@ export const AuctionCard = ({ project }: { project: Project }) => {
const checkAuctionStatus = useCallback(async () => {
const result = await client.getAuctionData(project.auctionId);
if (!result) {
return
}
setAuctionStatus(result.status);
setAuctionDetails(result);
}, [project.auctionId, project.deployers, project.fundsReleased]);
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import { DNSRecordAttributes, Domain, DomainStatus, Project } from 'gql-client';
import { Domain, DomainStatus, Project } from 'gql-client';
import {
Typography,
@@ -14,19 +14,17 @@ import EditDomainDialog from './EditDomainDialog';
import { useGQLClient } from 'context/GQLClientContext';
import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog';
import { useToast } from 'components/shared/Toast';
import { GearIcon } from 'components/shared/CustomIcon';
// import { Tag } from 'components/shared/Tag';
import {
// CheckIcon,
// CrossIcon,
GearIcon,
// LoadingIcon,
} from 'components/shared/CustomIcon';
import { Heading } from 'components/shared/Heading';
import { Button } from 'components/shared/Button';
import { useParams } from 'react-router-dom';
// NOTE: Commented code for verify domain functionality
// import { Tag } from 'components/shared/Tag';
// import {
// CheckIcon,
// CrossIcon,
// LoadingIcon,
// } from 'components/shared/CustomIcon';
// enum RefreshStatus {
// IDLE,
// CHECKING,
@@ -34,8 +32,6 @@ import { useParams } from 'react-router-dom';
// CHECK_FAIL,
// }
// const CHECK_FAIL_TIMEOUT = 5000; // In milliseconds
interface DomainCardProps {
domains: Domain[];
domain: Domain;
@@ -44,6 +40,14 @@ interface DomainCardProps {
onUpdate: () => Promise<void>;
}
// const CHECK_FAIL_TIMEOUT = 5000; // In milliseconds
// TODO: Get domain record
const DOMAIN_RECORD = {
type: 'A',
name: '@',
value: '56.49.19.21',
};
const DomainCard = ({
domains,
@@ -54,10 +58,10 @@ const DomainCard = ({
}: DomainCardProps) => {
const { toast, dismiss } = useToast();
const { id } = useParams();
// const [refreshStatus, SetRefreshStatus] = useState(RefreshStatus.IDLE);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [editDialogOpen, setEditDialogOpen] = useState(false);
const [dnsRecord, setDnsRecord] = useState<DNSRecordAttributes | null>(null);
// const [refreshStatus, SetRefreshStatus] = useState(RefreshStatus.IDLE);
const [IPAddress, setIPAddress] = useState<string>();
const client = useGQLClient();
@@ -94,9 +98,9 @@ const DomainCard = ({
return;
}
const dnsRecordResponse = await client.getLatestDNSRecordByProjectId(id);
const dnsData = await client.getLatestDNSDataByProjectId(id);
setDnsRecord(dnsRecordResponse.latestDNSRecord);
setIPAddress(dnsData.value);
};
fetchDNSData();
@@ -183,9 +187,9 @@ const DomainCard = ({
{domain.status === DomainStatus.Pending && (
<Card className="bg-slate-100 p-4 text-sm">
{/* {refreshStatus === RefreshStatus.IDLE ? ( */}
<Heading>
^ Add these records to your domain {/* and refresh to check */}
</Heading>
<Heading>
^ Add these records to your domain {/* and refresh to check */}
</Heading>
{/* ) : refreshStatus === RefreshStatus.CHECKING ? (
<Heading className="text-blue-500">
^ Checking records for {domain.name}
@@ -208,15 +212,11 @@ const DomainCard = ({
</tr>
</thead>
<tbody>
{dnsRecord ? (
<tr>
<td>{dnsRecord.resourceType}</td>
<td>@</td>
<td>{dnsRecord.value ?? 'Not Configured'}</td>
</tr>
) : (
<p className={'text-red-500'}>DNS record data not available</p>
)}
<tr>
<td>{DOMAIN_RECORD.type}</td>
<td>{DOMAIN_RECORD.name}</td>
<td>{IPAddress ?? 'Not Configured'}</td>
</tr>
</tbody>
</table>
</Card>
@@ -1,8 +1,10 @@
import {
useCallback,
useEffect,
// useMemo
} from 'react';
import {
// Controller,
useForm,
SubmitHandler,
} from 'react-hook-form';
@@ -10,6 +12,8 @@ import { Domain } from 'gql-client';
import {
Typography,
// Select,
// Option,
} from '@snowballtools/material-tailwind-react-fork';
import { useGQLClient } from 'context/GQLClientContext';
@@ -18,14 +22,6 @@ import { Button } from 'components/shared/Button';
import { Input } from 'components/shared/Input';
import { useToast } from 'components/shared/Toast';
// NOTE: Commented code for redirect domain functionality
// import {
// Select,
// Option,
// } from '@snowballtools/material-tailwind-react-fork';
// import { Controller } from 'react-hook-form';
// import { useMemo } from 'react';
// const DEFAULT_REDIRECT_OPTIONS = ['none'];
interface EditDomainDialogProp {
@@ -182,7 +178,8 @@ const EditDomainDialog = ({
})}
disabled={
!Boolean(branches.length)
// || watch('redirectedTo') !== DEFAULT_REDIRECT_OPTIONS[0]
// ||
// watch('redirectedTo') !== DEFAULT_REDIRECT_OPTIONS[0]
}
/>
{!isValid && (
@@ -1,13 +1,11 @@
// import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { Heading } from 'components/shared/Heading';
// import { InlineNotification } from 'components/shared/InlineNotification';
import { Input } from 'components/shared/Input';
import { Button } from 'components/shared/Button';
// NOTE: Commented code for redirect domain functionality
// import { useEffect, useState } from 'react';
// import { InlineNotification } from 'components/shared/InlineNotification';
// import { Radio } from 'components/shared/Radio';
interface SetupDomainFormValues {
@@ -30,8 +28,8 @@ const SetupDomain = () => {
mode: 'onChange',
});
const navigate = useNavigate();
// const [domainStr, setDomainStr] = useState<string>('');
const navigate = useNavigate();
// const isWWWRadioOptions = [
// { label: domainStr, value: 'false' },
// { label: `www.${domainStr}`, value: 'true' },
@@ -1,11 +1,14 @@
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 { motion } from 'framer-motion';
import { useDisconnect } from 'wagmi';
import { useGQLClient } from 'context/GQLClientContext';
import {
GlobeIcon,
LifeBuoyIcon,
LogoutIcon,
QuestionMarkRoundIcon,
} from 'components/shared/CustomIcon';
import { Tabs } from 'components/shared/Tabs';
@@ -13,9 +16,10 @@ import { Logo } from 'components/Logo';
import { Avatar } from 'components/shared/Avatar';
import { formatAddress } from 'utils/format';
import { getInitials } from 'utils/geInitials';
import { Button } from 'components/shared/Button';
import { cn } from 'utils/classnames';
import { useMediaQuery } from 'usehooks-ts';
import { SHOPIFY_APP_URL } from '../../../constants';
import { BASE_URL } from 'utils/constants';
interface SidebarProps {
mobileOpen?: boolean;
@@ -23,10 +27,12 @@ interface SidebarProps {
export const Sidebar = ({ mobileOpen }: SidebarProps) => {
const { orgSlug } = useParams();
const navigate = useNavigate();
const client = useGQLClient();
const isDesktop = useMediaQuery('(min-width: 960px)');
const [user, setUser] = useState<User>();
const { disconnect } = useDisconnect();
const fetchUser = useCallback(async () => {
const { user } = await client.getUser();
@@ -37,6 +43,16 @@ export const Sidebar = ({ mobileOpen }: SidebarProps) => {
fetchUser();
}, []);
const handleLogOut = useCallback(async () => {
await fetch(`${BASE_URL}/auth/logout`, {
method: 'POST',
credentials: 'include',
});
localStorage.clear();
disconnect();
navigate('/login');
}, [disconnect, navigate]);
return (
<motion.nav
initial={{ x: -320 }}
@@ -66,10 +82,19 @@ export const Sidebar = ({ mobileOpen }: SidebarProps) => {
<Tabs defaultValue="Projects" orientation="vertical">
{/* // TODO: use proper link buttons */}
<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="">
<a
className="cursor-pointer font-mono"
href={`${SHOPIFY_APP_URL}/pages/instruction-faq`}
href="https://store.laconic.com/pages/instruction-faq"
>
DOCUMENTATION
</a>
@@ -100,6 +125,14 @@ export const Sidebar = ({ mobileOpen }: SidebarProps) => {
</p>
</div>
)}
<Button
iconOnly
variant="ghost"
className="text-elements-low-em"
onClick={handleLogOut}
>
<LogoutIcon />
</Button>
</div>
</motion.nav>
);
@@ -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;
-13
View File
@@ -1,16 +1,3 @@
export const SHORT_COMMIT_HASH_LENGTH = 8;
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";
@@ -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>
);
}
@@ -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
};
};
@@ -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;
+7 -4
View File
@@ -14,6 +14,7 @@ import { SERVER_GQL_PATH } from './constants';
import { Toaster } from 'components/shared/Toast';
import { LogErrorBoundary } from 'utils/log-error';
import { BASE_URL } from 'utils/constants';
import Web3ModalProvider from './context/Web3Provider';
import './index.css';
console.log(`v-0.0.9`);
@@ -31,10 +32,12 @@ root.render(
<LogErrorBoundary>
<React.StrictMode>
<ThemeProvider>
<GQLClientProvider client={gqlClient}>
<App />
<Toaster />
</GQLClientProvider>
<Web3ModalProvider>
<GQLClientProvider client={gqlClient}>
<App />
<Toaster />
</GQLClientProvider>
</Web3ModalProvider>
</ThemeProvider>
</React.StrictMode>
</LogErrorBoundary>,
+4 -2
View File
@@ -1,4 +1,4 @@
import AutoSignInIFrameModal from 'components/shared/auth/AutoSignInIFrameModal';
import { Login } from './auth/Login';
const AuthPage = () => {
return (
@@ -13,7 +13,9 @@ const AuthPage = () => {
</div>
</div>
<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>
);
@@ -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;
@@ -9,6 +9,12 @@ export const Login = () => {
</div>
</div>
<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>
);
};
@@ -10,7 +10,6 @@ import { DeleteVariableDialog } from 'components/projects/Dialog/DeleteVariableD
import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog';
import { CancelDeploymentDialog } from 'components/projects/Dialog/CancelDeploymentDialog';
import {
AppDeploymentRecordAttributes,
Deployment,
DeploymentStatus,
Domain,
@@ -21,6 +20,15 @@ import { ChangeStateToProductionDialog } from 'components/projects/Dialog/Change
const deployment: Deployment = {
id: '1',
domain: {
id: 'domain1',
branch: 'main',
name: 'example.com',
status: DomainStatus.Live,
redirectTo: null,
createdAt: '1677609600', // 2023-02-25T12:00:00Z
updatedAt: '1677613200', // 2023-02-25T13:00:00Z
},
branch: 'main',
commitHash: 'a1b2c3d',
commitMessage:
@@ -49,7 +57,6 @@ const deployment: Deployment = {
updatedAt: '1677680400', // 2023-03-01T13:00:00Z
applicationDeploymentRequestId:
'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize',
applicationDeploymentRecordData: {} as AppDeploymentRecordAttributes,
};
const domains: Domain[] = [
@@ -245,7 +252,7 @@ const ModalsPage: React.FC = () => {
setRedeployToProduction((preVal) => !preVal)
}
deployment={deployment}
domains={domains}
domains={deployment.domain ? [deployment.domain] : []}
/>
{/* Rollback to this deployment */}
<Button onClick={() => setRollbackDeployment(true)}>
@@ -261,7 +268,7 @@ const ModalsPage: React.FC = () => {
}
deployment={deployment}
newDeployment={deployment}
domains={domains}
domains={deployment.domain ? [deployment.domain] : []}
/>
</div>
</div>
+2 -14
View File
@@ -1,20 +1,16 @@
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 { Heading, Badge, Button } from 'components/shared';
import { PlusIcon } from 'components/shared/CustomIcon';
import { useGQLClient } from 'context/GQLClientContext';
import { Project } from 'gql-client';
import CheckBalanceIframe from 'components/projects/create/CheckBalanceIframe';
const Projects = () => {
const [isBalanceSufficient, setIsBalanceSufficient] = useState<boolean>();
const [projects, setProjects] = useState<Project[]>([]);
const navigate = useNavigate();
const client = useGQLClient();
const { orgSlug } = useParams();
const [projects, setProjects] = useState<Project[]>([]);
const fetchProjects = useCallback(async () => {
const { projectsInOrganization } = await client.getProjectsInOrganization(
@@ -27,12 +23,6 @@ const Projects = () => {
fetchProjects();
}, [orgSlug]);
useEffect(() => {
if (isBalanceSufficient === false) {
navigate('/buy-prepaid-service');
}
}, [isBalanceSufficient]);
return (
<section className="px-4 md:px-6 py-6 flex flex-col gap-6">
{/* Header */}
@@ -59,8 +49,6 @@ const Projects = () => {
return <ProjectCard project={project} key={key} />;
})}
</div>
<CheckBalanceIframe onBalanceChange={setIsBalanceSufficient} isPollingEnabled={false} amount='1' />
</section>
);
};
@@ -1,42 +1,36 @@
import { useEffect, useState } from 'react';
import {
Link,
useOutletContext,
// useNavigate,
useOutletContext
} from 'react-router-dom';
import { RequestError } from 'octokit';
import { useOctokit } from 'context/OctokitContext';
import { GitCommitWithBranch, OutletContextType } from '../../../../types';
// import { useGQLClient } from 'context/GQLClientContext';
import {
// Button,
Heading,
Avatar,
// Tag
} from 'components/shared';
import { getInitials } from 'utils/geInitials';
import {
BranchStrokeIcon,
// CheckRoundFilledIcon,
// ClockIcon,
CursorBoxIcon,
GithubStrokeIcon,
// GlobeIcon,
LinkIcon,
CalendarDaysIcon,
} from 'components/shared/CustomIcon';
import { useOctokit } from 'context/OctokitContext';
import { GitCommitWithBranch, OutletContextType } from '../../../../types';
import { getInitials } from 'utils/geInitials';
import { Activity } from 'components/projects/project/overview/Activity';
import { OverviewInfo } from 'components/projects/project/overview/OverviewInfo';
import { relativeTimeMs } from 'utils/time';
import { AuctionCard } from 'components/projects/project/overview/Activity/AuctionCard';
// NOTE: Commented code for verify domain functionality
// import { useGQLClient } from 'context/GQLClientContext';
// import { Domain, DomainStatus } from 'gql-client';
// import {
// CheckRoundFilledIcon,
// ClockIcon,
// GlobeIcon,
// } from 'components/shared/CustomIcon';
// import {
// Button,
// Tag,
// } from 'components/shared';
// import { useNavigate } from 'react-router-dom';
import { AuctionCard } from 'components/projects/project/overview/Activity/AuctionCard';
const COMMITS_PER_PAGE = 4;
const PROJECT_UPDATE_WAIT_MS = 5000;
@@ -122,6 +116,8 @@ const OverviewTabPanel = () => {
return () => clearInterval(timerId);
}, [onUpdate]);
console.log(project.deployments)
// useEffect(() => {
// const fetchLiveProdDomain = async () => {
// const { domains } = await client.getDomains(project.id, {
@@ -156,11 +152,14 @@ const OverviewTabPanel = () => {
{project.deployments &&
project.deployments.length > 0 &&
project.deployments.map((deployment, index) => (
<p
key={index}
className="text-sm text-elements-low-em dark:text-foreground tracking-tight truncate"
>
{deployment.deployer.baseDomain}
<p>
<a
key={index}
// href={`https://${project.name.toLowerCase()}.${deployment.deployer.baseDomain}`}
className="text-sm text-elements-low-em dark:text-foreground tracking-tight truncate"
>
{deployment.deployer.baseDomain}
</a>
</p>
))}
</div>
@@ -204,10 +203,17 @@ const OverviewTabPanel = () => {
{project.deployments &&
project.deployments.length > 0 &&
project.deployments.map((deployment) => (
<div key={deployment.id} className="flex gap-2 items-center">
<Link to={deployment.applicationDeploymentRecordData.url}>
<div className="flex gap-2 items-center">
<Link
to={
deployment.domain?.name
? `https://${deployment.domain.name}`
: `https://${project.name.toLowerCase()}.${deployment.deployer.baseDomain}`
}
>
<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.domain?.name ??
`https://${project.name.toLowerCase()}.${deployment.deployer.baseDomain}`}
<LinkIcon className="group-hover:rotate-45 transition-transform" />
</span>
</Link>
@@ -60,19 +60,21 @@ const Domains = () => {
return (
<ProjectSettingContainer
headingText="Domains"
{...(!project.auctionId && {
button: (
<Button
as="a"
href="add"
variant="secondary"
leftIcon={<PlusIcon />}
size="md"
>
Add domain
</Button>
),
})}
button={
<>
{!project.auctionId && (
<Button
as="a"
href="add"
variant="secondary"
leftIcon={<PlusIcon />}
size="md"
>
Add domain
</Button>
)}
</>
}
>
{project.auctionId ? (
<p className="text-gray-500">
@@ -8,7 +8,6 @@ import { ArrowRightCircleIcon } from 'components/shared/CustomIcon';
import { ProjectSettingContainer } from 'components/projects/project/settings/ProjectSettingContainer';
import { useToast } from 'components/shared/Toast';
import { useEffect, useState } from 'react';
import { DNSRecordAttributes } from 'gql-client';
const Config = () => {
const { id, orgSlug } = useParams();
@@ -18,7 +17,7 @@ const Config = () => {
const primaryDomainName = searchParams.get('name');
const { toast, dismiss } = useToast();
const [dnsRecord, setDnsRecord] = useState<DNSRecordAttributes | null>(null);
const [IPAddress, setIPAddress] = useState<string>();
const handleSubmitDomain = async () => {
if (primaryDomainName === null) {
@@ -75,9 +74,9 @@ const Config = () => {
return;
}
const dnsRecordResponse = await client.getLatestDNSRecordByProjectId(id);
const dnsData = await client.getLatestDNSDataByProjectId(id);
setDnsRecord(dnsRecordResponse.latestDNSRecord);
setIPAddress(dnsData.value);
};
fetchDNSData();
@@ -86,57 +85,49 @@ const Config = () => {
// TODO: Figure out DNS Provider if possible and update appropriatly
return (
<ProjectSettingContainer headingText="Setup domain name">
{dnsRecord ? (
<>
<p className="text-blue-gray-500">
Add the following records to your domain.
</p>
<p className="text-blue-gray-500">
Add the following records to your domain.
</p>
<Table>
<Table.Header>
<Table.Row>
<Table.ColumnHeaderCell>Type</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>Host</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>Value</Table.ColumnHeaderCell>
</Table.Row>
</Table.Header>
<Table>
<Table.Header>
<Table.Row>
<Table.ColumnHeaderCell>Type</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>Host</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>Value</Table.ColumnHeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.RowHeaderCell>
{dnsRecord.resourceType}
</Table.RowHeaderCell>
<Table.Cell>@</Table.Cell>
<Table.Cell>
<p className={!dnsRecord.value ? 'text-red-500' : ''}>
{dnsRecord.value ?? 'Not available'}
</p>
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
<Table.Body>
<Table.Row>
<Table.RowHeaderCell>A</Table.RowHeaderCell>
<Table.Cell>@</Table.Cell>
<Table.Cell>
<p className={!IPAddress ? 'text-red-500' : ''}>
{IPAddress ?? 'Not available'}
</p>
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
{dnsRecord?.value && (
<InlineNotification
variant="info"
title={`It can take up to 48 hours for these updates to reflect
globally.`}
/>
)}
<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>
{IPAddress && (
<InlineNotification
variant="info"
title={`It can take up to 48 hours for these updates to reflect
globally.`}
/>
)}
<Button
className="w-fit"
disabled={!IPAddress}
onClick={handleSubmitDomain}
variant="primary"
shape="default"
rightIcon={<ArrowRightCircleIcon />}
>
FINISH
</Button>
</ProjectSettingContainer>
);
};
@@ -12,7 +12,6 @@ import {
Domain,
Environment,
Permission,
AppDeploymentRecordAttributes,
} from 'gql-client';
export const user: User = {
@@ -100,6 +99,7 @@ export const deployment0: Deployment = {
environment: Environment.Development,
isCurrent: true,
commitHash: 'Commit Hash',
domain: domain0,
commitMessage: 'Commit Message',
createdBy: user,
deployer: {
@@ -111,7 +111,6 @@ export const deployment0: Deployment = {
},
applicationDeploymentRequestId:
'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize',
applicationDeploymentRecordData: {} as AppDeploymentRecordAttributes,
};
export const project: Project = {
+2
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
.VITE_GITHUB_NEXT_APP_TEMPLATE_REPO;
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_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;
+8
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: [],
});
+20 -16
View File
@@ -393,6 +393,21 @@ export class GQLClient {
return data;
}
async oldestDomain(
projectId: string,
): Promise<types.OldestDomainResponse> {
const { data } = await this.client.query({
query: queries.oldestDomain,
variables: {
projectId,
},
});
console.log({data})
return data;
}
async authenticateGitHub(
code: string
): Promise<types.AuthenticateGitHubResponse> {
@@ -414,25 +429,14 @@ export class GQLClient {
return data;
}
async getAuctionData(auctionId: string): Promise<types.Auction | null> {
const { data, errors } = await this.client.query({
async getAuctionData(auctionId: string): Promise<types.Auction> {
const { data } = await this.client.query({
query: queries.getAuctionData,
variables: {
auctionId,
},
});
if (errors && errors.length) {
const isAuctionNotFound = errors.some((error) =>
error.message?.includes('Auction not found')
);
if (isAuctionNotFound) {
return data;
}
}
return data.getAuctionData;
}
@@ -465,14 +469,14 @@ export class GQLClient {
return data.verifyTx;
}
async getLatestDNSRecordByProjectId(projectId: string): Promise<types.GetLatestDNSDataResponse> {
async getLatestDNSDataByProjectId(projectId: string): Promise<types.DNSRecordAttributes> {
const { data } = await this.client.query({
query: queries.getLatestDNSRecordByProjectId,
query: queries.getLatestDNSDataByProjectId,
variables: {
projectId,
},
});
return data;
return data.getLatestDNSDataByProjectId;
}
}
+38 -7
View File
@@ -57,12 +57,17 @@ query ($projectId: String!) {
commitHash
createdAt
environment
applicationDeploymentRecordData {
url
}
deployer {
baseDomain
}
domain {
status
branch
createdAt
updatedAt
id
name
}
createdBy {
id
name
@@ -107,8 +112,13 @@ query ($organizationSlug: String!) {
commitMessage
createdAt
environment
applicationDeploymentRecordData {
url
domain {
status
branch
createdAt
updatedAt
id
name
}
}
}
@@ -131,6 +141,14 @@ export const getDeployments = gql`
query ($projectId: String!) {
deployments(projectId: $projectId) {
id
domain{
branch
createdAt
id
name
status
updatedAt
}
branch
commitHash
commitMessage
@@ -243,6 +261,19 @@ query ($projectId: String!, $filter: FilterDomainsInput) {
}
`;
export const oldestDomain = gql`
query ($projectId: String!) {
oldestDomain(projectId: $projectId) {
branch
createdAt
id
name
status
updatedAt
}
}
`
export const getAuctionData = gql`
query ($auctionId: String!) {
getAuctionData(auctionId: $auctionId){
@@ -326,9 +357,9 @@ query ($txHash: String!, $amount: String!, $senderAddress: String!) {
}
`;
export const getLatestDNSRecordByProjectId = gql`
export const getLatestDNSDataByProjectId = gql`
query($projectId: String!) {
latestDNSRecord(projectId: $projectId) {
getLatestDNSDataByProjectId(projectId: $projectId) {
name
value
request
+5 -18
View File
@@ -99,6 +99,7 @@ export type User = {
export type Deployment = {
id: string;
domain: Domain;
branch: string;
commitHash: string;
commitMessage: string;
@@ -107,7 +108,6 @@ export type Deployment = {
environment: Environment;
isCurrent: boolean;
baseDomain?: string;
applicationDeploymentRecordData: AppDeploymentRecordAttributes;
status: DeploymentStatus;
createdBy: User;
createdAt: string;
@@ -236,6 +236,10 @@ export type GetDomainsResponse = {
domains: Domain[];
};
export type OldestDomainResponse = {
oldestDomain: Domain | null;
}
export type GetDeployersResponse = {
deployers: Deployer[];
};
@@ -384,20 +388,3 @@ export type DNSRecordAttributes = {
resourceType: string;
version: string;
}
export type GetLatestDNSDataResponse = {
latestDNSRecord: DNSRecordAttributes | null
}
export interface AppDeploymentRecordAttributes {
application: string;
auction: string;
deployer: string;
dns: string;
meta: string;
name: string;
request: string;
type: string;
url: string;
version: string;
}
-7
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
+1112 -45
View File
File diff suppressed because it is too large Load Diff