Compare commits

..

10 Commits

Author SHA1 Message Date
c33a4e5574 Fix form input for creating project in auction flow (#53)
All checks were successful
Lint / lint (20.x) (push) Successful in 1m24s
Deploy Snowball frontend / deploy (20.x) (push) Successful in 1m58s
Part of https://www.notion.so/Simplify-login-flow-in-deploy-laconic-com-190a6b22d47280a9924cc38f8cf4c891

Co-authored-by: IshaVenikar <ishavenikar7@gmail.com>
Reviewed-on: #53
2025-02-12 11:17:08 +00:00
6c79ed37fa Auto sign-in using laconic wallet and show link to Laconic store on low balance (#52)
All checks were successful
Lint / lint (20.x) (push) Successful in 1m25s
Deploy Snowball frontend / deploy (20.x) (push) Successful in 2m1s
Part of https://www.notion.so/Simplify-login-flow-in-deploy-laconic-com-190a6b22d47280a9924cc38f8cf4c891

- Send SIWE message to laconic wallet for auto signing
- Remove WallletConnect
- Remove log out functionality

Co-authored-by: Shreerang Kale <shreerangkale@gmail.com>
Co-authored-by: IshaVenikar <ishavenikar7@gmail.com>
Reviewed-on: #52
2025-02-12 09:32:44 +00:00
a51765dae5 Support setting custom domain on app deployment (#49)
All checks were successful
Lint / lint (20.x) (push) Successful in 4m46s
Deploy Snowball frontend / deploy (20.x) (push) Successful in 4m54s
Part of https://www.notion.so/Support-custom-domains-in-deploy-laconic-com-18aa6b22d4728067a44ae27090c02ce5 and #47

- Support setting custom domain in deployments through targeted deployer
  - Store DNS record data for deployments
  - Show service provider IP address for creating required `A` record
  - Comment out verify domain and redirect domain functionality
  - Handle rollback deployment functionality
- Store DNS deployments record in Deployment table

Co-authored-by: IshaVenikar <ishavenikar7@gmail.com>
Co-authored-by: Shreerang Kale <shreerangkale@gmail.com>
Reviewed-on: #49
Co-authored-by: Prathamesh Musale <prathamesh@noreply.git.vdb.to>
Co-committed-by: Prathamesh Musale <prathamesh@noreply.git.vdb.to>
2025-02-04 13:45:47 +00:00
534871a7ae Implement functionality to encrypt environment variables (#48)
All checks were successful
Lint / lint (20.x) (push) Successful in 4m45s
Deploy Snowball frontend / deploy (20.x) (push) Successful in 5m1s
Part of https://www.notion.so/Support-encrypted-config-for-deploy-laconic-com-18aa6b22d4728099bc64fc7a310b530d

Co-authored-by: IshaVenikar <ishavenikar7@gmail.com>
Reviewed-on: #48
2025-01-30 09:44:18 +00:00
17640d3133 Copy updates (#38)
All checks were successful
Lint / lint (20.x) (push) Successful in 4m39s
Deploy Snowball frontend / deploy (20.x) (push) Successful in 4m47s
Co-authored-by: zramsay <zach@bluecollarcoding.ca>
Co-authored-by: Nabarun <nabarun@deepstacksoft.com>
Reviewed-on: #38
Co-authored-by: zramsay <zramsay@noreply.git.vdb.to>
Co-committed-by: zramsay <zramsay@noreply.git.vdb.to>
2024-11-14 09:10:19 +00:00
bba0b57bed Keep records directory for deploy-frontend script (#43)
All checks were successful
Deploy Snowball frontend / deploy (20.x) (push) Successful in 4m39s
Lint / lint (20.x) (push) Successful in 4m44s
Part of [Service provider auctions for web deployments](https://www.notion.so/Service-provider-auctions-for-web-deployments-104a6b22d47280dbad51d28aa3a91d75)

Reviewed-on: #43
Co-authored-by: Nabarun <nabarun@deepstacksoft.com>
Co-committed-by: Nabarun <nabarun@deepstacksoft.com>
2024-11-13 13:56:15 +00:00
c34e66aa93 Integrate wallet IFrame for payments (#42)
Some checks failed
Deploy Snowball frontend / deploy (20.x) (push) Failing after 4m2s
Lint / lint (20.x) (push) Successful in 4m41s
Part of [Service provider auctions for web deployments](https://www.notion.so/Service-provider-auctions-for-web-deployments-104a6b22d47280dbad51d28aa3a91d75)

- Replace wallet connect with iframe to display wallet in modal for deployment payments

![image](/attachments/b253d833-0730-45b7-8b65-b0af6d24678a)

Co-authored-by: Isha <ishavenikar7@gmail.com>
Co-authored-by: Adw8 <adwaitgharpure@gmail.com>
Co-authored-by: IshaVenikar <ishavenikar7@gmail.com>
Reviewed-on: #42
Co-authored-by: Nabarun <nabarun@deepstacksoft.com>
Co-committed-by: Nabarun <nabarun@deepstacksoft.com>
2024-11-13 13:32:27 +00:00
b61682dd20 Fix fetching build logs for redeployments (#39)
All checks were successful
Deploy Snowball frontend / deploy (20.x) (push) Successful in 4m35s
Lint / lint (20.x) (push) Successful in 4m41s
Part of [Service provider auctions for web deployments](https://www.notion.so/Service-provider-auctions-for-web-deployments-104a6b22d47280dbad51d28aa3a91d75)

Co-authored-by: IshaVenikar <ishavenikar7@gmail.com>
Reviewed-on: #39
2024-11-12 15:18:07 +00:00
bcb6ac241b Fix template tab in GitHub connect page (#41)
All checks were successful
Deploy Snowball frontend / deploy (20.x) (push) Successful in 4m33s
Lint / lint (20.x) (push) Successful in 4m39s
Part of #40 and [Service provider auctions for web deployments](https://www.notion.so/Service-provider-auctions-for-web-deployments-104a6b22d47280dbad51d28aa3a91d75)

Reviewed-on: #41
Co-authored-by: Nabarun <nabarun@deepstacksoft.com>
Co-committed-by: Nabarun <nabarun@deepstacksoft.com>
2024-11-12 14:21:10 +00:00
4a9f517d85 Merge pull request 'fix: colors for project template cards' (#37) from zach/ui-fixes into main
All checks were successful
Deploy Snowball frontend / deploy (20.x) (push) Successful in 4m36s
Lint / lint (20.x) (push) Successful in 4m42s
Reviewed-on: #37
2024-11-06 19:27:32 +00:00
67 changed files with 1734 additions and 2394 deletions

View File

@ -15,8 +15,8 @@ VITE_GITHUB_CLIENT_ID = 'LACONIC_HOSTED_CONFIG_github_clientid'
VITE_GITHUB_PWA_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_pwa_templaterepo' VITE_GITHUB_PWA_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_pwa_templaterepo'
VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_image_upload_templaterepo' VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_image_upload_templaterepo'
VITE_GITHUB_NEXT_APP_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_next_app_templaterepo' VITE_GITHUB_NEXT_APP_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_github_next_app_templaterepo'
VITE_WALLET_CONNECT_ID = 'LACONIC_HOSTED_CONFIG_wallet_connect_id'
VITE_LACONICD_CHAIN_ID = 'LACONIC_HOSTED_CONFIG_laconicd_chain_id' VITE_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_LIT_RELAY_API_KEY = 'LACONIC_HOSTED_CONFIG_lit_relay_api_key'
VITE_BUGSNAG_API_KEY = 'LACONIC_HOSTED_CONFIG_bugsnag_api_key' VITE_BUGSNAG_API_KEY = 'LACONIC_HOSTED_CONFIG_bugsnag_api_key'
VITE_PASSKEY_WALLET_RPID = 'LACONIC_HOSTED_CONFIG_passkey_wallet_rpid' VITE_PASSKEY_WALLET_RPID = 'LACONIC_HOSTED_CONFIG_passkey_wallet_rpid'

View File

@ -27,6 +27,7 @@
"nanoid": "3", "nanoid": "3",
"nanoid-dictionary": "^5.0.0-beta.1", "nanoid-dictionary": "^5.0.0-beta.1",
"octokit": "^3.1.2", "octokit": "^3.1.2",
"openpgp": "^6.0.1",
"reflect-metadata": "^0.2.1", "reflect-metadata": "^0.2.1",
"semver": "^7.6.0", "semver": "^7.6.0",
"toml": "^3.0.0", "toml": "^3.0.0",

View File

@ -17,13 +17,14 @@ import { DatabaseConfig } from './config';
import { User } from './entity/User'; import { User } from './entity/User';
import { Organization } from './entity/Organization'; import { Organization } from './entity/Organization';
import { Project } from './entity/Project'; import { Project } from './entity/Project';
import { Deployment } from './entity/Deployment'; import { Deployment, DeploymentStatus } from './entity/Deployment';
import { ProjectMember } from './entity/ProjectMember'; import { ProjectMember } from './entity/ProjectMember';
import { EnvironmentVariable } from './entity/EnvironmentVariable'; import { EnvironmentVariable } from './entity/EnvironmentVariable';
import { Domain } from './entity/Domain'; import { Domain } from './entity/Domain';
import { getEntities, loadAndSaveData } from './utils'; import { getEntities, loadAndSaveData } from './utils';
import { UserOrganization } from './entity/UserOrganization'; import { UserOrganization } from './entity/UserOrganization';
import { Deployer } from './entity/Deployer'; import { Deployer } from './entity/Deployer';
import { DNSRecordAttributes } from './types';
const ORGANIZATION_DATA_PATH = '../test/fixtures/organizations.json'; const ORGANIZATION_DATA_PATH = '../test/fixtures/organizations.json';
@ -157,10 +158,9 @@ export class Database {
.leftJoinAndSelect( .leftJoinAndSelect(
'project.deployments', 'project.deployments',
'deployments', 'deployments',
'deployments.isCurrent = true' 'deployments.isCurrent = true AND deployments.isCanonical = true'
) )
.leftJoinAndSelect('deployments.createdBy', 'user') .leftJoinAndSelect('deployments.createdBy', 'user')
.leftJoinAndSelect('deployments.domain', 'domain')
.leftJoinAndSelect('deployments.deployer', 'deployer') .leftJoinAndSelect('deployments.deployer', 'deployer')
.leftJoinAndSelect('project.owner', 'owner') .leftJoinAndSelect('project.owner', 'owner')
.leftJoinAndSelect('project.deployers', 'deployers') .leftJoinAndSelect('project.deployers', 'deployers')
@ -202,9 +202,8 @@ export class Database {
.leftJoinAndSelect( .leftJoinAndSelect(
'project.deployments', 'project.deployments',
'deployments', 'deployments',
'deployments.isCurrent = true' 'deployments.isCurrent = true AND deployments.isCanonical = true'
) )
.leftJoinAndSelect('deployments.domain', 'domain')
.leftJoin('project.projectMembers', 'projectMembers') .leftJoin('project.projectMembers', 'projectMembers')
.leftJoin('project.organization', 'organization') .leftJoin('project.organization', 'organization')
.where( .where(
@ -235,7 +234,6 @@ export class Database {
return this.getDeployments({ return this.getDeployments({
relations: { relations: {
project: true, project: true,
domain: true,
createdBy: true, createdBy: true,
deployer: true, deployer: true,
}, },
@ -250,6 +248,25 @@ export class Database {
}); });
} }
async getNonCanonicalDeploymentsByProjectId(projectId: string): Promise<Deployment[]> {
return this.getDeployments({
relations: {
project: true,
createdBy: true,
deployer: true,
},
where: {
project: {
id: projectId
},
isCanonical: false
},
order: {
createdAt: 'DESC'
}
});
}
async getDeployment( async getDeployment(
options: FindOneOptions<Deployment> options: FindOneOptions<Deployment>
): Promise<Deployment | null> { ): Promise<Deployment | null> {
@ -602,6 +619,49 @@ export class Database {
return domains; return domains;
} }
async getOldestDomainByProjectId(
projectId: string,
): Promise<Domain | null> {
const domainRepository = this.dataSource.getRepository(Domain);
const domain = await domainRepository.findOne({
where: {
project: {
id: projectId
},
},
order: {
createdAt: 'ASC'
}
});
return domain;
}
async getLatestDNSRecordByProjectId(
projectId: string,
): Promise<DNSRecordAttributes | null> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployment = await deploymentRepository.findOne({
where: {
project: {
id: projectId,
},
status: DeploymentStatus.Ready,
},
order: {
createdAt: 'DESC'
}
});
if (deployment === null) {
throw new Error(`No deployment found for project ${projectId}`);
}
return deployment.dnsRecordData;
}
async addDeployer(data: DeepPartial<Deployer>): Promise<Deployer> { async addDeployer(data: DeepPartial<Deployer>): Promise<Deployer> {
const deployerRepository = this.dataSource.getRepository(Deployer); const deployerRepository = this.dataSource.getRepository(Deployer);
const newDomain = await deployerRepository.save(data); const newDomain = await deployerRepository.save(data);

View File

@ -15,6 +15,9 @@ export class Deployer {
@Column('varchar') @Column('varchar')
baseDomain!: string; baseDomain!: string;
@Column('varchar', { nullable: true})
publicKey!: string | null;
@Column('varchar', { nullable: true }) @Column('varchar', { nullable: true })
minimumPayment!: string | null; minimumPayment!: string | null;

View File

@ -14,7 +14,7 @@ import { Project } from './Project';
import { Domain } from './Domain'; import { Domain } from './Domain';
import { User } from './User'; import { User } from './User';
import { Deployer } from './Deployer'; import { Deployer } from './Deployer';
import { AppDeploymentRecordAttributes, AppDeploymentRemovalRecordAttributes } from '../types'; import { AppDeploymentRecordAttributes, AppDeploymentRemovalRecordAttributes, DNSRecordAttributes } from '../types';
export enum Environment { export enum Environment {
Production = 'Production', Production = 'Production',
@ -39,6 +39,7 @@ export interface ApplicationDeploymentRequest {
config: string; config: string;
meta: string; meta: string;
payment?: string; payment?: string;
dns?: string;
} }
export interface ApplicationDeploymentRemovalRequest { export interface ApplicationDeploymentRemovalRequest {
@ -77,13 +78,6 @@ export class Deployment {
@JoinColumn({ name: 'projectId' }) @JoinColumn({ name: 'projectId' })
project!: Project; project!: Project;
@Column({ nullable: true })
domainId!: string | null;
@OneToOne(() => Domain)
@JoinColumn({ name: 'domainId' })
domain!: Domain | null;
@Column('varchar') @Column('varchar')
branch!: string; branch!: string;
@ -126,6 +120,9 @@ export class Deployment {
@Column('simple-json', { nullable: true }) @Column('simple-json', { nullable: true })
applicationDeploymentRemovalRecordData!: AppDeploymentRemovalRecordAttributes | null; applicationDeploymentRemovalRecordData!: AppDeploymentRemovalRecordAttributes | null;
@Column('simple-json', { nullable: true })
dnsRecordData!: DNSRecordAttributes | null;
@ManyToOne(() => Deployer) @ManyToOne(() => Deployer)
@JoinColumn({ name: 'deployerLrn' }) @JoinColumn({ name: 'deployerLrn' })
deployer!: Deployer; deployer!: Deployer;
@ -138,6 +135,9 @@ export class Deployment {
@Column('boolean', { default: false }) @Column('boolean', { default: false })
isCurrent!: boolean; isCurrent!: boolean;
@Column('boolean', { default: false })
isCanonical!: boolean;
@Column({ @Column({
enum: DeploymentStatus enum: DeploymentStatus
}) })

View File

@ -4,6 +4,7 @@ import { DateTime } from 'luxon';
import { Octokit } from 'octokit'; import { Octokit } from 'octokit';
import { inc as semverInc } from 'semver'; import { inc as semverInc } from 'semver';
import { DeepPartial } from 'typeorm'; 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 { DeliverTxResponse, IndexedTx } from '@cosmjs/stargate';
@ -15,7 +16,7 @@ import {
ApplicationDeploymentRequest, ApplicationDeploymentRequest,
ApplicationDeploymentRemovalRequest ApplicationDeploymentRemovalRequest
} from './entity/Deployment'; } from './entity/Deployment';
import { AppDeploymentRecord, AppDeploymentRemovalRecord, AuctionParams, DeployerRecord } from './types'; import { AppDeploymentRecord, AppDeploymentRemovalRecord, AuctionParams, DeployerRecord, RegistryRecord } from './types';
import { getConfig, getRepoDetails, registryTransactionWithRetry, sleep } from './utils'; import { getConfig, getRepoDetails, registryTransactionWithRetry, sleep } from './utils';
const log = debug('snowball:registry'); const log = debug('snowball:registry');
@ -26,7 +27,7 @@ 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_RECORD_TYPE = 'ApplicationDeploymentRecord';
const APP_DEPLOYMENT_REMOVAL_RECORD_TYPE = 'ApplicationDeploymentRemovalRecord'; const APP_DEPLOYMENT_REMOVAL_RECORD_TYPE = 'ApplicationDeploymentRemovalRecord';
const WEBAPP_DEPLOYER_RECORD_TYPE = 'WebappDeployer' const WEBAPP_DEPLOYER_RECORD_TYPE = 'WebappDeployer';
const SLEEP_DURATION = 1000; const SLEEP_DURATION = 1000;
// TODO: Move registry code to registry-sdk/watcher-ts // TODO: Move registry code to registry-sdk/watcher-ts
@ -107,19 +108,7 @@ export class Registry {
...(packageJSON.version && { app_version: packageJSON.version }) ...(packageJSON.version && { app_version: packageJSON.version })
}; };
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees); const result = await this.publishRecord(applicationRecord);
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(`Published application record ${result.id}`);
log('Application record data:', applicationRecord); log('Application record data:', applicationRecord);
@ -128,6 +117,8 @@ export class Registry {
const lrn = this.getLrn(repo); const lrn = this.getLrn(repo);
log(`Setting name: ${lrn} for record ID: ${result.id}`); log(`Setting name: ${lrn} for record ID: ${result.id}`);
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
await sleep(SLEEP_DURATION); await sleep(SLEEP_DURATION);
await registryTransactionWithRetry(() => await registryTransactionWithRetry(() =>
this.registry.setName( this.registry.setName(
@ -219,17 +210,7 @@ export class Registry {
type: APP_DEPLOYMENT_AUCTION_RECORD_TYPE, type: APP_DEPLOYMENT_AUCTION_RECORD_TYPE,
}; };
const result = await registryTransactionWithRetry(() => const result = await this.publishRecord(applicationDeploymentAuction);
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 created: ${auctionResult.auction.id}`);
log(`Application deployment auction record published: ${result.id}`); log(`Application deployment auction record published: ${result.id}`);
@ -246,8 +227,11 @@ export class Registry {
repository: string, repository: string,
auctionId?: string | null, auctionId?: string | null,
lrn: string, lrn: string,
apiUrl: string,
environmentVariables: { [key: string]: string }, environmentVariables: { [key: string]: string },
dns: string, dns: string,
requesterAddress: string,
publicKey: string,
payment?: string | null payment?: string | null
}): Promise<{ }): Promise<{
applicationDeploymentRequestId: string; applicationDeploymentRequestId: string;
@ -261,6 +245,16 @@ export class Registry {
throw new Error(`No record found for ${lrn}`); 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,
);
}
// Create record of type ApplicationDeploymentRequest and publish // Create record of type ApplicationDeploymentRequest and publish
const applicationDeploymentRequest = { const applicationDeploymentRequest = {
type: APP_DEPLOYMENT_REQUEST_TYPE, type: APP_DEPLOYMENT_REQUEST_TYPE,
@ -270,9 +264,7 @@ export class Registry {
dns: data.dns, dns: data.dns,
// https://git.vdb.to/cerc-io/laconic-registry-cli/commit/129019105dfb93bebcea02fde0ed64d0f8e5983b // https://git.vdb.to/cerc-io/laconic-registry-cli/commit/129019105dfb93bebcea02fde0ed64d0f8e5983b
config: JSON.stringify({ config: JSON.stringify(hash ? { ref: hash } : {}),
env: data.environmentVariables
}),
meta: JSON.stringify({ meta: JSON.stringify({
note: `Added by Snowball @ ${DateTime.utc().toFormat( note: `Added by Snowball @ ${DateTime.utc().toFormat(
"EEE LLL dd HH:mm:ss 'UTC' yyyy" "EEE LLL dd HH:mm:ss 'UTC' yyyy"
@ -287,19 +279,7 @@ export class Registry {
await sleep(SLEEP_DURATION); await sleep(SLEEP_DURATION);
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees); const result = await this.publishRecord(applicationDeploymentRequest);
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 record published: ${result.id}`);
log('Application deployment request data:', applicationDeploymentRequest); log('Application deployment request data:', applicationDeploymentRequest);
@ -371,12 +351,11 @@ export class Registry {
true true
); );
// Filter records with ApplicationDeploymentRequestId ID and Deployment specific URL // Filter records with ApplicationDeploymentRequestId ID
return records.filter((record: AppDeploymentRecord) => return records.filter((record: AppDeploymentRecord) =>
deployments.some( deployments.some(
(deployment) => (deployment) =>
deployment.applicationDeploymentRequestId === record.attributes.request && deployment.applicationDeploymentRequestId === record.attributes.request
record.attributes.url.includes(deployment.id)
) )
); );
} }
@ -431,6 +410,14 @@ export class Registry {
); );
} }
/**
* Fetch record by Id
*/
async getRecordById(id: string): Promise<RegistryRecord | null> {
const [record] = await this.registry.getRecordsByIds([id]);
return record ?? null;
}
async createApplicationDeploymentRemovalRequest(data: { async createApplicationDeploymentRemovalRequest(data: {
deploymentId: string; deploymentId: string;
deployerLrn: string; deployerLrn: string;
@ -449,18 +436,8 @@ export class Registry {
...(data.payment && { payment: data.payment }), ...(data.payment && { payment: data.payment }),
}; };
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees); const result = await this.publishRecord(
applicationDeploymentRemovalRequest,
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 record published: ${result.id}`);
@ -486,6 +463,27 @@ export class Registry {
return completedAuctions; 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> { async getRecordsByName(name: string): Promise<any> {
return this.registry.resolveNames([name]); return this.registry.resolveNames([name]);
} }
@ -532,4 +530,43 @@ export class Registry {
assert(this.registryConfig.authority, "Authority doesn't exist"); assert(this.registryConfig.authority, "Authority doesn't exist");
return `lrn://${this.registryConfig.authority}/applications/${appName}`; return `lrn://${this.registryConfig.authority}/applications/${appName}`;
} }
async generateConfigHash(
environmentVariables: { [key: string]: string },
requesterAddress: string,
pubKey: string,
url: string,
): Promise<string> {
// Config to be encrypted
const config = {
authorized: [requesterAddress],
config: { env: environmentVariables },
};
// Serialize the config
const serialized = JSON.stringify(config, null, 2);
const armoredKey = `-----BEGIN PGP PUBLIC KEY BLOCK-----\n\n${pubKey}\n\n-----END PGP PUBLIC KEY BLOCK-----`;
const publicKey = await openpgp.readKey({ armoredKey });
// Encrypt the config
const encrypted = await openpgp.encrypt({
message: await openpgp.createMessage({ text: serialized }),
encryptionKeys: publicKey,
format: 'binary',
});
// Get the hash after uploading encrypted config
const response = await fetch(`${url}/upload/config`, {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
},
body: encrypted,
});
const configHash = await response.json();
return configHash.id;
}
} }

View File

@ -38,7 +38,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
}, },
deployments: async (_: any, { projectId }: { projectId: string }) => { deployments: async (_: any, { projectId }: { projectId: string }) => {
return service.getDeploymentsByProjectId(projectId); return service.getNonCanonicalDeploymentsByProjectId(projectId);
}, },
environmentVariables: async ( environmentVariables: async (
@ -95,6 +95,13 @@ export const createResolvers = async (service: Service): Promise<any> => {
) => { ) => {
return service.verifyTx(txHash, amount, senderAddress); return service.verifyTx(txHash, amount, senderAddress);
}, },
latestDNSRecord: async (
_: any,
{ projectId }: { projectId: string },
) => {
return service.getLatestDNSRecordByProjectId(projectId);
},
}, },
// TODO: Return error in GQL response // TODO: Return error in GQL response

View File

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

View File

@ -100,7 +100,6 @@ type ProjectMember {
type Deployment { type Deployment {
id: String! id: String!
domain: Domain
branch: String! branch: String!
commitHash: String! commitHash: String!
commitMessage: String! commitMessage: String!
@ -108,6 +107,7 @@ type Deployment {
environment: Environment! environment: Environment!
deployer: Deployer deployer: Deployer
applicationDeploymentRequestId: String applicationDeploymentRequestId: String
applicationDeploymentRecordData: AppDeploymentRecordAttributes
isCurrent: Boolean! isCurrent: Boolean!
baseDomain: String baseDomain: String
status: DeploymentStatus! status: DeploymentStatus!
@ -249,6 +249,27 @@ type Auction {
bids: [Bid!]! bids: [Bid!]!
} }
type DNSRecordAttributes {
name: String
value: String
request: String
resourceType: String
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 { input AuctionParams {
maxPrice: String, maxPrice: String,
numProviders: Int, numProviders: Int,
@ -265,6 +286,7 @@ type Query {
projectMembers(projectId: String!): [ProjectMember!] projectMembers(projectId: String!): [ProjectMember!]
searchProjects(searchText: String!): [Project!] searchProjects(searchText: String!): [Project!]
getAuctionData(auctionId: String!): Auction! getAuctionData(auctionId: String!): Auction!
latestDNSRecord(projectId: String!): DNSRecordAttributes
domains(projectId: String!, filter: FilterDomainsInput): [Domain] domains(projectId: String!, filter: FilterDomainsInput): [Domain]
deployers: [Deployer] deployers: [Deployer]
address: String! address: String!

View File

@ -1,7 +1,8 @@
import assert from 'assert'; import assert from 'assert';
import debug from 'debug'; import debug from 'debug';
import { DeepPartial, FindOptionsWhere, IsNull, Not } from 'typeorm'; import { DeepPartial, FindOptionsWhere } from 'typeorm';
import { Octokit, RequestError } from 'octokit'; import { Octokit, RequestError } from 'octokit';
import { DateTime } from 'luxon';
import { OAuthApp } from '@octokit/oauth-app'; import { OAuthApp } from '@octokit/oauth-app';
@ -22,6 +23,8 @@ import {
AppDeploymentRemovalRecord, AppDeploymentRemovalRecord,
AuctionParams, AuctionParams,
DeployerRecord, DeployerRecord,
DNSRecord,
DNSRecordAttributes,
EnvironmentVariables, EnvironmentVariables,
GitPushEventPayload, GitPushEventPayload,
} from './types'; } from './types';
@ -199,52 +202,106 @@ export class Service {
if (!deployment.project) { if (!deployment.project) {
log(`Project ${deployment.projectId} not found`); log(`Project ${deployment.projectId} not found`);
return; return;
} else {
deployment.applicationDeploymentRecordId = record.id;
deployment.applicationDeploymentRecordData = record.attributes;
deployment.url = record.attributes.url;
deployment.status = DeploymentStatus.Ready;
deployment.isCurrent = deployment.environment === Environment.Production;
await this.db.updateDeploymentById(deployment.id, deployment);
// Release deployer funds on successful deployment
if (!deployment.project.fundsReleased) {
const fundsReleased = await this.releaseDeployerFundsByProjectId(deployment.projectId);
// Return remaining amount to owner
await this.returnUserFundsByProjectId(deployment.projectId, true);
await this.db.updateProjectById(deployment.projectId, {
fundsReleased,
});
}
log(
`Updated deployment ${deployment.id} with URL ${record.attributes.url}`,
);
} }
const registryRecord = await this.laconicRegistry.getRecordById(record.attributes.dns);
if (!registryRecord) {
log(`DNS record not found for deployment ${deployment.id}`);
return;
}
const dnsRecord = registryRecord as DNSRecord;
const dnsRecordData: DNSRecordAttributes = {
name: dnsRecord.attributes.name,
request: dnsRecord.attributes.request,
resourceType: dnsRecord.attributes.resource_type,
value: dnsRecord.attributes.value,
version: dnsRecord.attributes.version,
}
deployment.applicationDeploymentRecordId = record.id;
deployment.applicationDeploymentRecordData = record.attributes;
deployment.url = record.attributes.url;
deployment.status = DeploymentStatus.Ready;
deployment.isCurrent = deployment.environment === Environment.Production;
deployment.dnsRecordData = dnsRecordData;
if (deployment.isCanonical) {
const previousCanonicalDeployment = await this.db.getDeployment({
where: {
projectId: deployment.project.id,
deployer: deployment.deployer,
isCanonical: true,
isCurrent: true,
},
relations: {
project: true,
deployer: true,
}
});
if (previousCanonicalDeployment) {
// Send removal request for the previous canonical deployment and delete DB entry
if (previousCanonicalDeployment.url !== deployment.url) {
await this.laconicRegistry.createApplicationDeploymentRemovalRequest({
deploymentId: previousCanonicalDeployment.applicationDeploymentRecordId!,
deployerLrn: previousCanonicalDeployment.deployer.deployerLrn,
auctionId: previousCanonicalDeployment.project.auctionId,
payment: previousCanonicalDeployment.project.txHash
});
}
await this.db.deleteDeploymentById(previousCanonicalDeployment.id);
}
}
await this.db.updateDeploymentById(deployment.id, deployment);
// Release deployer funds on successful deployment
if (!deployment.project.fundsReleased) {
const fundsReleased = await this.releaseDeployerFundsByProjectId(deployment.projectId);
// Return remaining amount to owner
await this.returnUserFundsByProjectId(deployment.projectId, true);
await this.db.updateProjectById(deployment.projectId, {
fundsReleased,
});
}
log(
`Updated deployment ${deployment.id} with URL ${record.attributes.url}`,
);
}); });
await Promise.all(deploymentUpdatePromises); await Promise.all(deploymentUpdatePromises);
// Get deployments that are in production environment // Get deployments that are in production environment
const prodDeployments = Object.values(recordToDeploymentsMap).filter(deployment => deployment.isCurrent); const prodDeployments = Object.values(recordToDeploymentsMap).filter(
(deployment) => deployment.isCurrent,
);
// Set the isCurrent state to false for the old deployments // Set the isCurrent state to false for the old deployments
for (const deployment of prodDeployments) { for (const deployment of prodDeployments) {
const projectDeployments = await this.db.getDeploymentsByProjectId(deployment.projectId); const projectDeployments = await this.db.getDeploymentsByProjectId(
const oldDeployments = projectDeployments deployment.projectId,
.filter(projectDeployment => projectDeployment.deployer.deployerLrn === deployment.deployer.deployerLrn && projectDeployment.id !== deployment.id); );
const oldDeployments = projectDeployments.filter(
(projectDeployment) =>
projectDeployment.deployer.deployerLrn ===
deployment.deployer.deployerLrn &&
projectDeployment.id !== deployment.id &&
projectDeployment.isCanonical == deployment.isCanonical,
);
for (const oldDeployment of oldDeployments) { for (const oldDeployment of oldDeployments) {
await this.db.updateDeployment( await this.db.updateDeployment(
{ id: oldDeployment.id }, { id: oldDeployment.id },
{ isCurrent: false } { isCurrent: false },
); );
} }
} }
await Promise.all(deploymentUpdatePromises);
} }
/** /**
@ -428,9 +485,14 @@ export class Service {
return dbProjects; return dbProjects;
} }
async getDeploymentsByProjectId(projectId: string): Promise<Deployment[]> { async getNonCanonicalDeploymentsByProjectId(projectId: string): Promise<Deployment[]> {
const dbDeployments = await this.db.getDeploymentsByProjectId(projectId); const nonCanonicalDeployments = await this.db.getNonCanonicalDeploymentsByProjectId(projectId);
return dbDeployments; return nonCanonicalDeployments;
}
async getLatestDNSRecordByProjectId(projectId: string): Promise<DNSRecordAttributes | null> {
const dnsRecord = await this.db.getLatestDNSRecordByProjectId(projectId);
return dnsRecord;
} }
async getEnvironmentVariablesByProjectId( async getEnvironmentVariablesByProjectId(
@ -572,6 +634,7 @@ export class Service {
where: { id: deploymentId }, where: { id: deploymentId },
relations: { relations: {
project: true, project: true,
deployer: true,
}, },
}); });
@ -579,18 +642,12 @@ export class Service {
throw new Error('Deployment does not exist'); throw new Error('Deployment does not exist');
} }
const prodBranchDomains = await this.db.getDomainsByProjectId(
oldDeployment.project.id,
{ branch: oldDeployment.project.prodBranch },
);
const octokit = await this.getOctokit(user.id); const octokit = await this.getOctokit(user.id);
const newDeployment = await this.createDeployment(user.id, octokit, { const newDeployment = await this.createDeployment(user.id, octokit, {
project: oldDeployment.project, project: oldDeployment.project,
branch: oldDeployment.branch, branch: oldDeployment.branch,
environment: Environment.Production, environment: Environment.Production,
domain: prodBranchDomains[0],
commitHash: oldDeployment.commitHash, commitHash: oldDeployment.commitHash,
commitMessage: oldDeployment.commitMessage, commitMessage: oldDeployment.commitMessage,
deployer: oldDeployment.deployer deployer: oldDeployment.deployer
@ -619,19 +676,6 @@ export class Service {
commitHash: data.commitHash!, commitHash: data.commitHash!,
}); });
// Update previous deployment with prod branch domain
// TODO: Fix unique constraint error for domain
if (data.domain) {
await this.db.updateDeployment(
{
domainId: data.domain.id,
},
{
domain: null,
},
);
}
let deployer; let deployer;
if (deployerLrn) { if (deployerLrn) {
deployer = await this.db.getDeployerByLRN(deployerLrn); deployer = await this.db.getDeployerByLRN(deployerLrn);
@ -639,44 +683,62 @@ export class Service {
deployer = data.deployer; deployer = data.deployer;
} }
const newDeployment = await this.createDeploymentFromData(userId, data, deployer!.deployerLrn!, applicationRecordId, applicationRecordData); const deployment = await this.createDeploymentFromData(userId, data, deployer!.deployerLrn!, applicationRecordId, applicationRecordData, false);
const address = await this.getAddress();
const { repo, repoUrl } = await getRepoDetails(octokit, data.project.repository, data.commitHash); const { repo, repoUrl } = await getRepoDetails(octokit, data.project.repository, data.commitHash);
const environmentVariablesObj = await this.getEnvVariables(data.project!.id!); const environmentVariablesObj = await this.getEnvVariables(data.project!.id!);
// To set project DNS // To set project DNS
if (data.environment === Environment.Production) { if (data.environment === Environment.Production) {
// On deleting deployment later, project DNS deployment is also deleted const canonicalDeployment = await this.createDeploymentFromData(userId, data, deployer!.deployerLrn!, applicationRecordId, applicationRecordData, true);
// So publish project DNS deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later // If a custom domain is present then use that as the DNS in the deployment request
await this.laconicRegistry.createApplicationDeploymentRequest({ const customDomain = await this.db.getOldestDomainByProjectId(data.project!.id!);
deployment: newDeployment,
appName: repo, // On deleting deployment later, project canonical deployment is also deleted
repository: repoUrl, // So publish project canonical deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later
environmentVariables: environmentVariablesObj, const { applicationDeploymentRequestData, applicationDeploymentRequestId } =
dns: `${newDeployment.project.name}`, await this.laconicRegistry.createApplicationDeploymentRequest({
lrn: deployer!.deployerLrn!, deployment: canonicalDeployment,
payment: data.project.txHash, appName: repo,
auctionId: data.project.auctionId repository: repoUrl,
environmentVariables: environmentVariablesObj,
dns: customDomain?.name ?? `${canonicalDeployment.project.name}`,
lrn: deployer!.deployerLrn!,
apiUrl: deployer!.deployerApiUrl!,
payment: data.project.txHash,
auctionId: data.project.auctionId,
requesterAddress: address,
publicKey: deployer!.publicKey!
});
await this.db.updateDeploymentById(canonicalDeployment.id, {
applicationDeploymentRequestId,
applicationDeploymentRequestData,
}); });
} }
const { applicationDeploymentRequestId, applicationDeploymentRequestData } = const { applicationDeploymentRequestId, applicationDeploymentRequestData } =
await this.laconicRegistry.createApplicationDeploymentRequest({ await this.laconicRegistry.createApplicationDeploymentRequest({
deployment: newDeployment, deployment: deployment,
appName: repo, appName: repo,
repository: repoUrl, repository: repoUrl,
lrn: deployer!.deployerLrn!, lrn: deployer!.deployerLrn!,
apiUrl: deployer!.deployerApiUrl!,
environmentVariables: environmentVariablesObj, environmentVariables: environmentVariablesObj,
dns: `${newDeployment.project.name}-${newDeployment.id}`, dns: `${deployment.project.name}-${deployment.id}`,
payment: data.project.txHash, payment: data.project.txHash,
auctionId: data.project.auctionId auctionId: data.project.auctionId,
requesterAddress: address,
publicKey: deployer!.publicKey!
}); });
await this.db.updateDeploymentById(newDeployment.id, { await this.db.updateDeploymentById(deployment.id, {
applicationDeploymentRequestId, applicationDeploymentRequestId,
applicationDeploymentRequestData, applicationDeploymentRequestData,
}); });
return newDeployment; return deployment;
} }
async createDeploymentFromAuction( async createDeploymentFromAuction(
@ -719,42 +781,59 @@ export class Service {
commitMessage: latestCommit.commit.message, commitMessage: latestCommit.commit.message,
}; };
const newDeployment = await this.createDeploymentFromData(project.ownerId!, deploymentData, deployerLrn, applicationRecordId, applicationRecordData); const deployment = await this.createDeploymentFromData(project.ownerId!, deploymentData, deployerLrn, applicationRecordId, applicationRecordData, false);
const address = await this.getAddress();
const environmentVariablesObj = await this.getEnvVariables(project!.id!); const environmentVariablesObj = await this.getEnvVariables(project!.id!);
// To set project DNS // To set project DNS
if (deploymentData.environment === Environment.Production) { if (deploymentData.environment === Environment.Production) {
// On deleting deployment later, project DNS deployment is also deleted const canonicalDeployment = await this.createDeploymentFromData(project.ownerId!, deploymentData, deployerLrn, applicationRecordId, applicationRecordData, true);
// So publish project DNS deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later // If a custom domain is present then use that as the DNS in the deployment request
await this.laconicRegistry.createApplicationDeploymentRequest({ const customDomain = await this.db.getOldestDomainByProjectId(project!.id!);
deployment: newDeployment,
appName: repo, // On deleting deployment later, project canonical deployment is also deleted
repository: repoUrl, // So publish project canonical deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later
environmentVariables: environmentVariablesObj, const { applicationDeploymentRequestId, applicationDeploymentRequestData } =
dns: `${newDeployment.project.name}`, await this.laconicRegistry.createApplicationDeploymentRequest({
auctionId: project.auctionId!, deployment: canonicalDeployment,
lrn: deployerLrn, appName: repo,
repository: repoUrl,
environmentVariables: environmentVariablesObj,
dns: customDomain?.name ?? `${canonicalDeployment.project.name}`,
auctionId: project.auctionId!,
lrn: deployerLrn,
apiUrl: deployer!.deployerApiUrl!,
requesterAddress: address,
publicKey: deployer!.publicKey!
});
await this.db.updateDeploymentById(canonicalDeployment.id, {
applicationDeploymentRequestId,
applicationDeploymentRequestData,
}); });
} }
const { applicationDeploymentRequestId, applicationDeploymentRequestData } = const { applicationDeploymentRequestId, applicationDeploymentRequestData } =
// Create requests for all the deployers // Create requests for all the deployers
await this.laconicRegistry.createApplicationDeploymentRequest({ await this.laconicRegistry.createApplicationDeploymentRequest({
deployment: newDeployment, deployment: deployment,
appName: repo, appName: repo,
repository: repoUrl, repository: repoUrl,
auctionId: project.auctionId!, auctionId: project.auctionId!,
lrn: deployerLrn, lrn: deployerLrn,
apiUrl: deployer!.deployerApiUrl!,
environmentVariables: environmentVariablesObj, environmentVariables: environmentVariablesObj,
dns: `${newDeployment.project.name}-${newDeployment.id}`, dns: `${deployment.project.name}-${deployment.id}`,
requesterAddress: address,
publicKey: deployer!.publicKey!
}); });
await this.db.updateDeploymentById(newDeployment.id, { await this.db.updateDeploymentById(deployment.id, {
applicationDeploymentRequestId, applicationDeploymentRequestId,
applicationDeploymentRequestData, applicationDeploymentRequestData,
}); });
return newDeployment; return deployment;
} }
async createDeploymentFromData( async createDeploymentFromData(
@ -763,6 +842,7 @@ export class Service {
deployerLrn: string, deployerLrn: string,
applicationRecordId: string, applicationRecordId: string,
applicationRecordData: ApplicationRecord, applicationRecordData: ApplicationRecord,
isCanonical: boolean,
): Promise<Deployment> { ): Promise<Deployment> {
const newDeployment = await this.db.addDeployment({ const newDeployment = await this.db.addDeployment({
project: data.project, project: data.project,
@ -773,13 +853,13 @@ export class Service {
status: DeploymentStatus.Building, status: DeploymentStatus.Building,
applicationRecordId, applicationRecordId,
applicationRecordData, applicationRecordData,
domain: data.domain,
createdBy: Object.assign(new User(), { createdBy: Object.assign(new User(), {
id: userId, id: userId,
}), }),
deployer: Object.assign(new Deployer(), { deployer: Object.assign(new Deployer(), {
deployerLrn, deployerLrn,
}), }),
isCanonical
}); });
log(`Created deployment ${newDeployment.id}`); log(`Created deployment ${newDeployment.id}`);
@ -1012,9 +1092,6 @@ export class Service {
for await (const project of projects) { for await (const project of projects) {
const octokit = await this.getOctokit(project.ownerId); const octokit = await this.getOctokit(project.ownerId);
const [domain] = await this.db.getDomainsByProjectId(project.id, {
branch,
});
const deployers = project.deployers; const deployers = project.deployers;
if (!deployers) { if (!deployers) {
@ -1032,7 +1109,6 @@ export class Service {
project.prodBranch === branch project.prodBranch === branch
? Environment.Production ? Environment.Production
: Environment.Preview, : Environment.Preview,
domain,
commitHash: headCommit.id, commitHash: headCommit.id,
commitMessage: headCommit.message, commitMessage: headCommit.message,
deployer: deployer deployer: deployer
@ -1074,7 +1150,6 @@ export class Service {
const oldDeployment = await this.db.getDeployment({ const oldDeployment = await this.db.getDeployment({
relations: { relations: {
project: true, project: true,
domain: true,
deployer: true, deployer: true,
createdBy: true, createdBy: true,
}, },
@ -1100,7 +1175,6 @@ export class Service {
// TODO: Put isCurrent field in project // TODO: Put isCurrent field in project
branch: oldDeployment.branch, branch: oldDeployment.branch,
environment: Environment.Production, environment: Environment.Production,
domain: oldDeployment.domain,
commitHash: oldDeployment.commitHash, commitHash: oldDeployment.commitHash,
commitMessage: oldDeployment.commitMessage, commitMessage: oldDeployment.commitMessage,
deployer: oldDeployment.deployer deployer: oldDeployment.deployer
@ -1118,31 +1192,79 @@ export class Service {
// TODO: Implement transactions // TODO: Implement transactions
const oldCurrentDeployment = await this.db.getDeployment({ const oldCurrentDeployment = await this.db.getDeployment({
relations: { relations: {
domain: true, project: true,
deployer: true,
}, },
where: { where: {
project: { project: {
id: projectId, id: projectId,
}, },
isCurrent: true, isCurrent: true,
isCanonical: false,
}, },
}); });
if (!oldCurrentDeployment) { if (!oldCurrentDeployment) {
throw new Error('Current deployment doesnot exist'); throw new Error('Current deployment does not exist');
} }
const oldCurrentDeploymentUpdate = await this.db.updateDeploymentById( const oldCurrentDeploymentUpdate = await this.db.updateDeploymentById(
oldCurrentDeployment.id, oldCurrentDeployment.id,
{ isCurrent: false, domain: null }, { isCurrent: false },
); );
const newCurrentDeploymentUpdate = await this.db.updateDeploymentById( const newCurrentDeploymentUpdate = await this.db.updateDeploymentById(
deploymentId, deploymentId,
{ isCurrent: true, domain: oldCurrentDeployment?.domain }, { isCurrent: true },
); );
return newCurrentDeploymentUpdate && oldCurrentDeploymentUpdate; if (!newCurrentDeploymentUpdate || !oldCurrentDeploymentUpdate){
return false;
}
const newCurrentDeployment = await this.db.getDeployment({ where: { id: deploymentId }, relations: { project: true, deployer: true } });
if (!newCurrentDeployment) {
throw new Error(`Deployment with Id ${deploymentId} not found`);
}
const applicationDeploymentRequestData = newCurrentDeployment.applicationDeploymentRequestData;
const customDomain = await this.db.getOldestDomainByProjectId(projectId);
if (customDomain && applicationDeploymentRequestData) {
applicationDeploymentRequestData.dns = customDomain.name
}
// Create a canonical deployment for the new current deployment
const canonicalDeployment = await this.createDeploymentFromData(
newCurrentDeployment.project.ownerId,
newCurrentDeployment,
newCurrentDeployment.deployer!.deployerLrn!,
newCurrentDeployment.applicationRecordId,
newCurrentDeployment.applicationRecordData,
true,
);
applicationDeploymentRequestData!.meta = JSON.stringify({
...JSON.parse(applicationDeploymentRequestData!.meta),
note: `Updated by Snowball @ ${DateTime.utc().toFormat(
"EEE LLL dd HH:mm:ss 'UTC' yyyy"
)}`
});
const result = await this.laconicRegistry.publishRecord(
applicationDeploymentRequestData,
);
log(`Application deployment request record published: ${result.id}`)
const updateResult = await this.db.updateDeploymentById(canonicalDeployment.id, {
applicationDeploymentRequestId: result.id,
applicationDeploymentRequestData,
});
return updateResult;
} }
async deleteDeployment(deploymentId: string): Promise<boolean> { async deleteDeployment(deploymentId: string): Promise<boolean> {
@ -1159,33 +1281,65 @@ export class Service {
if (deployment && deployment.applicationDeploymentRecordId) { if (deployment && deployment.applicationDeploymentRecordId) {
// If deployment is current, remove deployment for project subdomain as well // If deployment is current, remove deployment for project subdomain as well
if (deployment.isCurrent) { if (deployment.isCurrent) {
const currentDeploymentURL = `https://${(deployment.project.name).toLowerCase()}.${deployment.deployer.baseDomain}`; const canonicalDeployment = await this.db.getDeployment({
where: {
projectId: deployment.project.id,
deployer: deployment.deployer,
isCanonical: true
},
relations: {
project: true,
deployer: true,
},
})
// TODO: Store the latest DNS deployment record // If the canonical deployment is not present then query the chain for the deployment record for backward compatibility
const deploymentRecords = if (!canonicalDeployment) {
await this.laconicRegistry.getDeploymentRecordsByFilter({ log(`Canonical deployment for deployment with id ${deployment.id} not found, querying the chain..`);
application: deployment.applicationRecordId, const currentDeploymentURL = `https://${(deployment.project.name).toLowerCase()}.${deployment.deployer.baseDomain}`;
url: currentDeploymentURL,
const deploymentRecords =
await this.laconicRegistry.getDeploymentRecordsByFilter({
application: deployment.applicationRecordId,
url: currentDeploymentURL,
});
if (!deploymentRecords.length) {
log(
`No ApplicationDeploymentRecord found for URL ${currentDeploymentURL} and ApplicationDeploymentRecord id ${deployment.applicationDeploymentRecordId}`,
);
return false;
}
// Multiple records are fetched, take the latest record
const latestRecord = deploymentRecords
.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())[0];
await this.laconicRegistry.createApplicationDeploymentRemovalRequest({
deploymentId: latestRecord.id,
deployerLrn: deployment.deployer.deployerLrn,
auctionId: deployment.project.auctionId,
payment: deployment.project.txHash
}); });
} else {
// If canonical deployment is found in the DB, then send the removal request with that deployment record Id
const result =
await this.laconicRegistry.createApplicationDeploymentRemovalRequest({
deploymentId: canonicalDeployment.applicationDeploymentRecordId!,
deployerLrn: canonicalDeployment.deployer.deployerLrn,
auctionId: canonicalDeployment.project.auctionId,
payment: canonicalDeployment.project.txHash
});
if (!deploymentRecords.length) { await this.db.updateDeploymentById(canonicalDeployment.id, {
log( status: DeploymentStatus.Deleting,
`No ApplicationDeploymentRecord found for URL ${currentDeploymentURL} and ApplicationDeploymentRecord id ${deployment.applicationDeploymentRecordId}`, applicationDeploymentRemovalRequestId:
); result.applicationDeploymentRemovalRequestId,
applicationDeploymentRemovalRequestData:
return false; result.applicationDeploymentRemovalRequestData,
});
} }
// Multiple records are fetched, take the latest record
const latestRecord = deploymentRecords
.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())[0];
await this.laconicRegistry.createApplicationDeploymentRemovalRequest({
deploymentId: latestRecord.id,
deployerLrn: deployment.deployer.deployerLrn,
auctionId: deployment.project.auctionId,
payment: deployment.project.txHash
});
} }
const result = const result =
@ -1215,7 +1369,7 @@ export class Service {
data: { name: string }, data: { name: string },
): Promise<{ ): Promise<{
primaryDomain: Domain; primaryDomain: Domain;
redirectedDomain: Domain; // redirectedDomain: Domain;
}> { }> {
const currentProject = await this.db.getProjectById(projectId); const currentProject = await this.db.getProjectById(projectId);
@ -1231,22 +1385,22 @@ export class Service {
const savedPrimaryDomain = await this.db.addDomain(primaryDomainDetails); const savedPrimaryDomain = await this.db.addDomain(primaryDomainDetails);
const domainArr = data.name.split('www.'); // const domainArr = data.name.split('www.');
const redirectedDomainDetails = { // const redirectedDomainDetails = {
name: domainArr.length > 1 ? domainArr[1] : `www.${domainArr[0]}`, // name: domainArr.length > 1 ? domainArr[1] : `www.${domainArr[0]}`,
branch: currentProject.prodBranch, // branch: currentProject.prodBranch,
project: currentProject, // project: currentProject,
redirectTo: savedPrimaryDomain, // redirectTo: savedPrimaryDomain,
}; // };
const savedRedirectedDomain = await this.db.addDomain( // const savedRedirectedDomain = await this.db.addDomain(
redirectedDomainDetails, // redirectedDomainDetails,
); // );
return { return {
primaryDomain: savedPrimaryDomain, primaryDomain: savedPrimaryDomain,
redirectedDomain: savedRedirectedDomain, // redirectedDomain: savedRedirectedDomain,
}; };
} }
@ -1434,6 +1588,7 @@ export class Service {
const deployerApiUrl = record.attributes.apiUrl; const deployerApiUrl = record.attributes.apiUrl;
const minimumPayment = record.attributes.minimumPayment; const minimumPayment = record.attributes.minimumPayment;
const paymentAddress = record.attributes.paymentAddress; const paymentAddress = record.attributes.paymentAddress;
const publicKey = record.attributes.publicKey;
const baseDomain = deployerApiUrl.substring(deployerApiUrl.indexOf('.') + 1); const baseDomain = deployerApiUrl.substring(deployerApiUrl.indexOf('.') + 1);
const deployerData = { const deployerData = {
@ -1442,7 +1597,8 @@ export class Service {
deployerApiUrl, deployerApiUrl,
baseDomain, baseDomain,
minimumPayment, minimumPayment,
paymentAddress paymentAddress,
publicKey
}; };
// TODO: Update deployers table in a separate job // TODO: Update deployers table in a separate job

View File

@ -40,6 +40,22 @@ export interface AppDeploymentRecordAttributes {
version: string; version: string;
} }
export interface DNSRecordAttributes {
name: string;
value: string;
request: string;
resourceType: string;
version: string;
}
export interface RegistryDNSRecordAttributes {
name: string;
value: string;
request: string;
resource_type: string;
version: string;
}
export interface AppDeploymentRemovalRecordAttributes { export interface AppDeploymentRemovalRecordAttributes {
deployment: string; deployment: string;
request: string; request: string;
@ -47,7 +63,7 @@ export interface AppDeploymentRemovalRecordAttributes {
version: string; version: string;
} }
interface RegistryRecord { export interface RegistryRecord {
id: string; id: string;
names: string[] | null; names: string[] | null;
owners: string[]; owners: string[];
@ -64,6 +80,10 @@ export interface AppDeploymentRemovalRecord extends RegistryRecord {
attributes: AppDeploymentRemovalRecordAttributes; attributes: AppDeploymentRemovalRecordAttributes;
} }
export interface DNSRecord extends RegistryRecord {
attributes: RegistryDNSRecordAttributes
}
export interface AddProjectFromTemplateInput { export interface AddProjectFromTemplateInput {
templateOwner: string; templateOwner: string;
templateRepo: string; templateRepo: string;

View File

@ -10,7 +10,7 @@ import { Deployment, DeploymentStatus, Environment } from '../src/entity/Deploym
const log = debug('snowball:publish-deploy-records'); const log = debug('snowball:publish-deploy-records');
async function main() { async function main() {
const { registryConfig, database, misc } = await getConfig(); const { registryConfig, database } = await getConfig();
const registry = new Registry( const registry = new Registry(
registryConfig.gqlEndpoint, registryConfig.gqlEndpoint,

1
packages/deployer/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
records/*.yml

View File

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

View File

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

View File

View File

@ -1,18 +0,0 @@
record:
type: ApplicationDeploymentRequest
version: '1.0.0'
name: deploy-frontend@1.0.0
application: lrn://vaasl/applications/deploy-frontend@1.0.0
dns: deploy
config:
env:
LACONIC_HOSTED_CONFIG_server_url: https://deploy-backend.apps.vaasl.io
LACONIC_HOSTED_CONFIG_github_clientid: Ov23liaet4yc0KX0iM1c
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
meta:
note: Added by Snowball @ Thu Apr 4 14:49:41 UTC 2024
repository: "https://git.vdb.to/cerc-io/snowballtools-base"
repository_ref: 351db16336eacc3e1f9119ceb8d1282b8e27a27e

View File

@ -1,8 +0,0 @@
record:
type: ApplicationRecord
version: 0.0.2
repository_ref: 351db16336eacc3e1f9119ceb8d1282b8e27a27e
repository: ["https://git.vdb.to/cerc-io/snowballtools-base"]
app_type: webapp
name: deploy-frontend
app_version: 1.0.0

View File

@ -1,7 +1,6 @@
#!/bin/bash #!/bin/bash
source .env source .env
echo "Using REGISTRY_BOND_ID: $REGISTRY_BOND_ID"
echo "Using DEPLOYER_LRN: $DEPLOYER_LRN" echo "Using DEPLOYER_LRN: $DEPLOYER_LRN"
# Generate application-deployment-removal-request.yml # Generate application-deployment-removal-request.yml

View File

@ -1,25 +0,0 @@
record:
type: ApplicationDeploymentRequest
version: '1.0.0'
name: staging-snowballtools-base-frontend@0.0.0
application: crn://staging-snowballtools/applications/staging-snowballtools-base-frontend@0.0.0
dns: dashboard.staging.apps.snowballtools.com
config:
env:
LACONIC_HOSTED_CONFIG_server_url: https://snowballtools-base-api.staging.apps.snowballtools.com
LACONIC_HOSTED_CONFIG_github_clientid: Ov23liOaoahRTYd4nSCV
LACONIC_HOSTED_CONFIG_github_templaterepo: snowball-tools/test-progressive-web-app
LACONIC_HOSTED_CONFIG_github_pwa_templaterepo: snowball-tools/test-progressive-web-app
LACONIC_HOSTED_CONFIG_github_image_upload_templaterepo: snowball-tools/image-upload-pwa-example
LACONIC_HOSTED_CONFIG_github_next_app_templaterepo: snowball-tools/starter.nextjs-react-tailwind
LACONIC_HOSTED_CONFIG_wallet_connect_id: eda9ba18042a5ea500f358194611ece2
LACONIC_HOSTED_CONFIG_lit_relay_api_key: 15DDD969-E75F-404D-AAD9-58A37C4FD354_snowball
LACONIC_HOSTED_CONFIG_aplchemy_api_key: THvPart_gqI5x02RNYSBntlmwA66I_qc
LACONIC_HOSTED_CONFIG_bugsnag_api_key: 8c480cd5386079f9dd44f9581264a073
LACONIC_HOSTED_CONFIG_passkey_wallet_rpid: dashboard.staging.apps.snowballtools.com
LACONIC_HOSTED_CONFIG_turnkey_api_base_url: https://api.turnkey.com
LACONIC_HOSTED_CONFIG_turnkey_organization_id: 5049ae99-5bca-40b3-8317-504384d4e591
meta:
note: Added by Snowball @ Mon Jun 24 23:51:48 UTC 2024
repository: "https://git.vdb.to/cerc-io/snowballtools-base"
repository_ref: 61e3e88a6c9d57e95441059369ee5a46f5c07601

View File

@ -1,8 +0,0 @@
record:
type: ApplicationRecord
version: 0.0.1
repository_ref: 61e3e88a6c9d57e95441059369ee5a46f5c07601
repository: ["https://git.vdb.to/cerc-io/snowballtools-base"]
app_type: webapp
name: staging-snowballtools-base-frontend
app_version: 0.0.0

View File

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

View File

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

View File

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

View File

@ -47,6 +47,7 @@ export const ChangeStateToProductionDialog = ({
handleCancel={handleCancel} handleCancel={handleCancel}
open={open} open={open}
handleConfirm={handleConfirm} handleConfirm={handleConfirm}
confirmButtonTitle={isConfirmButtonLoading ? 'Redeploying' : 'Redeploy'}
confirmButtonProps={{ confirmButtonProps={{
disabled: isConfirmButtonLoading, disabled: isConfirmButtonLoading,
rightIcon: isConfirmButtonLoading ? ( rightIcon: isConfirmButtonLoading ? (

View File

@ -4,7 +4,11 @@ import {
MenuItem, MenuItem,
MenuList, MenuList,
} from '@snowballtools/material-tailwind-react-fork'; } from '@snowballtools/material-tailwind-react-fork';
import { ComponentPropsWithoutRef, MouseEvent, useCallback } from 'react'; import {
ComponentPropsWithoutRef,
MouseEvent,
useCallback,
} from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Project } from 'gql-client'; import { Project } from 'gql-client';
import { Avatar } from 'components/shared/Avatar'; import { Avatar } from 'components/shared/Avatar';
@ -83,7 +87,7 @@ export const ProjectCard = ({
<p className={theme.title()}>{project.name}</p> <p className={theme.title()}>{project.name}</p>
</Tooltip> </Tooltip>
<p className={theme.description()}> <p className={theme.description()}>
{project.deployments[0]?.domain?.name ?? 'No domain'} {project.deployments[0]?.applicationDeploymentRecordData?.url ?? 'No domain'}
</p> </p>
</div> </div>
{/* Icons */} {/* Icons */}

View File

@ -0,0 +1,96 @@
import { useCallback, useEffect } from 'react';
import { Box, Modal } from '@mui/material';
import {
VITE_LACONICD_CHAIN_ID,
VITE_WALLET_IFRAME_URL,
} from 'utils/constants';
const ApproveTransactionModal = ({
setAccount,
setIsDataReceived,
isVisible,
}: {
setAccount: (account: string) => void;
setIsDataReceived: (isReceived: boolean) => void;
isVisible: boolean;
}) => {
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: ${VITE_LACONICD_CHAIN_ID}`);
return;
}
setAccount(event.data.data[0].address);
}
if (event.data.type === 'ERROR') {
console.error('Error from wallet:', event.data.message);
}
};
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, []);
const getDataFromWallet = useCallback(() => {
const iframe = document.getElementById('walletIframe') as HTMLIFrameElement;
if (!iframe.contentWindow) {
console.error('Iframe not found or not loaded');
return;
}
iframe.contentWindow.postMessage(
{
type: 'REQUEST_WALLET_ACCOUNTS',
chainId: VITE_LACONICD_CHAIN_ID,
},
VITE_WALLET_IFRAME_URL,
);
}, []);
return (
<Modal open={isVisible} disableEscapeKeyDown keepMounted>
<Box
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: '90%',
maxWidth: '1200px',
height: '600px',
maxHeight: '80vh',
overflow: 'auto',
boxShadow: 24,
borderRadius: '8px',
outline: 'none',
bgcolor: 'background.paper',
}}
>
<iframe
onLoad={getDataFromWallet}
id="walletIframe"
src={`${VITE_WALLET_IFRAME_URL}/wallet-embed`}
width="100%"
height="100%"
sandbox="allow-scripts allow-same-origin"
className="border rounded-md shadow-sm"
></iframe>
</Box>
</Modal>
);
};
export default ApproveTransactionModal;

View File

@ -0,0 +1,67 @@
import { useEffect, useState } from 'react';
import { Modal } from '@mui/material';
import { VITE_WALLET_IFRAME_URL } from 'utils/constants';
import useCheckBalance from '../../../hooks/useCheckBalance';
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 [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
if (!isLoaded) {
return;
}
checkBalance();
}, [amount, checkBalance, isLoaded]);
useEffect(() => {
if (!isPollingEnabled || !isLoaded || isBalanceSufficient) {
return;
}
const interval = setInterval(() => {
checkBalance();
}, CHECK_BALANCE_INTERVAL);
return () => {
clearInterval(interval);
};
}, [isBalanceSufficient, isPollingEnabled, checkBalance, isLoaded]);
useEffect(() => {
onBalanceChange(isBalanceSufficient);
}, [isBalanceSufficient]);
return (
<Modal open={false} disableEscapeKeyDown keepMounted>
<iframe
onLoad={() => setIsLoaded(true)}
id={IFRAME_ID}
src={VITE_WALLET_IFRAME_URL}
width="100%"
height="100%"
sandbox="allow-scripts allow-same-origin"
className="border rounded-md shadow-sm"
/>
</Modal>
);
};
export default CheckBalanceIframe;

View File

@ -1,4 +1,4 @@
import { useCallback, useState, useEffect } from 'react'; import { useCallback, useState, useEffect, useMemo } from 'react';
import { useForm, Controller } from 'react-hook-form'; import { useForm, Controller } from 'react-hook-form';
import { FormProvider, FieldValues } from 'react-hook-form'; import { FormProvider, FieldValues } from 'react-hook-form';
import { useNavigate, useSearchParams } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
@ -8,6 +8,7 @@ import {
AuctionParams, AuctionParams,
Deployer, Deployer,
} from 'gql-client'; } from 'gql-client';
import { BigNumber } from 'ethers';
import { Select, MenuItem, FormControl, FormHelperText } from '@mui/material'; import { Select, MenuItem, FormControl, FormHelperText } from '@mui/material';
@ -20,15 +21,19 @@ import { Button } from '../../shared/Button';
import { Input } from 'components/shared/Input'; import { Input } from 'components/shared/Input';
import { useToast } from 'components/shared/Toast'; import { useToast } from 'components/shared/Toast';
import { useGQLClient } from '../../../context/GQLClientContext'; import { useGQLClient } from '../../../context/GQLClientContext';
import ApproveTransactionModal from './ApproveTransactionModal';
import EnvironmentVariablesForm from 'pages/org-slug/projects/id/settings/EnvironmentVariablesForm'; import EnvironmentVariablesForm from 'pages/org-slug/projects/id/settings/EnvironmentVariablesForm';
import { EnvironmentVariablesFormValues } from 'types/types'; import { EnvironmentVariablesFormValues } from 'types/types';
import ConnectWallet from './ConnectWallet'; import {
import { useWalletConnectClient } from 'context/WalletConnectContext'; VITE_LACONICD_CHAIN_ID,
VITE_WALLET_IFRAME_URL,
} from 'utils/constants';
import CheckBalanceIframe from './CheckBalanceIframe';
type ConfigureDeploymentFormValues = { type ConfigureDeploymentFormValues = {
option: string; option: string;
lrn?: string; lrn?: string;
numProviders?: number; numProviders?: string;
maxPrice?: string; maxPrice?: string;
}; };
@ -36,16 +41,19 @@ type ConfigureFormValues = ConfigureDeploymentFormValues &
EnvironmentVariablesFormValues; EnvironmentVariablesFormValues;
const DEFAULT_MAX_PRICE = '10000'; const DEFAULT_MAX_PRICE = '10000';
const TX_APPROVAL_TIMEOUT_MS = 60000;
const Configure = () => { const Configure = () => {
const { signClient, session, accounts } = useWalletConnectClient();
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [deployers, setDeployers] = useState<Deployer[]>([]); const [deployers, setDeployers] = useState<Deployer[]>([]);
const [selectedAccount, setSelectedAccount] = useState<string>(); const [selectedAccount, setSelectedAccount] = useState<string>();
const [selectedDeployer, setSelectedDeployer] = useState<Deployer>(); const [selectedDeployer, setSelectedDeployer] = useState<Deployer>();
const [isPaymentLoading, setIsPaymentLoading] = useState(false); const [isPaymentLoading, setIsPaymentLoading] = useState(false);
const [isPaymentDone, setIsPaymentDone] = useState(false); const [isPaymentDone, setIsPaymentDone] = useState(false);
const [isFrameVisible, setIsFrameVisible] = useState(false);
const [isAccountsDataReceived, setIsAccountsDataReceived] = useState(false);
const [balanceMessage, setBalanceMessage] = useState<string>();
const [isBalanceSufficient, setIsBalanceSufficient] = useState<boolean>();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const templateId = searchParams.get('templateId'); const templateId = searchParams.get('templateId');
@ -69,16 +77,40 @@ const Configure = () => {
option: 'Auction', option: 'Auction',
maxPrice: DEFAULT_MAX_PRICE, maxPrice: DEFAULT_MAX_PRICE,
lrn: '', lrn: '',
numProviders: 1, numProviders: '1',
variables: [], variables: [],
}, },
}); });
const selectedOption = methods.watch('option'); const selectedOption = methods.watch('option');
const selectedNumProviders = methods.watch('numProviders') ?? '1';
const selectedMaxPrice = methods.watch('maxPrice') ?? DEFAULT_MAX_PRICE;
const isTabletView = useMediaQuery('(min-width: 720px)'); // md: const isTabletView = useMediaQuery('(min-width: 720px)'); // md:
const buttonSize = isTabletView ? { size: 'lg' as const } : {}; const buttonSize = isTabletView ? { size: 'lg' as const } : {};
const amountToBePaid = useMemo(() => {
let amount: string;
if (selectedOption === 'LRN') {
amount = selectedDeployer?.minimumPayment?.replace(/\D/g, '') ?? '0';
} else {
if (!selectedNumProviders || !selectedMaxPrice) {
return '';
}
const bigMaxPrice = BigNumber.from(selectedMaxPrice);
amount = bigMaxPrice.mul(selectedNumProviders).toString();
}
return amount;
}, [
selectedOption,
selectedDeployer?.minimumPayment,
selectedMaxPrice,
selectedNumProviders,
]);
const createProject = async ( const createProject = async (
data: FieldValues, data: FieldValues,
envVariables: AddEnvironmentVariableInput[], envVariables: AddEnvironmentVariableInput[],
@ -180,9 +212,8 @@ const Configure = () => {
(deployer) => deployer.deployerLrn === deployerLrn, (deployer) => deployer.deployerLrn === deployerLrn,
); );
let amount: string;
let senderAddress: string; let senderAddress: string;
let txHash: string; let txHash: string | null = null;
if (createFormData.option === 'LRN' && !deployer?.minimumPayment) { if (createFormData.option === 'LRN' && !deployer?.minimumPayment) {
toast({ toast({
id: 'no-payment-required', id: 'no-payment-required',
@ -196,39 +227,46 @@ const Configure = () => {
} else { } else {
if (!selectedAccount) return; if (!selectedAccount) return;
senderAddress = selectedAccount.split(':')[2]; senderAddress = selectedAccount;
if (createFormData.option === 'LRN') { txHash = await cosmosSendTokensHandler(senderAddress, amountToBePaid);
amount = deployer?.minimumPayment!;
} else { if (!txHash) {
amount = ( toast({
createFormData.numProviders * createFormData.maxPrice id: 'unsuccessful-tx',
).toString(); title: 'Transaction rejected',
variant: 'error',
onDismiss: dismiss,
});
setIsFrameVisible(false);
setIsPaymentLoading(false);
throw new Error('Transaction rejected');
} }
const amountToBePaid = amount.replace(/\D/g, '').toString(); // Validate transaction hash
const txHashResponse = await cosmosSendTokensHandler(
selectedAccount,
amountToBePaid,
);
if (!txHashResponse) {
console.error('Tx not successful');
return;
}
txHash = txHashResponse;
const isTxHashValid = await verifyTx( const isTxHashValid = await verifyTx(
senderAddress, senderAddress,
txHash, txHash,
amountToBePaid.toString(), amountToBePaid,
); );
setIsPaymentLoading(false);
if (isTxHashValid === false) { if (isTxHashValid) {
console.error('Invalid Tx hash', txHash); toast({
return; id: 'payment-successful',
title: 'Payment successful',
variant: 'success',
onDismiss: dismiss,
});
setIsPaymentDone(true);
} else {
toast({
id: 'invalid-tx-hash',
title: 'Transaction validation failed',
variant: 'error',
onDismiss: dismiss,
});
throw new Error('Transaction validation failed');
} }
} }
@ -248,7 +286,7 @@ const Configure = () => {
createFormData, createFormData,
environmentVariables, environmentVariables,
senderAddress, senderAddress,
txHash, txHash!,
); );
await client.getEnvironmentVariables(projectId); await client.getEnvironmentVariables(projectId);
@ -270,17 +308,17 @@ const Configure = () => {
`/${orgSlug}/projects/create/deploy?projectId=${projectId}`, `/${orgSlug}/projects/create/deploy?projectId=${projectId}`,
); );
} }
} catch (error) { } catch (error: any) {
console.error(error);
toast({ toast({
id: 'error-deploying-app', id: 'error-deploying-app',
title: 'Error deploying app', title: 'Error deploying app',
variant: 'error', variant: 'error',
onDismiss: dismiss, onDismiss: dismiss,
}); });
throw new Error(error);
} }
}, },
[client, createProject, dismiss, toast], [client, createProject, dismiss, toast, amountToBePaid],
); );
const fetchDeployers = useCallback(async () => { const fetchDeployers = useCallback(async () => {
@ -288,10 +326,6 @@ const Configure = () => {
setDeployers(res.deployers); setDeployers(res.deployers);
}, [client]); }, [client]);
const onAccountChange = useCallback((account: string) => {
setSelectedAccount(account);
}, []);
const onDeployerChange = useCallback( const onDeployerChange = useCallback(
(selectedLrn: string) => { (selectedLrn: string) => {
const deployer = deployers.find((d) => d.deployerLrn === selectedLrn); const deployer = deployers.find((d) => d.deployerLrn === selectedLrn);
@ -302,76 +336,112 @@ const Configure = () => {
const cosmosSendTokensHandler = useCallback( const cosmosSendTokensHandler = useCallback(
async (selectedAccount: string, amount: string) => { async (selectedAccount: string, amount: string) => {
if (!signClient || !session || !selectedAccount) { if (!selectedAccount) {
return; throw new Error('Account not selected');
} }
const chainId = selectedAccount.split(':')[1]; const senderAddress = selectedAccount;
const senderAddress = selectedAccount.split(':')[2];
const snowballAddress = await client.getAddress(); const snowballAddress = await client.getAddress();
let timeoutId;
try { try {
setIsPaymentDone(false); setIsPaymentDone(false);
setIsPaymentLoading(true); setIsPaymentLoading(true);
toast({ await requestTx(senderAddress, snowballAddress, amount);
id: 'sending-payment-request',
title: 'Check your wallet and approve payment request', const txHash = await new Promise<string | null>((resolve, reject) => {
variant: 'loading', // Call cleanup method only if appropriate event type is recieved
onDismiss: dismiss, 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'));
toast({
id: 'error-transaction',
title: 'Error during transaction',
variant: 'error',
onDismiss: dismiss,
});
cleanup();
}
};
window.addEventListener('message', handleTxStatus);
// Set a timeout, consider unsuccessful after 1 min
timeoutId = setTimeout(() => {
reject(new Error('Transaction timeout'));
window.removeEventListener('message', handleTxStatus);
toast({
id: 'transaction-timeout',
title: 'The transaction request timed out. Please try again',
variant: 'error',
onDismiss: dismiss,
});
setIsFrameVisible(false);
setIsPaymentLoading(false);
}, TX_APPROVAL_TIMEOUT_MS);
}); });
return txHash;
const result: { signature: string } = await signClient.request({ } catch (error) {
topic: session.topic, console.error('Error in transaction:', error);
chainId: `cosmos:${chainId}`, throw new Error('Error in transaction');
request: {
method: 'cosmos_sendTokens',
params: [
{
from: senderAddress,
to: snowballAddress,
value: amount,
},
],
},
});
if (!result) {
throw new Error('Error completing transaction');
}
toast({
id: 'payment-successful',
title: 'Payment successful',
variant: 'success',
onDismiss: dismiss,
});
setIsPaymentDone(true);
return result.signature;
} catch (error: any) {
console.error('Error sending tokens', error);
toast({
id: 'error-sending-tokens',
title: 'Error sending tokens',
variant: 'error',
onDismiss: dismiss,
});
setIsPaymentDone(false);
} finally { } finally {
setIsPaymentLoading(false); clearTimeout(timeoutId);
} }
}, },
[session, signClient, toast], [client, dismiss, toast],
); );
const requestTx = async (
sender: string,
recipient: string,
amount: string,
) => {
const iframe = document.getElementById('walletIframe') as HTMLIFrameElement;
if (!iframe.contentWindow) {
console.error('Iframe not found or not loaded');
throw new Error('Iframe not found or not loaded');
}
iframe.contentWindow.postMessage(
{
type: 'REQUEST_TX',
chainId: VITE_LACONICD_CHAIN_ID,
fromAddress: sender,
toAddress: recipient,
amount,
},
VITE_WALLET_IFRAME_URL,
);
setIsFrameVisible(true);
};
useEffect(() => { useEffect(() => {
fetchDeployers(); fetchDeployers();
}, []); }, []);
useEffect(() => {
if (isBalanceSufficient) {
setBalanceMessage(undefined);
}
}, [isBalanceSufficient]);
return ( return (
<div className="space-y-7 px-4 py-6"> <div className="space-y-7 px-4 py-6">
<div className="flex justify-between mb-6"> <div className="flex justify-between mb-6">
@ -488,6 +558,7 @@ const Configure = () => {
type="number" type="number"
value={value} value={value}
onChange={(e) => onChange(e)} onChange={(e) => onChange(e)}
min={1}
/> />
)} )}
/> />
@ -501,7 +572,7 @@ const Configure = () => {
control={methods.control} control={methods.control}
rules={{ required: true }} rules={{ required: true }}
render={({ field: { value, onChange } }) => ( render={({ field: { value, onChange } }) => (
<Input type="number" value={value} onChange={onChange} /> <Input type="number" value={value} onChange={onChange} min={1} />
)} )}
/> />
</div> </div>
@ -520,7 +591,7 @@ const Configure = () => {
<Button <Button
{...buttonSize} {...buttonSize}
type="submit" type="submit"
disabled={isLoading || !selectedDeployer || !selectedAccount} disabled={isLoading || !selectedDeployer}
rightIcon={ rightIcon={
isLoading ? ( isLoading ? (
<LoadingIcon className="animate-spin" /> <LoadingIcon className="animate-spin" />
@ -533,42 +604,83 @@ const Configure = () => {
</Button> </Button>
</div> </div>
) : ( ) : (
<> <div className="flex gap-4">
<Heading as="h4" className="md:text-lg font-medium mb-3"> <Button
Connect to your wallet {...buttonSize}
</Heading> type="submit"
<ConnectWallet onAccountChange={onAccountChange} /> shape="default"
{accounts.length > 0 && ( disabled={
<div> isLoading ||
<Button isPaymentLoading ||
{...buttonSize} !selectedAccount ||
type="submit" !isBalanceSufficient ||
shape="default" amountToBePaid === '' ||
disabled={ selectedNumProviders === ''
isLoading || isPaymentLoading || !selectedAccount }
} rightIcon={
rightIcon={ isLoading || isPaymentLoading ? (
isLoading || isPaymentLoading ? ( <LoadingIcon className="animate-spin" />
<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.'
) : ( ) : (
<ArrowRightCircleFilledIcon /> 'Insufficient funds.'
) )}
} </p>
> </div>
{!isPaymentDone ) : null
? isPaymentLoading ) : null}
? 'Transaction Requested' </div>
: 'Pay and Deploy'
: isLoading
? 'Deploying'
: 'Deploy'}
</Button>
</div>
)}
</>
)} )}
</form> </form>
</FormProvider> </FormProvider>
<ApproveTransactionModal
setAccount={setSelectedAccount}
setIsDataReceived={setIsAccountsDataReceived}
isVisible={isFrameVisible}
/>
<CheckBalanceIframe
onBalanceChange={setIsBalanceSufficient}
amount={amountToBePaid}
isPollingEnabled={true}
/>
</div> </div>
</div> </div>
); );

View File

@ -1,47 +0,0 @@
import { Select, Option } from '@snowballtools/material-tailwind-react-fork';
import { Button } from '../../shared/Button';
import { useWalletConnectClient } from 'context/WalletConnectContext';
const ConnectWallet = ({
onAccountChange,
}: {
onAccountChange: (selectedAccount: string) => void;
}) => {
const { onConnect, accounts } = useWalletConnectClient();
const handleConnect = async () => {
await onConnect();
};
return (
<div className="p-4 bg-slate-100 dark:bg-overlay3 rounded-lg mb-6">
{accounts.length === 0 ? (
<div>
<Button type={'button'} onClick={handleConnect}>
Connect Wallet
</Button>
</div>
) : (
<div>
<Select
label="Select Account"
defaultValue={accounts[0].address}
onChange={(value) => {
value && onAccountChange(value);
}}
className="dark:bg-overlay2 dark:text-foreground"
>
{accounts.map((account, index) => (
<Option key={index} value={account.address}>
{account.address.split(':').slice(1).join(':')}
</Option>
))}
</Select>
</div>
)}
</div>
);
};
export default ConnectWallet;

View File

@ -1,6 +1,8 @@
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
import { SegmentedControls } from 'components/shared/SegmentedControls'; import { SegmentedControls } from 'components/shared/SegmentedControls';
import { useState } from 'react'; import { useState } from 'react';
import { useMediaQuery } from 'usehooks-ts';
import { import {
GithubIcon, GithubIcon,
LockIcon, LockIcon,
@ -8,7 +10,7 @@ import {
TemplateIconType, TemplateIconType,
} from 'components/shared/CustomIcon'; } from 'components/shared/CustomIcon';
import { relativeTimeISO } from 'utils/time'; import { relativeTimeISO } from 'utils/time';
import { useMediaQuery } from 'usehooks-ts'; import templates from 'assets/templates';
export const MockConnectGitCard = () => { export const MockConnectGitCard = () => {
const [segmentedControlsValue, setSegmentedControlsValue] = const [segmentedControlsValue, setSegmentedControlsValue] =
@ -46,21 +48,6 @@ export const MockConnectGitCard = () => {
}, },
]; ];
const TEMPLATE_CONTENT = [
{
name: 'Web app',
icon: 'web',
},
{
name: 'Progressive Web App (PWA)',
icon: 'pwa',
},
{
name: 'Next.js + React + TailwindCSS',
icon: 'next-app',
},
];
const renderContent = useMemo(() => { const renderContent = useMemo(() => {
if (segmentedControlsValue === 'import') { if (segmentedControlsValue === 'import') {
return ( return (
@ -78,7 +65,7 @@ export const MockConnectGitCard = () => {
} }
return ( return (
<div className="grid grid-cols-1 lg:grid-cols-2 relative z-0"> <div className="grid grid-cols-1 lg:grid-cols-2 relative z-0">
{TEMPLATE_CONTENT.map((template, index) => ( {templates.map((template, index) => (
<MockTemplateCard key={index} {...template} /> <MockTemplateCard key={index} {...template} />
))} ))}
</div> </div>

View File

@ -1,42 +0,0 @@
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;

View File

@ -92,7 +92,7 @@ const DeploymentDetailsCard = ({
} }
}; };
const fetchDeploymentLogs = async () => { const fetchDeploymentLogs = useCallback(async () => {
setDeploymentLogs('Loading logs...'); setDeploymentLogs('Loading logs...');
handleOpenDialog(); handleOpenDialog();
const statusUrl = `${deployment.deployer.deployerApiUrl}/${deployment.applicationDeploymentRequestId}`; const statusUrl = `${deployment.deployer.deployerApiUrl}/${deployment.applicationDeploymentRequestId}`;
@ -108,7 +108,7 @@ const DeploymentDetailsCard = ({
); );
setDeploymentLogs(logsRes); setDeploymentLogs(logsRes);
} }
}; }, [deployment.deployer, deployment.applicationDeploymentRequestId]);
const renderDeploymentStatus = useCallback( const renderDeploymentStatus = useCallback(
(className?: string) => { (className?: string) => {
@ -127,7 +127,7 @@ const DeploymentDetailsCard = ({
</Tooltip> </Tooltip>
); );
}, },
[deployment.status, deployment.commitHash], [deployment.status, deployment.commitHash, fetchDeploymentLogs],
); );
return ( return (

View File

@ -10,7 +10,6 @@ import {
import { Deployment, Domain, Environment, Project } from 'gql-client'; import { Deployment, Domain, Environment, Project } from 'gql-client';
import { Button } from 'components/shared/Button'; import { Button } from 'components/shared/Button';
import { import {
GlobeIcon,
HorizontalDotIcon, HorizontalDotIcon,
LinkIcon, LinkIcon,
RefreshIcon, RefreshIcon,
@ -18,7 +17,6 @@ import {
UndoIcon, UndoIcon,
CrossCircleIcon, CrossCircleIcon,
} from 'components/shared/CustomIcon'; } from 'components/shared/CustomIcon';
import AssignDomainDialog from './AssignDomainDialog';
import { useGQLClient } from 'context/GQLClientContext'; import { useGQLClient } from 'context/GQLClientContext';
import { cn } from 'utils/classnames'; import { cn } from 'utils/classnames';
import { ChangeStateToProductionDialog } from 'components/projects/Dialog/ChangeStateToProductionDialog'; import { ChangeStateToProductionDialog } from 'components/projects/Dialog/ChangeStateToProductionDialog';
@ -49,8 +47,8 @@ export const DeploymentMenu = ({
const [redeployToProduction, setRedeployToProduction] = useState(false); const [redeployToProduction, setRedeployToProduction] = useState(false);
const [deleteDeploymentDialog, setDeleteDeploymentDialog] = useState(false); const [deleteDeploymentDialog, setDeleteDeploymentDialog] = useState(false);
const [isConfirmDeleteLoading, setIsConfirmDeleteLoading] = useState(false); const [isConfirmDeleteLoading, setIsConfirmDeleteLoading] = useState(false);
const [isConfirmUpdateLoading, setIsConfirmUpdateLoading] = useState(false);
const [rollbackDeployment, setRollbackDeployment] = useState(false); const [rollbackDeployment, setRollbackDeployment] = useState(false);
const [assignDomainDialog, setAssignDomainDialog] = useState(false);
const [isConfirmButtonLoading, setConfirmButtonLoadingLoading] = const [isConfirmButtonLoading, setConfirmButtonLoadingLoading] =
useState(false); useState(false);
@ -58,6 +56,8 @@ export const DeploymentMenu = ({
const isUpdated = await client.updateDeploymentToProd(deployment.id); const isUpdated = await client.updateDeploymentToProd(deployment.id);
if (isUpdated.updateDeploymentToProd) { if (isUpdated.updateDeploymentToProd) {
await onUpdate(); await onUpdate();
setIsConfirmUpdateLoading(false);
toast({ toast({
id: 'deployment_changed_to_production', id: 'deployment_changed_to_production',
title: 'Deployment changed to production', title: 'Deployment changed to production',
@ -102,6 +102,8 @@ export const DeploymentMenu = ({
); );
if (isRollbacked.rollbackDeployment) { if (isRollbacked.rollbackDeployment) {
await onUpdate(); await onUpdate();
setIsConfirmUpdateLoading(false);
toast({ toast({
id: 'deployment_rolled_back', id: 'deployment_rolled_back',
title: 'Deployment rolled back', title: 'Deployment rolled back',
@ -173,12 +175,6 @@ export const DeploymentMenu = ({
<LinkIcon /> Visit <LinkIcon /> Visit
</a> </a>
</MenuItem> </MenuItem>
<MenuItem
className="hover:bg-base-bg-emphasized flex items-center gap-3"
onClick={() => setAssignDomainDialog(!assignDomainDialog)}
>
<GlobeIcon /> Assign domain
</MenuItem>
<MenuItem <MenuItem
className="hover:bg-base-bg-emphasized flex items-center gap-3" className="hover:bg-base-bg-emphasized flex items-center gap-3"
onClick={() => setChangeToProduction(!changeToProduction)} onClick={() => setChangeToProduction(!changeToProduction)}
@ -226,9 +222,11 @@ export const DeploymentMenu = ({
handleCancel={() => setChangeToProduction((preVal) => !preVal)} handleCancel={() => setChangeToProduction((preVal) => !preVal)}
open={changeToProduction} open={changeToProduction}
handleConfirm={async () => { handleConfirm={async () => {
setIsConfirmUpdateLoading(true);
await updateDeployment(); await updateDeployment();
setChangeToProduction((preVal) => !preVal); setChangeToProduction((preVal) => !preVal);
}} }}
isConfirmButtonLoading={isConfirmUpdateLoading}
deployment={deployment} deployment={deployment}
domains={prodBranchDomains} domains={prodBranchDomains}
/> />
@ -243,7 +241,7 @@ export const DeploymentMenu = ({
setRedeployToProduction((preVal) => !preVal); setRedeployToProduction((preVal) => !preVal);
}} }}
deployment={deployment} deployment={deployment}
domains={deployment.domain ? [deployment.domain] : []} domains={prodBranchDomains}
isConfirmButtonLoading={isConfirmButtonLoading} isConfirmButtonLoading={isConfirmButtonLoading}
/> />
{Boolean(currentDeployment) && ( {Boolean(currentDeployment) && (
@ -253,18 +251,16 @@ export const DeploymentMenu = ({
open={rollbackDeployment} open={rollbackDeployment}
confirmButtonTitle="Rollback" confirmButtonTitle="Rollback"
handleConfirm={async () => { handleConfirm={async () => {
setIsConfirmUpdateLoading(true);
await rollbackDeploymentHandler(); await rollbackDeploymentHandler();
setRollbackDeployment((preVal) => !preVal); setRollbackDeployment((preVal) => !preVal);
}} }}
deployment={currentDeployment} deployment={currentDeployment}
newDeployment={deployment} newDeployment={deployment}
domains={currentDeployment.domain ? [currentDeployment.domain] : []} domains={prodBranchDomains}
isConfirmButtonLoading={isConfirmUpdateLoading}
/> />
)} )}
<AssignDomainDialog
open={assignDomainDialog}
handleOpen={() => setAssignDomainDialog(!assignDomainDialog)}
/>
<DeleteDeploymentDialog <DeleteDeploymentDialog
open={deleteDeploymentDialog} open={deleteDeploymentDialog}
handleConfirm={async () => { handleConfirm={async () => {

View File

@ -1,5 +1,5 @@
import { useState } from 'react'; import { useEffect, useState } from 'react';
import { Domain, DomainStatus, Project } from 'gql-client'; import { DNSRecordAttributes, Domain, DomainStatus, Project } from 'gql-client';
import { import {
Typography, Typography,
@ -14,22 +14,27 @@ import EditDomainDialog from './EditDomainDialog';
import { useGQLClient } from 'context/GQLClientContext'; import { useGQLClient } from 'context/GQLClientContext';
import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog'; import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog';
import { useToast } from 'components/shared/Toast'; import { useToast } from 'components/shared/Toast';
import { Tag } from 'components/shared/Tag'; import { GearIcon } from 'components/shared/CustomIcon';
import {
CheckIcon,
CrossIcon,
GearIcon,
LoadingIcon,
} from 'components/shared/CustomIcon';
import { Heading } from 'components/shared/Heading'; import { Heading } from 'components/shared/Heading';
import { Button } from 'components/shared/Button'; import { Button } from 'components/shared/Button';
import { useParams } from 'react-router-dom';
enum RefreshStatus { // NOTE: Commented code for verify domain functionality
IDLE, // import { Tag } from 'components/shared/Tag';
CHECKING, // import {
CHECK_SUCCESS, // CheckIcon,
CHECK_FAIL, // CrossIcon,
} // LoadingIcon,
// } from 'components/shared/CustomIcon';
// enum RefreshStatus {
// IDLE,
// CHECKING,
// CHECK_SUCCESS,
// CHECK_FAIL,
// }
// const CHECK_FAIL_TIMEOUT = 5000; // In milliseconds
interface DomainCardProps { interface DomainCardProps {
domains: Domain[]; domains: Domain[];
@ -39,14 +44,6 @@ interface DomainCardProps {
onUpdate: () => Promise<void>; 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 = ({ const DomainCard = ({
domains, domains,
@ -56,9 +53,11 @@ const DomainCard = ({
onUpdate, onUpdate,
}: DomainCardProps) => { }: DomainCardProps) => {
const { toast, dismiss } = useToast(); const { toast, dismiss } = useToast();
const [refreshStatus, SetRefreshStatus] = useState(RefreshStatus.IDLE); const { id } = useParams();
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [editDialogOpen, setEditDialogOpen] = useState(false); const [editDialogOpen, setEditDialogOpen] = useState(false);
const [dnsRecord, setDnsRecord] = useState<DNSRecordAttributes | null>(null);
// const [refreshStatus, SetRefreshStatus] = useState(RefreshStatus.IDLE);
const client = useGQLClient(); const client = useGQLClient();
@ -83,13 +82,33 @@ const DomainCard = ({
} }
}; };
useEffect(() => {
const fetchDNSData = async () => {
if (id === undefined) {
toast({
id: 'domain_cannot_find_project',
title: 'Cannot find project',
variant: 'error',
onDismiss: dismiss,
});
return;
}
const dnsRecordResponse = await client.getLatestDNSRecordByProjectId(id);
setDnsRecord(dnsRecordResponse.latestDNSRecord);
};
fetchDNSData();
}, [id, client]);
return ( return (
<> <>
<div className="flex justify-between py-3"> <div className="flex justify-between py-3">
<div className="flex justify-start gap-1"> <div className="flex justify-start gap-1">
<Heading as="h6" className="flex-col"> <Heading as="h6" className="flex-col">
{domain.name}{' '} {domain.name}{' '}
<Tag {/* <Tag
type={ type={
domain.status === DomainStatus.Live ? 'positive' : 'negative' domain.status === DomainStatus.Live ? 'positive' : 'negative'
} }
@ -102,12 +121,12 @@ const DomainCard = ({
} }
> >
{domain.status} {domain.status}
</Tag> </Tag> */}
</Heading> </Heading>
</div> </div>
<div className="flex justify-start gap-1"> <div className="flex justify-start gap-1">
<i {/* <i
id="refresh" id="refresh"
className="cursor-pointer" className="cursor-pointer"
onClick={() => { onClick={() => {
@ -122,7 +141,7 @@ const DomainCard = ({
) : ( ) : (
'L' 'L'
)} )}
</i> </i> */}
<Menu placement="bottom-end"> <Menu placement="bottom-end">
<MenuHandler> <MenuHandler>
<Button iconOnly> <Button iconOnly>
@ -163,11 +182,11 @@ const DomainCard = ({
<Typography variant="small">Production</Typography> <Typography variant="small">Production</Typography>
{domain.status === DomainStatus.Pending && ( {domain.status === DomainStatus.Pending && (
<Card className="bg-slate-100 p-4 text-sm"> <Card className="bg-slate-100 p-4 text-sm">
{refreshStatus === RefreshStatus.IDLE ? ( {/* {refreshStatus === RefreshStatus.IDLE ? ( */}
<Heading> <Heading>
^ Add these records to your domain and refresh to check ^ Add these records to your domain {/* and refresh to check */}
</Heading> </Heading>
) : refreshStatus === RefreshStatus.CHECKING ? ( {/* ) : refreshStatus === RefreshStatus.CHECKING ? (
<Heading className="text-blue-500"> <Heading className="text-blue-500">
^ Checking records for {domain.name} ^ Checking records for {domain.name}
</Heading> </Heading>
@ -178,7 +197,7 @@ const DomainCard = ({
hours. Please ensure you added the correct records and refresh. hours. Please ensure you added the correct records and refresh.
</div> </div>
</div> </div>
)} )} */}
<table> <table>
<thead> <thead>
@ -189,11 +208,15 @@ const DomainCard = ({
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr> {dnsRecord ? (
<td>{DOMAIN_RECORD.type}</td> <tr>
<td>{DOMAIN_RECORD.name}</td> <td>{dnsRecord.resourceType}</td>
<td>{DOMAIN_RECORD.value}</td> <td>@</td>
</tr> <td>{dnsRecord.value ?? 'Not Configured'}</td>
</tr>
) : (
<p className={'text-red-500'}>DNS record data not available</p>
)}
</tbody> </tbody>
</table> </table>
</Card> </Card>

View File

@ -1,11 +1,15 @@
import { useCallback, useEffect, useMemo } from 'react'; import {
import { Controller, useForm, SubmitHandler } from 'react-hook-form'; useCallback,
useEffect,
} from 'react';
import {
useForm,
SubmitHandler,
} from 'react-hook-form';
import { Domain } from 'gql-client'; import { Domain } from 'gql-client';
import { import {
Typography, Typography,
Select,
Option,
} from '@snowballtools/material-tailwind-react-fork'; } from '@snowballtools/material-tailwind-react-fork';
import { useGQLClient } from 'context/GQLClientContext'; import { useGQLClient } from 'context/GQLClientContext';
@ -14,7 +18,15 @@ import { Button } from 'components/shared/Button';
import { Input } from 'components/shared/Input'; import { Input } from 'components/shared/Input';
import { useToast } from 'components/shared/Toast'; import { useToast } from 'components/shared/Toast';
const DEFAULT_REDIRECT_OPTIONS = ['none']; // 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 { interface EditDomainDialogProp {
domains: Domain[]; domains: Domain[];
@ -28,7 +40,7 @@ interface EditDomainDialogProp {
type EditDomainValues = { type EditDomainValues = {
name: string; name: string;
branch: string; branch: string;
redirectedTo: string; // redirectedTo: string;
}; };
const EditDomainDialog = ({ const EditDomainDialog = ({
@ -42,58 +54,58 @@ const EditDomainDialog = ({
const client = useGQLClient(); const client = useGQLClient();
const { toast, dismiss } = useToast(); const { toast, dismiss } = useToast();
const getRedirectUrl = (domain: Domain) => { // const getRedirectUrl = (domain: Domain) => {
const redirectDomain = domain.redirectTo; // const redirectDomain = domain.redirectTo;
if (redirectDomain !== null) { // if (redirectDomain !== null) {
return redirectDomain?.name; // return redirectDomain?.name;
} else { // } else {
return 'none'; // return 'none';
} // }
}; // };
const redirectOptions = useMemo(() => { // const redirectOptions = useMemo(() => {
const domainNames = domains // const domainNames = domains
.filter((domainData) => domainData.id !== domain.id) // .filter((domainData) => domainData.id !== domain.id)
.map((domain) => domain.name); // .map((domain) => domain.name);
return ['none', ...domainNames]; // return ['none', ...domainNames];
}, [domain, domains]); // }, [domain, domains]);
const domainRedirectedFrom = useMemo(() => { // const domainRedirectedFrom = useMemo(() => {
return domains.find( // return domains.find(
(domainData) => domainData.redirectTo?.id === domain.id, // (domainData) => domainData.redirectTo?.id === domain.id,
); // );
}, [domains, domain]); // }, [domains, domain]);
const isDisableDropdown = useMemo(() => { // const isDisableDropdown = useMemo(() => {
return domainRedirectedFrom !== undefined; // return domainRedirectedFrom !== undefined;
}, [domain, domains]); // }, [domain, domains]);
const { const {
handleSubmit, handleSubmit,
register, register,
control, // control,
watch, // watch,
reset, reset,
formState: { isValid, isDirty }, formState: { isValid, isDirty },
} = useForm({ } = useForm({
defaultValues: { defaultValues: {
name: domain.name, name: domain.name,
branch: domain.branch, branch: domain.branch,
redirectedTo: getRedirectUrl(domain), // redirectedTo: getRedirectUrl(domain),
}, },
}); });
const updateDomainHandler: SubmitHandler<EditDomainValues> = useCallback( const updateDomainHandler: SubmitHandler<EditDomainValues> = useCallback(
async (data) => { async (data) => {
const domainRedirectTo = domains.find( // const domainRedirectTo = domains.find(
(domainData) => data.redirectedTo === domainData.name, // (domainData) => data.redirectedTo === domainData.name,
); // );
const updates = { const updates = {
name: data.name ? data.name : domain.name, name: data.name ? data.name : domain.name,
branch: data.branch ? data.branch : domain.branch, branch: data.branch ? data.branch : domain.branch,
redirectToId: domainRedirectTo ? domainRedirectTo.id : null, // redirectToId: domainRedirectTo ? domainRedirectTo.id : null,
}; };
const { updateDomain } = await client.updateDomain(domain.id, updates); const { updateDomain } = await client.updateDomain(domain.id, updates);
@ -125,7 +137,7 @@ const EditDomainDialog = ({
reset({ reset({
name: domain.name, name: domain.name,
branch: domain.branch, branch: domain.branch,
redirectedTo: getRedirectUrl(domain), // redirectedTo: getRedirectUrl(domain),
}); });
}, [domain]); }, [domain]);
@ -137,7 +149,7 @@ const EditDomainDialog = ({
<Modal.Body className="flex flex-col gap-2"> <Modal.Body className="flex flex-col gap-2">
<Typography variant="small">Domain name</Typography> <Typography variant="small">Domain name</Typography>
<Input {...register('name')} /> <Input {...register('name')} />
<Typography variant="small">Redirect to</Typography> {/* <Typography variant="small">Redirect to</Typography>
<Controller <Controller
name="redirectedTo" name="redirectedTo"
control={control} control={control}
@ -161,7 +173,7 @@ const EditDomainDialog = ({
further. further.
</Typography> </Typography>
</div> </div>
)} )} */}
<Typography variant="small">Git branch</Typography> <Typography variant="small">Git branch</Typography>
<Input <Input
{...register('branch', { {...register('branch', {
@ -169,8 +181,8 @@ const EditDomainDialog = ({
Boolean(branches.length) ? branches.includes(value) : true, Boolean(branches.length) ? branches.includes(value) : true,
})} })}
disabled={ disabled={
!Boolean(branches.length) || !Boolean(branches.length)
watch('redirectedTo') !== DEFAULT_REDIRECT_OPTIONS[0] // || watch('redirectedTo') !== DEFAULT_REDIRECT_OPTIONS[0]
} }
/> />
{!isValid && ( {!isValid && (

View File

@ -17,6 +17,7 @@ const GitSelectionSection = ({
<div className="grow">Github</div> <div className="grow">Github</div>
<div>{'>'}</div> <div>{'>'}</div>
</div> </div>
{/*
<div <div
className="flex gap-4 border-b-2 border-gray-200 cursor-pointer p-1" className="flex gap-4 border-b-2 border-gray-200 cursor-pointer p-1"
onClick={() => {}} onClick={() => {}}
@ -25,6 +26,7 @@ const GitSelectionSection = ({
<div className="grow">Gitea</div> <div className="grow">Gitea</div>
<div>{'>'}</div> <div>{'>'}</div>
</div> </div>
*/}
</> </>
); );
}; };

View File

@ -1,12 +1,14 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { Heading } from 'components/shared/Heading'; import { Heading } from 'components/shared/Heading';
import { InlineNotification } from 'components/shared/InlineNotification';
import { Input } from 'components/shared/Input'; import { Input } from 'components/shared/Input';
import { Button } from 'components/shared/Button'; import { Button } from 'components/shared/Button';
import { Radio } from 'components/shared/Radio';
// 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 { interface SetupDomainFormValues {
domainName: string; domainName: string;
@ -18,47 +20,45 @@ const SetupDomain = () => {
register, register,
handleSubmit, handleSubmit,
formState: { isValid }, formState: { isValid },
watch, // watch,
setValue, // setValue,
} = useForm<SetupDomainFormValues>({ } = useForm<SetupDomainFormValues>({
defaultValues: { defaultValues: {
domainName: '', domainName: '',
isWWW: 'false', // isWWW: 'false',
}, },
mode: 'onChange', mode: 'onChange',
}); });
const [domainStr, setDomainStr] = useState<string>('');
const navigate = useNavigate(); const navigate = useNavigate();
const isWWWRadioOptions = [ // const [domainStr, setDomainStr] = useState<string>('');
{ label: domainStr, value: 'false' }, // const isWWWRadioOptions = [
{ label: `www.${domainStr}`, value: 'true' }, // { label: domainStr, value: 'false' },
]; // { label: `www.${domainStr}`, value: 'true' },
// ];
useEffect(() => { // useEffect(() => {
const subscription = watch((value, { name }) => { // const subscription = watch((value, { name }) => {
if (name === 'domainName' && value.domainName) { // if (name === 'domainName' && value.domainName) {
const domainArr = value.domainName.split('www.'); // const domainArr = value.domainName.split('www.');
const cleanedDomain = // const cleanedDomain =
domainArr.length > 1 ? domainArr[1] : domainArr[0]; // domainArr.length > 1 ? domainArr[1] : domainArr[0];
setDomainStr(cleanedDomain); // setDomainStr(cleanedDomain);
setValue( // setValue(
'isWWW', // 'isWWW',
value.domainName.startsWith('www.') ? 'true' : 'false', // value.domainName.startsWith('www.') ? 'true' : 'false',
); // );
} // }
}); // });
return () => subscription.unsubscribe(); // return () => subscription.unsubscribe();
}, [watch, setValue]); // }, [watch, setValue]);
return ( return (
<form <form
onSubmit={handleSubmit(() => { onSubmit={handleSubmit((e) => {
watch('isWWW') === 'true' navigate(`config?name=${e.domainName}`)
? navigate(`config?name=www.${domainStr}`)
: navigate(`config?name=${domainStr}`);
})} })}
className="flex flex-col gap-6 w-full" className="flex flex-col gap-6 w-full"
> >
@ -67,7 +67,7 @@ const SetupDomain = () => {
Setup domain name Setup domain name
</Heading> </Heading>
<p className="text-slate-500 text-sm font-normal leading-tight"> <p className="text-slate-500 text-sm font-normal leading-tight">
Add your domain and setup redirects Add your domain {/* and setup redirects */}
</p> </p>
</div> </div>
@ -80,7 +80,7 @@ const SetupDomain = () => {
label="Domain name" label="Domain name"
/> />
{isValid && ( {/* {isValid && (
<div className="self-stretch flex flex-col gap-4"> <div className="self-stretch flex flex-col gap-4">
<Heading className="text-sky-950 text-lg font-medium leading-normal"> <Heading className="text-sky-950 text-lg font-medium leading-normal">
Primary domain Primary domain
@ -99,7 +99,7 @@ const SetupDomain = () => {
}. Redirect preferences can be changed later`} }. Redirect preferences can be changed later`}
/> />
</div> </div>
)} )} */}
<div className="self-stretch"> <div className="self-stretch">
<Button disabled={!isValid} type="submit" shape="default"> <Button disabled={!isValid} type="submit" shape="default">

View File

@ -4,10 +4,7 @@ import { cloneIcon } from 'utils/cloneIcon';
import { PWAIcon } from './PWAIcon'; import { PWAIcon } from './PWAIcon';
import { WebAppIcon } from './WebAppIcon'; import { WebAppIcon } from './WebAppIcon';
const TEMPLATE_ICONS = [ const TEMPLATE_ICONS = ['pwa', 'web'] as const;
'pwa',
'web'
] as const;
export type TemplateIconType = (typeof TEMPLATE_ICONS)[number]; export type TemplateIconType = (typeof TEMPLATE_ICONS)[number];
export interface TemplateIconProps extends CustomIconProps { export interface TemplateIconProps extends CustomIconProps {

View File

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

View File

@ -0,0 +1,154 @@
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';
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].address);
}
};
window.addEventListener('message', handleAccountsDataResponse);
return () => {
window.removeEventListener('message', handleAccountsDataResponse);
};
}, []);
const getAddressFromWallet = useCallback(() => {
const iframe = document.getElementById(
'autoSignInFrame',
) as HTMLIFrameElement;
if (!iframe.contentWindow) {
console.error('Iframe not found or not loaded');
return;
}
iframe.contentWindow.postMessage(
{
type: 'REQUEST_CREATE_OR_GET_ACCOUNTS',
chainId: '1',
},
VITE_WALLET_IFRAME_URL,
);
}, []);
return (
<Modal open={true} disableEscapeKeyDown keepMounted>
<Box
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: '90%',
maxWidth: '1200px',
height: '600px',
maxHeight: '80vh',
overflow: 'auto',
outline: 'none',
}}
>
<iframe
onLoad={getAddressFromWallet}
id="autoSignInFrame"
src={`${VITE_WALLET_IFRAME_URL}/auto-sign-in`}
width="100%"
height="100%"
sandbox="allow-scripts allow-same-origin"
></iframe>
</Box>
</Modal>
);
};
export default AutoSignInIFrameModal;

View File

@ -1,3 +1,5 @@
export const SHORT_COMMIT_HASH_LENGTH = 8; export const SHORT_COMMIT_HASH_LENGTH = 8;
export const SERVER_GQL_PATH = 'graphql'; export const SERVER_GQL_PATH = 'graphql';
export const SHOPIFY_APP_URL = 'https://store.laconic.com';

View File

@ -1,210 +0,0 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from 'react';
import SignClient from '@walletconnect/sign-client';
import { getSdkError } from '@walletconnect/utils';
import { SessionTypes } from '@walletconnect/types';
import { walletConnectModal } from '../utils/web3modal';
import {
VITE_LACONICD_CHAIN_ID,
VITE_WALLET_CONNECT_ID,
} from 'utils/constants';
interface ClientInterface {
signClient: SignClient | undefined;
session: SessionTypes.Struct | undefined;
loadingSession: boolean;
onConnect: () => Promise<void>;
onDisconnect: () => Promise<void>;
onSessionDelete: () => void;
accounts: { address: string }[];
}
const ClientContext = createContext({} as ClientInterface);
export const useWalletConnectClient = () => {
return useContext(ClientContext);
};
export const WalletConnectClientProvider = ({
children,
}: {
children: JSX.Element;
}) => {
const [signClient, setSignClient] = useState<SignClient>();
const [session, setSession] = useState<SessionTypes.Struct>();
const [loadingSession, setLoadingSession] = useState(true);
const [accounts, setAccounts] = useState<{ address: string }[]>([]);
const isSignClientInitializing = useRef<boolean>(false);
const onSessionConnect = useCallback(async (session: SessionTypes.Struct) => {
setSession(session);
}, []);
const subscribeToEvents = useCallback(
async (client: SignClient) => {
client.on('session_update', ({ topic, params }) => {
const { namespaces } = params;
const currentSession = client.session.get(topic);
const updatedSession = { ...currentSession, namespaces };
setSession(updatedSession);
});
},
[setSession],
);
const onConnect = async () => {
const proposalNamespace = {
cosmos: {
methods: ['cosmos_sendTokens'],
chains: [`cosmos:${VITE_LACONICD_CHAIN_ID}`],
events: [],
},
};
try {
const { uri, approval } = await signClient!.connect({
requiredNamespaces: proposalNamespace,
});
if (uri) {
walletConnectModal.openModal({ uri });
const session = await approval();
onSessionConnect(session);
walletConnectModal.closeModal();
}
} catch (e) {
console.error(e);
}
};
const onDisconnect = useCallback(async () => {
if (typeof signClient === 'undefined') {
throw new Error('WalletConnect is not initialized');
}
if (typeof session === 'undefined') {
throw new Error('Session is not connected');
}
await signClient.disconnect({
topic: session.topic,
reason: getSdkError('USER_DISCONNECTED'),
});
onSessionDelete();
}, [signClient, session]);
const onSessionDelete = () => {
setAccounts([]);
setSession(undefined);
};
const checkPersistedState = useCallback(
async (signClient: SignClient) => {
if (typeof signClient === 'undefined') {
throw new Error('WalletConnect is not initialized');
}
if (typeof session !== 'undefined') return;
if (signClient.session.length) {
const lastKeyIndex = signClient.session.keys.length - 1;
const previousSsession = signClient.session.get(
signClient.session.keys[lastKeyIndex],
);
await onSessionConnect(previousSsession);
return previousSsession;
}
},
[session, onSessionConnect],
);
const createClient = useCallback(async () => {
isSignClientInitializing.current = true;
try {
const signClient = await SignClient.init({
projectId: VITE_WALLET_CONNECT_ID,
metadata: {
name: 'Deploy App',
description: '',
url: window.location.href,
icons: ['https://avatars.githubusercontent.com/u/92608123'],
},
});
setSignClient(signClient);
await checkPersistedState(signClient);
await subscribeToEvents(signClient);
setLoadingSession(false);
} catch (e) {
console.error('error in createClient', e);
}
isSignClientInitializing.current = false;
}, [setSignClient, checkPersistedState, subscribeToEvents]);
useEffect(() => {
if (!signClient && !isSignClientInitializing.current) {
createClient();
}
}, [signClient, createClient]);
useEffect(() => {
const populateAccounts = async () => {
if (!session) {
return;
}
if (!session.namespaces['cosmos']) {
console.log('Accounts for cosmos namespace not found');
return;
}
const cosmosAddresses = session.namespaces['cosmos'].accounts;
const cosmosAccounts = cosmosAddresses.map((address) => ({
address,
}));
const allAccounts = cosmosAccounts;
setAccounts(allAccounts);
};
populateAccounts();
}, [session]);
useEffect(() => {
if (!signClient) {
return;
}
signClient.on('session_delete', onSessionDelete);
return () => {
signClient.off('session_delete', onSessionDelete);
};
});
return (
<ClientContext.Provider
value={{
signClient,
onConnect,
onDisconnect,
onSessionDelete,
loadingSession,
session,
accounts,
}}
>
{children}
</ClientContext.Provider>
);
};

View File

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

View File

@ -0,0 +1,44 @@
import { useState, useEffect, useCallback } from 'react';
import { VITE_LACONICD_CHAIN_ID } from 'utils/constants';
const useCheckBalance = (amount: string, iframeId: string) => {
const [isBalanceSufficient, setIsBalanceSufficient] = useState<boolean>();
const checkBalance = useCallback(() => {
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: VITE_LACONICD_CHAIN_ID,
amount,
},
import.meta.env.VITE_WALLET_IFRAME_URL
);
}, [iframeId, amount]);
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
if (event.origin !== import.meta.env.VITE_WALLET_IFRAME_URL) return;
if (event.data.type !== 'IS_SUFFICIENT') return;
setIsBalanceSufficient(event.data.data);
};
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, []);
return { isBalanceSufficient, checkBalance };
};
export default useCheckBalance;

View File

@ -4,10 +4,9 @@ import assert from 'assert';
import { GQLClient } from 'gql-client'; import { GQLClient } from 'gql-client';
import { ThemeProvider } from '@snowballtools/material-tailwind-react-fork'; import { ThemeProvider } from '@snowballtools/material-tailwind-react-fork';
import './index.css';
import '@fontsource/inter'; import '@fontsource/inter';
import '@fontsource-variable/jetbrains-mono'; import '@fontsource-variable/jetbrains-mono';
import App from './App'; import App from './App';
import reportWebVitals from './reportWebVitals'; import reportWebVitals from './reportWebVitals';
import { GQLClientProvider } from './context/GQLClientContext'; import { GQLClientProvider } from './context/GQLClientContext';
@ -15,8 +14,7 @@ import { SERVER_GQL_PATH } from './constants';
import { Toaster } from 'components/shared/Toast'; import { Toaster } from 'components/shared/Toast';
import { LogErrorBoundary } from 'utils/log-error'; import { LogErrorBoundary } from 'utils/log-error';
import { BASE_URL } from 'utils/constants'; import { BASE_URL } from 'utils/constants';
import Web3ModalProvider from './context/Web3Provider'; import './index.css';
import { WalletConnectClientProvider } from 'context/WalletConnectContext';
console.log(`v-0.0.9`); console.log(`v-0.0.9`);
@ -32,16 +30,12 @@ const gqlClient = new GQLClient({ gqlEndpoint });
root.render( root.render(
<LogErrorBoundary> <LogErrorBoundary>
<React.StrictMode> <React.StrictMode>
<WalletConnectClientProvider> <ThemeProvider>
<ThemeProvider> <GQLClientProvider client={gqlClient}>
<Web3ModalProvider> <App />
<GQLClientProvider client={gqlClient}> <Toaster />
<App /> </GQLClientProvider>
<Toaster /> </ThemeProvider>
</GQLClientProvider>
</Web3ModalProvider>
</ThemeProvider>
</WalletConnectClientProvider>
</React.StrictMode> </React.StrictMode>
</LogErrorBoundary>, </LogErrorBoundary>,
); );

View File

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

View File

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

View File

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

View File

@ -10,6 +10,7 @@ import { DeleteVariableDialog } from 'components/projects/Dialog/DeleteVariableD
import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog'; import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog';
import { CancelDeploymentDialog } from 'components/projects/Dialog/CancelDeploymentDialog'; import { CancelDeploymentDialog } from 'components/projects/Dialog/CancelDeploymentDialog';
import { import {
AppDeploymentRecordAttributes,
Deployment, Deployment,
DeploymentStatus, DeploymentStatus,
Domain, Domain,
@ -20,15 +21,6 @@ import { ChangeStateToProductionDialog } from 'components/projects/Dialog/Change
const deployment: Deployment = { const deployment: Deployment = {
id: '1', 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', branch: 'main',
commitHash: 'a1b2c3d', commitHash: 'a1b2c3d',
commitMessage: commitMessage:
@ -57,6 +49,7 @@ const deployment: Deployment = {
updatedAt: '1677680400', // 2023-03-01T13:00:00Z updatedAt: '1677680400', // 2023-03-01T13:00:00Z
applicationDeploymentRequestId: applicationDeploymentRequestId:
'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize', 'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize',
applicationDeploymentRecordData: {} as AppDeploymentRecordAttributes,
}; };
const domains: Domain[] = [ const domains: Domain[] = [
@ -252,7 +245,7 @@ const ModalsPage: React.FC = () => {
setRedeployToProduction((preVal) => !preVal) setRedeployToProduction((preVal) => !preVal)
} }
deployment={deployment} deployment={deployment}
domains={deployment.domain ? [deployment.domain] : []} domains={domains}
/> />
{/* Rollback to this deployment */} {/* Rollback to this deployment */}
<Button onClick={() => setRollbackDeployment(true)}> <Button onClick={() => setRollbackDeployment(true)}>
@ -268,7 +261,7 @@ const ModalsPage: React.FC = () => {
} }
deployment={deployment} deployment={deployment}
newDeployment={deployment} newDeployment={deployment}
domains={deployment.domain ? [deployment.domain] : []} domains={domains}
/> />
</div> </div>
</div> </div>

View File

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

View File

@ -60,9 +60,9 @@ const Id = () => {
fetchProject(id); fetchProject(id);
}, [id]); }, [id]);
const onUpdate = async () => { const onUpdate = useCallback(async () => {
await fetchProject(id); await fetchProject(id);
}; }, [fetchProject, id]);
return ( return (
<div className="h-full"> <div className="h-full">
@ -118,9 +118,11 @@ const Id = () => {
<Tabs.Trigger value="deployments"> <Tabs.Trigger value="deployments">
<Link to="deployments">Deployments</Link> <Link to="deployments">Deployments</Link>
</Tabs.Trigger> </Tabs.Trigger>
{/*
<Tabs.Trigger value="integrations"> <Tabs.Trigger value="integrations">
<Link to="integrations">Integrations</Link> <Link to="integrations">Integrations</Link>
</Tabs.Trigger> </Tabs.Trigger>
*/}
<Tabs.Trigger value="settings"> <Tabs.Trigger value="settings">
<Link to="settings">Settings</Link> <Link to="settings">Settings</Link>
</Tabs.Trigger> </Tabs.Trigger>

View File

@ -1,12 +1,14 @@
import { ComponentPropsWithoutRef } from 'react'; import { ComponentPropsWithoutRef } from 'react';
import { Link, Outlet, useParams } from 'react-router-dom'; import { Link, Outlet, useParams } from 'react-router-dom';
import { useMediaQuery } from 'usehooks-ts';
import * as Dialog from '@radix-ui/react-dialog';
import { Heading } from 'components/shared/Heading'; import { Heading } from 'components/shared/Heading';
import { WavyBorder } from 'components/shared/WavyBorder'; import { WavyBorder } from 'components/shared/WavyBorder';
import { Button } from 'components/shared/Button'; import { Button } from 'components/shared/Button';
import { CrossIcon } from 'components/shared/CustomIcon'; import { CrossIcon } from 'components/shared/CustomIcon';
import { cn } from 'utils/classnames'; import { cn } from 'utils/classnames';
import * as Dialog from '@radix-ui/react-dialog';
export interface CreateProjectLayoutProps export interface CreateProjectLayoutProps
extends ComponentPropsWithoutRef<'section'> {} extends ComponentPropsWithoutRef<'section'> {}
@ -16,6 +18,7 @@ export const CreateProjectLayout = ({
...props ...props
}: CreateProjectLayoutProps) => { }: CreateProjectLayoutProps) => {
const { orgSlug } = useParams(); const { orgSlug } = useParams();
const isDesktopView = useMediaQuery('(min-width: 720px)'); // md:
const closeBtnLink = `/${orgSlug}`; const closeBtnLink = `/${orgSlug}`;
@ -28,72 +31,69 @@ export const CreateProjectLayout = ({
</Heading> </Heading>
); );
return ( return isDesktopView ? (
<> // Desktop
{/* Desktop */} <section
<section {...props}
{...props} className={cn(
className={cn( 'dark:bg-background h-full flex-col hidden md:flex',
'dark:bg-background h-full flex-col hidden md:flex', className,
className, )}
)} >
> <div className="sticky top-0">
<div className="sticky top-0"> <div className="flex px-6 py-4 dark:bg-overlay bg-base-bg items-center gap-4">
<div className="flex px-6 py-4 dark:bg-overlay bg-base-bg items-center gap-4"> {heading}
{heading}
{/* Cannot save btn as variable since responsive variant don't work with compoundVariant */} {/* Cannot save btn as variable since responsive variant don't work with compoundVariant */}
<Link to={closeBtnLink}> <Link to={closeBtnLink}>
<Button <Button
iconOnly iconOnly
variant="primary" variant="primary"
leftIcon={<CrossIcon />} leftIcon={<CrossIcon />}
aria-label="close" aria-label="close"
/> />
</Link> </Link>
</div>
<WavyBorder />
</div> </div>
<WavyBorder />
<section className="px-6 h-full flex-1 py-6 overflow-y-auto"> </div>
<Outlet /> <section className="px-6 h-full flex-1 py-6 overflow-y-auto">
</section> <Outlet />
</section> </section>
</section>
) : (
// Mobile
// Setting modal={false} so even if modal is active on desktop, it doesn't block clicks
<Dialog.Root modal={false} open={true}>
<Dialog.Portal>
{/* Not using <Dialog.Overlay> since modal={false} disables it and its content will not show */}
<div className="bg-base-canvas fixed inset-0 md:hidden overflow-y-auto p-1">
<Dialog.Content className="min-h-full overflow-hidden rounded-2xl bg-base-bg shadow-card focus:outline-none">
{/* Heading */}
<div className="flex px-6 py-4 h-20 items-center gap-4">
{heading}
<Dialog.Close asChild>
<Link to={closeBtnLink}>
<Button
iconOnly
variant="tertiary"
leftIcon={<CrossIcon />}
aria-label="close"
size="sm"
/>
</Link>
</Dialog.Close>
</div>
{/* Mobile */} {/* Border */}
{/* Setting modal={false} so even if modal is active on desktop, it doesn't block clicks */} <WavyBorder />
<Dialog.Root modal={false} open={true}>
<Dialog.Portal>
{/* Not using <Dialog.Overlay> since modal={false} disables it and its content will not show */}
<div className="bg-base-canvas fixed inset-0 md:hidden overflow-y-auto p-1">
<Dialog.Content className="min-h-full overflow-hidden rounded-2xl bg-base-bg shadow-card focus:outline-none">
{/* Heading */}
<div className="flex px-6 py-4 h-20 items-center gap-4">
{heading}
<Dialog.Close asChild>
<Link to={closeBtnLink}>
<Button
iconOnly
variant="tertiary"
leftIcon={<CrossIcon />}
aria-label="close"
size="sm"
/>
</Link>
</Dialog.Close>
</div>
{/* Border */} {/* Page content */}
<WavyBorder /> <div className="px-4 py-6">
<Outlet />
{/* Page content */} </div>
<div className="px-4 py-6"> </Dialog.Content>
<Outlet /> </div>
</div> </Dialog.Portal>
</Dialog.Content> </Dialog.Root>
</div>
</Dialog.Portal>
</Dialog.Root>
</>
); );
}; };

View File

@ -1,40 +1,55 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Link, useNavigate, useOutletContext } from 'react-router-dom'; import {
Link,
useOutletContext,
} from 'react-router-dom';
import { RequestError } from 'octokit'; import { RequestError } from 'octokit';
import { useOctokit } from 'context/OctokitContext'; import {
import { GitCommitWithBranch, OutletContextType } from '../../../../types'; Heading,
import { useGQLClient } from 'context/GQLClientContext'; Avatar,
import { Button, Heading, Avatar, Tag } from 'components/shared'; } from 'components/shared';
import { getInitials } from 'utils/geInitials';
import { import {
BranchStrokeIcon, BranchStrokeIcon,
CheckRoundFilledIcon,
ClockIcon,
CursorBoxIcon, CursorBoxIcon,
GithubStrokeIcon, GithubStrokeIcon,
GlobeIcon,
LinkIcon, LinkIcon,
CalendarDaysIcon, CalendarDaysIcon,
} from 'components/shared/CustomIcon'; } 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 { Activity } from 'components/projects/project/overview/Activity';
import { OverviewInfo } from 'components/projects/project/overview/OverviewInfo'; import { OverviewInfo } from 'components/projects/project/overview/OverviewInfo';
import { relativeTimeMs } from 'utils/time'; import { relativeTimeMs } from 'utils/time';
import { Domain, DomainStatus } from 'gql-client';
import { AuctionCard } from 'components/projects/project/overview/Activity/AuctionCard'; 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';
const COMMITS_PER_PAGE = 4; const COMMITS_PER_PAGE = 4;
const PROJECT_UPDATE_WAIT_MS = 5000;
const OverviewTabPanel = () => { const OverviewTabPanel = () => {
const { octokit } = useOctokit(); const { octokit } = useOctokit();
const navigate = useNavigate(); // const navigate = useNavigate();
const [activities, setActivities] = useState<GitCommitWithBranch[]>([]); const [activities, setActivities] = useState<GitCommitWithBranch[]>([]);
const [fetchingActivities, setFetchingActivities] = useState(true); const [fetchingActivities, setFetchingActivities] = useState(true);
const [liveDomain, setLiveDomain] = useState<Domain>(); // const [liveDomain, setLiveDomain] = useState<Domain>();
const client = useGQLClient(); // const client = useGQLClient();
const { project, onUpdate } = useOutletContext<OutletContextType>();
const { project } = useOutletContext<OutletContextType>();
useEffect(() => { useEffect(() => {
setFetchingActivities(true); setFetchingActivities(true);
@ -96,24 +111,33 @@ const OverviewTabPanel = () => {
}; };
fetchRepoActivity(); fetchRepoActivity();
}, [octokit, project]); }, [project.repository]);
useEffect(() => { useEffect(() => {
const fetchLiveProdDomain = async () => { onUpdate();
const { domains } = await client.getDomains(project.id, { const timerId = setInterval(() => {
branch: project.prodBranch, onUpdate();
status: DomainStatus.Live, }, PROJECT_UPDATE_WAIT_MS);
});
if (domains.length === 0) { return () => clearInterval(timerId);
return; }, [onUpdate]);
}
setLiveDomain(domains[0]); // useEffect(() => {
}; // const fetchLiveProdDomain = async () => {
// const { domains } = await client.getDomains(project.id, {
// branch: project.prodBranch,
// status: DomainStatus.Live,
// });
fetchLiveProdDomain(); // if (domains.length === 0) {
}, [project]); // return;
// }
// setLiveDomain(domains[0]);
// };
// fetchLiveProdDomain();
// }, [project]);
return ( return (
<div className="grid grid-cols-5 gap-6 md:gap-[72px]"> <div className="grid grid-cols-5 gap-6 md:gap-[72px]">
@ -132,19 +156,16 @@ const OverviewTabPanel = () => {
{project.deployments && {project.deployments &&
project.deployments.length > 0 && project.deployments.length > 0 &&
project.deployments.map((deployment, index) => ( project.deployments.map((deployment, index) => (
<p> <p
<a key={index}
key={index} className="text-sm text-elements-low-em dark:text-foreground tracking-tight truncate"
href={`https://${project.name.toLowerCase()}.${deployment.deployer.baseDomain}`} >
className="text-sm text-elements-low-em dark:text-foreground tracking-tight truncate" {deployment.deployer.baseDomain}
>
{deployment.deployer.baseDomain}
</a>
</p> </p>
))} ))}
</div> </div>
</div> </div>
<OverviewInfo label="Domain" icon={<GlobeIcon />}> {/* <OverviewInfo label="Domain" icon={<GlobeIcon />}>
{liveDomain ? ( {liveDomain ? (
<Tag type="positive" size="xs" leftIcon={<CheckRoundFilledIcon />}> <Tag type="positive" size="xs" leftIcon={<CheckRoundFilledIcon />}>
Connected Connected
@ -165,7 +186,7 @@ const OverviewTabPanel = () => {
</Button> </Button>
</div> </div>
)} )}
</OverviewInfo> </OverviewInfo> */}
{project.deployments.length !== 0 ? ( {project.deployments.length !== 0 ? (
<> <>
{/* SOURCE */} {/* SOURCE */}
@ -184,11 +205,9 @@ const OverviewTabPanel = () => {
project.deployments.length > 0 && project.deployments.length > 0 &&
project.deployments.map((deployment) => ( project.deployments.map((deployment) => (
<div className="flex gap-2 items-center"> <div className="flex gap-2 items-center">
<Link <Link to={deployment.applicationDeploymentRecordData.url}>
to={`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"> <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">
{`https://${project.name.toLowerCase()}.${deployment.deployer.baseDomain}`} {deployment.applicationDeploymentRecordData.url}
<LinkIcon className="group-hover:rotate-45 transition-transform" /> <LinkIcon className="group-hover:rotate-45 transition-transform" />
</span> </span>
</Link> </Link>

View File

@ -10,7 +10,7 @@ import {
} from 'components/shared/Tabs'; } from 'components/shared/Tabs';
import { import {
BranchStrokeIcon, BranchStrokeIcon,
CollaboratorsIcon, //CollaboratorsIcon,
GearIcon, GearIcon,
GlobeIcon, GlobeIcon,
SwitchIcon, SwitchIcon,
@ -37,11 +37,11 @@ const tabsData = [
icon: <SwitchIcon />, icon: <SwitchIcon />,
value: 'environment-variables', value: 'environment-variables',
}, },
{ // {
label: 'Collaborators', // label: 'Collaborators',
icon: <CollaboratorsIcon />, // icon: <CollaboratorsIcon />,
value: 'collaborators', // value: 'collaborators',
}, // },
]; ];
const SettingsTabPanel = () => { const SettingsTabPanel = () => {

View File

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

View File

@ -73,17 +73,17 @@ const EnvironmentVariablesForm = () => {
<div className="flex gap-2 p-2"> <div className="flex gap-2 p-2">
<Checkbox <Checkbox
label="Production" label="Production"
labelProps={{ className: "text-gray-900 dark:text-white" }} labelProps={{ className: 'text-gray-900 dark:text-white' }}
{...register('environment.production')} {...register('environment.production')}
/> />
<Checkbox <Checkbox
label="Preview" label="Preview"
labelProps={{ className: "text-gray-900 dark:text-white" }} labelProps={{ className: 'text-gray-900 dark:text-white' }}
{...register('environment.preview')} {...register('environment.preview')}
/> />
<Checkbox <Checkbox
label="Development" label="Development"
labelProps={{ className: "text-gray-900 dark:text-white" }} labelProps={{ className: 'text-gray-900 dark:text-white' }}
{...register('environment.development')} {...register('environment.development')}
/> />
</div> </div>

View File

@ -18,7 +18,6 @@ const GeneralTabPanel = () => {
const client = useGQLClient(); const client = useGQLClient();
const { toast } = useToast(); const { toast } = useToast();
const { project, onUpdate } = useOutletContext<OutletContextType>(); const { project, onUpdate } = useOutletContext<OutletContextType>();
console.log(project);
const [transferOrganizations, setTransferOrganizations] = useState< const [transferOrganizations, setTransferOrganizations] = useState<
SelectOption[] SelectOption[]

View File

@ -7,6 +7,8 @@ import { InlineNotification } from 'components/shared/InlineNotification';
import { ArrowRightCircleIcon } from 'components/shared/CustomIcon'; import { ArrowRightCircleIcon } from 'components/shared/CustomIcon';
import { ProjectSettingContainer } from 'components/projects/project/settings/ProjectSettingContainer'; import { ProjectSettingContainer } from 'components/projects/project/settings/ProjectSettingContainer';
import { useToast } from 'components/shared/Toast'; import { useToast } from 'components/shared/Toast';
import { useEffect, useState } from 'react';
import { DNSRecordAttributes } from 'gql-client';
const Config = () => { const Config = () => {
const { id, orgSlug } = useParams(); const { id, orgSlug } = useParams();
@ -16,6 +18,8 @@ const Config = () => {
const primaryDomainName = searchParams.get('name'); const primaryDomainName = searchParams.get('name');
const { toast, dismiss } = useToast(); const { toast, dismiss } = useToast();
const [dnsRecord, setDnsRecord] = useState<DNSRecordAttributes | null>(null);
const handleSubmitDomain = async () => { const handleSubmitDomain = async () => {
if (primaryDomainName === null) { if (primaryDomainName === null) {
toast({ toast({
@ -59,54 +63,80 @@ const Config = () => {
} }
}; };
useEffect(() => {
const fetchDNSData = async () => {
if (id === undefined) {
toast({
id: 'domain_cannot_find_project',
title: 'Cannot find project',
variant: 'error',
onDismiss: dismiss,
});
return;
}
const dnsRecordResponse = await client.getLatestDNSRecordByProjectId(id);
setDnsRecord(dnsRecordResponse.latestDNSRecord);
};
fetchDNSData();
}, [id, client]);
// TODO: Figure out DNS Provider if possible and update appropriatly // TODO: Figure out DNS Provider if possible and update appropriatly
return ( return (
<ProjectSettingContainer headingText="Setup domain name"> <ProjectSettingContainer headingText="Setup domain name">
<p className="text-blue-gray-500"> {dnsRecord ? (
Add the following records to your domain.&nbsp; <>
<a href="https://www.namecheap.com/" target="_blank" rel="noreferrer"> <p className="text-blue-gray-500">
<span className="underline">Go to NameCheap</span> Add the following records to your domain.
</a> </p>
</p>
<Table> <Table>
<Table.Header> <Table.Header>
<Table.Row> <Table.Row>
<Table.ColumnHeaderCell>Type</Table.ColumnHeaderCell> <Table.ColumnHeaderCell>Type</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>Host</Table.ColumnHeaderCell> <Table.ColumnHeaderCell>Host</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>Value</Table.ColumnHeaderCell> <Table.ColumnHeaderCell>Value</Table.ColumnHeaderCell>
</Table.Row> </Table.Row>
</Table.Header> </Table.Header>
<Table.Body> <Table.Body>
<Table.Row> <Table.Row>
<Table.RowHeaderCell>A</Table.RowHeaderCell> <Table.RowHeaderCell>
<Table.Cell>@</Table.Cell> {dnsRecord.resourceType}
<Table.Cell>56.49.19.21</Table.Cell> </Table.RowHeaderCell>
</Table.Row> <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.Row> {dnsRecord?.value && (
<Table.RowHeaderCell>CNAME</Table.RowHeaderCell> <InlineNotification
<Table.Cell>www</Table.Cell> variant="info"
<Table.Cell>cname.snowballtools.xyz</Table.Cell> title={`It can take up to 48 hours for these updates to reflect
</Table.Row> globally.`}
</Table.Body> />
</Table> )}
<Button
<InlineNotification className="w-fit"
variant="info" disabled={!dnsRecord?.value}
title={`It can take up to 48 hours for these updates to reflect onClick={handleSubmitDomain}
globally.`} variant="primary"
/> shape="default"
<Button rightIcon={<ArrowRightCircleIcon />}
className="w-fit" >
onClick={handleSubmitDomain} FINISH
variant="primary" </Button>
shape="default" </>
rightIcon={<ArrowRightCircleIcon />} ) : (
> <p className={'text-red-500'}>DNS record data not available</p>
FINISH )}
</Button>
</ProjectSettingContainer> </ProjectSettingContainer>
); );
}; };

View File

@ -49,9 +49,6 @@ const AddDomain = () => {
<div className=" w-2/3 mx-auto"> <div className=" w-2/3 mx-auto">
<div className="bg-blue-gray-50 dark:bg-overlay rounded-lg mt-6 mb-10"> <div className="bg-blue-gray-50 dark:bg-overlay rounded-lg mt-6 mb-10">
<div className="flex justify-start gap-3 p-5"> <div className="flex justify-start gap-3 p-5">
<i className="bg-gray-100 dark:bg-overlay dark:text-foreground w-12 h-12 rounded-lg">
^
</i>
<Typography <Typography
className="my-auto w-1/3 dark:text-foreground" className="my-auto w-1/3 dark:text-foreground"
variant="h5" variant="h5"

View File

@ -12,6 +12,7 @@ import {
Domain, Domain,
Environment, Environment,
Permission, Permission,
AppDeploymentRecordAttributes,
} from 'gql-client'; } from 'gql-client';
export const user: User = { export const user: User = {
@ -99,7 +100,6 @@ export const deployment0: Deployment = {
environment: Environment.Development, environment: Environment.Development,
isCurrent: true, isCurrent: true,
commitHash: 'Commit Hash', commitHash: 'Commit Hash',
domain: domain0,
commitMessage: 'Commit Message', commitMessage: 'Commit Message',
createdBy: user, createdBy: user,
deployer: { deployer: {
@ -111,6 +111,7 @@ export const deployment0: Deployment = {
}, },
applicationDeploymentRequestId: applicationDeploymentRequestId:
'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize', 'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize',
applicationDeploymentRecordData: {} as AppDeploymentRecordAttributes,
}; };
export const project: Project = { export const project: Project = {

View File

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

View File

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

View File

@ -453,4 +453,15 @@ export class GQLClient {
return data.verifyTx; return data.verifyTx;
} }
async getLatestDNSRecordByProjectId(projectId: string): Promise<types.GetLatestDNSDataResponse> {
const { data } = await this.client.query({
query: queries.getLatestDNSRecordByProjectId,
variables: {
projectId,
},
});
return data;
}
} }

View File

@ -57,17 +57,12 @@ query ($projectId: String!) {
commitHash commitHash
createdAt createdAt
environment environment
applicationDeploymentRecordData {
url
}
deployer { deployer {
baseDomain baseDomain
} }
domain {
status
branch
createdAt
updatedAt
id
name
}
createdBy { createdBy {
id id
name name
@ -112,13 +107,8 @@ query ($organizationSlug: String!) {
commitMessage commitMessage
createdAt createdAt
environment environment
domain { applicationDeploymentRecordData {
status url
branch
createdAt
updatedAt
id
name
} }
} }
} }
@ -141,14 +131,6 @@ export const getDeployments = gql`
query ($projectId: String!) { query ($projectId: String!) {
deployments(projectId: $projectId) { deployments(projectId: $projectId) {
id id
domain{
branch
createdAt
id
name
status
updatedAt
}
branch branch
commitHash commitHash
commitMessage commitMessage
@ -343,3 +325,15 @@ query ($txHash: String!, $amount: String!, $senderAddress: String!) {
verifyTx(txHash: $txHash, amount: $amount, senderAddress: $senderAddress) verifyTx(txHash: $txHash, amount: $amount, senderAddress: $senderAddress)
} }
`; `;
export const getLatestDNSRecordByProjectId = gql`
query($projectId: String!) {
latestDNSRecord(projectId: $projectId) {
name
value
request
resourceType
version
}
}
`;

View File

@ -99,7 +99,6 @@ export type User = {
export type Deployment = { export type Deployment = {
id: string; id: string;
domain: Domain;
branch: string; branch: string;
commitHash: string; commitHash: string;
commitMessage: string; commitMessage: string;
@ -108,6 +107,7 @@ export type Deployment = {
environment: Environment; environment: Environment;
isCurrent: boolean; isCurrent: boolean;
baseDomain?: string; baseDomain?: string;
applicationDeploymentRecordData: AppDeploymentRecordAttributes;
status: DeploymentStatus; status: DeploymentStatus;
createdBy: User; createdBy: User;
createdAt: string; createdAt: string;
@ -376,3 +376,28 @@ export type AuctionParams = {
maxPrice: string; maxPrice: string;
numProviders: number; numProviders: number;
}; };
export type DNSRecordAttributes = {
name: string;
value: string;
request: string;
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;
}

1162
yarn.lock

File diff suppressed because it is too large Load Diff