Environment Variable Sanitization

We have seen many teams struggle to get up and running with ACP quickly because they messed up their environment variables. In our examples, we provide environment variable santisation with some helper code. Use them! Alternatively, you can also implement your own.

This ensure you can run your code smoothly and errors related to environment variables are caught and addressed quickly.

// Sanitize environment variables
function sanitizeEnvironmentVariables() {
  const requiredVars = [
    'WHITELISTED_WALLET_PRIVATE_KEY',
    'WHITELISTED_WALLET_ENTITY_ID',
    'SELLER_AGENT_WALLET_ADDRESS'
  ];
  
  for (const varName of requiredVars) {
    const value = process.env[varName];
    
    if (!value) {
      throw new Error(`Missing required environment variable: ${varName}`);
    }
    
    // Validate specific formats
    if (varName.includes('WALLET_ADDRESS')) {
      if (!/^0x[a-fA-F0-9]{40}$/.test(value)) {
        throw new Error(`Invalid wallet address format: ${varName}`);
      }
    }
    
    if (varName.includes('PRIVATE_KEY')) {
      if (!/^0x[a-fA-F0-9]{64}$/.test(value)) {
        throw new Error(`Invalid private key format: ${varName}`);
      }
    }
    
    if (varName.includes('ENTITY_ID')) {
      const entityId = parseInt(value);
      if (isNaN(entityId) || entityId < 0) {
        throw new Error(`Invalid entity ID: ${varName}`);
      }
    }
  }
}

// Call at startup
sanitizeEnvironmentVariables();

Last updated