Compare commits

...
58 Commits
Author SHA1 Message Date
IshaVenikar 59329c18f6 Update method to rollback deployment 2025-02-03 19:33:40 +05:30
Shreerang Kale 8553c30b0d Update comment note 2025-02-03 19:04:41 +05:30
IshaVenikar b409d43e51 Update flow for deleting deployments 2025-02-03 17:49:06 +05:30
Shreerang Kale b50efe315b Remove hyperlink from deployer base domains 2025-02-03 17:14:49 +05:30
IshaVenikar ced815802e Update deployment request config value if not env variables are set 2025-02-03 16:40:03 +05:30
Shreerang Kale 22bb409617 Add check for while accessing project URL 2025-02-03 15:47:06 +05:30
IshaVenikar 8322f877c0 Fix check for old DNS deployment 2025-02-03 15:40:05 +05:30
Shreerang Kale fd38127cb5 Update query to get latest DNS record 2025-02-03 13:39:58 +05:30
Shreerang Kale b6084008b8 Remove unused GQL methods 2025-02-03 13:28:35 +05:30
IshaVenikar d1e6171874 Send DNS deployment removal request on changing custom domain 2025-02-03 13:26:26 +05:30
Shreerang Kale ce56a4dc29 Update UI when DNS record is not present 2025-02-03 11:54:16 +05:30
IshaVenikar c685b7d5b1 Rename method for getting commit deployments by Id 2025-02-03 11:15:19 +05:30
IshaVenikar 32001b3d5a Set types for fetched registry records 2025-02-03 10:47:45 +05:30
IshaVenikar 6f32ea4da8 Update comments for update deployment data flow 2025-02-03 10:30:26 +05:30
Shreerang Kale a16b44b43a Rename Latest DNS response type 2025-02-03 10:10:19 +05:30
IshaVenikar a17386eb68 Update method name to get record by Id 2025-02-03 09:23:03 +05:30
Shreerang Kale f318a95641 Fix custom domain not showing up in UI 2025-02-03 09:23:03 +05:30
Shreerang Kale e9f746cd8b Revert removing order while getting latest DNS data 2025-02-03 09:23:03 +05:30
IshaVenikar e59c14440c Fix check for setting isCurrent 2025-02-03 09:23:03 +05:30
IshaVenikar 22f8a8c943 Update method to return single DNS record by ID 2025-02-03 09:23:03 +05:30
IshaVenikar df5062c75f Remove ununsed imports 2025-02-03 09:23:03 +05:30
Shreerang Kale 22e814840e Fix method to get latest DNS data 2025-02-03 09:23:03 +05:30
IshaVenikar 9d27dd568a Update isCurrent status for commit deployments 2025-02-03 09:23:03 +05:30
Shreerang Kale fc62392c83 Update methods for using stored DNS deployments in UI 2025-02-03 09:23:03 +05:30
IshaVenikar 2ee65b8fd8 Remove ununsed variables 2025-02-03 09:23:03 +05:30
IshaVenikar d0302d0153 Store domain for DNS deployments after previous deployment is deleted 2025-02-03 09:23:03 +05:30
Shreerang Kale 90e9260eb6 Update UI when IP address is unavailable and project is created via auctions 2025-02-03 09:23:03 +05:30
IshaVenikar 6dcee29487 Update flow for deleting deployments 2025-02-03 09:23:03 +05:30
IshaVenikar 5be10b6b0a Implement functionality to store DNS deployment 2025-02-03 09:23:01 +05:30
Shreerang Kale 6e8af82dc2 Make service provider domains non clickable 2025-02-03 09:18:14 +05:30
Shreerang Kale 1a5ab4d47e Remove showing domain status in overview pannel 2025-02-03 09:18:14 +05:30
Shreerang Kale 6df685831f Populate domainId while creating deployment 2025-02-03 09:18:14 +05:30
IshaVenikar 13892015a5 Store DNS deployment records data in Deployment entity 2025-02-03 09:18:14 +05:30
Shreerang Kale 55500b5914 Display custom domain in project card 2025-02-03 09:18:14 +05:30
Shreerang Kale a7190ed804 Show custom domain in overview tabs panel 2025-02-03 09:18:14 +05:30
Shreerang Kale 6a79ee5c47 Remove UI elements for domain verification 2025-02-03 09:18:14 +05:30
Shreerang Kale f2ba931961 Update method to show IP address 2025-02-03 09:18:14 +05:30
IshaVenikar 85b4265fbe Query DNS records by Id 2025-02-03 09:18:14 +05:30
Shreerang Kale 63223a4807 Get DNS records for all completed deployments 2025-02-03 09:18:14 +05:30
Shreerang Kale 9784eb4f4a Fix DNS records data not getting stored in the DB 2025-02-03 09:18:14 +05:30
Shreerang Kale 624f36155a Fix deploy button disabled for deployers with no min payment 2025-02-03 09:18:14 +05:30
IshaVenikar 82c4b71694 Use oldest custom domain in deployment requests 2025-02-03 09:18:14 +05:30
Shreerang Kale 5d9c965f54 Show service provider IP address while creating custom domain 2025-02-03 09:18:14 +05:30
IshaVenikar 56eccb48b3 Add method to fetch DNS data for latest deployment 2025-02-03 09:18:14 +05:30
Shreerang Kale b5762432e6 Remove redirect domain from edit domain form 2025-02-03 09:18:14 +05:30
Shreerang Kale 4ae4670dca Remove redirect domain creation while adding custom domain 2025-02-03 09:18:14 +05:30
IshaVenikar c202554002 Store DNS record data for deployments 2025-02-03 09:18:14 +05:30
nabarunandIshaVenikar 534871a7ae Implement functionality to encrypt environment variables (#48)
Part of https://www.notion.so/Support-encrypted-config-for-deploy-laconic-com-18aa6b22d4728099bc64fc7a310b530d

Co-authored-by: IshaVenikar <ishavenikar7@gmail.com>
Reviewed-on: cerc-io/snowballtools-base#48
2025-01-30 09:44:18 +00:00
17640d3133 Copy updates (#38)
Co-authored-by: zramsay <zach@bluecollarcoding.ca>
Co-authored-by: Nabarun <nabarun@deepstacksoft.com>
Reviewed-on: cerc-io/snowballtools-base#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
nabarun bba0b57bed Keep records directory for deploy-frontend script (#43)
Part of [Service provider auctions for web deployments](https://www.notion.so/Service-provider-auctions-for-web-deployments-104a6b22d47280dbad51d28aa3a91d75)

Reviewed-on: cerc-io/snowballtools-base#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)
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: cerc-io/snowballtools-base#42
Co-authored-by: Nabarun <nabarun@deepstacksoft.com>
Co-committed-by: Nabarun <nabarun@deepstacksoft.com>
2024-11-13 13:32:27 +00:00
nabarunandIshaVenikar b61682dd20 Fix fetching build logs for redeployments (#39)
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: cerc-io/snowballtools-base#39
2024-11-12 15:18:07 +00:00
nabarun bcb6ac241b Fix template tab in GitHub connect page (#41)
Part of cerc-io/snowballtools-base#40 and [Service provider auctions for web deployments](https://www.notion.so/Service-provider-auctions-for-web-deployments-104a6b22d47280dbad51d28aa3a91d75)

Reviewed-on: cerc-io/snowballtools-base#41
Co-authored-by: Nabarun <nabarun@deepstacksoft.com>
Co-committed-by: Nabarun <nabarun@deepstacksoft.com>
2024-11-12 14:21:10 +00:00
zramsay 4a9f517d85 Merge pull request 'fix: colors for project template cards' (#37) from zach/ui-fixes into main
Reviewed-on: cerc-io/snowballtools-base#37
2024-11-06 19:27:32 +00:00
cfbender 6d1135645b fix: colors for project template cards 2024-11-06 14:16:23 -05:00
nabarunandIsha e5748e768c Fix check boxes in environment variables form (#36)
Part of [Service provider auctions for web deployments](https://www.notion.so/Service-provider-auctions-for-web-deployments-104a6b22d47280dbad51d28aa3a91d75)

![image](/attachments/0d90877d-86c7-4e3a-94c9-3c0d480f8b8c)

Co-authored-by: Isha <ishavenikar7@gmail.com>
Reviewed-on: cerc-io/snowballtools-base#36
2024-11-06 13:11:03 +00:00
prathameshandAdw8 9158e3a840 Add a CI workflow to deploy frontend (#35)
Part of [Service provider auctions for web deployments](https://www.notion.so/Service-provider-auctions-for-web-deployments-104a6b22d47280dbad51d28aa3a91d75)

Co-authored-by: Adw8 <adwaitgharpure@gmail.com>
Reviewed-on: cerc-io/snowballtools-base#35
Co-authored-by: Prathamesh Musale <prathamesh.musale0@gmail.com>
Co-committed-by: Prathamesh Musale <prathamesh.musale0@gmail.com>
2024-11-06 09:20:01 +00:00
nabarunandIsha 8bd1e17fd2 Add template for NextJS app (#34)
Part of [Service provider auctions for web deployments](https://www.notion.so/Service-provider-auctions-for-web-deployments-104a6b22d47280dbad51d28aa3a91d75)

- Add hotfix for updating old DB with new org slug
- Add remove-deployment script (for debugging)
- Part of cerc-io/snowballtools-base#28
![image](/attachments/ceb0d4d6-4fa7-4914-ad18-c57d9d0f5b95)

Co-authored-by: Isha <ishavenikar7@gmail.com>
Reviewed-on: cerc-io/snowballtools-base#34
Co-authored-by: Nabarun <nabarun@deepstacksoft.com>
Co-committed-by: Nabarun <nabarun@deepstacksoft.com>
2024-11-06 07:26:53 +00:00
60 changed files with 1499 additions and 986 deletions
+61
View File
@@ -0,0 +1,61 @@
name: Deploy Snowball frontend
on:
push:
branches:
- main
env:
REGISTRY_USER_KEY: ${{ secrets.REGISTRY_USER_KEY }}
REGISTRY_BOND_ID: ${{ secrets.REGISTRY_BOND_ID }}
DEPLOYER_LRN: lrn://vaasl-provider/deployers/webapp-deployer-api.apps.vaasl.io
AUTHORITY: laconic-deploy
jobs:
deploy:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20.x]
steps:
- name: Check out repository
uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- name: Download yarn
run: |
curl -fsSL -o /usr/local/bin/yarn https://github.com/yarnpkg/yarn/releases/download/v1.22.21/yarn-1.22.21.js
chmod +x /usr/local/bin/yarn
- name: Install dependencies
run: |
yarn install
- name: Set up environment
run: |
# Create a .env file with the necessary variables
echo "REGISTRY_BOND_ID=$REGISTRY_BOND_ID" > packages/deployer/.env
echo "DEPLOYER_LRN=$DEPLOYER_LRN" >> packages/deployer/.env
echo "AUTHORITY=$AUTHORITY" >> packages/deployer/.env
# Create a config file with necessary endpoints and secrets
cat > packages/deployer/config.yml <<EOF
services:
registry:
rpcEndpoint: https://laconicd-sapo.laconic.com
gqlEndpoint: https://laconicd-sapo.laconic.com/api
userKey: $REGISTRY_USER_KEY
bondId: $REGISTRY_BOND_ID
chainId: laconic-testnet-2
gasPrice: 0.001alnt
EOF
- name: Run deploy script
run: |
cd packages/deployer
./deploy-frontend.sh
+2
View File
@@ -14,8 +14,10 @@ VITE_SERVER_URL = 'LACONIC_HOSTED_CONFIG_server_url'
VITE_GITHUB_CLIENT_ID = 'LACONIC_HOSTED_CONFIG_github_clientid' 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_WALLET_CONNECT_ID = 'LACONIC_HOSTED_CONFIG_wallet_connect_id' 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'
+1
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",
+90 -5
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';
@@ -49,12 +50,25 @@ export class Database {
await this.dataSource.initialize(); await this.dataSource.initialize();
log('database initialized'); log('database initialized');
const organizations = await this.getOrganizations({}); let organizations = await this.getOrganizations({});
// Load an organization if none exist // Load an organization if none exist
if (!organizations.length) { if (!organizations.length) {
const orgEntities = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH)); const orgEntities = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH));
await loadAndSaveData(Organization, this.dataSource, [orgEntities[0]]); organizations = await loadAndSaveData(Organization, this.dataSource, [orgEntities[0]]);
}
// Hotfix for updating old DB data
if (organizations[0].slug === 'snowball-tools-1') {
const [orgEntity] = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH));
await this.updateOrganization(
organizations[0].id,
{
slug: orgEntity.slug as string,
name: orgEntity.name as string
}
)
} }
} }
@@ -121,6 +135,14 @@ export class Database {
return newUserOrganization; return newUserOrganization;
} }
async updateOrganization(organizationId: string, data: DeepPartial<Organization>): Promise<boolean> {
const organizationRepository = this.dataSource.getRepository(Organization);
const updateResult = await organizationRepository.update({ id: organizationId }, data);
assert(updateResult.affected);
return updateResult.affected > 0;
}
async getProjects(options: FindManyOptions<Project>): Promise<Project[]> { async getProjects(options: FindManyOptions<Project>): Promise<Project[]> {
const projectRepository = this.dataSource.getRepository(Project); const projectRepository = this.dataSource.getRepository(Project);
const projects = await projectRepository.find(options); const projects = await projectRepository.find(options);
@@ -136,7 +158,7 @@ export class Database {
.leftJoinAndSelect( .leftJoinAndSelect(
'project.deployments', 'project.deployments',
'deployments', 'deployments',
'deployments.isCurrent = true' 'deployments.isCurrent = true AND deployments.isDNS = true'
) )
.leftJoinAndSelect('deployments.createdBy', 'user') .leftJoinAndSelect('deployments.createdBy', 'user')
.leftJoinAndSelect('deployments.domain', 'domain') .leftJoinAndSelect('deployments.domain', 'domain')
@@ -181,7 +203,7 @@ export class Database {
.leftJoinAndSelect( .leftJoinAndSelect(
'project.deployments', 'project.deployments',
'deployments', 'deployments',
'deployments.isCurrent = true' 'deployments.isCurrent = true AND deployments.isDNS = true'
) )
.leftJoinAndSelect('deployments.domain', 'domain') .leftJoinAndSelect('deployments.domain', 'domain')
.leftJoin('project.projectMembers', 'projectMembers') .leftJoin('project.projectMembers', 'projectMembers')
@@ -229,6 +251,26 @@ export class Database {
}); });
} }
async getCommitDeploymentsByProjectId(projectId: string): Promise<Deployment[]> {
return this.getDeployments({
relations: {
project: true,
domain: true,
createdBy: true,
deployer: true,
},
where: {
project: {
id: projectId
},
isDNS: false
},
order: {
createdAt: 'DESC'
}
});
}
async getDeployment( async getDeployment(
options: FindOneOptions<Deployment> options: FindOneOptions<Deployment>
): Promise<Deployment | null> { ): Promise<Deployment | null> {
@@ -581,6 +623,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);
+3
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;
+8 -1
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',
@@ -126,6 +126,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 +141,10 @@ export class Deployment {
@Column('boolean', { default: false }) @Column('boolean', { default: false })
isCurrent!: boolean; isCurrent!: boolean;
// TODO: Rename field
@Column('boolean', { default: false })
isDNS!: boolean;
@Column({ @Column({
enum: DeploymentStatus enum: DeploymentStatus
}) })
+98 -57
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,18 @@ export class Registry {
); );
} }
/**
* Fetch record by Id
*/
async getRecordById(id: string): Promise<RegistryRecord | null> {
const record = await this.registry.getRecordsByIds([id]);
if (record.length === 0) {
return null;
}
return record[0];
}
async createApplicationDeploymentRemovalRequest(data: { async createApplicationDeploymentRemovalRequest(data: {
deploymentId: string; deploymentId: string;
deployerLrn: string; deployerLrn: string;
@@ -449,18 +440,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 +467,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 +534,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;
}
} }
+8 -1
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.getCommitDeploymentsByProjectId(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
+23
View File
@@ -108,6 +108,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 +250,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 +287,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!
+216 -64
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,12 +202,68 @@ export class Service {
if (!deployment.project) { if (!deployment.project) {
log(`Project ${deployment.projectId} not found`); log(`Project ${deployment.projectId} not found`);
return; return;
} else { }
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.applicationDeploymentRecordId = record.id;
deployment.applicationDeploymentRecordData = record.attributes; deployment.applicationDeploymentRecordData = record.attributes;
deployment.url = record.attributes.url; deployment.url = record.attributes.url;
deployment.status = DeploymentStatus.Ready; deployment.status = DeploymentStatus.Ready;
deployment.isCurrent = deployment.environment === Environment.Production; deployment.isCurrent = deployment.environment === Environment.Production;
deployment.dnsRecordData = dnsRecordData;
if (deployment.isDNS) {
const oldDNSDeployment = await this.db.getDeployment({
where: {
projectId: deployment.project.id,
deployer: deployment.deployer,
isDNS: true,
isCurrent: true,
},
relations: {
project: true,
deployer: true,
}
});
if (oldDNSDeployment) {
// Send removal request for the previous DNS deployment and delete DB entry
if (oldDNSDeployment.url !== deployment.url) {
await this.laconicRegistry.createApplicationDeploymentRemovalRequest({
deploymentId: oldDNSDeployment.applicationDeploymentRecordId!,
deployerLrn: oldDNSDeployment.deployer.deployerLrn,
auctionId: oldDNSDeployment.project.auctionId,
payment: oldDNSDeployment.project.txHash
});
}
await this.db.deleteDeploymentById(oldDNSDeployment.id);
}
// Update domain after the previous DNS deployment is deleted due to unique key constraint for domain
// Set the domain for the new current DNS deployment to the custom domain that was added for that project
const customDomain = await this.db.getOldestDomainByProjectId(deployment.project.id);
if (customDomain) {
deployment.domain = customDomain;
}
}
await this.db.updateDeploymentById(deployment.id, deployment); await this.db.updateDeploymentById(deployment.id, deployment);
@@ -223,28 +282,34 @@ export class Service {
log( log(
`Updated deployment ${deployment.id} with URL ${record.attributes.url}`, `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.isDNS == deployment.isDNS,
);
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 +493,14 @@ export class Service {
return dbProjects; return dbProjects;
} }
async getDeploymentsByProjectId(projectId: string): Promise<Deployment[]> { async getCommitDeploymentsByProjectId(projectId: string): Promise<Deployment[]> {
const dbDeployments = await this.db.getDeploymentsByProjectId(projectId); const commitDeployments = await this.db.getCommitDeploymentsByProjectId(projectId);
return dbDeployments; return commitDeployments;
}
async getLatestDNSRecordByProjectId(projectId: string): Promise<DNSRecordAttributes | null> {
const dnsDeployments = await this.db.getLatestDNSRecordByProjectId(projectId);
return dnsDeployments;
} }
async getEnvironmentVariablesByProjectId( async getEnvironmentVariablesByProjectId(
@@ -639,44 +709,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 dnsDeployment = await this.createDeploymentFromData(userId, data, deployer!.deployerLrn!, applicationRecordId, applicationRecordData, true);
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!);
// If a custom domain is present then use that as the DNS in the deployment request
const customDomain = await this.db.getOldestDomainByProjectId(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 // On deleting deployment later, project DNS deployment is also deleted
// So publish project DNS deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later // So publish project DNS deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later
const { applicationDeploymentRequestData, applicationDeploymentRequestId } =
await this.laconicRegistry.createApplicationDeploymentRequest({ await this.laconicRegistry.createApplicationDeploymentRequest({
deployment: newDeployment, deployment: dnsDeployment,
appName: repo, appName: repo,
repository: repoUrl, repository: repoUrl,
environmentVariables: environmentVariablesObj, environmentVariables: environmentVariablesObj,
dns: `${newDeployment.project.name}`, dns: customDomain?.name ?? `${dnsDeployment.project.name}`,
lrn: deployer!.deployerLrn!, lrn: deployer!.deployerLrn!,
apiUrl: deployer!.deployerApiUrl!,
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(dnsDeployment.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 +807,56 @@ 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 dnsDeployment = await this.createDeploymentFromData(project.ownerId!, deploymentData, deployerLrn, applicationRecordId, applicationRecordData, true);
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 // On deleting deployment later, project DNS deployment is also deleted
// So publish project DNS deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later // So publish project DNS deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later
const { applicationDeploymentRequestId, applicationDeploymentRequestData } =
await this.laconicRegistry.createApplicationDeploymentRequest({ await this.laconicRegistry.createApplicationDeploymentRequest({
deployment: newDeployment, deployment: dnsDeployment,
appName: repo, appName: repo,
repository: repoUrl, repository: repoUrl,
environmentVariables: environmentVariablesObj, environmentVariables: environmentVariablesObj,
dns: `${newDeployment.project.name}`, dns: `${dnsDeployment.project.name}`,
auctionId: project.auctionId!, auctionId: project.auctionId!,
lrn: deployerLrn, lrn: deployerLrn,
apiUrl: deployer!.deployerApiUrl!,
requesterAddress: address,
publicKey: deployer!.publicKey!
});
await this.db.updateDeploymentById(dnsDeployment.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 +865,7 @@ export class Service {
deployerLrn: string, deployerLrn: string,
applicationRecordId: string, applicationRecordId: string,
applicationRecordData: ApplicationRecord, applicationRecordData: ApplicationRecord,
isDNS: boolean,
): Promise<Deployment> { ): Promise<Deployment> {
const newDeployment = await this.db.addDeployment({ const newDeployment = await this.db.addDeployment({
project: data.project, project: data.project,
@@ -780,6 +883,7 @@ export class Service {
deployer: Object.assign(new Deployer(), { deployer: Object.assign(new Deployer(), {
deployerLrn, deployerLrn,
}), }),
isDNS
}); });
log(`Created deployment ${newDeployment.id}`); log(`Created deployment ${newDeployment.id}`);
@@ -1119,12 +1223,15 @@ export class Service {
const oldCurrentDeployment = await this.db.getDeployment({ const oldCurrentDeployment = await this.db.getDeployment({
relations: { relations: {
domain: true, domain: true,
project: true,
deployer: true,
}, },
where: { where: {
project: { project: {
id: projectId, id: projectId,
}, },
isCurrent: true, isCurrent: true,
isDNS: false,
}, },
}); });
@@ -1139,9 +1246,46 @@ export class Service {
const newCurrentDeploymentUpdate = await this.db.updateDeploymentById( const newCurrentDeploymentUpdate = await this.db.updateDeploymentById(
deploymentId, deploymentId,
{ isCurrent: true, domain: oldCurrentDeployment?.domain }, { isCurrent: true, domain: oldCurrentDeployment.domain },
); );
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`);
}
// Create a DNS deployment for the new current deployment
const dnsDeployment = await this.createDeploymentFromData(
newCurrentDeployment.project.ownerId,
newCurrentDeployment,
newCurrentDeployment.deployer!.deployerLrn!,
newCurrentDeployment.applicationRecordId,
newCurrentDeployment.applicationRecordData,
true,
);
const applicationDeploymentRequestData = newCurrentDeployment.applicationDeploymentRequestData;
applicationDeploymentRequestData!.version = (Number(applicationDeploymentRequestData?.version) + 1).toString();
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}`)
await this.db.updateDeploymentById(dnsDeployment.id, {
applicationDeploymentRequestId: result.id,
applicationDeploymentRequestData,
});
return newCurrentDeploymentUpdate && oldCurrentDeploymentUpdate; return newCurrentDeploymentUpdate && oldCurrentDeploymentUpdate;
} }
@@ -1159,32 +1303,38 @@ 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 dnsDeployment = await this.db.getDeployment({
where: {
projectId: deployment.project.id,
deployer: deployment.deployer,
isDNS: true
},
relations: {
project: true,
deployer: true,
},
})
// TODO: Store the latest DNS deployment record if (!dnsDeployment) {
const deploymentRecords = log(`DNS deployment for deployment with id ${deployment.id} not found`);
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; return false;
} }
// Multiple records are fetched, take the latest record const dnsResult =
const latestRecord = deploymentRecords
.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())[0];
await this.laconicRegistry.createApplicationDeploymentRemovalRequest({ await this.laconicRegistry.createApplicationDeploymentRemovalRequest({
deploymentId: latestRecord.id, deploymentId: dnsDeployment.applicationDeploymentRecordId!,
deployerLrn: deployment.deployer.deployerLrn, deployerLrn: dnsDeployment.deployer.deployerLrn,
auctionId: deployment.project.auctionId, auctionId: dnsDeployment.project.auctionId,
payment: deployment.project.txHash payment: dnsDeployment.project.txHash
});
await this.db.updateDeploymentById(dnsDeployment.id, {
status: DeploymentStatus.Deleting,
applicationDeploymentRemovalRequestId:
dnsResult.applicationDeploymentRemovalRequestId,
applicationDeploymentRemovalRequestData:
dnsResult.applicationDeploymentRemovalRequestData,
}); });
} }
@@ -1215,7 +1365,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 +1381,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 +1584,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 +1593,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
+21 -1
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;
@@ -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
View File
@@ -0,0 +1 @@
records/*.yml
+2 -2
View File
@@ -4,5 +4,5 @@ services:
gqlEndpoint: https://laconicd-sapo.laconic.com/api gqlEndpoint: https://laconicd-sapo.laconic.com/api
userKey: userKey:
bondId: bondId:
chainId: laconic_9000-2 chainId: laconic-testnet-2
gasPrice: 1alnt gasPrice: 0.001alnt
+14 -6
View File
@@ -8,8 +8,11 @@ echo "Using AUTHORITY: $AUTHORITY"
# Repository URL # Repository URL
REPO_URL="https://git.vdb.to/cerc-io/snowballtools-base" REPO_URL="https://git.vdb.to/cerc-io/snowballtools-base"
# Get the latest commit hash from the repository # Get the latest commit hash for a branch
LATEST_HASH=$(git ls-remote $REPO_URL HEAD | awk '{print $1}') BRANCH_NAME="main"
LATEST_HASH=$(git ls-remote $REPO_URL refs/heads/$BRANCH_NAME | awk '{print $1}')
echo "Latest commit hash for branch $BRANCH_NAME: $LATEST_HASH"
# Extract version from ../frontend/package.json # Extract version from ../frontend/package.json
PACKAGE_VERSION=$(jq -r '.version' ../frontend/package.json) PACKAGE_VERSION=$(jq -r '.version' ../frontend/package.json)
@@ -99,6 +102,9 @@ fi
# Get payment address for deployer # Get payment address for deployer
paymentAddress=$(yarn --silent laconic -c config.yml registry name resolve "$DEPLOYER_LRN" | jq -r '.[0].attributes.paymentAddress') paymentAddress=$(yarn --silent laconic -c config.yml registry name resolve "$DEPLOYER_LRN" | jq -r '.[0].attributes.paymentAddress')
paymentAmount=$(yarn --silent laconic -c config.yml registry name resolve "$DEPLOYER_LRN" | jq -r '.[0].attributes.minimumPayment' | sed 's/alnt//g') paymentAmount=$(yarn --silent laconic -c config.yml registry name resolve "$DEPLOYER_LRN" | jq -r '.[0].attributes.minimumPayment' | sed 's/alnt//g')
echo "Paying address: $paymentAddress with amount $paymentAmount..."
# Pay deployer if paymentAmount is not null # Pay deployer if paymentAmount is not null
if [[ -n "$paymentAmount" && "$paymentAmount" != "null" ]]; then if [[ -n "$paymentAmount" && "$paymentAmount" != "null" ]]; then
payment=$(yarn --silent laconic -c config.yml registry tokens send --address "$paymentAddress" --type alnt --quantity "$paymentAmount") payment=$(yarn --silent laconic -c config.yml registry tokens send --address "$paymentAddress" --type alnt --quantity "$paymentAmount")
@@ -119,17 +125,19 @@ record:
name: deploy-frontend@$PACKAGE_VERSION name: deploy-frontend@$PACKAGE_VERSION
application: lrn://$AUTHORITY/applications/deploy-frontend@$PACKAGE_VERSION application: lrn://$AUTHORITY/applications/deploy-frontend@$PACKAGE_VERSION
deployer: $DEPLOYER_LRN deployer: $DEPLOYER_LRN
dns: deploy dns: deploy.laconic.com
config: config:
env: env:
LACONIC_HOSTED_CONFIG_server_url: https://deploy-backend.apps.vaasl.io LACONIC_HOSTED_CONFIG_server_url: https://deploy-backend.laconic.com
LACONIC_HOSTED_CONFIG_github_clientid: Ov23liaet4yc0KX0iM1c LACONIC_HOSTED_CONFIG_github_clientid: Ov23li4NtYybQlF6u5Dk
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_wallet_connect_id: 63cad7ba97391f63652161f484670e15 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 by Snowball @ $CURRENT_DATE_TIME note: Added @ $CURRENT_DATE_TIME
repository: "$REPO_URL" repository: "$REPO_URL"
repository_ref: $LATEST_HASH repository_ref: $LATEST_HASH
payment: $txHash payment: $txHash
@@ -1,5 +1,10 @@
#!/bin/bash #!/bin/bash
source .env
echo "Using REGISTRY_BOND_ID: $REGISTRY_BOND_ID"
echo "Using DEPLOYER_LRN: $DEPLOYER_LRN"
echo "Using AUTHORITY: $AUTHORITY"
# Repository URL # Repository URL
REPO_URL="https://git.vdb.to/cerc-io/snowballtools-base" REPO_URL="https://git.vdb.to/cerc-io/snowballtools-base"
@@ -12,63 +17,33 @@ PACKAGE_VERSION=$(jq -r '.version' ../frontend/package.json)
# Current date and time for note # Current date and time for note
CURRENT_DATE_TIME=$(date -u) CURRENT_DATE_TIME=$(date -u)
CONFIG_FILE=config.staging.yml CONFIG_FILE=config.yml
REGISTRY_BOND_ID="098c906850b87412f02200e41f449bc79e055eab77acfef32c0b22443bb46661"
# Reference: https://git.vdb.to/cerc-io/test-progressive-web-app/src/branch/main/scripts # Reference: https://git.vdb.to/cerc-io/test-progressive-web-app/src/branch/main/scripts
# Get latest version from registry and increment application-record version # Get latest version from registry and increment application-record version
NEW_APPLICATION_VERSION=$(yarn --silent laconic -c $CONFIG_FILE registry record list --type ApplicationRecord --all --name "staging-snowballtools-base-frontend" 2>/dev/null | jq -r -s ".[] | sort_by(.createTime) | reverse | [ .[] | select(.bondId == \"$REGISTRY_BOND_ID\") ] | .[0].attributes.version" | awk -F. -v OFS=. '{$NF += 1 ; print}') NEW_APPLICATION_VERSION=$(yarn --silent laconic -c $CONFIG_FILE registry record list --type ApplicationRecord --all --name "deploy-frontend" 2>/dev/null | jq -r -s ".[] | sort_by(.createTime) | reverse | [ .[] | select(.bondId == \"$REGISTRY_BOND_ID\") ] | .[0].attributes.version" | awk -F. -v OFS=. '{$NF += 1 ; print}')
if [ -z "$NEW_APPLICATION_VERSION" ] || [ "1" == "$NEW_APPLICATION_VERSION" ]; then if [ -z "$NEW_APPLICATION_VERSION" ] || [ "1" == "$NEW_APPLICATION_VERSION" ]; then
# Set application-record version if no previous records were found # Set application-record version if no previous records were found
NEW_APPLICATION_VERSION=0.0.1 NEW_APPLICATION_VERSION=0.0.1
fi fi
# Generate application-deployment-request.yml
cat >./staging-records/application-deployment-request.yml <<EOF
record:
type: ApplicationDeploymentRequest
version: '1.0.0'
name: staging-snowballtools-base-frontend@$PACKAGE_VERSION
application: lrn://staging-snowballtools/applications/staging-snowballtools-base-frontend@$PACKAGE_VERSION
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_wallet_connect_id: eda9ba18042a5ea500f358194611ece2
LACONIC_HOSTED_CONFIG_laconicd_chain_id: laconic-testnet-2
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 @ $CURRENT_DATE_TIME
repository: "$REPO_URL"
repository_ref: $LATEST_HASH
EOF
# Generate application-record.yml with incremented version # Generate application-record.yml with incremented version
cat >./staging-records/application-record.yml <<EOF cat >./records/application-record.yml <<EOF
record: record:
type: ApplicationRecord type: ApplicationRecord
version: $NEW_APPLICATION_VERSION version: $NEW_APPLICATION_VERSION
repository_ref: $LATEST_HASH repository_ref: $LATEST_HASH
repository: ["$REPO_URL"] repository: ["$REPO_URL"]
app_type: webapp app_type: webapp
name: staging-snowballtools-base-frontend name: deploy-frontend
app_version: $PACKAGE_VERSION app_version: $PACKAGE_VERSION
EOF EOF
echo "Files generated successfully." echo "Files generated successfully"
RECORD_FILE=staging-records/application-record.yml RECORD_FILE=records/application-record.yml
# Publish ApplicationRecord # Publish ApplicationRecord
publish_response=$(yarn --silent laconic -c $CONFIG_FILE registry record publish --filename $RECORD_FILE) publish_response=$(yarn --silent laconic -c $CONFIG_FILE registry record publish --filename $RECORD_FILE)
@@ -82,7 +57,7 @@ echo "ApplicationRecord published"
echo $RECORD_ID echo $RECORD_ID
# Set name to record # Set name to record
REGISTRY_APP_LRN="lrn://staging-snowballtools/applications/staging-snowballtools-base-frontend" REGISTRY_APP_LRN="lrn://$AUTHORITY/applications/deploy-frontend"
sleep 2 sleep 2
yarn --silent laconic -c $CONFIG_FILE registry name set "$REGISTRY_APP_LRN@${PACKAGE_VERSION}" "$RECORD_ID" yarn --silent laconic -c $CONFIG_FILE registry name set "$REGISTRY_APP_LRN@${PACKAGE_VERSION}" "$RECORD_ID"
@@ -121,7 +96,47 @@ if [ -z "$APP_RECORD" ] || [ "null" == "$APP_RECORD" ]; then
exit 1 exit 1
fi fi
RECORD_FILE=staging-records/application-deployment-request.yml # Get payment address for deployer
paymentAddress=$(yarn --silent laconic -c config.yml registry name resolve "$DEPLOYER_LRN" | jq -r '.[0].attributes.paymentAddress')
paymentAmount=$(yarn --silent laconic -c config.yml registry name resolve "$DEPLOYER_LRN" | jq -r '.[0].attributes.minimumPayment' | sed 's/alnt//g')
# Pay deployer if paymentAmount is not null
if [[ -n "$paymentAmount" && "$paymentAmount" != "null" ]]; then
payment=$(yarn --silent laconic -c config.yml registry tokens send --address "$paymentAddress" --type alnt --quantity "$paymentAmount")
# Extract the transaction hash
txHash=$(echo "$payment" | jq -r '.tx.hash')
echo "Paid deployer with txHash as $txHash"
else
echo "Payment amount is null; skipping payment."
fi
# Generate application-deployment-request.yml
cat >./records/application-deployment-request.yml <<EOF
record:
type: ApplicationDeploymentRequest
version: '1.0.0'
name: deploy-frontend@$PACKAGE_VERSION
application: lrn://$AUTHORITY/applications/deploy-frontend@$PACKAGE_VERSION
deployer: $DEPLOYER_LRN
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
LACONIC_HOSTED_CONFIG_laconicd_chain_id: laconic-testnet-2
meta:
note: Added by Snowball @ $CURRENT_DATE_TIME
repository: "$REPO_URL"
repository_ref: $LATEST_HASH
payment: $txHash
EOF
RECORD_FILE=records/application-deployment-request.yml
sleep 2 sleep 2
deployment_response=$(yarn --silent laconic -c $CONFIG_FILE registry record publish --filename $RECORD_FILE) deployment_response=$(yarn --silent laconic -c $CONFIG_FILE registry record publish --filename $RECORD_FILE)
View File
@@ -1,17 +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_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
@@ -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
+56
View File
@@ -0,0 +1,56 @@
#!/bin/bash
source .env
echo "Using DEPLOYER_LRN: $DEPLOYER_LRN"
# Generate application-deployment-removal-request.yml
REMOVAL_REQUEST_RECORD_FILE=records/application-deployment-removal-request.yml
# TODO: Pass deployment record ID as arg
DEPLOYMENT_RECORD_ID=bafyreidjho77xeczaqpyawhc4wbpm5it5atibtuxk6ost6vnpu2svlp3ka
cat > $REMOVAL_REQUEST_RECORD_FILE <<EOF
record:
deployer: $DEPLOYER_LRN
deployment: $DEPLOYMENT_RECORD_ID
type: ApplicationDeploymentRemovalRequest
version: 1.0.0
EOF
CONFIG_FILE=config.yml
sleep 2
REMOVAL_REQUEST_ID=$(yarn --silent laconic -c $CONFIG_FILE registry record publish --filename $REMOVAL_REQUEST_RECORD_FILE | jq -r '.id')
echo "ApplicationDeploymentRemovalRequest published"
echo $REMOVAL_REQUEST_ID
# Deployment checks
RETRY_INTERVAL=30
MAX_RETRIES=20
# Check that an ApplicationDeploymentRemovalRecord is published
retry_count=0
while true; do
removal_records_response=$(yarn --silent laconic -c $CONFIG_FILE registry record list --type ApplicationDeploymentRemovalRecord --all request $REMOVAL_REQUEST_ID)
len_removal_records=$(echo $removal_records_response | jq 'length')
# Check if number of records returned is 0
if [ $len_removal_records -eq 0 ]; then
# Check if retries are exhausted
if [ $retry_count -eq $MAX_RETRIES ]; then
echo "Retries exhausted"
echo "ApplicationDeploymentRemovalRecord for deployment removal request $REMOVAL_REQUEST_ID not found"
exit 1
else
echo "ApplicationDeploymentRemovalRecord not found, retrying in $RETRY_INTERVAL sec..."
sleep $RETRY_INTERVAL
retry_count=$((retry_count+1))
fi
else
echo "ApplicationDeploymentRemovalRecord found"
REMOVAL_RECORD_ID=$(echo $removal_records_response | jq -r '.[0].id')
echo $REMOVAL_RECORD_ID
break
fi
done
echo "Deployment removal successful"
@@ -1,24 +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_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
@@ -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
+2
View File
@@ -3,6 +3,7 @@ VITE_SERVER_URL='http://localhost:8000'
VITE_GITHUB_CLIENT_ID= VITE_GITHUB_CLIENT_ID=
VITE_GITHUB_PWA_TEMPLATE_REPO="snowball-tools/test-progressive-web-app" 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_WALLET_CONNECT_ID= VITE_WALLET_CONNECT_ID=
@@ -14,3 +15,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=
+6 -19
View File
@@ -1,13 +1,14 @@
import { import {
VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO, VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO,
VITE_GITHUB_PWA_TEMPLATE_REPO, VITE_GITHUB_PWA_TEMPLATE_REPO,
VITE_GITHUB_NEXT_APP_TEMPLATE_REPO,
} from 'utils/constants'; } from 'utils/constants';
export default [ export default [
{ {
id: '1', id: '1',
name: 'Progressive Web App (PWA)', name: 'Progressive Web App (PWA)',
icon: 'pwa', icon: 'web',
repoFullName: `${VITE_GITHUB_PWA_TEMPLATE_REPO}`, repoFullName: `${VITE_GITHUB_PWA_TEMPLATE_REPO}`,
isComingSoon: false, isComingSoon: false,
}, },
@@ -20,23 +21,9 @@ export default [
}, },
{ {
id: '3', id: '3',
name: 'Kotlin', name: 'Next.js + React + TailwindCSS',
icon: 'kotlin', icon: 'web',
repoFullName: '', repoFullName: `${VITE_GITHUB_NEXT_APP_TEMPLATE_REPO}`,
isComingSoon: true, isComingSoon: false,
},
{
id: '4',
name: 'React Native',
icon: 'react-native',
repoFullName: '',
isComingSoon: true,
},
{
id: '5',
name: 'Swift',
icon: 'swift',
repoFullName: '',
isComingSoon: true,
}, },
]; ];
@@ -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 ? (
@@ -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 */}
@@ -0,0 +1,60 @@
import {
Select,
Option,
Spinner,
} from '@snowballtools/material-tailwind-react-fork';
const AccountsDropdown = ({
accounts,
isDataReceived,
onAccountChange,
}: {
accounts: string[];
isDataReceived: boolean;
onAccountChange: (selectedAccount: string) => void;
}) => {
return (
<div className="p-6 bg-slate-100 dark:bg-overlay3 rounded-lg mb-6 shadow-md">
{isDataReceived ? (
!accounts.length ? (
<div className="text-center">
<p className="text-gray-700 dark:text-gray-300 mb-4">
No accounts found. Please visit{' '}
<a
href="https://store.laconic.com"
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 underline dark:text-blue-400"
>
store.laconic.com
</a>{' '}
to create a wallet.
</p>
</div>
) : (
<div>
<Select
label="Select Account"
defaultValue={accounts[0]}
onChange={(value) => value && onAccountChange(value)}
className="dark:bg-overlay2 dark:text-foreground"
aria-label="Wallet Account Selector"
>
{accounts.map((account, index) => (
<Option key={index} value={account}>
{account}
</Option>
))}
</Select>
</div>
)
) : (
<div className="flex items-center justify-center h-12">
<Spinner className="h-6 w-6" />
</div>
)}
</div>
);
};
export default AccountsDropdown;
@@ -20,10 +20,14 @@ 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 IFrameModal from './IFrameModal';
import EnvironmentVariablesForm from 'pages/org-slug/projects/id/settings/EnvironmentVariablesForm'; import EnvironmentVariablesForm from 'pages/org-slug/projects/id/settings/EnvironmentVariablesForm';
import { EnvironmentVariablesFormValues } from 'types/types'; import { EnvironmentVariablesFormValues } from 'types/types';
import ConnectWallet from './ConnectWallet'; import {
import { useWalletConnectClient } from 'context/WalletConnectContext'; VITE_LACONICD_CHAIN_ID,
VITE_WALLET_IFRAME_URL,
} from 'utils/constants';
import AccountsDropdown from './AccountsDropdown';
type ConfigureDeploymentFormValues = { type ConfigureDeploymentFormValues = {
option: string; option: string;
@@ -36,16 +40,18 @@ 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 [accounts, setAccounts] = useState<string[]>([]);
const [selectedDeployer, setSelectedDeployer] = useState<Deployer>(); const [selectedDeployer, setSelectedDeployer] = useState<Deployer>();
const [isPaymentLoading, setIsPaymentLoading] = useState(false); const [isPaymentLoading, setIsPaymentLoading] = useState(false);
const [isPaymentDone, setIsPaymentDone] = useState(false); const [isPaymentDone, setIsPaymentDone] = useState(false);
const [isFrameVisible, setIsFrameVisible] = useState(false);
const [isAccountsDataReceived, setIsAccountsDataReceived] = useState(false);
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const templateId = searchParams.get('templateId'); const templateId = searchParams.get('templateId');
@@ -182,7 +188,7 @@ const Configure = () => {
let amount: string; 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,7 +202,7 @@ const Configure = () => {
} else { } else {
if (!selectedAccount) return; if (!selectedAccount) return;
senderAddress = selectedAccount.split(':')[2]; senderAddress = selectedAccount;
if (createFormData.option === 'LRN') { if (createFormData.option === 'LRN') {
amount = deployer?.minimumPayment!; amount = deployer?.minimumPayment!;
@@ -208,27 +214,44 @@ const Configure = () => {
const amountToBePaid = amount.replace(/\D/g, '').toString(); const amountToBePaid = amount.replace(/\D/g, '').toString();
const txHashResponse = await cosmosSendTokensHandler( txHash = await cosmosSendTokensHandler(senderAddress, amountToBePaid);
selectedAccount,
amountToBePaid,
);
if (!txHashResponse) { if (!txHash) {
console.error('Tx not successful'); toast({
return; id: 'unsuccessful-tx',
title: 'Transaction rejected',
variant: 'error',
onDismiss: dismiss,
});
setIsFrameVisible(false);
setIsPaymentLoading(false);
throw new Error('Transaction rejected');
} }
txHash = txHashResponse; // Validate transaction hash
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 +271,7 @@ const Configure = () => {
createFormData, createFormData,
environmentVariables, environmentVariables,
senderAddress, senderAddress,
txHash, txHash!,
); );
await client.getEnvironmentVariables(projectId); await client.getEnvironmentVariables(projectId);
@@ -270,14 +293,14 @@ 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],
@@ -302,72 +325,95 @@ 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);
await requestTx(senderAddress, snowballAddress, amount);
const txHash = await new Promise<string | null>((resolve, reject) => {
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);
} else if (event.data.type === 'ERROR') {
console.error('Error from wallet:', event.data.message);
reject(new Error('Transaction failed'));
toast({ toast({
id: 'sending-payment-request', id: 'error-transaction',
title: 'Check your wallet and approve payment request', title: 'Error during transaction',
variant: 'loading',
onDismiss: dismiss,
});
const result: { signature: string } = await signClient.request({
topic: session.topic,
chainId: `cosmos:${chainId}`,
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', variant: 'error',
onDismiss: dismiss, onDismiss: dismiss,
}); });
}
setIsFrameVisible(false);
setIsPaymentDone(false); window.removeEventListener('message', handleTxStatus);
} finally { };
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); setIsPaymentLoading(false);
}, TX_APPROVAL_TIMEOUT_MS);
});
return txHash;
} catch (error) {
console.error('Error in transaction:', error);
throw new Error('Error in transaction');
} finally {
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();
}, []); }, []);
@@ -520,7 +566,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" />
@@ -534,10 +580,11 @@ const Configure = () => {
</div> </div>
) : ( ) : (
<> <>
<Heading as="h4" className="md:text-lg font-medium mb-3"> <AccountsDropdown
Connect to your wallet accounts={accounts}
</Heading> onAccountChange={onAccountChange}
<ConnectWallet onAccountChange={onAccountChange} /> isDataReceived={isAccountsDataReceived}
/>
{accounts.length > 0 && ( {accounts.length > 0 && (
<div> <div>
<Button <Button
@@ -569,6 +616,12 @@ const Configure = () => {
)} )}
</form> </form>
</FormProvider> </FormProvider>
<IFrameModal
setAccounts={setAccounts}
setIsDataReceived={setIsAccountsDataReceived}
isVisible={isFrameVisible}
/>
</div> </div>
</div> </div>
); );
@@ -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;
@@ -0,0 +1,88 @@
import { useCallback, useEffect } from 'react';
import { Box, Modal } from '@mui/material';
import {
VITE_LACONICD_CHAIN_ID,
VITE_WALLET_IFRAME_URL,
} from 'utils/constants';
const IFrameModal = ({
setAccounts,
setIsDataReceived,
isVisible,
}: {
setAccounts: (accounts: string[]) => void;
setIsDataReceived: (isReceived: boolean) => void;
isVisible: boolean;
}) => {
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
if (event.origin !== VITE_WALLET_IFRAME_URL) return;
setIsDataReceived(true);
if (event.data.type === 'WALLET_ACCOUNTS_DATA') {
setAccounts(event.data.data);
} else if (event.data.type === 'ERROR') {
console.error('Error from wallet:', event.data.message);
}
};
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 IFrameModal;
@@ -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,29 +48,6 @@ export const MockConnectGitCard = () => {
}, },
]; ];
const TEMPLATE_CONTENT = [
{
name: 'Web app',
icon: 'web',
},
{
name: 'Progressive Web App (PWA)',
icon: 'pwa',
},
{
name: 'React Native',
icon: 'react-native',
},
{
name: 'Kotlin',
icon: 'kotlin',
},
{
name: 'Swift',
icon: 'swift',
},
];
const renderContent = useMemo(() => { const renderContent = useMemo(() => {
if (segmentedControlsValue === 'import') { if (segmentedControlsValue === 'import') {
return ( return (
@@ -86,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>
@@ -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 (
@@ -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>
{dnsRecord ? (
<tr> <tr>
<td>{DOMAIN_RECORD.type}</td> <td>{dnsRecord.resourceType}</td>
<td>{DOMAIN_RECORD.name}</td> <td>@</td>
<td>{DOMAIN_RECORD.value}</td> <td>{dnsRecord.value ?? 'Not Configured'}</td>
</tr> </tr>
) : (
<p className={'text-red-500'}>DNS record data not available</p>
)}
</tbody> </tbody>
</table> </table>
</Card> </Card>
@@ -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 && (
@@ -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>
*/}
</> </>
); );
}; };
@@ -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">
@@ -1,19 +1,10 @@
import { useMemo } from 'react'; import { useMemo } from 'react';
import { CustomIconProps } from '../CustomIcon'; import { CustomIconProps } from '../CustomIcon';
import { ReactNativeIcon } from './ReactNativeIcon';
import { cloneIcon } from 'utils/cloneIcon'; import { cloneIcon } from 'utils/cloneIcon';
import { PWAIcon } from './PWAIcon'; import { PWAIcon } from './PWAIcon';
import { WebAppIcon } from './WebAppIcon'; import { WebAppIcon } from './WebAppIcon';
import { KotlinIcon } from './KotlinIcon';
import { SwitfIcon } from './SwiftIcon';
const TEMPLATE_ICONS = [ const TEMPLATE_ICONS = ['pwa', 'web'] as const;
'react-native',
'pwa',
'web',
'kotlin',
'swift',
] 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 {
@@ -23,16 +14,10 @@ export interface TemplateIconProps extends CustomIconProps {
export const TemplateIcon = ({ type, ...props }: TemplateIconProps) => { export const TemplateIcon = ({ type, ...props }: TemplateIconProps) => {
const renderIcon = useMemo(() => { const renderIcon = useMemo(() => {
switch (type) { switch (type) {
case 'react-native':
return <ReactNativeIcon />;
case 'pwa': case 'pwa':
return <PWAIcon />; return <PWAIcon />;
case 'web': case 'web':
return <WebAppIcon />; return <WebAppIcon />;
case 'kotlin':
return <KotlinIcon />;
case 'swift':
return <SwitfIcon />;
default: default:
throw new Error(`Invalid template icon type: ${type}`); throw new Error(`Invalid template icon type: ${type}`);
} }
@@ -92,10 +92,20 @@ export const Sidebar = ({ mobileOpen }: SidebarProps) => {
</a> </a>
</Tabs.Trigger> </Tabs.Trigger>
<Tabs.Trigger icon={<QuestionMarkRoundIcon />} value=""> <Tabs.Trigger icon={<QuestionMarkRoundIcon />} value="">
<a className="cursor-pointer font-mono">DOCUMENTATION</a> <a
className="cursor-pointer font-mono"
href="https://store.laconic.com/pages/instruction-faq"
>
DOCUMENTATION
</a>
</Tabs.Trigger> </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>
@@ -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>
);
};
@@ -17,7 +17,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { VITE_WALLET_CONNECT_ID, BASE_URL } from 'utils/constants'; import { VITE_WALLET_CONNECT_ID, BASE_URL } from 'utils/constants';
if (!VITE_WALLET_CONNECT_ID) { if (!VITE_WALLET_CONNECT_ID) {
throw new Error('Error: REACT_APP_WALLET_CONNECT_ID env config is not set'); throw new Error('Error: VITE_WALLET_CONNECT_ID env config is not set');
} }
assert(BASE_URL, 'VITE_SERVER_URL is not set in env'); assert(BASE_URL, 'VITE_SERVER_URL is not set in env');
+2 -5
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';
@@ -16,7 +15,7 @@ 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 Web3ModalProvider from './context/Web3Provider';
import { WalletConnectClientProvider } from 'context/WalletConnectContext'; import './index.css';
console.log(`v-0.0.9`); console.log(`v-0.0.9`);
@@ -32,7 +31,6 @@ const gqlClient = new GQLClient({ gqlEndpoint });
root.render( root.render(
<LogErrorBoundary> <LogErrorBoundary>
<React.StrictMode> <React.StrictMode>
<WalletConnectClientProvider>
<ThemeProvider> <ThemeProvider>
<Web3ModalProvider> <Web3ModalProvider>
<GQLClientProvider client={gqlClient}> <GQLClientProvider client={gqlClient}>
@@ -41,7 +39,6 @@ root.render(
</GQLClientProvider> </GQLClientProvider>
</Web3ModalProvider> </Web3ModalProvider>
</ThemeProvider> </ThemeProvider>
</WalletConnectClientProvider>
</React.StrictMode> </React.StrictMode>
</LogErrorBoundary>, </LogErrorBoundary>,
); );
@@ -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,
@@ -57,6 +58,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[] = [
@@ -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>
@@ -57,7 +57,7 @@ const CreateWithTemplate = () => {
return ( return (
<div className="flex flex-col items-center gap-6 lg:gap-10 mx-auto w-full lg:w-5/6"> <div className="flex flex-col items-center gap-6 lg:gap-10 mx-auto w-full lg:w-5/6">
<div className="flex flex-col lg:flex-row justify-between w-full my-4 bg-base-bg-alternate rounded-xl p-6 gap-3 items-start lg:items-center"> <div className="flex flex-col lg:flex-row justify-between w-full my-4 bg-base-bg-alternate dark:bg-overlay rounded-xl p-6 gap-3 items-start lg:items-center">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<TemplateIcon type={template?.icon as TemplateIconType} size={48} /> <TemplateIcon type={template?.icon as TemplateIconType} size={48} />
<Heading className="font-medium">{template?.name}</Heading> <Heading className="font-medium">{template?.name}</Heading>
@@ -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,9 +31,8 @@ export const CreateProjectLayout = ({
</Heading> </Heading>
); );
return ( return isDesktopView ? (
<> // Desktop
{/* Desktop */}
<section <section
{...props} {...props}
className={cn( className={cn(
@@ -54,14 +56,13 @@ export const CreateProjectLayout = ({
</div> </div>
<WavyBorder /> <WavyBorder />
</div> </div>
<section className="px-6 h-full flex-1 py-6 overflow-y-auto"> <section className="px-6 h-full flex-1 py-6 overflow-y-auto">
<Outlet /> <Outlet />
</section> </section>
</section> </section>
) : (
{/* Mobile */} // Mobile
{/* Setting modal={false} so even if modal is active on desktop, it doesn't block clicks */} // Setting modal={false} so even if modal is active on desktop, it doesn't block clicks
<Dialog.Root modal={false} open={true}> <Dialog.Root modal={false} open={true}>
<Dialog.Portal> <Dialog.Portal>
{/* Not using <Dialog.Overlay> since modal={false} disables it and its content will not show */} {/* Not using <Dialog.Overlay> since modal={false} disables it and its content will not show */}
@@ -94,6 +95,5 @@ export const CreateProjectLayout = ({
</div> </div>
</Dialog.Portal> </Dialog.Portal>
</Dialog.Root> </Dialog.Root>
</>
); );
}; };
@@ -55,7 +55,7 @@ const Id = () => {
</div> </div>
{/* Card */} {/* Card */}
<div className="bg-base-bg-alternate rounded-xl shadow-inset w-full px-1 py-1"> <div className="bg-base-bg-alternate dark:bg-overlay2 rounded-xl shadow-inset w-full px-1 py-1">
{/* Trigger question */} {/* Trigger question */}
<div className="flex gap-2 justify-center items-center py-3"> <div className="flex gap-2 justify-center items-center py-3">
<div className="h-5 w-5"> <div className="h-5 w-5">
@@ -67,7 +67,7 @@ const Id = () => {
</div> </div>
{/* CTA card */} {/* CTA card */}
<div className="bg-surface-card rounded-xl shadow-card-sm px-4 py-4"> <div className="bg-surface-card dark:bg-overlay rounded-xl shadow-card-sm dark:shadow-background px-4 py-4">
<div className="flex gap-2"> <div className="flex gap-2">
<Badge variant="secondary">1</Badge> <Badge variant="secondary">1</Badge>
<div className="space-y-3"> <div className="space-y-3">
@@ -75,7 +75,7 @@ const Id = () => {
<Heading as="h6" className="text-sm font-sans"> <Heading as="h6" className="text-sm font-sans">
Add a custom domain Add a custom domain
</Heading> </Heading>
<p className="text-xs text-elements-low-em font-sans"> <p className="text-xs text-elements-low-em dark:text-foreground-secondary font-sans">
Make it easy for your visitors to remember your URL with a Make it easy for your visitors to remember your URL with a
custom domain. custom domain.
</p> </p>
@@ -152,13 +152,18 @@ const CreateRepo = () => {
<Heading as="h3" className="text-lg font-medium"> <Heading as="h3" className="text-lg font-medium">
Create a repository Create a repository
</Heading> </Heading>
<Heading as="h5" className="text-sm font-sans text-elements-low-em"> <Heading
as="h5"
className="text-sm font-sans text-elements-low-em dark:text-foreground-secondary"
>
The project will be cloned into this repository The project will be cloned into this repository
</Heading> </Heading>
</div> </div>
<div className="flex flex-col justify-start gap-3"> <div className="flex flex-col justify-start gap-3">
<span className="text-sm text-elements-high-em">Git account</span> <span className="text-sm text-elements-high-em dark:text-foreground">
Git account
</span>
{gitAccounts.length > 0 ? ( {gitAccounts.length > 0 ? (
<Controller <Controller
name="account" name="account"
@@ -181,7 +186,9 @@ const CreateRepo = () => {
)} )}
</div> </div>
<div className="flex flex-col justify-start gap-3"> <div className="flex flex-col justify-start gap-3">
<span className="text-sm text-elements-high-em">Name the repo</span> <span className="text-sm text-elements-high-em dark:text-foreground">
Name the repo
</span>
<Controller <Controller
name="repoName" name="repoName"
control={control} control={control}
@@ -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}
href={`https://${project.name.toLowerCase()}.${deployment.deployer.baseDomain}`}
className="text-sm text-elements-low-em dark:text-foreground tracking-tight truncate" 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>
@@ -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 = () => {
@@ -60,7 +60,8 @@ const Domains = () => {
return ( return (
<ProjectSettingContainer <ProjectSettingContainer
headingText="Domains" headingText="Domains"
button={ {...(!project.auctionId && {
button: (
<Button <Button
as="a" as="a"
href="add" href="add"
@@ -70,9 +71,15 @@ const Domains = () => {
> >
Add domain Add domain
</Button> </Button>
} ),
})}
> >
{domains.map((domain) => { {project.auctionId ? (
<p className="text-gray-500">
Custom domains not supported for auction driven deployments.
</p>
) : (
domains.map((domain) => {
return ( return (
<DomainCard <DomainCard
domains={domains} domains={domains}
@@ -84,7 +91,8 @@ const Domains = () => {
onUpdate={fetchDomains} onUpdate={fetchDomains}
/> />
); );
})} })
)}
</ProjectSettingContainer> </ProjectSettingContainer>
); );
}; };
@@ -1,11 +1,15 @@
import { useEffect, useMemo } from 'react'; import { useEffect, useMemo } from 'react';
import { useFieldArray, useFormContext } from 'react-hook-form'; import { useFieldArray, useFormContext } from 'react-hook-form';
// TODO: Use custom checkbox component
// Custom checkbox component does not work with react-hook-form
import { Checkbox } from '@snowballtools/material-tailwind-react-fork';
// import { Checkbox } from 'components/shared/Checkbox';
import { Button } from 'components/shared/Button'; import { Button } from 'components/shared/Button';
import { InlineNotification } from 'components/shared/InlineNotification'; import { InlineNotification } from 'components/shared/InlineNotification';
import AddEnvironmentVariableRow from 'components/projects/project/settings/AddEnvironmentVariableRow'; import AddEnvironmentVariableRow from 'components/projects/project/settings/AddEnvironmentVariableRow';
import { EnvironmentVariablesFormValues } from 'types/types'; import { EnvironmentVariablesFormValues } from 'types/types';
import { Checkbox } from 'components/shared/Checkbox';
const EnvironmentVariablesForm = () => { const EnvironmentVariablesForm = () => {
const { const {
@@ -67,10 +71,19 @@ const EnvironmentVariablesForm = () => {
/> />
)} )}
<div className="flex gap-2 p-2"> <div className="flex gap-2 p-2">
<Checkbox label="Production" {...register('environment.production')} /> <Checkbox
<Checkbox label="Preview" {...register('environment.preview')} /> label="Production"
labelProps={{ className: 'text-gray-900 dark:text-white' }}
{...register('environment.production')}
/>
<Checkbox
label="Preview"
labelProps={{ className: 'text-gray-900 dark:text-white' }}
{...register('environment.preview')}
/>
<Checkbox <Checkbox
label="Development" label="Development"
labelProps={{ className: 'text-gray-900 dark:text-white' }}
{...register('environment.development')} {...register('environment.development')}
/> />
</div> </div>
@@ -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[]
@@ -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,14 +63,33 @@ 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">
{dnsRecord ? (
<>
<p className="text-blue-gray-500"> <p className="text-blue-gray-500">
Add the following records to your domain.&nbsp; Add the following records to your domain.
<a href="https://www.namecheap.com/" target="_blank" rel="noreferrer">
<span className="underline">Go to NameCheap</span>
</a>
</p> </p>
<Table> <Table>
@@ -80,26 +103,29 @@ const Config = () => {
<Table.Body> <Table.Body>
<Table.Row> <Table.Row>
<Table.RowHeaderCell>A</Table.RowHeaderCell> <Table.RowHeaderCell>
{dnsRecord.resourceType}
</Table.RowHeaderCell>
<Table.Cell>@</Table.Cell> <Table.Cell>@</Table.Cell>
<Table.Cell>56.49.19.21</Table.Cell> <Table.Cell>
</Table.Row> <p className={!dnsRecord.value ? 'text-red-500' : ''}>
{dnsRecord.value ?? 'Not available'}
<Table.Row> </p>
<Table.RowHeaderCell>CNAME</Table.RowHeaderCell> </Table.Cell>
<Table.Cell>www</Table.Cell>
<Table.Cell>cname.snowballtools.xyz</Table.Cell>
</Table.Row> </Table.Row>
</Table.Body> </Table.Body>
</Table> </Table>
{dnsRecord?.value && (
<InlineNotification <InlineNotification
variant="info" variant="info"
title={`It can take up to 48 hours for these updates to reflect title={`It can take up to 48 hours for these updates to reflect
globally.`} globally.`}
/> />
)}
<Button <Button
className="w-fit" className="w-fit"
disabled={!dnsRecord?.value}
onClick={handleSubmitDomain} onClick={handleSubmitDomain}
variant="primary" variant="primary"
shape="default" shape="default"
@@ -107,6 +133,10 @@ const Config = () => {
> >
FINISH FINISH
</Button> </Button>
</>
) : (
<p className={'text-red-500'}>DNS record data not available</p>
)}
</ProjectSettingContainer> </ProjectSettingContainer>
); );
}; };
@@ -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"
@@ -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 = {
@@ -111,6 +112,7 @@ export const deployment0: Deployment = {
}, },
applicationDeploymentRequestId: applicationDeploymentRequestId:
'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize', 'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize',
applicationDeploymentRecordData: {} as AppDeploymentRecordAttributes,
}; };
export const project: Project = { export const project: Project = {
+3
View File
@@ -5,8 +5,11 @@ export const VITE_GITHUB_PWA_TEMPLATE_REPO = import.meta.env
.VITE_GITHUB_PWA_TEMPLATE_REPO; .VITE_GITHUB_PWA_TEMPLATE_REPO;
export const VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO = import.meta.env export const VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO = import.meta.env
.VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO; .VITE_GITHUB_IMAGE_UPLOAD_PWA_TEMPLATE_REPO;
export const VITE_GITHUB_NEXT_APP_TEMPLATE_REPO = import.meta.env
.VITE_GITHUB_NEXT_APP_TEMPLATE_REPO;
export const VITE_GITHUB_CLIENT_ID = import.meta.env.VITE_GITHUB_CLIENT_ID; export const VITE_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_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;
+11
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;
}
} }
+18
View File
@@ -57,6 +57,9 @@ query ($projectId: String!) {
commitHash commitHash
createdAt createdAt
environment environment
applicationDeploymentRecordData {
url
}
deployer { deployer {
baseDomain baseDomain
} }
@@ -112,6 +115,9 @@ query ($organizationSlug: String!) {
commitMessage commitMessage
createdAt createdAt
environment environment
applicationDeploymentRecordData {
url
}
domain { domain {
status status
branch branch
@@ -343,3 +349,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
}
}
`;
+26
View File
@@ -108,6 +108,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 +377,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;
}
+5
View File
@@ -14407,6 +14407,11 @@ open@^8.0.4, open@^8.4.0:
is-docker "^2.1.1" is-docker "^2.1.1"
is-wsl "^2.2.0" is-wsl "^2.2.0"
openpgp@^6.0.1:
version "6.0.1"
resolved "https://registry.yarnpkg.com/openpgp/-/openpgp-6.0.1.tgz#ab3a2c08a3e23ac7f85c4fc62a3e715d50dc08fb"
integrity sha512-3lReDKjgWsKFArZT4Y/yj7/Q0q6/VhXarn4WqKEkyiBWckNjrThSGoB1t0IKo3Ke0ClvBpyQfTwumkGUkxOwww==
optimism@^0.18.0: optimism@^0.18.0:
version "0.18.0" version "0.18.0"
resolved "https://registry.yarnpkg.com/optimism/-/optimism-0.18.0.tgz#e7bb38b24715f3fdad8a9a7fc18e999144bbfa63" resolved "https://registry.yarnpkg.com/optimism/-/optimism-0.18.0.tgz#e7bb38b24715f3fdad8a9a7fc18e999144bbfa63"