### Install Dependencies and Setup Development Environment (Bash) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/README.md This script installs project dependencies using 'bun', enables remote caching with 'bun turbo link', generates necessary artifacts, and starts the Docker Compose setup for local development. It's essential for setting up the project environment. ```bash bun install bun turbo link bun run artifacts bun run dev:up ``` -------------------------------- ### Turborepo Build Order Configuration Example Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/CLAUDE.md Example configuration for Turborepo tasks, specifying build dependencies and caching strategies. Ensures correct build order and efficient artifact caching. ```json { "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] }, "dev": { "persistent": true, "cache": false } } } ``` -------------------------------- ### Generate Project Artifacts and Deploy with Bun Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/README.md Commands to update project artifacts and manage Docker Compose for development environments. `bun run artifacts` updates genesis files, databases, and ABIs, while `bun run dev:up` starts the Docker setup, and `bun run dev:reset` restarts it. ```bash bun run artifacts bun run dev:up # OR restart the docker compose setup bun run dev:reset ``` -------------------------------- ### Run dApp Integration Tests and Start Development Server (Bash) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/README.md This sequence navigates to the dApp directory, generates SDK types and GraphQL schemas, runs integration tests, and finally starts the dApp in development mode. Integration tests help ensure data integrity and functionality, while the development server allows for live changes. ```bash cd kit/dapp bun run codegen:settlemint bun run test:integration bun dev ``` -------------------------------- ### Build and Production Server Commands using Bun Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/content/docs/architecture/application/frontend-architecture.mdx Commands to build the project for production and start the production server using Bun. This generates optimized static assets with Server-Side Rendering (SSR) support. ```bash bun run build # Production build ``` ```bash bun run start # Production server ``` -------------------------------- ### Shell Script for MinIO User and Policy Setup Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/atk/charts/support/charts/minio/templates/_helper_create_user.txt This shell script is designed to configure MinIO users and their associated policies. It handles connection to the MinIO server, user creation, and policy attachment. The script can dynamically create users based on configuration values, supporting both new secret keys and existing secrets. ```shell #!/bin/sh set -e ; # Have script exit in the event of a failed command. {{- if .Values.configPathmc }} MC_CONFIG_DIR="{{ .Values.configPathmc }}" MC="/usr/bin/mc --insecure --config-dir ${MC_CONFIG_DIR}" {{- else }} MC="/usr/bin/mc --insecure" {{- end }} # AccessKey and secretkey credentials file are added to prevent shell execution errors caused by special characters. # Special characters for example : ',",<,>,{} MINIO_ACCESSKEY_SECRETKEY_TMP="/tmp/accessKey_and_secretKey_tmp" # connectToMinio # Use a check-sleep-check loop to wait for MinIO service to be available connectToMinio() { SCHEME=$1 ATTEMPTS=0 ; LIMIT=29 ; # Allow 30 attempts set -e ; # fail if we can't read the keys. ACCESS=$(cat /config/rootUser) ; SECRET=$(cat /config/rootPassword) ; set +e ; # The connections to minio are allowed to fail. echo "Connecting to MinIO server: $SCHEME://$MINIO_ENDPOINT:$MINIO_PORT" ; MC_COMMAND="${MC} alias set myminio $SCHEME://$MINIO_ENDPOINT:$MINIO_PORT $ACCESS $SECRET" ; $MC_COMMAND ; STATUS=$? ; until [ $STATUS = 0 ] do ATTEMPTS=`expr $ATTEMPTS + 1` ; echo "Failed attempts: $ATTEMPTS" ; if [ $ATTEMPTS -gt $LIMIT ]; then exit 1 ; fi ; sleep 2 ; # 1 second intervals between attempts $MC_COMMAND ; STATUS=$? ; done ; set -e ; # reset `e` as active return 0 } # checkUserExists () # Check if the user exists, by using the exit code of `mc admin user info` checkUserExists() { CMD=$(${MC} admin user info myminio $(head -1 $MINIO_ACCESSKEY_SECRETKEY_TMP) > /dev/null 2>&1) return $? } # createUser ($policy) createUser() { POLICY=$1 #check accessKey_and_secretKey_tmp file if [[ ! -f $MINIO_ACCESSKEY_SECRETKEY_TMP ]];then echo "credentials file does not exist" return 1 fi if [[ $(cat $MINIO_ACCESSKEY_SECRETKEY_TMP|wc -l) -ne 2 ]];then echo "credentials file is invalid" rm -f $MINIO_ACCESSKEY_SECRETKEY_TMP return 1 fi USER=$(head -1 $MINIO_ACCESSKEY_SECRETKEY_TMP) # Create the user if it does not exist if ! checkUserExists ; then echo "Creating user '$USER'" cat $MINIO_ACCESSKEY_SECRETKEY_TMP | ${MC} admin user add myminio else echo "User '$USER' already exists." fi #clean up credentials files. rm -f $MINIO_ACCESSKEY_SECRETKEY_TMP # set policy for user if [ ! -z $POLICY -a $POLICY != " " ] ; then echo "Adding policy '$POLICY' for '$USER'" set +e ; # policy already attach errors out, allow it. ${MC} admin policy attach myminio $POLICY --user=$USER set -e else echo "User '$USER' has no policy attached." fi } # Try connecting to MinIO instance {{- if .Values.tls.enabled }} scheme=https {{- else }} scheme=http {{- end }} connectToMinio $scheme {{ if .Values.users }} {{ $global := . }} # Create the users {{- range .Values.users }} echo {{ tpl .accessKey $global }} > $MINIO_ACCESSKEY_SECRETKEY_TMP {{- if .existingSecret }} cat /config/secrets/{{ tpl .existingSecret $global }}/{{ tpl .existingSecretKey $global }} >> $MINIO_ACCESSKEY_SECRETKEY_TMP # Add a new line if it doesn't exist echo >> $MINIO_ACCESSKEY_SECRETKEY_TMP createUser {{ .policy }} {{ else }} echo {{ .secretKey }} >> $MINIO_ACCESSKEY_SECRETKEY_TMP createUser {{ .policy }} {{- end }} {{- end }} {{- end }} ``` -------------------------------- ### TanStack Query Usage Example (useQuery) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/AGENTS.md Shows a basic example of using TanStack Query's `useQuery` hook for data fetching in a React application. It highlights configuration options like stale time and cache time for optimizing data fetching and caching strategies. ```typescript // Example of useQuery hook from TanStack Query // import { useQuery } from '@tanstack/react-query'; // // const { data, isLoading, error } = useQuery({ // queryKey: ['todos'], // queryFn: fetchTodos, // staleTime: 5 * 60 * 1000, // 5 minutes // cacheTime: 10 * 60 * 1000, // 10 minutes // }); ``` -------------------------------- ### Solidity: Example Transfer Approval Configuration (Japan FSA) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/contracts/contracts/smart/modules/README.md Provides a concrete example of how to configure the TransferApprovalComplianceModule for Japanese FSA compliance. It demonstrates setting approval authorities, enabling exemptions for QII investors, and configuring single-use approvals with a 7-day expiry. ```solidity // Configure for Japanese regulatory requirements Config memory config = Config({ approvalAuthorities: [issuerIdentity, brokerIdentity], // Authorized entities allowExemptions: true, // QII investors exempt exemptionExpression: [ ExpressionNode(ExpressionType.TOPIC, TOPIC_QII) ], approvalExpiry: 7 days, // Approvals valid for 7 days oneTimeUse: true // Single-use approvals only }); ``` -------------------------------- ### MDX Template Callout Box Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/content/TEMPLATE-MAPPING.md This snippet demonstrates how an MDX file indicates the template to be followed for a page. It uses a React-like component syntax to display a callout box with information about the template guide. ```mdx # Page title This page follows The Good Docs Project **[Template Name](URL)** template. ``` -------------------------------- ### List Deployment Pods - Kubernetes Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/atk/charts/network/charts/network-nodes/templates/NOTES.txt Lists all pods associated with the asset tokenization kit deployment within a specified namespace. This command helps in monitoring the running components of the application. ```bash kubectl -n {{ $namespace }} get pods -l app.kubernetes.io/instance={{ .Release.Name }} ``` -------------------------------- ### Onboarded Endpoint Example (Create Token) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/content/docs/architecture/application/backend-api.mdx Shows an endpoint requiring user authentication, connected wallet, and system contract availability. This is used for actions like creating a new token. ```typescript export const createToken = onboardedRouter.token.create.handler( async ({ context, input }) => { // context.auth, context.wallet, context.system all guaranteed const factoryAddress = context.system.tokenFactories.find( (f) => f.type === input.type )?.address; return deployToken(factoryAddress, input, context.wallet.address); } ); ``` -------------------------------- ### Monorepo Commands (Bun) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/CLAUDE.md Common commands for managing the Turborepo monorepo using Bun. These commands cover dependency installation, development server startup, building, testing, linting, and CI processes. ```bash bun install bun run dev bun run dev:up bun run dev:reset bun run build bun run test bun run lint bun run format bun run typecheck bun run ci bun run artifacts ``` -------------------------------- ### Middleware Composition Example - TypeScript Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/src/orpc/middlewares/README.md Demonstrates composing different middlewares using the `.use()` method to create specialized routers for various access levels, from public to fully onboarded users. ```typescript import { implement } from "@orpc/server"; import { contract } from "@/orpc/contract"; import { Context } from "@/orpc/context"; import { sessionMiddleware } from "@/orpc/middlewares/session.middleware"; import { authMiddleware } from "@/orpc/middlewares/auth.middleware"; import { walletMiddleware } from "@/orpc/middlewares/wallet.middleware"; import { systemMiddleware } from "@/orpc/middlewares/system.middleware"; import { userClaimsMiddleware } from "@/orpc/middlewares/user-claims.middleware"; // Base router - no middleware export const baseRouter = implement(contract).$context(); // Public router - optional session export const publicRouter = baseRouter.use(sessionMiddleware); // Authenticated router - adds required authentication export const authRouter = publicRouter.use(authMiddleware); // Onboarded router - adds onboarding check export const onboardedRouter = authRouter .use(walletMiddleware) .use(systemMiddleware) .use(userClaimsMiddleware); ``` -------------------------------- ### Inspect All Release Resources Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/atk/charts/network/templates/NOTES.txt Retrieves a list of all Kubernetes resources created by the specified release instance. This command is helpful for getting an overview of the deployed components and their status. ```shell kubectl -n {{ $namespace }} get all -l app.kubernetes.io/instance={{ $release }} ``` -------------------------------- ### Onboarded User Token Creation Endpoint Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/src/orpc/procedures/README.md Shows how to define an endpoint for users who have completed onboarding, using the `onboardedRouter`. This example demonstrates accessing user and system context to deploy a token. ```typescript // Requires full onboarding export const createToken = onboardedRouter.token.create.handler( async ({ context }) => { // User is authenticated, onboarded, and has identity claims return deployToken(context.auth.user, context.system); } ); ``` -------------------------------- ### Example Handler Selection - TypeScript Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/content/docs/architecture/application/backend-api.mdx Demonstrates correct and incorrect ways to select routers and handlers for different use cases, emphasizing the use of appropriate router layers for authentication and authorization. ```typescript ```typescript // ❌ Wrong - using auth router for public data export const getPublicStats = authRouter.stats.public.handler(...) // ✅ Correct - using public router export const getPublicStats = publicRouter.stats.public.handler(...) // ❌ Wrong - manual auth check in public router export const createToken = publicRouter.token.create.handler(({ context }) => { if (!context.auth) throw new Error('Unauthorized') // ... }) // ✅ Correct - using onboarded router export const createToken = onboardedRouter.token.create.handler(({ context }) => { // context.auth is guaranteed to exist // context.system has deployed contracts }) ``` ``` -------------------------------- ### Port-Forward Metrics Service - Kubernetes Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/atk/charts/network/charts/network-nodes/templates/NOTES.txt Sets up port-forwarding for the metrics service of the asset tokenization kit. This enables external access to application metrics, typically on port 9545. ```bash kubectl -n {{ $namespace }} port-forward svc/{{ $fullname }} 9545:{{ .Values.service.ports.metrics }} ``` -------------------------------- ### Deploy Token Sale with Factory Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/content/docs/architecture/smart-contracts/factory-upgradeability.mdx Deploys a new token sale contract using the factory pattern. Requires token address, admin, start time, duration, hard cap, price, and a nonce. Returns the deployed sale contract address. ```solidity // Using the factory address saleAddress = factory.deployTokenSale( tokenAddress, // ATK token address adminAddress, // Sale administrator startTime, // Unix timestamp 86400, // 24 hours duration 1000000e18, // 1M tokens hard cap 1e15, // 0.001 ETH per token nonce // Deployment nonce ); ``` -------------------------------- ### dApp ORPC APIs - Authentication and Session Management Source: https://context7.com/settlemint/asset-tokenization-kit/llms.txt This section details the dApp ORPC APIs for user authentication, including sign-up, sign-in with credentials, 2FA management, pincode setup, and session management. ```APIDOC ## dApp REST-like ORPC APIs - Authentication and Session Management ### Description Provides APIs for user authentication and session management within the dApp. Supports email/password sign-up and sign-in, two-factor authentication (2FA) setup and verification, pincode configuration and usage for quick access, and session retrieval. ### Methods #### 1. Sign Up New User - **Endpoint**: `/auth/signup` (POST) - **Description**: Creates a new user account. - **Request Body**: ```json { "email": "investor@example.com", "password": "SecurePass123!", "name": "Jane Investor" } ``` - **Response**: User object upon successful creation. #### 2. Sign In with Credentials - **Endpoint**: `/auth/signin` (POST) - **Description**: Authenticates a user using their email and password. - **Request Body**: ```json { "email": "investor@example.com", "password": "SecurePass123!" } ``` - **Response**: Authenticated user object. #### 3. Enable Two-Factor Authentication (2FA) - **Endpoint**: `/auth/twoFactor/enable` (POST) - **Description**: Initiates the 2FA setup process. Returns a secret and QR code for authenticator app configuration. - **Request Body**: ```json { "password": "SecurePass123!" } ``` - **Response**: Object containing `secret` and `qrCode`. #### 4. Verify 2FA Code - **Endpoint**: `/auth/twoFactor/verify` (POST) - **Description**: Verifies the 2FA code provided by the user. - **Request Body**: ```json { "code": "123456" } ``` #### 5. Set Pincode - **Endpoint**: `/auth/pincode/set` (POST) - **Description**: Sets a pincode for quick authentication. - **Request Body**: ```json { "pincode": "123456" } ``` #### 6. Sign In with Pincode - **Endpoint**: `/auth/pincode/signin` (POST) - **Description**: Authenticates a user using their email and pincode. - **Request Body**: ```json { "email": "investor@example.com", "pincode": "123456" } ``` - **Response**: Authenticated user object. #### 7. Get Current Session - **Endpoint**: `/auth/session` (GET) - **Description**: Retrieves the current user's session information. - **Response**: Session object including user details (email, role, wallet). #### 8. Sign Out - **Endpoint**: `/auth/signout` (POST) - **Description**: Logs the user out and invalidates the current session. ``` -------------------------------- ### Basic Table with URL State Example (TypeScript/React) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/src/components/data-table/README-url-state.md An example demonstrating a complete setup for a users table with URL state enabled. It includes route validation and DataTable configuration with search capabilities. ```tsx export const Route = createFileRoute("/users")({ validateSearch: dataTableSearchParamsSchema, component: UsersPage, }); function UsersPage() { return ( userColumns} urlState={{ enabled: true, defaultPageSize: 25, }} advancedToolbar={{ enableGlobalSearch: true, enableFilters: true, }} /> ); } ``` -------------------------------- ### Foundry Test Example Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/contracts/AGENTS.md Demonstrates a basic structure for Foundry tests in Solidity, adhering to clear setup, execution, and assertion phases. Foundry is a smart contract testing framework known for its speed and powerful features like fuzzing and code coverage. ```solidity // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; import "forge-std/Test.sol"; contract MyContractTest is Test { // Setup: Deploy contracts, set up initial state function setUp() public { // ... deployment code ... } // Execution & Assertion: Test specific functions function testMyFunction() public { // ... call function ... // assertEq(...); } } ``` -------------------------------- ### AWS Marketplace Automation Output Example Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/tools/README.md This snippet shows the expected output during a successful AWS Marketplace automation run, including starting ECR uploads, image uploads, and marketplace submission monitoring. It demonstrates the progress and completion messages. ```plaintext 🚀 Starting AWS Marketplace automation... 🚀 Starting Helm chart upload to ECR... ✅ Successfully uploaded Helm chart: 709825985650.dkr.ecr.us-east-1.amazonaws.com/settlemint/atk:0.0.6 🚀 Starting image upload to ECR... 📦 Found 33 images to upload: ✅ Successfully uploaded: 709825985650.dkr.ecr.us-east-1.amazonaws.com/settlemint/docker.io/nginx:1.29.1-alpine ... (32 more images) 🚀 Creating new version 0.0.6 in AWS Marketplace... ✅ Change set created successfully! 🆔 Change Set ID: abc123def456 ⏳ Monitoring change set: abc123def456 📊 Check 1/5 - Status: PREPARING ⏱️ Waiting 15 seconds before next check... 📊 Check 5/5 - Status: PREPARING ✅ Change set is still in progress after 5 checks. 🎯 Assuming successful publication - AWS review typically takes hours/days. ✅ AWS Marketplace automation completed successfully! ``` -------------------------------- ### Develop dApp Locally with Bun Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/README.md Steps to run the dApp locally. This involves navigating to the dApp directory, generating necessary SDK types and GraphQL schemas using `bun run codegen:settlemint`, and then starting the dApp in development mode with `bun run dev`. ```bash # Start the docker compose setup bun run dev:up # Navigate to the dApp directory cd kit/dapp # Generate the required SDK types and GraphQL schemas bun run codegen:settlemint # Start the dApp in development mode bun run dev ``` -------------------------------- ### Optimized Docker Multi-Stage Build Example Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/AGENTS.md Illustrates an optimized Docker multi-stage build strategy. This approach uses `turbo prune` to minimize the final image size by including only necessary artifacts and leveraging build cache for efficiency. ```dockerfile # Example Dockerfile using multi-stage builds and turbo prune # Stage 1: Build stage # FROM node:18-alpine AS builder # WORKDIR /app # COPY . . # RUN bun install --frozen-lockfile # RUN turbo run build --filter=./packages/app # Stage 2: Production stage # FROM node:18-alpine AS runner # WORKDIR /app # COPY --from=builder /app/packages/app/dist ./dist # CMD ["node", "dist/index.js"] ``` -------------------------------- ### Public Endpoint Usage Example Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/src/orpc/procedures/README.md Demonstrates how to define a public endpoint using the `publicRouter`. This example shows how to create a handler for retrieving public statistics without requiring authentication. ```typescript // Public endpoint - no auth needed export const getPublicStats = publicRouter.stats.public.handler(async () => { return getPublicStatistics(); }); ``` -------------------------------- ### Authentication Flow Handler Example - TypeScript Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/src/orpc/middlewares/README.md An example of an ORPC handler that requires authentication. It demonstrates accessing authenticated user information from the context, which is guaranteed to exist due to the preceding `authRouter`. ```typescript // Handler that requires authentication export const updateProfile = authRouter.user.update.handler( async ({ context, input }) => { // context.auth is guaranteed to exist const userId = context.auth.user.id; return updateUser(userId, input); } ); ``` -------------------------------- ### Testing Commands using Bun Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/content/docs/architecture/application/frontend-architecture.mdx Commands to run unit tests and visual tests using Bun. `test:unit` utilizes Vitest with React Testing Library for component testing, while `test:unit:ui` likely starts a visual testing runner. ```bash bun run test:unit # Vitest with React Testing Library ``` ```bash bun run test:unit:ui # Visual test runner ``` -------------------------------- ### Local Development Command using Bun Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/content/docs/architecture/application/frontend-architecture.mdx Command to start the local development server using Bun. It typically launches Vite with features like Hot Module Replacement (HMR), type-safe routing, and developer tools for React Query and TanStack Router. ```bash bun run dev ``` -------------------------------- ### Error Handling in Middleware Example - TypeScript Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/src/orpc/middlewares/README.md Demonstrates how to implement robust error handling within an ORPC middleware. This example shows validation of input and how to throw specific errors or re-throw caught exceptions. ```typescript import { baseRouter } from "@/orpc/procedures/base.router"; import logger from "@/lib/logger"; // Assuming a logger utility export const validationMiddleware = baseRouter.middleware( async ({ context, next, errors, input }) => { try { // Validate input if (!isValid(input)) { throw errors.BAD_REQUEST("Invalid input"); } return next({ context }); } catch (error) { // Log and re-throw logger.error("Validation failed", { error, input }); throw error; } } ); ``` -------------------------------- ### Create Multiple MinIO Service Accounts from Values (Helm Templating) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/atk/charts/support/charts/minio/templates/_helper_create_svcacct.txt This section, using Helm templating, iterates through defined service accounts in `.Values.svcaccts`. For each service account, it prepares temporary credentials, creates the service account using the `createSvcacct` function, and handles the case where a policy is specified. It ensures that service accounts are created based on the provided configuration. ```helm {{ if .Values.svcaccts }} {{ $global := . }} # Create the svcaccts {{- range $idx, $svc := .Values.svcaccts }} echo {{ tpl .accessKey $global }} > $MINIO_ACCESSKEY_SECRETKEY_TMP {{- if .existingSecret }} cat /config/secrets-svc/{{ tpl .existingSecret $global }}/{{ tpl .existingSecretKey $global }} >> $MINIO_ACCESSKEY_SECRETKEY_TMP # Add a new line if it doesn't exist echo >> $MINIO_ACCESSKEY_SECRETKEY_TMP {{ else }} echo {{ .secretKey }} >> $MINIO_ACCESSKEY_SECRETKEY_TMP {{- end }} {{- if $svc.policy}} createSvcacct {{ .user }} svc_policy_{{ $idx }} {{ else }} createSvcacct {{ .user }} {{- end }} {{- end }} {{- end }} ``` -------------------------------- ### Get External Access URL with Ingress Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/atk/charts/erpc/templates/NOTES.txt Retrieves the eRPC URL when Ingress is enabled. It involves getting the Kubernetes cluster IP and configuring the host file to associate the eRPC hostname with the cluster IP. ```bash export CLUSTER_IP=$(minikube ip) # On Minikube. Use: `kubectl cluster-info` on others K8s clusters export SERVICE_IP=$(kubectl get svc --namespace {{ include "common.names.namespace" . }} {{ include "common.names.fullname" . }} --template "{{ output "range" (index .status.loadBalancer.ingress 0) "" }}") echo "eRPC URL: http{{ if .Values.ingress.tls }}s{{ end }}://{{ .Values.ingress.hostname }}/" echo "$CLUSTER_IP {{ .Values.ingress.hostname }}" | sudo tee -a /etc/hosts ``` -------------------------------- ### Configure PostgreSQL Initialization Scripts Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/atk/charts/support/charts/postgresql/README.md This SQL script defines the creation of databases and users for all ATK services, including blockscout, thegraph, hasura, portal, and txsigner. It sets up default passwords and grants necessary privileges. ```sql -- Create databases and users for all ATK services CREATE DATABASE blockscout; CREATE USER blockscout WITH PASSWORD 'atk' SUPERUSER; GRANT ALL PRIVILEGES ON DATABASE blockscout TO blockscout; \c blockscout; GRANT ALL ON SCHEMA public TO blockscout; \c postgres; CREATE DATABASE thegraph WITH ENCODING 'UTF8' LC_COLLATE='C' LC_CTYPE='C' TEMPLATE template0; CREATE USER thegraph WITH PASSWORD 'atk' SUPERUSER; GRANT ALL PRIVILEGES ON DATABASE thegraph TO thegraph; \c thegraph; GRANT ALL ON SCHEMA public TO thegraph; \c postgres; CREATE DATABASE hasura; CREATE USER hasura WITH PASSWORD 'atk' SUPERUSER; GRANT ALL PRIVILEGES ON DATABASE hasura TO hasura; \c hasura; GRANT ALL ON SCHEMA public TO hasura; \c postgres; CREATE DATABASE portal; CREATE USER portal WITH PASSWORD 'atk' SUPERUSER; GRANT ALL PRIVILEGES ON DATABASE portal TO portal; \c portal; GRANT ALL ON SCHEMA public TO portal; \c postgres; CREATE DATABASE txsigner; CREATE USER txsigner WITH PASSWORD 'atk' SUPERUSER; GRANT ALL PRIVILEGES ON DATABASE txsigner TO txsigner; \c txsigner; GRANT ALL ON SCHEMA public TO txsigner; ``` -------------------------------- ### Check Helm Installation Command Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/tools/README.md This command is used to verify if Helm is installed on the system. It's a crucial first step in troubleshooting issues related to the Helm chart upload phase. ```bash helm version ``` -------------------------------- ### Router Error Handling Example (TypeScript) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/src/orpc/procedures/README.md Demonstrates how routers inherit error handling capabilities. This example shows how to use standardized error types like `errors.FORBIDDEN` and `errors.BAD_REQUEST` which are automatically formatted and logged by the router's middleware. ```typescript // All routers have error middleware from public router export const handler = authRouter.action.handler(async ({ errors }) => { // Use standardized errors if (!hasPermission) { throw errors.FORBIDDEN("Insufficient permissions"); } if (!isValid) { throw errors.BAD_REQUEST("Invalid input"); } // Errors are automatically formatted and logged }); ``` -------------------------------- ### Turborepo Build Order Configuration Example Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/AGENTS.md Demonstrates a Turborepo configuration for setting build order dependencies. The `dependsOn: ["^build"]` setting ensures that a package's build process waits for its dependencies' build processes to complete, typically indicated by a '^build' task. ```javascript // Example Turborepo configuration snippet // "dependsOn: ["^build"]" ensures correct build order // "outputs: ["dist/**"]" for caching build artifacts // "persistent: true" with "cache: false" for dev tasks ``` -------------------------------- ### Shell Script: Connect to MinIO and Manage Policies Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/atk/charts/support/charts/minio/templates/_helper_create_policy.txt This script handles the connection to a MinIO instance and the creation of custom access policies. It includes retry logic for establishing the connection and checks for existing policies before creating new ones. Dependencies include `mc` (MinIO Client) and files containing policy configurations. ```shell #!/bin/sh set -e ; # Have script exit in the event of a failed command. {{- if .Values.configPathmc }} MC_CONFIG_DIR="{{ .Values.configPathmc }}" MC="/usr/bin/mc --insecure --config-dir ${MC_CONFIG_DIR}" {{- else }} MC="/usr/bin/mc --insecure" {{- end }} # connectToMinio # Use a check-sleep-check loop to wait for MinIO service to be available connectToMinio() { SCHEME=$1 ATTEMPTS=0 ; LIMIT=29 ; # Allow 30 attempts set -e ; # fail if we can't read the keys. ACCESS=$(cat /config/rootUser) ; SECRET=$(cat /config/rootPassword) ; set +e ; # The connections to minio are allowed to fail. echo "Connecting to MinIO server: $SCHEME://$MINIO_ENDPOINT:$MINIO_PORT" ; MC_COMMAND="${MC} alias set myminio $SCHEME://$MINIO_ENDPOINT:$MINIO_PORT $ACCESS $SECRET" ; $MC_COMMAND ; STATUS=$? ; until [ $STATUS = 0 ] do ATTEMPTS=`expr $ATTEMPTS + 1` ; echo "Failed attempts: $ATTEMPTS" ; if [ $ATTEMPTS -gt $LIMIT ]; then exit 1 ; fi ; sleep 2 ; # 1 second intervals between attempts $MC_COMMAND ; STATUS=$? ; done ; set -e ; # reset `e` as active return 0 } # checkPolicyExists ($policy) # Check if the policy exists, by using the exit code of `mc admin policy info` checkPolicyExists() { POLICY=$1 CMD=$(${MC} admin policy info myminio $POLICY > /dev/null 2>&1) return $? } # createPolicy($name, $filename) createPolicy () { NAME=$1 FILENAME=$2 # Create the name if it does not exist echo "Checking policy: $NAME (in /config/$FILENAME.json)" if ! checkPolicyExists $NAME ; then echo "Creating policy '$NAME'" else echo "Policy '$NAME' already exists." fi ${MC} admin policy create myminio $NAME /config/$FILENAME.json } # Try connecting to MinIO instance {{- if .Values.tls.enabled }} scheme=https {{- else }} scheme=http {{- end }} connectToMinio $scheme {{ if .Values.policies }} # Create the policies {{- range $idx, $policy := .Values.policies }} createPolicy {{ $policy.name }} policy_{{ $idx }} {{- end }} {{- end }} ``` -------------------------------- ### Drizzle ORM Schema Definition Example Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/AGENTS.md No description ```typescript // Example Drizzle ORM schema definition in TypeScript // import { pgTable, serial, text, timestamp } from 'drizzle-orm/pg-core'; // // export const users = pgTable('users', { // id: serial('id').primaryKey(), // name: text('name'), // createdAt: timestamp('created_at') // }); ``` -------------------------------- ### Viem Type-Safe Contract Interaction Example Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/AGENTS.md Illustrates the use of Viem for type-safe smart contract interactions in TypeScript. It emphasizes leveraging generated ABIs for accurate contract calls and using utility functions for Ether conversions. ```typescript // Example using Viem with generated ABIs for type safety // const contract = getContract({ address: '0x...', abi: myAbi }); // const balance = await contract.read.balanceOf([userAddress]); // Using Viem utilities for Ether conversions // import { parseEther, formatEther } from 'viem'; // const amountInEther = parseEther('1'); // const amountInWei = formatEther(amountInWei); ``` -------------------------------- ### GET /token - List tokens with filters Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/content/docs/architecture/application/backend-api.mdx Retrieves a list of deployed tokens. This endpoint supports filtering to narrow down the results. ```APIDOC ## GET /token ### Description Retrieves a list of deployed tokens. This endpoint supports filtering to narrow down the results. ### Method GET ### Endpoint /token ### Parameters #### Query Parameters *(Note: Specific query parameters for filtering are not detailed in the provided text but are implied by the description "List tokens with filters".)* ### Request Example *(No request body for GET request. Query parameters would be appended to the URL, e.g., /token?type=bond)* ### Response #### Success Response (200) - **Array of Token Objects**: Each object contains details of a deployed token. - **address** (string) - The Ethereum address of the deployed token contract. - **factoryAddress** (string) - The Ethereum address of the factory contract used for deployment. - **deployedAt** (date) - The timestamp when the token was deployed. - **status** (string) - The deployment status of the token (e.g., "pending", "deployed", "failed"). - **type** (string) - The type of the token. - **name** (string) - The name of the token. - **symbol** (string) - The symbol of the token. - **initialSupply** (bigint) - The initial supply of the token. - **complianceRules** (array) - Compliance rules associated with the token. #### Response Example ```json [ { "address": "0xabcdef1234567890abcdef1234567890abcdef12", "factoryAddress": "0x1234567890abcdef1234567890abcdef12345678", "deployedAt": "2023-10-27T10:00:00Z", "status": "deployed", "type": "bond", "name": "Example Bond", "symbol": "EXBND", "initialSupply": 1000000000000000000, "complianceRules": [ { "moduleAddress": "0x1234567890abcdef1234567890abcdef12345678", "parameters": {} } ] } ] ``` ``` -------------------------------- ### Running Local CI Commands Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/AGENTS.md Commands to run the full Continuous Integration pipeline locally or a pre-push validation that skips integration tests. These commands are executed using the 'bun' package manager. ```shell bun run ci bun run ci:base bun run --cwd kit/contracts test ``` -------------------------------- ### Public Endpoint Example (Health Check) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/content/docs/architecture/application/backend-api.mdx Demonstrates how to define a public endpoint that does not require authentication. This is suitable for health checks or public statistics. ```typescript export const publicStats = publicRouter.stats.public.handler( async ({ context }) => { // context.auth is optional const stats = await getPublicStatistics(); return stats; } ); ``` -------------------------------- ### Authenticated Endpoint Example (User Profile) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/content/docs/architecture/application/backend-api.mdx Illustrates creating an authenticated endpoint that requires user login. The 'auth' middleware guarantees that 'context.auth' is available. ```typescript export const getProfile = authRouter.user.me.handler(async ({ context }) => { // context.auth is required return getUserProfile(context.auth.user.id); }); ``` -------------------------------- ### Test eRPC Connection with Curl Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/atk/charts/erpc/templates/NOTES.txt Tests the eRPC connection by sending a POST request to the eRPC endpoint with a JSON-RPC payload to get the block number. ```bash curl -X POST http://[eRPC_URL]/53771311147 \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' ``` -------------------------------- ### Test Contracts with Bun Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/README.md Command to deploy and test smart contracts locally. It utilizes `bunx turbo contracts#publish` to execute the deployment script located at `kit/contracts/scripts/hardhat/main.ts` on a local network. ```bash bunx turbo contracts#publish ``` -------------------------------- ### Advanced Usage Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/src/components/data-table/README-url-state.md Examples of advanced usage patterns, including defining custom search parameter schemas and managing multiple tables on a single page. ```APIDOC ## Advanced Usage ### Custom Search Parameter Schema Extend the default table state schema to include custom parameters. **Example:** ```typescript import * as z from "zod"; const customTableSchema = z.object({ // Include base table state ...dataTableSearchParamsSchema.shape, // Add custom parameters viewMode: z.enum(["grid", "list"]).default("grid"), dateRange: z .object({ from: z.string().optional(), to: z.string().optional(), }) .optional(), }); export const Route = createFileRoute("/custom-table")({ validateSearch: customTableSchema, component: CustomTable, }); ``` ### Multiple Tables on Same Page Manage multiple independent tables on a single page by using distinct parameter namespaces. **Example:** ```typescript // Use different parameter namespaces const usersTableSchema = dataTableSearchParamsSchema.transform((data) => ({ users: data, })); const ordersTableSchema = dataTableSearchParamsSchema.transform((data) => ({ orders: data, })); // Combine schemas const pageSchema = usersTableSchema.merge(ordersTableSchema); ``` ``` -------------------------------- ### Dapp UI Unit Testing Command Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/CLAUDE.md Command to run unit tests specifically for the dapp's UI components. ```bash bun run --cwd kit/dapp test:unit:ui ``` -------------------------------- ### Run Complete QA Suite with Bun Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/README.md This command executes the entire quality assurance suite for the project. It sequentially runs tasks like format checking, compilation, code generation, linting, and testing to ensure code quality and consistency. ```bash bun run ci ``` -------------------------------- ### Inspect Generated ConfigMaps (Kubectl) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/charts/atk/charts/network/charts/network-bootstrapper/templates/NOTES.txt This command lists all ConfigMaps within a specified Kubernetes namespace. This is relevant when the `settings.outputType` is set to `kubernetes` to review generated configuration. ```bash kubectl -n {{ $namespace }} get configmaps ``` -------------------------------- ### Testing Onboarded Router Handler (TypeScript) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/src/orpc/procedures/README.md Shows how to test a handler for an 'onboarded' router, which requires specific system context. The example mock context includes authentication, system details (address, token factories), and user claim topics, verifying the handler's access to this specialized data. ```typescript // Testing onboarded router handler describe("onboardedHandler", () => { it("has system context", async () => { const result = await onboardedHandler({ context: { headers: {}, auth: { user: { id: "123" }, session: {} }, system: { address: "0x...", tokenFactories: [{ address: "0x...", type: "ERC20" }], }, userClaimTopics: ["COUNTRY", "KYC_VERIFIED"], }, input: {}, }); expect(result.systemAddress).toBe("0x..."); }); }); ``` -------------------------------- ### Token-Specific Minting Operation Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/src/orpc/procedures/README.md Demonstrates defining a token-specific operation using the `tokenRouter`. This example shows how to access token context and user information to mint tokens. ```typescript // Token-specific operation export const mintTokens = tokenRouter.token.mint.handler( async ({ context }) => { // Has token context and permissions return mint(context.token, context.auth.user); } ); ``` -------------------------------- ### Deploy Token Sale using Factory Contract Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/contracts/contracts/addons/token-sale/README.md Demonstrates how to deploy a new token sale instance using the ATKTokenSaleFactory. It specifies the ATK token address, sale administrator, sale timing, duration, hard cap, price per token, and a deployment nonce. ```solidity address saleAddress = factory.deployTokenSale( tokenAddress, // ATK token address adminAddress, // Sale administrator startTime, // Unix timestamp 86400, // 24 hours duration 1000000e18, // 1M tokens hard cap 1e15, // 0.001 ETH per token nonce // Deployment nonce ); ``` -------------------------------- ### Router Selection Examples (TypeScript) Source: https://github.com/settlemint/asset-tokenization-kit/blob/main/kit/dapp/src/orpc/procedures/README.md Demonstrates the correct and incorrect ways to select routers for public and authenticated endpoints. It highlights the importance of using `authRouter` for protected routes and `publicRouter` for public ones to ensure security and avoid manual checks. ```typescript // ❌ Bad - using auth router for public endpoint export const publicInfo = authRouter.info.get.handler(async () => { return getPublicInfo(); // Doesn't need auth! }); // ✅ Good - using public router export const publicInfo = publicRouter.info.get.handler(async () => { return getPublicInfo(); }); // ❌ Bad - using public router for protected endpoint export const deleteUser = publicRouter.user.delete.handler( async ({ context }) => { if (!context.auth) throw new Error("Unauthorized"); // Manual check } ); // ✅ Good - using auth router export const deleteUser = authRouter.user.delete.handler( async ({ context }) => { // Auth is guaranteed return deleteUserById(context.auth.user.id); } ); ```