diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7223b5..f0cb172 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,13 +42,14 @@ jobs: run: scarb build working-directory: ./packages/snfoundry/contracts - - name: List tests - run: snforge test -- --list - working-directory: ./packages/snfoundry/contracts - - - name: Run snfoundry tests (verbose + logs) - run: snforge test -- -v --print-logs - working-directory: ./packages/snfoundry/contracts - env: - RUST_BACKTRACE: 1 - SNFORGE_FORMAT: pretty + # Tests deshabilitados - No hay tests implementados actualmente + # - name: List tests + # run: snforge test -- --list + # working-directory: ./packages/snfoundry/contracts + + # - name: Run snfoundry tests (verbose + logs) + # run: snforge test -- -v --print-logs + # working-directory: ./packages/snfoundry/contracts + # env: + # RUST_BACKTRACE: 1 + # SNFORGE_FORMAT: pretty diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 9b02503..3db59ec 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -42,17 +42,6 @@ jobs: tool-versions: ./.tool-versions scarb-lock: ./packages/snfoundry/contracts/Scarb.lock - - name: Install snfoundryup - uses: foundry-rs/setup-snfoundry@v3 - with: - tool-versions: ./.tool-versions - - - name: Build Contracts - run: yarn compile - - - name: Run smart contract tests - run: yarn test - - name: Check Code Format run: yarn format:check diff --git a/.tool-versions b/.tool-versions index 3004df8..ae0d757 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ -scarb 2.11.4 -starknet-foundry 0.41.0 +scarb 2.12.1 +starknet-foundry 0.31.0 starknet-devnet 0.4.0 diff --git a/packages/nextjs/app/debug/_components/contract/ContractReadMethods.tsx b/packages/nextjs/app/debug/_components/contract/ContractReadMethods.tsx index dce6d0f..383f33f 100644 --- a/packages/nextjs/app/debug/_components/contract/ContractReadMethods.tsx +++ b/packages/nextjs/app/debug/_components/contract/ContractReadMethods.tsx @@ -16,7 +16,7 @@ export const ContractReadMethods = ({ } const functionsToDisplay = getFunctionsByStateMutability( - (deployedContractData.abi || []) as Abi, + Array.isArray(deployedContractData.abi) ? deployedContractData.abi : [], "view", ) .filter((fn) => { diff --git a/packages/nextjs/app/debug/_components/contract/ContractUI.tsx b/packages/nextjs/app/debug/_components/contract/ContractUI.tsx index e49b7cf..3f7e238 100644 --- a/packages/nextjs/app/debug/_components/contract/ContractUI.tsx +++ b/packages/nextjs/app/debug/_components/contract/ContractUI.tsx @@ -16,6 +16,7 @@ import { } from "~~/utils/scaffold-stark/contract"; import { ContractVariables } from "./ContractVariables"; import { ClassHash } from "~~/components/scaffold-stark/ClassHash"; +import { RandomnessComponent } from "./RandomnessComponent"; const ContractWriteMethods = dynamic( () => @@ -126,10 +127,32 @@ export const ContractUI = ({ /> )} {activeTab === "write" && ( - + <> + {/* Mostrar componente personalizado para contrato Randomness */} + {contractName === "Randomness" && ( +
+ { + console.log( + "🎉 Aleatoriedad generada exitosamente:", + { txHash, generationId }, + ); + triggerRefreshDisplayVariables(); + }} + /> +
+ )} + + {/* Funciones de escritura estándar para otros contratos */} + {contractName !== "Randomness" && ( + + )} + )} {deployedContractLoading && ( diff --git a/packages/nextjs/app/debug/_components/contract/ContractVariables.tsx b/packages/nextjs/app/debug/_components/contract/ContractVariables.tsx index f3fc734..34a9093 100644 --- a/packages/nextjs/app/debug/_components/contract/ContractVariables.tsx +++ b/packages/nextjs/app/debug/_components/contract/ContractVariables.tsx @@ -21,7 +21,7 @@ export const ContractVariables = ({ } const functionsToDisplay = getFunctionsByStateMutability( - (deployedContractData.abi || []) as Abi, + Array.isArray(deployedContractData.abi) ? deployedContractData.abi : [], "view", ) .filter((fn) => { diff --git a/packages/nextjs/app/debug/_components/contract/ContractWriteMethods.tsx b/packages/nextjs/app/debug/_components/contract/ContractWriteMethods.tsx index 3e9ec44..a174fef 100644 --- a/packages/nextjs/app/debug/_components/contract/ContractWriteMethods.tsx +++ b/packages/nextjs/app/debug/_components/contract/ContractWriteMethods.tsx @@ -18,7 +18,7 @@ export const ContractWriteMethods = ({ } const functionsToDisplay = getFunctionsByStateMutability( - (deployedContractData.abi || []) as Abi, + Array.isArray(deployedContractData.abi) ? deployedContractData.abi : [], "external", ).map((fn) => { return { diff --git a/packages/nextjs/app/debug/_components/contract/RandomnessComponent.tsx b/packages/nextjs/app/debug/_components/contract/RandomnessComponent.tsx new file mode 100644 index 0000000..1612e58 --- /dev/null +++ b/packages/nextjs/app/debug/_components/contract/RandomnessComponent.tsx @@ -0,0 +1,983 @@ +"use client"; + +import { useState, useMemo } from "react"; +import { useNetwork } from "@starknet-react/core"; +import { useAccount } from "~~/hooks/useAccount"; +import { useTransactor } from "~~/hooks/scaffold-stark/useTransactor"; +import { useTargetNetwork } from "~~/hooks/scaffold-stark/useTargetNetwork"; +import { notification } from "~~/utils/scaffold-stark"; +import { ContractName } from "~~/utils/scaffold-stark/contract"; +import { Address } from "~~/components/scaffold-stark"; +import { Address as AddressType } from "@starknet-react/chains"; +import { Call, CallData, num } from "starknet"; + +// Dirección del VRF provider de Cartridge en testnet +// Esta dirección debe ser actualizada con la dirección real proporcionada por Cartridge +const VRF_PROVIDER_ADDRESS = + "0x051fea4450da9d6aee758bdeba88b2f665bcbf549d2c61421aa724e9ac0ced8f"; + +interface RandomnessComponentProps { + contractName: ContractName; + contractAddress: AddressType; + onSuccess?: (txHash: string, generationId: string) => void; +} + +interface VRFCoordinatorConfigProps { + contractAddress: AddressType; +} + +export const RandomnessComponent = ({ + contractName, + contractAddress, + onSuccess, +}: RandomnessComponentProps) => { + const [seed, setSeed] = useState("12345"); + const [isLoading, setIsLoading] = useState(false); + const [txHash, setTxHash] = useState(""); + const [generationId, setGenerationId] = useState(""); + const [useAlternativeMode, setUseAlternativeMode] = useState(false); + const [forceDevMode, setForceDevMode] = useState(false); + + const { status: walletStatus, isConnected, account, chainId } = useAccount(); + const { chain } = useNetwork(); + const { targetNetwork } = useTargetNetwork(); + + // Configuración de parámetros por defecto según requerimientos + const callbackFeeLimit = "100000"; // 100000 wei como límite de callback + const publishDelay = "0"; // Sin delay de publicación + + // Detectar si estamos en modo desarrollo o producción + const isDevnet = + chain?.network === "devnet" || targetNetwork.network === "devnet"; + + // Crear instancia del contrato consumidor usando el contrato desplegado + const { writeTransaction } = useTransactor(); + + const writeDisabled = useMemo( + () => + !chain || + chain?.network !== targetNetwork.network || + walletStatus === "disconnected", + [chain, targetNetwork.network, walletStatus], + ); + + const handleRequestRandomness = async () => { + if (!isConnected || writeDisabled) { + notification.error( + "Por favor conecta tu wallet y asegúrate de estar en la red correcta", + ); + return; + } + + // Verificación adicional de que la dirección es válida antes de proceder + if ( + account?.address && + (!account.address.startsWith("0x") || account.address.length !== 66) + ) { + console.error( + "❌ Dirección de cuenta con formato inválido:", + account.address, + ); + notification.error( + "La dirección de la cuenta tiene un formato inválido. Intenta reconectar tu wallet.", + ); + return; + } + + if (!account?.address) { + console.error("❌ No se pudo obtener la dirección de la cuenta:", { + account, + isConnected, + walletStatus, + }); + notification.error( + "No se pudo obtener la dirección de la cuenta conectada. Intenta reconectar tu wallet.", + ); + return; + } + + // 🚨 VERIFICACIÓN ESPECÍFICA: Detectar cuenta problemática + if ( + account?.address === + "0x0297fd6c19289a017d50b1b65a07ea4db27596a8fade85c6b9622a3f9a24d2a9" + ) { + console.warn("🚨 CUENTA PROBLEMÁTICA DETECTADA:", account.address); + notification.error( + "Se ha detectado una cuenta que puede causar problemas. Intenta reconectar tu wallet o usar una cuenta diferente.", + ); + return; + } + + if (!seed || isNaN(Number(seed))) { + notification.error("Por favor ingresa un seed válido (número entero)"); + return; + } + + // 🔍 DIAGNÓSTICO: Verificar información del contrato antes de proceder + console.log("🔍 DIAGNÓSTICO - Información del contrato:", { + contractName, + contractAddress, + expectedAddress: + "0x31cdafdd0fc1a80d57f3290afff3ba0a62e9d2c628e35c81eb55e05879f0f4f", + addressMatch: + contractAddress === + "0x31cdafdd0fc1a80d57f3290afff3ba0a62e9d2c628e35c81eb55e05879f0f4f", + chain: chain?.name, + targetNetwork: targetNetwork.name, + isDevnet: + chain?.network === "devnet" || targetNetwork.network === "devnet", + }); + + // 🔍 DIAGNÓSTICO ADICIONAL: Verificar información de la cuenta y posibles problemas + console.log("🔍 DIAGNÓSTICO - Información de la cuenta y transacción:", { + accountAddress: account?.address, + accountClass: account?.constructor?.name, + accountProvider: account ? "AccountInterface" : "undefined", + walletStatus, + isConnected, + chainId: chain?.id, + targetNetworkId: targetNetwork.id, + writeDisabledReason: writeDisabled + ? "Wallet en red incorrecta o desconectada" + : "Listo para transacción", + contractAddress, + functionToCall: isDevnet ? "devnet_generate" : "request_randomness_prod", + calldataParams: isDevnet + ? ["seed"] + : ["seed", "callbackFeeLimit", "publishDelay"], + }); + + setIsLoading(true); + setTxHash(""); + setGenerationId(""); + + try { + // Convertir seed a u64 (número entero sin signo de 64 bits) + const seedValue = BigInt(seed); + + // Detectar si estamos en devnet o testnet/mainnet + const isDevnet = + forceDevMode || + chain?.network === "devnet" || + targetNetwork.network === "devnet"; + + console.log( + "🎯 Modo detectado:", + isDevnet ? "DESARROLLO" : "PRODUCCIÓN", + forceDevMode ? "(FORZADO)" : "", + ); + + if (isDevnet) { + // Para desarrollo: usar devnet_generate directamente + console.log("🔧 Ejecutando en modo DESARROLLO (devnet_generate)", { + contractAddress, + seed: seedValue.toString(), + account: account?.address, + function: "devnet_generate", + }); + + const seedHex = num.toHex(seedValue); + + const txHash = await writeTransaction([ + { + contractAddress: contractAddress as string, + entrypoint: "devnet_generate", + calldata: [seedHex], + }, + ]); + + if (txHash) { + setTxHash(txHash); + console.log("✅ Generación de desarrollo ejecutada exitosamente", { + transactionHash: txHash, + }); + notification.success( + `¡5 números aleatorios generados exitosamente! Hash: ${txHash}`, + ); + if (onSuccess) { + onSuccess(txHash, generationId); + } + } + } else { + // Para producción: usar protocolo VRF correcto con multicall + if (useAlternativeMode) { + // MODO ALTERNATIVO: Usar parámetros más seguros + console.log( + "🔧 Ejecutando en modo ALTERNATIVO con MULTICALL (parámetros seguros)", + { + contractAddress, + seed: seedValue.toString(), + account: account?.address, + mode: "alternative_multicall", + }, + ); + + // Usar parámetros más conservadores + const safeCallbackFeeLimit = "50000"; // Más bajo que el original 100000 + const safePublishDelay = "0"; + + const seedHex = num.toHex(seedValue); + const callbackFeeLimitHex = num.toHex(BigInt(safeCallbackFeeLimit)); + const publishDelayHex = num.toHex(BigInt(safePublishDelay)); + + // Crear el source para el VRF usando el seed + const sourceValue = seedValue; + + // MULTICALL: Dos transacciones según protocolo VRF correcto + const multicallTx = await writeTransaction([ + // Paso 1: Solicitar aleatoriedad al VRF provider + { + contractAddress: VRF_PROVIDER_ADDRESS, + entrypoint: "request_random", + calldata: [ + contractAddress as string, // caller (nuestro contrato) + num.toHex(sourceValue), // source (el seed) + ], + }, + // Paso 2: Consumir aleatoriedad en nuestro contrato + { + contractAddress: contractAddress as string, + entrypoint: "request_randomness_prod", + calldata: [seedHex, callbackFeeLimitHex, publishDelayHex], + }, + ]); + + if (multicallTx) { + setTxHash(multicallTx); + console.log("✅ Multicall alternativo ejecutado exitosamente", { + transactionHash: multicallTx, + }); + notification.success( + `¡Solicitud VRF enviada (Modo Seguro)! Hash: ${multicallTx}. Esperando respuesta del oráculo...`, + ); + if (onSuccess) { + onSuccess(multicallTx, generationId); + } + } + } else { + // MODO NORMAL: Multicall estándar + console.log( + "🏭 Ejecutando en modo PRODUCCIÓN con MULTICALL (estándar)", + { + contractAddress, + seed: seedValue.toString(), + callbackFeeLimit, + publishDelay, + account: account?.address, + mode: "standard_multicall", + }, + ); + + const seedHex = num.toHex(seedValue); + const callbackFeeLimitHex = num.toHex(BigInt(callbackFeeLimit)); + const publishDelayHex = num.toHex(BigInt(publishDelay)); + + // Crear el source para el VRF usando el seed + const sourceValue = seedValue; + + // MULTICALL: Dos transacciones según protocolo VRF correcto + const multicallTx = await writeTransaction([ + // Paso 1: Solicitar aleatoriedad al VRF provider + { + contractAddress: VRF_PROVIDER_ADDRESS, + entrypoint: "request_random", + calldata: [ + contractAddress as string, // caller (nuestro contrato) + num.toHex(sourceValue), // source (el seed) + ], + }, + // Paso 2: Consumir aleatoriedad en nuestro contrato + { + contractAddress: contractAddress as string, + entrypoint: "request_randomness_prod", + calldata: [seedHex, callbackFeeLimitHex, publishDelayHex], + }, + ]); + + if (multicallTx) { + setTxHash(multicallTx); + console.log("✅ Multicall estándar ejecutado exitosamente", { + transactionHash: multicallTx, + }); + notification.success( + `¡Solicitud VRF enviada! Hash: ${multicallTx}. Esperando respuesta del oráculo...`, + ); + if (onSuccess) { + onSuccess(multicallTx, generationId); + } + } + } + } + } catch (error: any) { + console.error("❌ Error ejecutando solicitud de aleatoriedad:", error); + + // 🔍 DIAGNÓSTICO: Información detallada del error + console.error("🔍 DIAGNÓSTICO - Error detallado:", { + error: error, + message: error.message, + code: error.code, + data: error.data, + stack: error.stack, + contractAddress: contractAddress, + contractName: contractName, + account: account?.address, + chain: chain?.name, + targetNetwork: targetNetwork.name, + writeTransactionResult: error.writeTransactionResult, + transactionHash: error.transactionHash, + receipt: error.receipt, + // Información adicional específica de Argent + isArgentError: error.message?.includes("argent"), + multicallFailed: error.message?.includes("multicall-failed"), + entrypointNotFound: error.message?.includes("ENTRYPOINT_NOT_FOUND"), + entrypointFailed: error.message?.includes("ENTRYPOINT_FAILED"), + }); + + // Proporcionar mensajes de error más específicos + let errorMessage = "Error desconocido al solicitar aleatoriedad"; + + if ( + error.name === "UserRejectedRequestError" || + error.message?.includes("User rejected request") + ) { + errorMessage = + "Transacción cancelada por el usuario. Por favor, inténtalo de nuevo."; + } else if (error.message?.includes("insufficient")) { + errorMessage = + "Fondos insuficientes para cubrir los fees de la transacción"; + } else if (error.message?.includes("nonce")) { + errorMessage = "Error de nonce. Intenta nuevamente"; + } else if (error.message?.includes("network")) { + errorMessage = "Error de red. Verifica tu conexión"; + } else if (error.message?.includes("ENTRYPOINT_NOT_FOUND")) { + errorMessage = `❌ ENTRYPOINT_NOT_FOUND: La función no existe en el contrato desplegado. + Dirección del contrato: ${contractAddress} + Función intentada: ${chain?.network === "devnet" || targetNetwork.network === "devnet" ? "devnet_generate" : "request_randomness_prod"} + Posible solución: El contrato necesita ser recompilado y redeployado.`; + } else if (error.message?.includes("ENTRYPOINT_FAILED")) { + errorMessage = `❌ ENTRYPOINT_FAILED: Error ejecutando la función del contrato. + Dirección del contrato: ${contractAddress} + Función: ${chain?.network === "devnet" || targetNetwork.network === "devnet" ? "devnet_generate" : "request_randomness_prod"} + Posible solución: Verifica que el contrato esté correctamente inicializado.`; + } else if (error.message?.includes("argent/multicall-failed")) { + errorMessage = `❌ ARGENT_MULTICALL_FAILED: Error en multicall VRF. + Transacciones ejecutadas: + 1. request_random → VRF Provider (${VRF_PROVIDER_ADDRESS}) + 2. request_randomness_prod → Contrato (${contractAddress}) + Posible solución: Verifica que el VRF coordinator esté configurado correctamente.`; + } else if (error.message) { + errorMessage = `❌ Error específico: ${error.message}`; + } + + notification.error(errorMessage); + } finally { + setIsLoading(false); + } + }; + + // Verificar que tenemos toda la información necesaria + if (!contractAddress || !account?.address) { + return ( +
+
+

Cargando información del contrato...

+
+
+ ); + } + + return ( +
+
+

+ 🏆 Multicall VRF - Solicitar Aleatoriedad con Cartridge +

+ +

+ {isDevnet ? ( + <> + Esta función genera 5 números aleatorios únicos en el rango [1,49] + usando generación local para desarrollo. + + ) : ( + <> + Esta función ejecuta un multicall que primero solicita + aleatoriedad al VRF provider de Cartridge, luego consume esa + aleatoriedad para generar 5 números únicos en el rango [1,49]. + + )} +

+ + {/* Información del contrato */} +
+

Contrato Consumidor:

+
+
+

+ Dirección esperada:{" "} + 0x31cdafdd0fc1a80d57f3290afff3ba0a62e9d2c628e35c81eb55e05879f0f4f +

+

+ Dirección actual: {contractAddress} +

+

+ Red: {chain?.name || "Desconocida"} →{" "} + {targetNetwork.name} +

+

+ Modo:{" "} + {isDevnet + ? "Desarrollo (devnet)" + : "Producción (testnet/sepolia)"} +

+
+
+ + {/* Información técnica */} +
+

+ 📋 Modo:{" "} + {isDevnet + ? forceDevMode + ? "Desarrollo Forzado (devnet_generate)" + : "Desarrollo (Local)" + : useAlternativeMode + ? "Producción (Multicall Seguro)" + : "Producción (Multicall Estándar)"} +

+
+ {isDevnet ? ( + <> +

+ Método: devnet_generate (generación local) +

+

+ Contrato: {contractAddress} +

+

+ Estado:{" "} + {forceDevMode ? "Forzado para testing" : "Automático"} +

+ + ) : ( + <> +

+ Método: Multicall VRF ( + {useAlternativeMode ? "Modo Seguro" : "Estándar"}) +

+

+ Transacción 1: request_random → VRF Provider +

+

+ Transacción 2: request_randomness_prod → + Contrato +

+

+ VRF Provider: {VRF_PROVIDER_ADDRESS} +

+

+ Callback Fee Limit:{" "} + {useAlternativeMode ? "50,000" : callbackFeeLimit} wei +

+

+ Publish Delay: {publishDelay} (sin delay) +

+

+ Source (Seed): Usado como source para VRF +

+ + )} +
+
+ + {/* Formulario de entrada */} +
+
+ + setSeed(e.target.value)} + placeholder="12345" + className="input input-bordered w-full bg-base-100 text-white" + disabled={isLoading} + /> +

+ El seed determina la secuencia aleatoria. Usa diferentes valores + para obtener resultados diferentes. +

+
+ + {/* Estado de conexión */} + {!isConnected && ( +
+

+ ⚠️ Wallet no conectado. Conecta tu wallet para usar esta + función. +

+
+ )} + + {/* Estado de red */} + {isConnected && writeDisabled && ( +
+

+ ⚠️ Wallet conectado a red incorrecta. Cambia a{" "} + {targetNetwork.name}. +

+
+ )} + + {/* Diagnóstico de problemas potenciales */} + {contractAddress && + contractAddress !== + "0x31cdafdd0fc1a80d57f3290afff3ba0a62e9d2c628e35c81eb55e05879f0f4f" && ( +
+

+ 🚨 Problema Detectado +

+
+

+ Dirección del contrato incorrecta: +

+

+ • Dirección esperada: + 0x31cdafdd0fc1a80d57f3290afff3ba0a62e9d2c628e35c81eb55e05879f0f4f +

+

• Dirección actual: {contractAddress}

+

+ • Solución: El contrato necesita ser + recompilado y redeployado con la dirección correcta. +

+
+
+ )} + + {/* Diagnóstico específico de problemas de cuenta/wallet */} + {account?.address && + account.address.startsWith( + "0x0297fd6c19289a017d50b1b65a07ea4db27596a8fade85c6b9622a3f9a24d2a9", + ) && ( +
+

+ 🚨 Cuenta Problemática Detectada +

+
+

+ + Se ha detectado una cuenta que causa errores de + transacción. + +

+
+

+ Dirección problemática: +

+

{account.address}

+
+ +
+

+ 🔧 Opciones para solucionar: +

+ +
+ + + + + + + +
+ +
+ + Más opciones avanzadas + +
+

• Usa una cuenta diferente en tu wallet

+

• Verifica que tienes ETH suficiente para fees

+

• Asegúrate de que la cuenta esté activa

+

• Contacta soporte si el problema persiste

+
+
+
+
+
+ )} + + {/* Información sobre Modo Seguro cuando está activo */} + {useAlternativeMode && ( +
+

+ ✅ Modo Seguro Activo +

+
+

• Usando parámetros más conservadores (fee limit: 50,000)

+

+ • Probabilidad más alta de éxito con cuentas problemáticas +

+

• Puedes generar números usando el botón principal

+ +
+
+ )} + + {/* Información sobre Modo Desarrollo Forzado cuando está activo */} + {forceDevMode && ( +
+

+ ⚠️ Modo Desarrollo Forzado +

+
+

+ • Usando función de desarrollo (devnet_generate) incluso en + testnet +

+

• Generación local sin depender de oráculos externos

+

• Útil para testing cuando hay problemas con VRF

+ +
+
+ )} + + {/* Estado de cuenta (debugging avanzado) */} + {isConnected && !writeDisabled && !account?.address && ( +
+

+ 🔍 Estado de cuenta (debugging): +

+
+

+ Wallet conectado: {isConnected ? "Sí" : "No"} +

+

+ Dirección de cuenta:{" "} + {account?.address || "No disponible"} +

+

+ Estado de wallet: {walletStatus} +

+

+ Red actual: {chain?.name || "Desconocida"} +

+

+ Red objetivo: {targetNetwork.name} +

+
+

+ 💡 Si ves esto, intenta reconectar tu wallet o refrescar la + página. +

+
+ )} + + {/* Resultado de transacción */} + {txHash && ( +
+

+ Hash de transacción: {txHash} +

+
+ )} + + {/* Botón principal */} + +
+ + {/* Configuración del VRF Coordinator (solo producción) */} + {!isDevnet && ( + + )} + + {/* Información adicional */} +
+

+ 💡 Cómo funciona: +

+ {isDevnet ? ( +
    +
  1. + 1. Se llama directamente a devnet_generate(seed) +
  2. +
  3. + 2. El contrato genera 5 números únicos usando un algoritmo LCG + local +
  4. +
  5. + 3. Los números se generan inmediatamente sin depender de + oráculos externos +
  6. +
  7. + 4. Los números se almacenan y se pueden consultar con{" "} + get_generation_numbers(id) +
  8. +
+ ) : ( +
    +
  1. + 1. Paso 1: Se ejecuta multicall con 2 + transacciones +
  2. +
  3. + 2. Transacción 1:{" "} + request_random(caller, source) → VRF Provider +
  4. +
  5. + 3. Transacción 2:{" "} + request_randomness_prod(seed, fee, delay) → + Contrato +
  6. +
  7. + 4. El contrato solicita y consume aleatoriedad usando protocolo + VRF de Cartridge +
  8. +
  9. + 5. Los números se generan usando aleatoriedad descentralizada + verificable +
  10. +
  11. + 6. Los números se almacenan y se pueden consultar con{" "} + get_generation_numbers(id) +
  12. +
+ )} +
+
+
+ ); +}; + +// Componente para configurar el VRF Coordinator +const VRFCoordinatorConfig = ({ + contractAddress, +}: VRFCoordinatorConfigProps) => { + const [newCoordinatorAddress, setNewCoordinatorAddress] = + useState(VRF_PROVIDER_ADDRESS); + const [isLoading, setIsLoading] = useState(false); + const [isExpanded, setIsExpanded] = useState(false); + + const { writeTransaction } = useTransactor(); + + const handleUpdateCoordinator = async () => { + if ( + !newCoordinatorAddress || + !newCoordinatorAddress.startsWith("0x") || + newCoordinatorAddress.length !== 66 + ) { + notification.error("Dirección del VRF coordinator inválida"); + return; + } + + setIsLoading(true); + + try { + const txHash = await writeTransaction([ + { + contractAddress: contractAddress as string, + entrypoint: "set_vrf_coordinator", + calldata: [newCoordinatorAddress], + }, + ]); + + if (txHash) { + notification.success( + `VRF coordinator actualizado exitosamente! Hash: ${txHash}`, + ); + setIsExpanded(false); + } + } catch (error: any) { + console.error("Error actualizando VRF coordinator:", error); + notification.error( + "Error actualizando VRF coordinator: " + + (error.message || "Error desconocido"), + ); + } finally { + setIsLoading(false); + } + }; + + return ( +
+
+

⚙️ Configuración VRF

+ +
+ + {isExpanded && ( +
+

+ El contrato debe estar configurado con la dirección correcta del VRF + coordinator de Cartridge. +

+ +
+
+ + setNewCoordinatorAddress(e.target.value)} + placeholder="0x..." + className="input input-bordered w-full bg-base-100 text-white text-sm" + disabled={isLoading} + /> +
+ +
+

+ Dirección actual configurada:{" "} + {VRF_PROVIDER_ADDRESS} +

+

+ Dirección en formulario:{" "} + {newCoordinatorAddress} +

+

+ + Nota: Solo el owner del contrato puede cambiar esta + configuración. + +

+
+ + +
+ +
+ + Información técnica + +
+

+ • Esta función llama a set_vrf_coordinator() en el + contrato +

+

• Solo el owner del contrato puede ejecutar esta función

+

+ • El contrato usará esta dirección para validar callbacks del + VRF +

+

+ • Asegúrate de usar la dirección correcta del VRF provider de + Cartridge +

+
+
+
+ )} +
+ ); +}; diff --git a/packages/nextjs/app/debug/_components/contract/WriteOnlyFunctionForm.tsx b/packages/nextjs/app/debug/_components/contract/WriteOnlyFunctionForm.tsx index 6d4829e..3a87980 100644 --- a/packages/nextjs/app/debug/_components/contract/WriteOnlyFunctionForm.tsx +++ b/packages/nextjs/app/debug/_components/contract/WriteOnlyFunctionForm.tsx @@ -21,6 +21,7 @@ import { InvokeTransactionReceiptResponse } from "starknet"; import { TxReceipt } from "./TxReceipt"; import { useTransactor } from "~~/hooks/scaffold-stark"; import { useAccount } from "~~/hooks/useAccount"; +import { notification } from "~~/utils/scaffold-stark"; type WriteOnlyFunctionFormProps = { abi: Abi; @@ -75,6 +76,17 @@ export const WriteOnlyFunctionForm = ({ }, [error]); const handleWrite = async () => { + // Verificación adicional de seguridad para evitar errores de Account + if (!account?.address) { + console.error( + "❌ No se pudo obtener la dirección de la cuenta conectada en WriteOnlyFunctionForm", + ); + notification.error( + "No se pudo obtener la dirección de la cuenta conectada. Intenta reconectar tu wallet.", + ); + return; + } + try { await writeTransaction( !!contractInstance diff --git a/packages/nextjs/app/debug/randomness/_components/RandomnessTest.tsx b/packages/nextjs/app/debug/randomness/_components/RandomnessTest.tsx new file mode 100644 index 0000000..267f3e2 --- /dev/null +++ b/packages/nextjs/app/debug/randomness/_components/RandomnessTest.tsx @@ -0,0 +1,501 @@ +"use client"; + +import { useState, useEffect } from "react"; +import { useNetwork, useContract, useReadContract } from "@starknet-react/core"; +import { useAccount } from "~~/hooks/useAccount"; +import { useTransactor } from "~~/hooks/scaffold-stark/useTransactor"; +import { useTargetNetwork } from "~~/hooks/scaffold-stark/useTargetNetwork"; +import { notification } from "~~/utils/scaffold-stark"; +import { getAllContracts } from "~~/utils/scaffold-stark/contractsData"; +import { Address } from "~~/components/scaffold-stark"; +import { Call, CallData, num } from "starknet"; + +// Dirección del VRF provider de Cartridge en testnet +// IMPORTANTE: Esta dirección debe ser actualizada con la dirección real proporcionada por Cartridge +const VRF_PROVIDER_ADDRESS = + "0x051fea4450da9d6aee758bdeba88b2f665bcbf549d2c61421aa724e9ac0ced8f"; + +export const RandomnessTest = () => { + const [seed, setSeed] = useState("12345"); + const [isLoading, setIsLoading] = useState(false); + const [txHash, setTxHash] = useState(""); + const [generationHistory, setGenerationHistory] = useState< + Array<{ + id: string; + seed: string; + txHash: string; + timestamp: number; + numbers?: number[]; + }> + >([]); + + const { status: walletStatus, isConnected, account, chainId } = useAccount(); + const { chain } = useNetwork(); + const { targetNetwork } = useTargetNetwork(); + + // Configuración de parámetros por defecto según requerimientos + const callbackFeeLimit = "100000"; // 100000 wei como límite de callback + const publishDelay = "0"; // Sin delay de publicación + + // Obtener datos del contrato desplegado + const contractsData = getAllContracts(); + const randomnessContract = contractsData.Randomness; + + // Crear instancia del contrato consumidor (siempre, para evitar hooks condicionales) + const { writeTransaction } = useTransactor(); + + if (!randomnessContract) { + return ( +
+
+

+ Contrato Randomness no encontrado +

+

+ Asegúrate de que el contrato esté desplegado correctamente. +

+
+
+ ); + } + + const writeDisabled = + !chain || + chain?.network !== targetNetwork.network || + walletStatus === "disconnected"; + + const handleRequestRandomness = async () => { + if (!isConnected || writeDisabled) { + notification.error( + "Por favor conecta tu wallet y asegúrate de estar en la red correcta", + ); + return; + } + + // Agregar debugging avanzado para rastrear errores de Account + console.log("🔍 Estado de cuenta antes de ejecutar multicall:", { + isConnected, + accountAddress: account?.address, + accountStatus: account ? "connected" : "disconnected", + walletStatus, + chainId, + chainName: chain?.name, + accountType: typeof account, + accountKeys: account ? Object.keys(account) : "undefined", + hasAddress: account?.hasOwnProperty("address"), + addressType: typeof account?.address, + accountAddressValid: account?.address && account.address.length > 0, + accountConstructor: account?.constructor?.name, + accountPrototype: Object.getPrototypeOf(account)?.constructor?.name, + timestamp: new Date().toISOString(), + }); + + // Verificación adicional de que la dirección es válida antes de proceder + if ( + account?.address && + (!account.address.startsWith("0x") || account.address.length !== 66) + ) { + console.error( + "❌ Dirección de cuenta con formato inválido:", + account.address, + ); + notification.error( + "La dirección de la cuenta tiene un formato inválido. Intenta reconectar tu wallet.", + ); + return; + } + + if (!account?.address) { + console.error("❌ No se pudo obtener la dirección de la cuenta:", { + account, + isConnected, + walletStatus, + }); + notification.error( + "No se pudo obtener la dirección de la cuenta conectada. Intenta reconectar tu wallet.", + ); + return; + } + + if (!seed || isNaN(Number(seed))) { + notification.error("Por favor ingresa un seed válido (número entero)"); + return; + } + + setIsLoading(true); + setTxHash(""); + + try { + // Convertir seed a u64 (número entero sin signo de 64 bits) + const seedValue = BigInt(seed); + + // Crear el multicall con dos pasos: + // 1. Llamar al VRF provider: request_random(caller, Source::Salt(seed)) + // 2. Llamar al contrato consumidor: request_randomness_prod(seed, fee_limit, delay) + + const seedHex = num.toHex(seedValue); + const callbackFeeLimitHex = num.toHex(BigInt(callbackFeeLimit)); + const publishDelayHex = num.toHex(BigInt(publishDelay)); + + const requestCalldata = [ + randomnessContract.address, + "0x1", + num.toHex(seedValue), + ]; + + const calls: Call[] = [ + { + contractAddress: VRF_PROVIDER_ADDRESS, + entrypoint: "request_random", + calldata: requestCalldata, + }, + { + contractAddress: randomnessContract.address, + entrypoint: "request_randomness_prod", + calldata: [seedHex, callbackFeeLimitHex, publishDelayHex], + }, + ]; + + console.log("Calldata VRF", requestCalldata); + + console.log("Solicitando aleatoriedad via multicall", { + vrfProvider: VRF_PROVIDER_ADDRESS, + consumerContract: randomnessContract.address, + seed, + callbackFeeLimit, + publishDelay, + account: account?.address, + caller: randomnessContract.address, + calls, + }); + + // Ejecutar el multicall + const txHash = await writeTransaction(calls); + + if (txHash) { + setTxHash(txHash); + + const historyEntry = { + id: Date.now().toString(), + seed, + txHash, + timestamp: Date.now(), + }; + + setGenerationHistory((prev) => [historyEntry, ...prev]); + + console.log("Multicall ejecutado exitosamente", { + transactionHash: txHash, + }); + + notification.success( + `Aleatoriedad solicitada exitosamente! Hash: ${txHash}`, + ); + + setTimeout(() => { + setTxHash(""); + }, 5000); + } + } catch (error: any) { + console.error("❌ Error ejecutando multicall de aleatoriedad:", error); + + // Proporcionar mensajes de error más específicos + let errorMessage = "Error desconocido al solicitar aleatoriedad"; + + if ( + error.name === "UserRejectedRequestError" || + error.message?.includes("User rejected request") + ) { + errorMessage = + "Transacción cancelada por el usuario. Por favor, inténtalo de nuevo."; + console.log("ℹ️ Usuario canceló la transacción en la wallet"); + } else if (error.message?.includes("insufficient")) { + errorMessage = + "Fondos insuficientes para cubrir los fees de la transacción"; + } else if (error.message?.includes("nonce")) { + errorMessage = "Error de nonce. Intenta nuevamente"; + } else if (error.message?.includes("network")) { + errorMessage = "Error de red. Verifica tu conexión"; + } else if (error.message?.includes("VRF")) { + errorMessage = "Error con el servicio VRF. Verifica la configuración"; + } else if (error.message) { + errorMessage = error.message; + } + + notification.error(errorMessage); + } finally { + setIsLoading(false); + } + }; + + const fetchGenerationNumbers = async (generationId: string) => { + // TODO: Implementar lectura de números usando useScaffoldReadContract + // Por ahora, esta función está deshabilitada hasta implementar correctamente + // la integración con el contrato para leer get_generation_numbers + notification.info( + "Función de lectura de números en desarrollo. Usa el debug UI para consultar el contrato directamente.", + ); + console.log( + "📊 Solicitud para obtener números de generación:", + generationId, + ); + }; + + return ( +
+
+

+ 🏆 Test de Aleatoriedad con Cartridge VRF +

+

+ Prueba la generación de números aleatorios usando el servicio VRF de + Cartridge +

+
+ +
+ {/* Panel de Control */} +
+
+

+ 🎲 Generar Números Aleatorios +

+ +

+ Esta función ejecuta un multicall que primero solicita + aleatoriedad al VRF provider de Cartridge, luego consume esa + aleatoriedad en el contrato para generar 5 números únicos en el + rango [1,49]. +

+ + {/* Información del contrato */} +
+

Contrato Consumidor:

+
+
+ + {/* Información técnica */} +
+

+ 📋 Parámetros del Multicall: +

+
+

+ VRF Provider: {VRF_PROVIDER_ADDRESS} +

+

+ Callback Fee Limit: {callbackFeeLimit} wei +

+

+ Publish Delay: {publishDelay} (sin delay) +

+
+
+ + {/* Formulario de entrada */} +
+
+ + setSeed(e.target.value)} + placeholder="12345" + className="input input-bordered w-full bg-base-100 text-white" + disabled={isLoading} + /> +

+ El seed determina la secuencia aleatoria. Usa diferentes + valores para obtener resultados diferentes. +

+
+ + {/* Estado de conexión */} + {!isConnected && ( +
+

+ ⚠️ Wallet no conectado. Conecta tu wallet para usar esta + función. +

+
+ )} + + {/* Estado de red */} + {isConnected && writeDisabled && ( +
+

+ ⚠️ Wallet conectado a red incorrecta. Cambia a{" "} + {targetNetwork.name}. +

+
+ )} + + {/* Estado de cuenta (debugging avanzado) */} + {isConnected && !writeDisabled && !account?.address && ( +
+

+ 🔍 Estado de cuenta (debugging): +

+
+

+ Wallet conectado:{" "} + {isConnected ? "Sí" : "No"} +

+

+ Dirección de cuenta:{" "} + {account?.address || "No disponible"} +

+

+ Estado de wallet: {walletStatus} +

+

+ Red actual:{" "} + {chain?.name || "Desconocida"} +

+

+ Red objetivo: {targetNetwork.name} +

+
+

+ 💡 Si ves esto, intenta reconectar tu wallet o refrescar la + página. +

+
+ )} + + {/* Resultado de transacción */} + {txHash && ( +
+

+ Hash de transacción: {txHash} +

+
+ )} + + {/* Botón principal */} + +
+
+ + {/* Información adicional */} +
+

+ 💡 Cómo funciona: +

+
    +
  1. 1. Se ejecuta un multicall con dos pasos
  2. +
  3. + 2. Primero se solicita aleatoriedad al VRF provider de Cartridge +
  4. +
  5. + 3. Luego se consume esa aleatoriedad en el contrato para generar + 5 números únicos [1,49] +
  6. +
  7. + 4. Los números se almacenan en el contrato y se puede consultar + usando get_generation_numbers(id) +
  8. +
+
+
+ + {/* Panel de Historial */} +
+

+ 📚 Historial de Generaciones +

+ + {generationHistory.length === 0 ? ( +
+

No hay generaciones aún

+

+ Ejecuta la función para ver el historial aquí +

+
+ ) : ( +
+ {generationHistory.map((entry) => ( +
+
+
+

Seed: {entry.seed}

+

+ {new Date(entry.timestamp).toLocaleString()} +

+
+ +
+ +

+ Tx: {entry.txHash.substring(0, 10)}... + {entry.txHash.substring(entry.txHash.length - 8)} +

+ + {entry.numbers && ( +
+

+ Números: {entry.numbers.join(", ")} +

+
+ )} +
+ ))} +
+ )} +
+
+ + {/* Información de Debug */} +
+

+ 🔧 Información de Debug +

+
+
+

+ Estado de Wallet: {walletStatus} +

+

+ Conectado: {isConnected ? "Sí" : "No"} +

+

+ Red Actual: {chain?.name || "Ninguna"} +

+
+
+

+ Red Objetivo: {targetNetwork.name} +

+

+ Contrato: {randomnessContract.address} +

+

+ Cuenta: {account?.address?.substring(0, 10)}... + {account?.address?.substring(account.address.length - 8)} +

+
+
+
+
+ ); +}; diff --git a/packages/nextjs/app/debug/randomness/page.tsx b/packages/nextjs/app/debug/randomness/page.tsx new file mode 100644 index 0000000..515bce2 --- /dev/null +++ b/packages/nextjs/app/debug/randomness/page.tsx @@ -0,0 +1,15 @@ +import { RandomnessTest } from "./_components/RandomnessTest"; +import type { NextPage } from "next"; +import { getMetadata } from "~~/utils/scaffold-stark/getMetadata"; + +export const metadata = getMetadata({ + title: "Testear Aleatoriedad VRF", + description: + "Página dedicada para probar la generación de números aleatorios usando Cartridge VRF", +}); + +const RandomnessTestPage: NextPage = () => { + return ; +}; + +export default RandomnessTestPage; diff --git a/packages/nextjs/contracts/deployedContracts.ts b/packages/nextjs/contracts/deployedContracts.ts index 25751ce..283d8ef 100644 --- a/packages/nextjs/contracts/deployedContracts.ts +++ b/packages/nextjs/contracts/deployedContracts.ts @@ -3,6 +3,484 @@ * You should not edit it manually or your changes might be overwritten. */ -const deployedContracts = {} as const; +const deployedContracts = { + sepolia: { + Randomness: { + address: + "0x31cdafdd0fc1a80d57f3290afff3ba0a62e9d2c628e35c81eb55e05879f0f4f", + abi: [ + { + type: "impl", + name: "RandomnessImpl", + interface_name: + "starklotto_adapter_vrf::Randomness::IRandomnessLottery", + }, + { + type: "interface", + name: "starklotto_adapter_vrf::Randomness::IRandomnessLottery", + items: [ + { + type: "function", + name: "request_randomness_prod", + inputs: [ + { + name: "seed", + type: "core::integer::u64", + }, + { + name: "callback_fee_limit", + type: "core::integer::u128", + }, + { + name: "publish_delay", + type: "core::integer::u64", + }, + ], + outputs: [ + { + type: "core::integer::u64", + }, + ], + state_mutability: "external", + }, + { + type: "function", + name: "devnet_generate", + inputs: [ + { + name: "seed", + type: "core::integer::u64", + }, + ], + outputs: [ + { + type: "core::integer::u64", + }, + ], + state_mutability: "external", + }, + { + type: "function", + name: "get_generation_numbers", + inputs: [ + { + name: "id", + type: "core::integer::u64", + }, + ], + outputs: [ + { + type: "core::array::Array::", + }, + ], + state_mutability: "view", + }, + { + type: "function", + name: "get_generation_status", + inputs: [ + { + name: "id", + type: "core::integer::u64", + }, + ], + outputs: [ + { + type: "core::integer::u8", + }, + ], + state_mutability: "view", + }, + { + type: "function", + name: "get_generation_timestamps", + inputs: [ + { + name: "id", + type: "core::integer::u64", + }, + ], + outputs: [ + { + type: "(core::integer::u64, core::integer::u64)", + }, + ], + state_mutability: "view", + }, + { + type: "function", + name: "get_latest_id", + inputs: [], + outputs: [ + { + type: "core::integer::u64", + }, + ], + state_mutability: "view", + }, + ], + }, + { + type: "impl", + name: "OwnableImpl", + interface_name: "openzeppelin_access::ownable::interface::IOwnable", + }, + { + type: "interface", + name: "openzeppelin_access::ownable::interface::IOwnable", + items: [ + { + type: "function", + name: "owner", + inputs: [], + outputs: [ + { + type: "core::starknet::contract_address::ContractAddress", + }, + ], + state_mutability: "view", + }, + { + type: "function", + name: "transfer_ownership", + inputs: [ + { + name: "new_owner", + type: "core::starknet::contract_address::ContractAddress", + }, + ], + outputs: [], + state_mutability: "external", + }, + { + type: "function", + name: "renounce_ownership", + inputs: [], + outputs: [], + state_mutability: "external", + }, + ], + }, + { + type: "enum", + name: "core::bool", + variants: [ + { + name: "False", + type: "()", + }, + { + name: "True", + type: "()", + }, + ], + }, + { + type: "constructor", + name: "constructor", + inputs: [ + { + name: "owner", + type: "core::starknet::contract_address::ContractAddress", + }, + { + name: "vrf_coordinator", + type: "core::starknet::contract_address::ContractAddress", + }, + { + name: "dev_mode", + type: "core::bool", + }, + ], + }, + { + type: "struct", + name: "core::array::Span::", + members: [ + { + name: "snapshot", + type: "@core::array::Array::", + }, + ], + }, + { + type: "function", + name: "receive_random_words", + inputs: [ + { + name: "requester_address", + type: "core::starknet::contract_address::ContractAddress", + }, + { + name: "request_id", + type: "core::integer::u64", + }, + { + name: "random_words", + type: "core::array::Span::", + }, + { + name: "_calldata", + type: "core::array::Array::", + }, + ], + outputs: [], + state_mutability: "external", + }, + { + type: "function", + name: "mark_generation_failed", + inputs: [ + { + name: "id", + type: "core::integer::u64", + }, + { + name: "code", + type: "core::felt252", + }, + ], + outputs: [], + state_mutability: "external", + }, + { + type: "function", + name: "set_vrf_coordinator", + inputs: [ + { + name: "addr", + type: "core::starknet::contract_address::ContractAddress", + }, + ], + outputs: [], + state_mutability: "external", + }, + { + type: "event", + name: "openzeppelin_access::ownable::ownable::OwnableComponent::OwnershipTransferred", + kind: "struct", + members: [ + { + name: "previous_owner", + type: "core::starknet::contract_address::ContractAddress", + kind: "key", + }, + { + name: "new_owner", + type: "core::starknet::contract_address::ContractAddress", + kind: "key", + }, + ], + }, + { + type: "event", + name: "openzeppelin_access::ownable::ownable::OwnableComponent::OwnershipTransferStarted", + kind: "struct", + members: [ + { + name: "previous_owner", + type: "core::starknet::contract_address::ContractAddress", + kind: "key", + }, + { + name: "new_owner", + type: "core::starknet::contract_address::ContractAddress", + kind: "key", + }, + ], + }, + { + type: "event", + name: "openzeppelin_access::ownable::ownable::OwnableComponent::Event", + kind: "enum", + variants: [ + { + name: "OwnershipTransferred", + type: "openzeppelin_access::ownable::ownable::OwnableComponent::OwnershipTransferred", + kind: "nested", + }, + { + name: "OwnershipTransferStarted", + type: "openzeppelin_access::ownable::ownable::OwnableComponent::OwnershipTransferStarted", + kind: "nested", + }, + ], + }, + { + type: "event", + name: "starklotto_adapter_vrf::Randomness::Randomness::GenerationRequested", + kind: "struct", + members: [ + { + name: "id", + type: "core::integer::u64", + kind: "key", + }, + { + name: "requester", + type: "core::starknet::contract_address::ContractAddress", + kind: "data", + }, + { + name: "timestamp", + type: "core::integer::u64", + kind: "data", + }, + { + name: "is_test", + type: "core::bool", + kind: "data", + }, + ], + }, + { + type: "event", + name: "starklotto_adapter_vrf::Randomness::Randomness::GenerationCompleted", + kind: "struct", + members: [ + { + name: "id", + type: "core::integer::u64", + kind: "key", + }, + { + name: "n1", + type: "core::integer::u8", + kind: "data", + }, + { + name: "n2", + type: "core::integer::u8", + kind: "data", + }, + { + name: "n3", + type: "core::integer::u8", + kind: "data", + }, + { + name: "n4", + type: "core::integer::u8", + kind: "data", + }, + { + name: "n5", + type: "core::integer::u8", + kind: "data", + }, + { + name: "timestamp", + type: "core::integer::u64", + kind: "data", + }, + { + name: "is_test", + type: "core::bool", + kind: "data", + }, + ], + }, + { + type: "event", + name: "starklotto_adapter_vrf::Randomness::Randomness::GenerationFailed", + kind: "struct", + members: [ + { + name: "id", + type: "core::integer::u64", + kind: "key", + }, + { + name: "code", + type: "core::felt252", + kind: "data", + }, + { + name: "timestamp", + type: "core::integer::u64", + kind: "data", + }, + ], + }, + { + type: "event", + name: "starklotto_adapter_vrf::Randomness::Randomness::TestGeneration", + kind: "struct", + members: [ + { + name: "id", + type: "core::integer::u64", + kind: "key", + }, + { + name: "n1", + type: "core::integer::u8", + kind: "data", + }, + { + name: "n2", + type: "core::integer::u8", + kind: "data", + }, + { + name: "n3", + type: "core::integer::u8", + kind: "data", + }, + { + name: "n4", + type: "core::integer::u8", + kind: "data", + }, + { + name: "n5", + type: "core::integer::u8", + kind: "data", + }, + { + name: "timestamp", + type: "core::integer::u64", + kind: "data", + }, + ], + }, + { + type: "event", + name: "starklotto_adapter_vrf::Randomness::Randomness::Event", + kind: "enum", + variants: [ + { + name: "OwnableEvent", + type: "openzeppelin_access::ownable::ownable::OwnableComponent::Event", + kind: "flat", + }, + { + name: "GenerationRequested", + type: "starklotto_adapter_vrf::Randomness::Randomness::GenerationRequested", + kind: "nested", + }, + { + name: "GenerationCompleted", + type: "starklotto_adapter_vrf::Randomness::Randomness::GenerationCompleted", + kind: "nested", + }, + { + name: "GenerationFailed", + type: "starklotto_adapter_vrf::Randomness::Randomness::GenerationFailed", + kind: "nested", + }, + { + name: "TestGeneration", + type: "starklotto_adapter_vrf::Randomness::Randomness::TestGeneration", + kind: "nested", + }, + ], + }, + ], + classHash: + "0x342eab9caa3364fe668dfeaddf7c5ff2516f791c35e39dc7065c00e1b9fc017", + }, + }, +} as const; export default deployedContracts; diff --git a/packages/nextjs/hooks/scaffold-stark/index.ts b/packages/nextjs/hooks/scaffold-stark/index.ts index 0d54934..83da378 100644 --- a/packages/nextjs/hooks/scaffold-stark/index.ts +++ b/packages/nextjs/hooks/scaffold-stark/index.ts @@ -5,3 +5,4 @@ export * from "./useAnimationConfig"; export * from "./useTransactor"; export * from "./useAutoConnect"; export * from "./useSwitchNetwork"; +export * from "./useScaffoldMultiWriteContract"; diff --git a/packages/nextjs/public/sw.js b/packages/nextjs/public/sw.js new file mode 100644 index 0000000..924c508 --- /dev/null +++ b/packages/nextjs/public/sw.js @@ -0,0 +1,392 @@ +if (!self.define) { + let e, + s = {}; + const n = (n, i) => ( + (n = new URL(n + ".js", i).href), + s[n] || + new Promise((s) => { + if ("document" in self) { + const e = document.createElement("script"); + (e.src = n), (e.onload = s), document.head.appendChild(e); + } else (e = n), importScripts(n), s(); + }).then(() => { + let e = s[n]; + if (!e) throw new Error(`Module ${n} didn’t register its module`); + return e; + }) + ); + self.define = (i, c) => { + const a = + e || + ("document" in self ? document.currentScript.src : "") || + location.href; + if (s[a]) return; + let t = {}; + const r = (e) => n(e, a), + o = { module: { uri: a }, exports: t, require: r }; + s[a] = Promise.all(i.map((e) => o[e] || r(e))).then((e) => (c(...e), t)); + }; +} +define(["./workbox-4754cb34"], function (e) { + "use strict"; + importScripts(), + self.skipWaiting(), + e.clientsClaim(), + e.precacheAndRoute( + [ + { + url: "/_next/app-build-manifest.json", + revision: "b275a34557ea1a9cb4b65203cdd486b3", + }, + { + url: "/_next/static/FQQienyxJ-IKX7XJN9c-U/_buildManifest.js", + revision: "51da8d50ab8ae1c1afafe38c7e424e4e", + }, + { + url: "/_next/static/FQQienyxJ-IKX7XJN9c-U/_ssgManifest.js", + revision: "b6652df95db52feb4daf4eca35380933", + }, + { + url: "/_next/static/chunks/141-d196c46095c0e291.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/145-87bbd58530c47b49.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/2f0b94e8-734829800d3eb38b.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/473f56c0-0933f1e2ac7ad0b5.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/486-3b991d95cef62049.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/4bd1b696-48a906261550a4c5.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/658-e54429557207cf0c.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/668-1fc7cc2fee87ff24.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/684-3cf479aafee24c45.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/70646a03-d8bbffbaf77fafd0.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/850-4a1aa8fcc9cc8597.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/929-7d9534372e77efc8.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/94-3076be7aeedb9512.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/972.6d641f23fb3b1bd5.js", + revision: "6d641f23fb3b1bd5", + }, + { + url: "/_next/static/chunks/app/_not-found/page-04d3b5ab1d5bc6de.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/app/api/price/route-6c0ab67fce666a7b.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/app/configure/page-2501fcf559af4c9f.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/app/debug/page-00e35916938cbdb1.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/app/debug/randomness/page-01ec39be690d1ca3.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/app/layout-2dc3d265bddc1be4.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/app/page-f53cfa65768f16c0.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/e6909d18-d7c7e73117910c02.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/framework-859199dea06580b0.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/main-a106802aa546c841.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/main-app-58ca74d35777be74.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/pages/_app-da15c11dea942c36.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/pages/_error-cc3f077a18ea1793.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/chunks/polyfills-42372ed130431b0a.js", + revision: "846118c33b2c0e922d7b3a7676f81f6f", + }, + { + url: "/_next/static/chunks/webpack-8cb4a62bb51bf237.js", + revision: "FQQienyxJ-IKX7XJN9c-U", + }, + { + url: "/_next/static/css/a3de78c781ee431c.css", + revision: "a3de78c781ee431c", + }, + { + url: "/blast-icon-color.svg", + revision: "f455c22475a343be9fcd764de7e7147e", + }, + { + url: "/debug-icon.svg", + revision: "25aadc709736507034d14ca7aabcd29d", + }, + { + url: "/debug-image.png", + revision: "34c4ca2676dd59ff24d6338faa1af371", + }, + { + url: "/explorer-icon.svg", + revision: "84507da0e8989bb5b7616a3f66d31f48", + }, + { + url: "/gradient-s.svg", + revision: "c003f595a6d30b1b476115f64476e2cf", + }, + { url: "/logo.ico", revision: "0359e607e29a3d3b08095d84a9d25c39" }, + { url: "/logo.svg", revision: "962a8546ade641ef7ad4e1b669f0548c" }, + { url: "/manifest.json", revision: "781788f3e2bc4b2b176b5d8c425d7475" }, + { + url: "/rpc-version.png", + revision: "cf97fd668cfa1221bec0210824978027", + }, + { + url: "/scaffold-config.png", + revision: "1ebfc244c31732dc4273fe292bd07596", + }, + { + url: "/sn-symbol-gradient.png", + revision: "908b60a4f6b92155b8ea38a009fa7081", + }, + { + url: "/starkcompass-icon.svg", + revision: "eccc2ece017ee9e73e512996b74e49ac", + }, + { + url: "/voyager-icon.svg", + revision: "06663dd5ba2c49423225a8e3893b45fe", + }, + ], + { ignoreURLParametersMatching: [] }, + ), + e.cleanupOutdatedCaches(), + e.registerRoute( + "/", + new e.NetworkFirst({ + cacheName: "start-url", + plugins: [ + { + cacheWillUpdate: async ({ + request: e, + response: s, + event: n, + state: i, + }) => + s && "opaqueredirect" === s.type + ? new Response(s.body, { + status: 200, + statusText: "OK", + headers: s.headers, + }) + : s, + }, + ], + }), + "GET", + ), + e.registerRoute( + /^https:\/\/fonts\.(?:gstatic)\.com\/.*/i, + new e.CacheFirst({ + cacheName: "google-fonts-webfonts", + plugins: [ + new e.ExpirationPlugin({ maxEntries: 4, maxAgeSeconds: 31536e3 }), + ], + }), + "GET", + ), + e.registerRoute( + /^https:\/\/fonts\.(?:googleapis)\.com\/.*/i, + new e.StaleWhileRevalidate({ + cacheName: "google-fonts-stylesheets", + plugins: [ + new e.ExpirationPlugin({ maxEntries: 4, maxAgeSeconds: 604800 }), + ], + }), + "GET", + ), + e.registerRoute( + /\.(?:eot|otf|ttc|ttf|woff|woff2|font.css)$/i, + new e.StaleWhileRevalidate({ + cacheName: "static-font-assets", + plugins: [ + new e.ExpirationPlugin({ maxEntries: 4, maxAgeSeconds: 604800 }), + ], + }), + "GET", + ), + e.registerRoute( + /\.(?:jpg|jpeg|gif|png|svg|ico|webp)$/i, + new e.StaleWhileRevalidate({ + cacheName: "static-image-assets", + plugins: [ + new e.ExpirationPlugin({ maxEntries: 64, maxAgeSeconds: 86400 }), + ], + }), + "GET", + ), + e.registerRoute( + /\/_next\/image\?url=.+$/i, + new e.StaleWhileRevalidate({ + cacheName: "next-image", + plugins: [ + new e.ExpirationPlugin({ maxEntries: 64, maxAgeSeconds: 86400 }), + ], + }), + "GET", + ), + e.registerRoute( + /\.(?:mp3|wav|ogg)$/i, + new e.CacheFirst({ + cacheName: "static-audio-assets", + plugins: [ + new e.RangeRequestsPlugin(), + new e.ExpirationPlugin({ maxEntries: 32, maxAgeSeconds: 86400 }), + ], + }), + "GET", + ), + e.registerRoute( + /\.(?:mp4)$/i, + new e.CacheFirst({ + cacheName: "static-video-assets", + plugins: [ + new e.RangeRequestsPlugin(), + new e.ExpirationPlugin({ maxEntries: 32, maxAgeSeconds: 86400 }), + ], + }), + "GET", + ), + e.registerRoute( + /\.(?:js)$/i, + new e.StaleWhileRevalidate({ + cacheName: "static-js-assets", + plugins: [ + new e.ExpirationPlugin({ maxEntries: 32, maxAgeSeconds: 86400 }), + ], + }), + "GET", + ), + e.registerRoute( + /\.(?:css|less)$/i, + new e.StaleWhileRevalidate({ + cacheName: "static-style-assets", + plugins: [ + new e.ExpirationPlugin({ maxEntries: 32, maxAgeSeconds: 86400 }), + ], + }), + "GET", + ), + e.registerRoute( + /\/_next\/data\/.+\/.+\.json$/i, + new e.StaleWhileRevalidate({ + cacheName: "next-data", + plugins: [ + new e.ExpirationPlugin({ maxEntries: 32, maxAgeSeconds: 86400 }), + ], + }), + "GET", + ), + e.registerRoute( + /\.(?:json|xml|csv)$/i, + new e.NetworkFirst({ + cacheName: "static-data-assets", + plugins: [ + new e.ExpirationPlugin({ maxEntries: 32, maxAgeSeconds: 86400 }), + ], + }), + "GET", + ), + e.registerRoute( + ({ url: e }) => { + if (!(self.origin === e.origin)) return !1; + const s = e.pathname; + return !s.startsWith("/api/auth/") && !!s.startsWith("/api/"); + }, + new e.NetworkFirst({ + cacheName: "apis", + networkTimeoutSeconds: 10, + plugins: [ + new e.ExpirationPlugin({ maxEntries: 16, maxAgeSeconds: 86400 }), + ], + }), + "GET", + ), + e.registerRoute( + ({ url: e }) => { + if (!(self.origin === e.origin)) return !1; + return !e.pathname.startsWith("/api/"); + }, + new e.NetworkFirst({ + cacheName: "others", + networkTimeoutSeconds: 10, + plugins: [ + new e.ExpirationPlugin({ maxEntries: 32, maxAgeSeconds: 86400 }), + ], + }), + "GET", + ), + e.registerRoute( + ({ url: e }) => !(self.origin === e.origin), + new e.NetworkFirst({ + cacheName: "cross-origin", + networkTimeoutSeconds: 10, + plugins: [ + new e.ExpirationPlugin({ maxEntries: 32, maxAgeSeconds: 3600 }), + ], + }), + "GET", + ); +}); diff --git a/packages/nextjs/public/workbox-4754cb34.js b/packages/nextjs/public/workbox-4754cb34.js new file mode 100644 index 0000000..3f04c68 --- /dev/null +++ b/packages/nextjs/public/workbox-4754cb34.js @@ -0,0 +1,1319 @@ +define(["exports"], function (t) { + "use strict"; + try { + self["workbox:core:6.5.4"] && _(); + } catch (t) {} + const e = (t, ...e) => { + let s = t; + return e.length > 0 && (s += ` :: ${JSON.stringify(e)}`), s; + }; + class s extends Error { + constructor(t, s) { + super(e(t, s)), (this.name = t), (this.details = s); + } + } + try { + self["workbox:routing:6.5.4"] && _(); + } catch (t) {} + const n = (t) => (t && "object" == typeof t ? t : { handle: t }); + class r { + constructor(t, e, s = "GET") { + (this.handler = n(e)), (this.match = t), (this.method = s); + } + setCatchHandler(t) { + this.catchHandler = n(t); + } + } + class i extends r { + constructor(t, e, s) { + super( + ({ url: e }) => { + const s = t.exec(e.href); + if (s && (e.origin === location.origin || 0 === s.index)) + return s.slice(1); + }, + e, + s, + ); + } + } + class a { + constructor() { + (this.t = new Map()), (this.i = new Map()); + } + get routes() { + return this.t; + } + addFetchListener() { + self.addEventListener("fetch", (t) => { + const { request: e } = t, + s = this.handleRequest({ request: e, event: t }); + s && t.respondWith(s); + }); + } + addCacheListener() { + self.addEventListener("message", (t) => { + if (t.data && "CACHE_URLS" === t.data.type) { + const { payload: e } = t.data, + s = Promise.all( + e.urlsToCache.map((e) => { + "string" == typeof e && (e = [e]); + const s = new Request(...e); + return this.handleRequest({ request: s, event: t }); + }), + ); + t.waitUntil(s), + t.ports && t.ports[0] && s.then(() => t.ports[0].postMessage(!0)); + } + }); + } + handleRequest({ request: t, event: e }) { + const s = new URL(t.url, location.href); + if (!s.protocol.startsWith("http")) return; + const n = s.origin === location.origin, + { params: r, route: i } = this.findMatchingRoute({ + event: e, + request: t, + sameOrigin: n, + url: s, + }); + let a = i && i.handler; + const o = t.method; + if ((!a && this.i.has(o) && (a = this.i.get(o)), !a)) return; + let c; + try { + c = a.handle({ url: s, request: t, event: e, params: r }); + } catch (t) { + c = Promise.reject(t); + } + const h = i && i.catchHandler; + return ( + c instanceof Promise && + (this.o || h) && + (c = c.catch(async (n) => { + if (h) + try { + return await h.handle({ + url: s, + request: t, + event: e, + params: r, + }); + } catch (t) { + t instanceof Error && (n = t); + } + if (this.o) return this.o.handle({ url: s, request: t, event: e }); + throw n; + })), + c + ); + } + findMatchingRoute({ url: t, sameOrigin: e, request: s, event: n }) { + const r = this.t.get(s.method) || []; + for (const i of r) { + let r; + const a = i.match({ url: t, sameOrigin: e, request: s, event: n }); + if (a) + return ( + (r = a), + ((Array.isArray(r) && 0 === r.length) || + (a.constructor === Object && 0 === Object.keys(a).length) || + "boolean" == typeof a) && + (r = void 0), + { route: i, params: r } + ); + } + return {}; + } + setDefaultHandler(t, e = "GET") { + this.i.set(e, n(t)); + } + setCatchHandler(t) { + this.o = n(t); + } + registerRoute(t) { + this.t.has(t.method) || this.t.set(t.method, []), + this.t.get(t.method).push(t); + } + unregisterRoute(t) { + if (!this.t.has(t.method)) + throw new s("unregister-route-but-not-found-with-method", { + method: t.method, + }); + const e = this.t.get(t.method).indexOf(t); + if (!(e > -1)) throw new s("unregister-route-route-not-registered"); + this.t.get(t.method).splice(e, 1); + } + } + let o; + const c = () => ( + o || ((o = new a()), o.addFetchListener(), o.addCacheListener()), o + ); + function h(t, e, n) { + let a; + if ("string" == typeof t) { + const s = new URL(t, location.href); + a = new r(({ url: t }) => t.href === s.href, e, n); + } else if (t instanceof RegExp) a = new i(t, e, n); + else if ("function" == typeof t) a = new r(t, e, n); + else { + if (!(t instanceof r)) + throw new s("unsupported-route-type", { + moduleName: "workbox-routing", + funcName: "registerRoute", + paramName: "capture", + }); + a = t; + } + return c().registerRoute(a), a; + } + try { + self["workbox:strategies:6.5.4"] && _(); + } catch (t) {} + const u = { + cacheWillUpdate: async ({ response: t }) => + 200 === t.status || 0 === t.status ? t : null, + }, + l = { + googleAnalytics: "googleAnalytics", + precache: "precache-v2", + prefix: "workbox", + runtime: "runtime", + suffix: "undefined" != typeof registration ? registration.scope : "", + }, + f = (t) => + [l.prefix, t, l.suffix].filter((t) => t && t.length > 0).join("-"), + w = (t) => t || f(l.precache), + d = (t) => t || f(l.runtime); + function p(t, e) { + const s = new URL(t); + for (const t of e) s.searchParams.delete(t); + return s.href; + } + class y { + constructor() { + this.promise = new Promise((t, e) => { + (this.resolve = t), (this.reject = e); + }); + } + } + const g = new Set(); + function m(t) { + return "string" == typeof t ? new Request(t) : t; + } + class v { + constructor(t, e) { + (this.h = {}), + Object.assign(this, e), + (this.event = e.event), + (this.u = t), + (this.l = new y()), + (this.p = []), + (this.m = [...t.plugins]), + (this.v = new Map()); + for (const t of this.m) this.v.set(t, {}); + this.event.waitUntil(this.l.promise); + } + async fetch(t) { + const { event: e } = this; + let n = m(t); + if ( + "navigate" === n.mode && + e instanceof FetchEvent && + e.preloadResponse + ) { + const t = await e.preloadResponse; + if (t) return t; + } + const r = this.hasCallback("fetchDidFail") ? n.clone() : null; + try { + for (const t of this.iterateCallbacks("requestWillFetch")) + n = await t({ request: n.clone(), event: e }); + } catch (t) { + if (t instanceof Error) + throw new s("plugin-error-request-will-fetch", { + thrownErrorMessage: t.message, + }); + } + const i = n.clone(); + try { + let t; + t = await fetch( + n, + "navigate" === n.mode ? void 0 : this.u.fetchOptions, + ); + for (const s of this.iterateCallbacks("fetchDidSucceed")) + t = await s({ event: e, request: i, response: t }); + return t; + } catch (t) { + throw ( + (r && + (await this.runCallbacks("fetchDidFail", { + error: t, + event: e, + originalRequest: r.clone(), + request: i.clone(), + })), + t) + ); + } + } + async fetchAndCachePut(t) { + const e = await this.fetch(t), + s = e.clone(); + return this.waitUntil(this.cachePut(t, s)), e; + } + async cacheMatch(t) { + const e = m(t); + let s; + const { cacheName: n, matchOptions: r } = this.u, + i = await this.getCacheKey(e, "read"), + a = Object.assign(Object.assign({}, r), { cacheName: n }); + s = await caches.match(i, a); + for (const t of this.iterateCallbacks("cachedResponseWillBeUsed")) + s = + (await t({ + cacheName: n, + matchOptions: r, + cachedResponse: s, + request: i, + event: this.event, + })) || void 0; + return s; + } + async cachePut(t, e) { + const n = m(t); + var r; + await ((r = 0), new Promise((t) => setTimeout(t, r))); + const i = await this.getCacheKey(n, "write"); + if (!e) + throw new s("cache-put-with-no-response", { + url: + ((a = i.url), + new URL(String(a), location.href).href.replace( + new RegExp(`^${location.origin}`), + "", + )), + }); + var a; + const o = await this.R(e); + if (!o) return !1; + const { cacheName: c, matchOptions: h } = this.u, + u = await self.caches.open(c), + l = this.hasCallback("cacheDidUpdate"), + f = l + ? await (async function (t, e, s, n) { + const r = p(e.url, s); + if (e.url === r) return t.match(e, n); + const i = Object.assign(Object.assign({}, n), { + ignoreSearch: !0, + }), + a = await t.keys(e, i); + for (const e of a) if (r === p(e.url, s)) return t.match(e, n); + })(u, i.clone(), ["__WB_REVISION__"], h) + : null; + try { + await u.put(i, l ? o.clone() : o); + } catch (t) { + if (t instanceof Error) + throw ( + ("QuotaExceededError" === t.name && + (await (async function () { + for (const t of g) await t(); + })()), + t) + ); + } + for (const t of this.iterateCallbacks("cacheDidUpdate")) + await t({ + cacheName: c, + oldResponse: f, + newResponse: o.clone(), + request: i, + event: this.event, + }); + return !0; + } + async getCacheKey(t, e) { + const s = `${t.url} | ${e}`; + if (!this.h[s]) { + let n = t; + for (const t of this.iterateCallbacks("cacheKeyWillBeUsed")) + n = m( + await t({ + mode: e, + request: n, + event: this.event, + params: this.params, + }), + ); + this.h[s] = n; + } + return this.h[s]; + } + hasCallback(t) { + for (const e of this.u.plugins) if (t in e) return !0; + return !1; + } + async runCallbacks(t, e) { + for (const s of this.iterateCallbacks(t)) await s(e); + } + *iterateCallbacks(t) { + for (const e of this.u.plugins) + if ("function" == typeof e[t]) { + const s = this.v.get(e), + n = (n) => { + const r = Object.assign(Object.assign({}, n), { state: s }); + return e[t](r); + }; + yield n; + } + } + waitUntil(t) { + return this.p.push(t), t; + } + async doneWaiting() { + let t; + for (; (t = this.p.shift()); ) await t; + } + destroy() { + this.l.resolve(null); + } + async R(t) { + let e = t, + s = !1; + for (const t of this.iterateCallbacks("cacheWillUpdate")) + if ( + ((e = + (await t({ + request: this.request, + response: e, + event: this.event, + })) || void 0), + (s = !0), + !e) + ) + break; + return s || (e && 200 !== e.status && (e = void 0)), e; + } + } + class R { + constructor(t = {}) { + (this.cacheName = d(t.cacheName)), + (this.plugins = t.plugins || []), + (this.fetchOptions = t.fetchOptions), + (this.matchOptions = t.matchOptions); + } + handle(t) { + const [e] = this.handleAll(t); + return e; + } + handleAll(t) { + t instanceof FetchEvent && (t = { event: t, request: t.request }); + const e = t.event, + s = "string" == typeof t.request ? new Request(t.request) : t.request, + n = "params" in t ? t.params : void 0, + r = new v(this, { event: e, request: s, params: n }), + i = this.q(r, s, e); + return [i, this.D(i, r, s, e)]; + } + async q(t, e, n) { + let r; + await t.runCallbacks("handlerWillStart", { event: n, request: e }); + try { + if (((r = await this.U(e, t)), !r || "error" === r.type)) + throw new s("no-response", { url: e.url }); + } catch (s) { + if (s instanceof Error) + for (const i of t.iterateCallbacks("handlerDidError")) + if (((r = await i({ error: s, event: n, request: e })), r)) break; + if (!r) throw s; + } + for (const s of t.iterateCallbacks("handlerWillRespond")) + r = await s({ event: n, request: e, response: r }); + return r; + } + async D(t, e, s, n) { + let r, i; + try { + r = await t; + } catch (i) {} + try { + await e.runCallbacks("handlerDidRespond", { + event: n, + request: s, + response: r, + }), + await e.doneWaiting(); + } catch (t) { + t instanceof Error && (i = t); + } + if ( + (await e.runCallbacks("handlerDidComplete", { + event: n, + request: s, + response: r, + error: i, + }), + e.destroy(), + i) + ) + throw i; + } + } + function b(t) { + t.then(() => {}); + } + function q() { + return ( + (q = Object.assign + ? Object.assign.bind() + : function (t) { + for (var e = 1; e < arguments.length; e++) { + var s = arguments[e]; + for (var n in s) ({}).hasOwnProperty.call(s, n) && (t[n] = s[n]); + } + return t; + }), + q.apply(null, arguments) + ); + } + let D, U; + const x = new WeakMap(), + L = new WeakMap(), + I = new WeakMap(), + C = new WeakMap(), + E = new WeakMap(); + let N = { + get(t, e, s) { + if (t instanceof IDBTransaction) { + if ("done" === e) return L.get(t); + if ("objectStoreNames" === e) return t.objectStoreNames || I.get(t); + if ("store" === e) + return s.objectStoreNames[1] + ? void 0 + : s.objectStore(s.objectStoreNames[0]); + } + return k(t[e]); + }, + set: (t, e, s) => ((t[e] = s), !0), + has: (t, e) => + (t instanceof IDBTransaction && ("done" === e || "store" === e)) || + e in t, + }; + function O(t) { + return t !== IDBDatabase.prototype.transaction || + "objectStoreNames" in IDBTransaction.prototype + ? ( + U || + (U = [ + IDBCursor.prototype.advance, + IDBCursor.prototype.continue, + IDBCursor.prototype.continuePrimaryKey, + ]) + ).includes(t) + ? function (...e) { + return t.apply(B(this), e), k(x.get(this)); + } + : function (...e) { + return k(t.apply(B(this), e)); + } + : function (e, ...s) { + const n = t.call(B(this), e, ...s); + return I.set(n, e.sort ? e.sort() : [e]), k(n); + }; + } + function T(t) { + return "function" == typeof t + ? O(t) + : (t instanceof IDBTransaction && + (function (t) { + if (L.has(t)) return; + const e = new Promise((e, s) => { + const n = () => { + t.removeEventListener("complete", r), + t.removeEventListener("error", i), + t.removeEventListener("abort", i); + }, + r = () => { + e(), n(); + }, + i = () => { + s(t.error || new DOMException("AbortError", "AbortError")), + n(); + }; + t.addEventListener("complete", r), + t.addEventListener("error", i), + t.addEventListener("abort", i); + }); + L.set(t, e); + })(t), + (e = t), + ( + D || + (D = [ + IDBDatabase, + IDBObjectStore, + IDBIndex, + IDBCursor, + IDBTransaction, + ]) + ).some((t) => e instanceof t) + ? new Proxy(t, N) + : t); + var e; + } + function k(t) { + if (t instanceof IDBRequest) + return (function (t) { + const e = new Promise((e, s) => { + const n = () => { + t.removeEventListener("success", r), + t.removeEventListener("error", i); + }, + r = () => { + e(k(t.result)), n(); + }, + i = () => { + s(t.error), n(); + }; + t.addEventListener("success", r), t.addEventListener("error", i); + }); + return ( + e + .then((e) => { + e instanceof IDBCursor && x.set(e, t); + }) + .catch(() => {}), + E.set(e, t), + e + ); + })(t); + if (C.has(t)) return C.get(t); + const e = T(t); + return e !== t && (C.set(t, e), E.set(e, t)), e; + } + const B = (t) => E.get(t); + const P = ["get", "getKey", "getAll", "getAllKeys", "count"], + M = ["put", "add", "delete", "clear"], + W = new Map(); + function j(t, e) { + if (!(t instanceof IDBDatabase) || e in t || "string" != typeof e) return; + if (W.get(e)) return W.get(e); + const s = e.replace(/FromIndex$/, ""), + n = e !== s, + r = M.includes(s); + if ( + !(s in (n ? IDBIndex : IDBObjectStore).prototype) || + (!r && !P.includes(s)) + ) + return; + const i = async function (t, ...e) { + const i = this.transaction(t, r ? "readwrite" : "readonly"); + let a = i.store; + return ( + n && (a = a.index(e.shift())), + (await Promise.all([a[s](...e), r && i.done]))[0] + ); + }; + return W.set(e, i), i; + } + N = ((t) => + q({}, t, { + get: (e, s, n) => j(e, s) || t.get(e, s, n), + has: (e, s) => !!j(e, s) || t.has(e, s), + }))(N); + try { + self["workbox:expiration:6.5.4"] && _(); + } catch (t) {} + const S = "cache-entries", + K = (t) => { + const e = new URL(t, location.href); + return (e.hash = ""), e.href; + }; + class A { + constructor(t) { + (this._ = null), (this.L = t); + } + I(t) { + const e = t.createObjectStore(S, { keyPath: "id" }); + e.createIndex("cacheName", "cacheName", { unique: !1 }), + e.createIndex("timestamp", "timestamp", { unique: !1 }); + } + C(t) { + this.I(t), + this.L && + (function (t, { blocked: e } = {}) { + const s = indexedDB.deleteDatabase(t); + e && s.addEventListener("blocked", (t) => e(t.oldVersion, t)), + k(s).then(() => {}); + })(this.L); + } + async setTimestamp(t, e) { + const s = { + url: (t = K(t)), + timestamp: e, + cacheName: this.L, + id: this.N(t), + }, + n = (await this.getDb()).transaction(S, "readwrite", { + durability: "relaxed", + }); + await n.store.put(s), await n.done; + } + async getTimestamp(t) { + const e = await this.getDb(), + s = await e.get(S, this.N(t)); + return null == s ? void 0 : s.timestamp; + } + async expireEntries(t, e) { + const s = await this.getDb(); + let n = await s + .transaction(S) + .store.index("timestamp") + .openCursor(null, "prev"); + const r = []; + let i = 0; + for (; n; ) { + const s = n.value; + s.cacheName === this.L && + ((t && s.timestamp < t) || (e && i >= e) ? r.push(n.value) : i++), + (n = await n.continue()); + } + const a = []; + for (const t of r) await s.delete(S, t.id), a.push(t.url); + return a; + } + N(t) { + return this.L + "|" + K(t); + } + async getDb() { + return ( + this._ || + (this._ = await (function ( + t, + e, + { blocked: s, upgrade: n, blocking: r, terminated: i } = {}, + ) { + const a = indexedDB.open(t, e), + o = k(a); + return ( + n && + a.addEventListener("upgradeneeded", (t) => { + n( + k(a.result), + t.oldVersion, + t.newVersion, + k(a.transaction), + t, + ); + }), + s && + a.addEventListener("blocked", (t) => + s(t.oldVersion, t.newVersion, t), + ), + o + .then((t) => { + i && t.addEventListener("close", () => i()), + r && + t.addEventListener("versionchange", (t) => + r(t.oldVersion, t.newVersion, t), + ); + }) + .catch(() => {}), + o + ); + })("workbox-expiration", 1, { upgrade: this.C.bind(this) })), + this._ + ); + } + } + class F { + constructor(t, e = {}) { + (this.O = !1), + (this.T = !1), + (this.k = e.maxEntries), + (this.B = e.maxAgeSeconds), + (this.P = e.matchOptions), + (this.L = t), + (this.M = new A(t)); + } + async expireEntries() { + if (this.O) return void (this.T = !0); + this.O = !0; + const t = this.B ? Date.now() - 1e3 * this.B : 0, + e = await this.M.expireEntries(t, this.k), + s = await self.caches.open(this.L); + for (const t of e) await s.delete(t, this.P); + (this.O = !1), this.T && ((this.T = !1), b(this.expireEntries())); + } + async updateTimestamp(t) { + await this.M.setTimestamp(t, Date.now()); + } + async isURLExpired(t) { + if (this.B) { + const e = await this.M.getTimestamp(t), + s = Date.now() - 1e3 * this.B; + return void 0 === e || e < s; + } + return !1; + } + async delete() { + (this.T = !1), await this.M.expireEntries(1 / 0); + } + } + try { + self["workbox:range-requests:6.5.4"] && _(); + } catch (t) {} + async function H(t, e) { + try { + if (206 === e.status) return e; + const n = t.headers.get("range"); + if (!n) throw new s("no-range-header"); + const r = (function (t) { + const e = t.trim().toLowerCase(); + if (!e.startsWith("bytes=")) + throw new s("unit-must-be-bytes", { normalizedRangeHeader: e }); + if (e.includes(",")) + throw new s("single-range-only", { normalizedRangeHeader: e }); + const n = /(\d*)-(\d*)/.exec(e); + if (!n || (!n[1] && !n[2])) + throw new s("invalid-range-values", { normalizedRangeHeader: e }); + return { + start: "" === n[1] ? void 0 : Number(n[1]), + end: "" === n[2] ? void 0 : Number(n[2]), + }; + })(n), + i = await e.blob(), + a = (function (t, e, n) { + const r = t.size; + if ((n && n > r) || (e && e < 0)) + throw new s("range-not-satisfiable", { size: r, end: n, start: e }); + let i, a; + return ( + void 0 !== e && void 0 !== n + ? ((i = e), (a = n + 1)) + : void 0 !== e && void 0 === n + ? ((i = e), (a = r)) + : void 0 !== n && void 0 === e && ((i = r - n), (a = r)), + { start: i, end: a } + ); + })(i, r.start, r.end), + o = i.slice(a.start, a.end), + c = o.size, + h = new Response(o, { + status: 206, + statusText: "Partial Content", + headers: e.headers, + }); + return ( + h.headers.set("Content-Length", String(c)), + h.headers.set( + "Content-Range", + `bytes ${a.start}-${a.end - 1}/${i.size}`, + ), + h + ); + } catch (t) { + return new Response("", { + status: 416, + statusText: "Range Not Satisfiable", + }); + } + } + function $(t, e) { + const s = e(); + return t.waitUntil(s), s; + } + try { + self["workbox:precaching:6.5.4"] && _(); + } catch (t) {} + function z(t) { + if (!t) throw new s("add-to-cache-list-unexpected-type", { entry: t }); + if ("string" == typeof t) { + const e = new URL(t, location.href); + return { cacheKey: e.href, url: e.href }; + } + const { revision: e, url: n } = t; + if (!n) throw new s("add-to-cache-list-unexpected-type", { entry: t }); + if (!e) { + const t = new URL(n, location.href); + return { cacheKey: t.href, url: t.href }; + } + const r = new URL(n, location.href), + i = new URL(n, location.href); + return ( + r.searchParams.set("__WB_REVISION__", e), + { cacheKey: r.href, url: i.href } + ); + } + class G { + constructor() { + (this.updatedURLs = []), + (this.notUpdatedURLs = []), + (this.handlerWillStart = async ({ request: t, state: e }) => { + e && (e.originalRequest = t); + }), + (this.cachedResponseWillBeUsed = async ({ + event: t, + state: e, + cachedResponse: s, + }) => { + if ( + "install" === t.type && + e && + e.originalRequest && + e.originalRequest instanceof Request + ) { + const t = e.originalRequest.url; + s ? this.notUpdatedURLs.push(t) : this.updatedURLs.push(t); + } + return s; + }); + } + } + class V { + constructor({ precacheController: t }) { + (this.cacheKeyWillBeUsed = async ({ request: t, params: e }) => { + const s = + (null == e ? void 0 : e.cacheKey) || this.W.getCacheKeyForURL(t.url); + return s ? new Request(s, { headers: t.headers }) : t; + }), + (this.W = t); + } + } + let J, Q; + async function X(t, e) { + let n = null; + if (t.url) { + n = new URL(t.url).origin; + } + if (n !== self.location.origin) + throw new s("cross-origin-copy-response", { origin: n }); + const r = t.clone(), + i = { + headers: new Headers(r.headers), + status: r.status, + statusText: r.statusText, + }, + a = e ? e(i) : i, + o = (function () { + if (void 0 === J) { + const t = new Response(""); + if ("body" in t) + try { + new Response(t.body), (J = !0); + } catch (t) { + J = !1; + } + J = !1; + } + return J; + })() + ? r.body + : await r.blob(); + return new Response(o, a); + } + class Y extends R { + constructor(t = {}) { + (t.cacheName = w(t.cacheName)), + super(t), + (this.j = !1 !== t.fallbackToNetwork), + this.plugins.push(Y.copyRedirectedCacheableResponsesPlugin); + } + async U(t, e) { + const s = await e.cacheMatch(t); + return ( + s || + (e.event && "install" === e.event.type + ? await this.S(t, e) + : await this.K(t, e)) + ); + } + async K(t, e) { + let n; + const r = e.params || {}; + if (!this.j) + throw new s("missing-precache-entry", { + cacheName: this.cacheName, + url: t.url, + }); + { + const s = r.integrity, + i = t.integrity, + a = !i || i === s; + (n = await e.fetch( + new Request(t, { integrity: "no-cors" !== t.mode ? i || s : void 0 }), + )), + s && + a && + "no-cors" !== t.mode && + (this.A(), await e.cachePut(t, n.clone())); + } + return n; + } + async S(t, e) { + this.A(); + const n = await e.fetch(t); + if (!(await e.cachePut(t, n.clone()))) + throw new s("bad-precaching-response", { + url: t.url, + status: n.status, + }); + return n; + } + A() { + let t = null, + e = 0; + for (const [s, n] of this.plugins.entries()) + n !== Y.copyRedirectedCacheableResponsesPlugin && + (n === Y.defaultPrecacheCacheabilityPlugin && (t = s), + n.cacheWillUpdate && e++); + 0 === e + ? this.plugins.push(Y.defaultPrecacheCacheabilityPlugin) + : e > 1 && null !== t && this.plugins.splice(t, 1); + } + } + (Y.defaultPrecacheCacheabilityPlugin = { + cacheWillUpdate: async ({ response: t }) => + !t || t.status >= 400 ? null : t, + }), + (Y.copyRedirectedCacheableResponsesPlugin = { + cacheWillUpdate: async ({ response: t }) => + t.redirected ? await X(t) : t, + }); + class Z { + constructor({ + cacheName: t, + plugins: e = [], + fallbackToNetwork: s = !0, + } = {}) { + (this.F = new Map()), + (this.H = new Map()), + (this.$ = new Map()), + (this.u = new Y({ + cacheName: w(t), + plugins: [...e, new V({ precacheController: this })], + fallbackToNetwork: s, + })), + (this.install = this.install.bind(this)), + (this.activate = this.activate.bind(this)); + } + get strategy() { + return this.u; + } + precache(t) { + this.addToCacheList(t), + this.G || + (self.addEventListener("install", this.install), + self.addEventListener("activate", this.activate), + (this.G = !0)); + } + addToCacheList(t) { + const e = []; + for (const n of t) { + "string" == typeof n + ? e.push(n) + : n && void 0 === n.revision && e.push(n.url); + const { cacheKey: t, url: r } = z(n), + i = "string" != typeof n && n.revision ? "reload" : "default"; + if (this.F.has(r) && this.F.get(r) !== t) + throw new s("add-to-cache-list-conflicting-entries", { + firstEntry: this.F.get(r), + secondEntry: t, + }); + if ("string" != typeof n && n.integrity) { + if (this.$.has(t) && this.$.get(t) !== n.integrity) + throw new s("add-to-cache-list-conflicting-integrities", { + url: r, + }); + this.$.set(t, n.integrity); + } + if ((this.F.set(r, t), this.H.set(r, i), e.length > 0)) { + const t = `Workbox is precaching URLs without revision info: ${e.join(", ")}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`; + console.warn(t); + } + } + } + install(t) { + return $(t, async () => { + const e = new G(); + this.strategy.plugins.push(e); + for (const [e, s] of this.F) { + const n = this.$.get(s), + r = this.H.get(e), + i = new Request(e, { + integrity: n, + cache: r, + credentials: "same-origin", + }); + await Promise.all( + this.strategy.handleAll({ + params: { cacheKey: s }, + request: i, + event: t, + }), + ); + } + const { updatedURLs: s, notUpdatedURLs: n } = e; + return { updatedURLs: s, notUpdatedURLs: n }; + }); + } + activate(t) { + return $(t, async () => { + const t = await self.caches.open(this.strategy.cacheName), + e = await t.keys(), + s = new Set(this.F.values()), + n = []; + for (const r of e) s.has(r.url) || (await t.delete(r), n.push(r.url)); + return { deletedURLs: n }; + }); + } + getURLsToCacheKeys() { + return this.F; + } + getCachedURLs() { + return [...this.F.keys()]; + } + getCacheKeyForURL(t) { + const e = new URL(t, location.href); + return this.F.get(e.href); + } + getIntegrityForCacheKey(t) { + return this.$.get(t); + } + async matchPrecache(t) { + const e = t instanceof Request ? t.url : t, + s = this.getCacheKeyForURL(e); + if (s) { + return (await self.caches.open(this.strategy.cacheName)).match(s); + } + } + createHandlerBoundToURL(t) { + const e = this.getCacheKeyForURL(t); + if (!e) throw new s("non-precached-url", { url: t }); + return (s) => ( + (s.request = new Request(t)), + (s.params = Object.assign({ cacheKey: e }, s.params)), + this.strategy.handle(s) + ); + } + } + const tt = () => (Q || (Q = new Z()), Q); + class et extends r { + constructor(t, e) { + super(({ request: s }) => { + const n = t.getURLsToCacheKeys(); + for (const r of (function* ( + t, + { + ignoreURLParametersMatching: e = [/^utm_/, /^fbclid$/], + directoryIndex: s = "index.html", + cleanURLs: n = !0, + urlManipulation: r, + } = {}, + ) { + const i = new URL(t, location.href); + (i.hash = ""), yield i.href; + const a = (function (t, e = []) { + for (const s of [...t.searchParams.keys()]) + e.some((t) => t.test(s)) && t.searchParams.delete(s); + return t; + })(i, e); + if ((yield a.href, s && a.pathname.endsWith("/"))) { + const t = new URL(a.href); + (t.pathname += s), yield t.href; + } + if (n) { + const t = new URL(a.href); + (t.pathname += ".html"), yield t.href; + } + if (r) { + const t = r({ url: i }); + for (const e of t) yield e.href; + } + })(s.url, e)) { + const e = n.get(r); + if (e) { + return { cacheKey: e, integrity: t.getIntegrityForCacheKey(e) }; + } + } + }, t.strategy); + } + } + (t.CacheFirst = class extends R { + async U(t, e) { + let n, + r = await e.cacheMatch(t); + if (!r) + try { + r = await e.fetchAndCachePut(t); + } catch (t) { + t instanceof Error && (n = t); + } + if (!r) throw new s("no-response", { url: t.url, error: n }); + return r; + } + }), + (t.ExpirationPlugin = class { + constructor(t = {}) { + (this.cachedResponseWillBeUsed = async ({ + event: t, + request: e, + cacheName: s, + cachedResponse: n, + }) => { + if (!n) return null; + const r = this.V(n), + i = this.J(s); + b(i.expireEntries()); + const a = i.updateTimestamp(e.url); + if (t) + try { + t.waitUntil(a); + } catch (t) {} + return r ? n : null; + }), + (this.cacheDidUpdate = async ({ cacheName: t, request: e }) => { + const s = this.J(t); + await s.updateTimestamp(e.url), await s.expireEntries(); + }), + (this.X = t), + (this.B = t.maxAgeSeconds), + (this.Y = new Map()), + t.purgeOnQuotaError && + (function (t) { + g.add(t); + })(() => this.deleteCacheAndMetadata()); + } + J(t) { + if (t === d()) throw new s("expire-custom-caches-only"); + let e = this.Y.get(t); + return e || ((e = new F(t, this.X)), this.Y.set(t, e)), e; + } + V(t) { + if (!this.B) return !0; + const e = this.Z(t); + if (null === e) return !0; + return e >= Date.now() - 1e3 * this.B; + } + Z(t) { + if (!t.headers.has("date")) return null; + const e = t.headers.get("date"), + s = new Date(e).getTime(); + return isNaN(s) ? null : s; + } + async deleteCacheAndMetadata() { + for (const [t, e] of this.Y) + await self.caches.delete(t), await e.delete(); + this.Y = new Map(); + } + }), + (t.NetworkFirst = class extends R { + constructor(t = {}) { + super(t), + this.plugins.some((t) => "cacheWillUpdate" in t) || + this.plugins.unshift(u), + (this.tt = t.networkTimeoutSeconds || 0); + } + async U(t, e) { + const n = [], + r = []; + let i; + if (this.tt) { + const { id: s, promise: a } = this.et({ + request: t, + logs: n, + handler: e, + }); + (i = s), r.push(a); + } + const a = this.st({ timeoutId: i, request: t, logs: n, handler: e }); + r.push(a); + const o = await e.waitUntil( + (async () => (await e.waitUntil(Promise.race(r))) || (await a))(), + ); + if (!o) throw new s("no-response", { url: t.url }); + return o; + } + et({ request: t, logs: e, handler: s }) { + let n; + return { + promise: new Promise((e) => { + n = setTimeout(async () => { + e(await s.cacheMatch(t)); + }, 1e3 * this.tt); + }), + id: n, + }; + } + async st({ timeoutId: t, request: e, logs: s, handler: n }) { + let r, i; + try { + i = await n.fetchAndCachePut(e); + } catch (t) { + t instanceof Error && (r = t); + } + return ( + t && clearTimeout(t), (!r && i) || (i = await n.cacheMatch(e)), i + ); + } + }), + (t.RangeRequestsPlugin = class { + constructor() { + this.cachedResponseWillBeUsed = async ({ + request: t, + cachedResponse: e, + }) => (e && t.headers.has("range") ? await H(t, e) : e); + } + }), + (t.StaleWhileRevalidate = class extends R { + constructor(t = {}) { + super(t), + this.plugins.some((t) => "cacheWillUpdate" in t) || + this.plugins.unshift(u); + } + async U(t, e) { + const n = e.fetchAndCachePut(t).catch(() => {}); + e.waitUntil(n); + let r, + i = await e.cacheMatch(t); + if (i); + else + try { + i = await n; + } catch (t) { + t instanceof Error && (r = t); + } + if (!i) throw new s("no-response", { url: t.url, error: r }); + return i; + } + }), + (t.cleanupOutdatedCaches = function () { + self.addEventListener("activate", (t) => { + const e = w(); + t.waitUntil( + (async (t, e = "-precache-") => { + const s = (await self.caches.keys()).filter( + (s) => + s.includes(e) && s.includes(self.registration.scope) && s !== t, + ); + return await Promise.all(s.map((t) => self.caches.delete(t))), s; + })(e).then((t) => {}), + ); + }); + }), + (t.clientsClaim = function () { + self.addEventListener("activate", () => self.clients.claim()); + }), + (t.precacheAndRoute = function (t, e) { + !(function (t) { + tt().precache(t); + })(t), + (function (t) { + const e = tt(); + h(new et(e, t)); + })(e); + }), + (t.registerRoute = h); +}); diff --git a/packages/nextjs/scaffold.config.ts b/packages/nextjs/scaffold.config.ts index 993d640..230cf80 100644 --- a/packages/nextjs/scaffold.config.ts +++ b/packages/nextjs/scaffold.config.ts @@ -13,7 +13,7 @@ export type ScaffoldConfig = { }; const scaffoldConfig = { - targetNetworks: [chains.devnet], + targetNetworks: [chains.sepolia], // Only show the Burner Wallet when running on devnet onlyLocalBurnerWallet: false, rpcProviderUrl: { diff --git a/packages/snfoundry/.tool-versions b/packages/snfoundry/.tool-versions index fdc07ce..7a1a975 100644 --- a/packages/snfoundry/.tool-versions +++ b/packages/snfoundry/.tool-versions @@ -1,3 +1,3 @@ -starknet-devnet 0.1.2 +starknet-devnet 0.4.0 starknet-foundry 0.31.0 -scarb 2.9.2 +scarb 2.12.1 diff --git a/packages/snfoundry/contracts/.tool-versions b/packages/snfoundry/contracts/.tool-versions index 45dcb27..7a1a975 100644 --- a/packages/snfoundry/contracts/.tool-versions +++ b/packages/snfoundry/contracts/.tool-versions @@ -1,3 +1,3 @@ starknet-devnet 0.4.0 starknet-foundry 0.31.0 -scarb 2.9.2 +scarb 2.12.1 diff --git a/packages/snfoundry/contracts/README_RANDOMNESS.md b/packages/snfoundry/contracts/README_RANDOMNESS.md new file mode 100644 index 0000000..e622856 --- /dev/null +++ b/packages/snfoundry/contracts/README_RANDOMNESS.md @@ -0,0 +1,113 @@ +## Guía: Contrato de Aleatoriedad (VRF Cartridge) para StarkLotto + +Esta guía explica cómo implementar desde cero el contrato `Randomness.cairo`, compilarlo y desplegarlo con Scaffold-Stark, y cómo probar la generación de números en Sepolia Testnet desde el `Debug` de la dApp. + +### 1) Requisitos previos +- Node.js 18+ +- Yarn +- Cairo/Scarb (instalación de Starknet Foundry) +- Wallet con fondos en la red que uses (devnet no requiere fondos) + +### 2) Estructura del proyecto relevante +- Código Cairo: `packages/snfoundry/contracts/src` +- Contrato nuevo: `Randomness.cairo` +- Export en `src/lib.cairo` +- Scripts de deploy: `packages/snfoundry/scripts-ts` +- Generación de artefactos para front: `packages/nextjs/contracts/deployedContracts.ts` + +### 3) Dependencias de VRF +En `packages/snfoundry/contracts/Scarb.toml` ya se declara la dependencia `cartridge_vrf`. + +### 4) Contrato `Randomness.cairo` +El contrato implementa: +- Solicitud de aleatoriedad (producción) vía VRF (Cartridge). +- Generación local para devnet (`devnet_generate`). +- Almacenamiento transparente: ID incremental, estado, timestamps, números. +- Eventos: requested, completed, failed y test. +- Lecturas: `get_generation_numbers`, `get_generation_status`, `get_generation_timestamps`, `get_latest_id`. + +Constructor: +```text +constructor(owner: ContractAddress, vrf_coordinator: ContractAddress, dev_mode: bool) +``` + +Entradas principales: +- `request_randomness_prod(seed, callback_fee_limit, publish_delay) -> id` +- `devnet_generate(seed) -> id` +- `receive_random_words(...)` (callback VRF, expuesto como `external`) + +Notas importantes: +- El contrato valida rango 1..49 y unicidad en 5 números derivados. +- Para producción, debes pasar la dirección del coordinador VRF real al constructor o usar `set_vrf_coordinator`. + +### 5) Compilar contratos +Desde la raíz del workspace del paquete `snfoundry`: +```bash +yarn workspace @ss-2/snfoundry compile +``` + +Si hay errores, verifica `Scarb.toml` y que `lib.cairo` exporte `pub mod Randomness;`. + +### 6) Deploy con Scaffold-Stark +El script `packages/snfoundry/scripts-ts/deploy.ts` ya apunta a `Randomness` y utiliza constructor con: +- `owner = deployer.address` +- `vrf_coordinator = deployer.address` (placeholder en devnet) +- `dev_mode = true` + +Para devnet: +```bash +yarn workspace @ss-2/snfoundry deploy --network devnet +``` + +Para Sepolia (testnet): +1. Configura variables en `packages/snfoundry/.env` (cuenta, provider RPC). +2. Ajusta el `vrf_coordinator` a la dirección del coordinador VRF de Cartridge en Sepolia. +3. Ejecuta: +```bash +yarn workspace @ss-2/snfoundry deploy --network sepolia +``` + +Al final, el script actualizará `packages/nextjs/contracts/deployedContracts.ts` con dirección y ABI. + +### 7) Probar en Debug (Scaffold) – Devnet +1. Ejecuta la dApp: +```bash +yarn workspace @ss-2/nextjs dev +``` +2. Abre `http://localhost:3000/debug` y localiza el contrato `Randomness` desplegado. +3. Prueba el flujo dev: + - Llama `devnet_generate(seed: u64)` → retorna `id`. + - Llama `get_generation_status(id)` → debe ser `2` (COMPLETED). + - Llama `get_generation_numbers(id)` → devuelve `[n1..n5]`, únicos en 1..49. + - Revisa eventos `TestGeneration` y timestamps con `get_generation_timestamps(id)`. + +### 8) Probar en Debug – Testnet (Sepolia) +1. Asegúrate de haber desplegado con `dev_mode=false` si no necesitas pruebas locales. +2. Asegúrate de que `vrf_coordinator` apunte al coordinador VRF de Cartridge. +3. (Opcional) Financia el contrato si el oracle requiere fees para callback. +4. En `Debug` del front: + - Llama `request_randomness_prod(seed, callback_fee_limit, publish_delay)` → retorna `id`. + - Espera el fulfillment del VRF; luego `get_generation_status(id)` → `2`. + - Llama `get_generation_numbers(id)`. + - Revisa los eventos `GenerationRequested` y `GenerationCompleted`. + +### 9) Consideraciones de producción +- Reemplaza el placeholder del import/comentario del dispatcher VRF por el real de `cartridge_vrf` y ajusta los nombres de interfaz si difieren. +- Asegura control de acceso si deseas que sólo el owner pueda solicitar aleatoriedad. +- Cubre el costo de callback si el oracle lo requiere (aprobar tokens/ETH según documentación del VRF). +- Implementa monitoreo de eventos y reintentos mediante `mark_generation_failed` si hay problemas. + +### 10) Tests sugeridos (snforge) +- `devnet_generate` devuelve 5 valores únicos en 1..49. +- `get_generation_numbers` falla si el estado no es COMPLETED. +- Orden cronológico: `requested_at <= fulfilled_at`. +- Eventos emitidos correctamente. + +### 11) Errores comunes +- Constructor con `vrf_coordinator` incorrecto en testnet. +- ABI/artefactos no presentes por no compilar antes de deploy. +- No ejecutar `executeDeployCalls()` dentro del flujo de deploy. + +Con esto tendrás un flujo completo para generar números aleatorios trazables con un timeline transparente, tanto en devnet como en testnet con VRF de Cartridge. + + diff --git a/packages/snfoundry/contracts/Scarb.lock b/packages/snfoundry/contracts/Scarb.lock index 14a5014..b2be1ce 100644 --- a/packages/snfoundry/contracts/Scarb.lock +++ b/packages/snfoundry/contracts/Scarb.lock @@ -4,55 +4,122 @@ version = 1 [[package]] name = "cartridge_vrf" version = "0.1.0" -source = "git+https://github.com/cartridge-gg/vrf.git#38d71385f939a19829113c122f1ab12dbbe0f877" +source = "git+https://github.com/cartridge-gg/vrf.git#f748d4acab736464dcd96c5a4d047ed3aeb63801" +dependencies = [ + "openzeppelin", + "stark_vrf", +] + +[[package]] +name = "openzeppelin" +version = "2.0.0" +source = "registry+https://scarbs.xyz/" +checksum = "sha256:5e4fdecc957cfca7854d95912dc72d9f725517c063b116512900900add29fd77" dependencies = [ "openzeppelin_access", + "openzeppelin_account", + "openzeppelin_finance", + "openzeppelin_governance", + "openzeppelin_introspection", + "openzeppelin_merkle_tree", + "openzeppelin_presets", + "openzeppelin_security", + "openzeppelin_token", "openzeppelin_upgrades", - "snforge_std", - "stark_vrf", + "openzeppelin_utils", ] [[package]] name = "openzeppelin_access" -version = "0.18.0" +version = "2.0.0" source = "registry+https://scarbs.xyz/" -checksum = "sha256:424314072ae27d5b6f4264472a5c403711448ea62763a661b89e6ff5f23297fd" +checksum = "sha256:511681dd26d814ee2bc996d44ff8cb4aaa5ae9d14272130def7eb901cf004850" dependencies = [ "openzeppelin_introspection", - "openzeppelin_utils", ] [[package]] name = "openzeppelin_account" -version = "0.18.0" +version = "2.0.0" +source = "registry+https://scarbs.xyz/" +checksum = "sha256:fb3381c50d68b028d3801feb43df378e2bd62137b6884844f8f60aefe796188b" +dependencies = [ + "openzeppelin_introspection", + "openzeppelin_utils", +] + +[[package]] +name = "openzeppelin_finance" +version = "2.0.0" +source = "registry+https://scarbs.xyz/" +checksum = "sha256:e9456ef69502a87c4c99bf50145351b50950f8b11244847d92935c466c4ba787" +dependencies = [ + "openzeppelin_access", + "openzeppelin_token", +] + +[[package]] +name = "openzeppelin_governance" +version = "2.0.0" source = "registry+https://scarbs.xyz/" -checksum = "sha256:83e6571cac4c67049c8d0ab4e3c7ad146d582d7605e7354248835833e1d26c4a" +checksum = "sha256:056e6d6f3d48193b53f06283884f8a9675f986fc85425f6a40e8c1aeb3b3ecfa" dependencies = [ + "openzeppelin_access", + "openzeppelin_account", "openzeppelin_introspection", + "openzeppelin_token", "openzeppelin_utils", ] [[package]] name = "openzeppelin_introspection" -version = "0.18.0" +version = "2.0.0" source = "registry+https://scarbs.xyz/" -checksum = "sha256:46c4cc6c95c9baa4c7d5cc0ed2bdaf334f46c25a8c92b3012829fff936e3042b" +checksum = "sha256:87773ed6cd2318f169283ecbbb161890d1996260a80302d81ec45b70ee5e54c1" + +[[package]] +name = "openzeppelin_merkle_tree" +version = "2.0.0" +source = "registry+https://scarbs.xyz/" +checksum = "sha256:47f80c9ce59557774243214f8e75c5e866f30f3d8daa755855f6ffd01c89ca89" + +[[package]] +name = "openzeppelin_presets" +version = "2.0.0" +source = "registry+https://scarbs.xyz/" +checksum = "sha256:36c761ee923f1dc0887c0eab8c224b49ac242dbfe9163fbb0b08562042ab3d98" +dependencies = [ + "openzeppelin_access", + "openzeppelin_account", + "openzeppelin_finance", + "openzeppelin_introspection", + "openzeppelin_token", + "openzeppelin_upgrades", + "openzeppelin_utils", +] + +[[package]] +name = "openzeppelin_security" +version = "2.0.0" +source = "registry+https://scarbs.xyz/" +checksum = "sha256:902932ec296c2f400e0ac7c579edeaafd6067b6ce6d9854c1191de28e396ffe3" [[package]] name = "openzeppelin_testing" -version = "0.18.0" +version = "4.3.0" source = "registry+https://scarbs.xyz/" -checksum = "sha256:87a8f984f68870e0039fa678112a22ec67db263e53b5faa23775f495b14455d1" +checksum = "sha256:0cbdd8531a4bf7474a06492a671ed09f3b555e90e4a65180db341fcb43e2bcc1" dependencies = [ "snforge_std", ] [[package]] name = "openzeppelin_token" -version = "0.18.0" +version = "2.0.0" source = "registry+https://scarbs.xyz/" -checksum = "sha256:eafbe13f6a0487ce212459e25a81ae07f340ba76208ad4616626eb2d25a9625e" +checksum = "sha256:6fe61f63b5a6706018265fb7373b6e5bd3ff829bdc760b2b90296b1e708d180c" dependencies = [ + "openzeppelin_access", "openzeppelin_account", "openzeppelin_introspection", "openzeppelin_utils", @@ -60,35 +127,36 @@ dependencies = [ [[package]] name = "openzeppelin_upgrades" -version = "0.18.0" +version = "2.0.0" source = "registry+https://scarbs.xyz/" -checksum = "sha256:33c9d0865364fc18a5e7b471fe53c3b0f3e0aec56a94f435089638fad2a4a35b" +checksum = "sha256:560d57a9c3f3ec5a476e82fec8963c93c8df63a4ff9ff134f64ab8383bde3c61" [[package]] name = "openzeppelin_utils" -version = "0.18.0" +version = "2.0.0" source = "registry+https://scarbs.xyz/" -checksum = "sha256:725b212839f3eddc32791408609099c5e808c167ca0cf331d8c1d778b07a4e21" +checksum = "sha256:bf799c794139837f397975ffdf6a7ed5032d198bbf70e87a8f44f144a9dfc505" [[package]] name = "snforge_scarb_plugin" -version = "0.31.1" +version = "0.46.0" source = "registry+https://scarbs.xyz/" -checksum = "sha256:239c8566048808c7f15733f27f604623ed7ceb16324bacafed70291f2c4fe57e" +checksum = "sha256:6ffa10fe0ff525678138afd584fc2012e7b248f9c8e7b44aeae033cef3ee7826" [[package]] name = "snforge_std" -version = "0.31.1" +version = "0.46.0" source = "registry+https://scarbs.xyz/" -checksum = "sha256:1148da046c253f4e11e3d34cb9b99c9a45233381f48158a101a780746dc04a9d" +checksum = "sha256:a4d4b4d3e8506a3907d1eabacb058c390aa13a70132f475cba5e3dcd7a60d0bb" dependencies = [ "snforge_scarb_plugin", ] [[package]] name = "stark_vrf" -version = "0.1.0" -source = "git+https://github.com/dojoengine/stark-vrf.git#96d6d2a88b1ef46c4a285d0ccc334237205edae3" +version = "0.1.1" +source = "registry+https://scarbs.xyz/" +checksum = "sha256:5345a2ec33f50f7e372b74179b0421da022775b72b9de3c51cb15b7530482475" [[package]] name = "starklotto_adapter_vrf" diff --git a/packages/snfoundry/contracts/Scarb.toml b/packages/snfoundry/contracts/Scarb.toml index 5a65250..395b46f 100644 --- a/packages/snfoundry/contracts/Scarb.toml +++ b/packages/snfoundry/contracts/Scarb.toml @@ -1,25 +1,25 @@ [package] name = "starklotto_adapter_vrf" version = "0.1.0" -edition = "2023_10" +edition = "2024_07" # See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html [dependencies] -starknet = "2.9.2" +starknet = "2.12.1" cartridge_vrf = { git = "https://github.com/cartridge-gg/vrf.git" } -openzeppelin_access = "0.18.0" -openzeppelin_token = "0.18.0" +openzeppelin_access = "2.0.0" +openzeppelin_token = "2.0.0" [dev-dependencies] -openzeppelin_testing = "0.18.0" -openzeppelin_utils = "0.18.0" +openzeppelin_testing = "4.0.0" +openzeppelin_utils = "2.0.0" # vlf -snforge_std = "0.31.0" +snforge_std = "0.46.0" [[target.starknet-contract]] casm = true # taggle this to `false` to speed up compilation/script tests -allowed-libfuncs-list.name = "experimental" +sierra = true [tool.scarb] allow-prebuilt-plugins = [ diff --git a/packages/snfoundry/contracts/src/Randomness.cairo b/packages/snfoundry/contracts/src/Randomness.cairo new file mode 100644 index 0000000..aa1b016 --- /dev/null +++ b/packages/snfoundry/contracts/src/Randomness.cairo @@ -0,0 +1,433 @@ +#[starknet::interface] +pub trait IRandomnessLottery { + fn request_randomness_prod( + ref self: TContractState, seed: u64, callback_fee_limit: u128, publish_delay: u64, + ) -> u64; + + fn devnet_generate(ref self: TContractState, seed: u64) -> u64; + + fn get_generation_numbers(self: @TContractState, id: u64) -> Array; + + fn get_generation_status(self: @TContractState, id: u64) -> u8; + + fn get_generation_timestamps(self: @TContractState, id: u64) -> (u64, u64); + + fn get_latest_id(self: @TContractState) -> u64; +} + +#[starknet::contract] +pub mod Randomness { + // Cartridge VRF dispatcher (README of cartridge-gg/vrf) + use cartridge_vrf::{IVrfProviderDispatcher, IVrfProviderDispatcherTrait, Source}; + use openzeppelin_access::ownable::OwnableComponent; + use starknet::storage::{ + Map, StorageMapReadAccess, StorageMapWriteAccess, StoragePointerReadAccess, + StoragePointerWriteAccess, + }; + use starknet::{ContractAddress, get_block_timestamp, get_caller_address}; + use super::IRandomnessLottery; + + component!(path: OwnableComponent, storage: ownable, event: OwnableEvent); + + #[abi(embed_v0)] + impl OwnableImpl = OwnableComponent::OwnableImpl; + impl OwnableInternalImpl = OwnableComponent::InternalImpl; + + // Status codes + const STATUS_PENDING: u8 = 1_u8; + const STATUS_COMPLETED: u8 = 2_u8; + const STATUS_FAILED: u8 = 3_u8; + + #[event] + #[derive(Drop, starknet::Event)] + enum Event { + #[flat] + OwnableEvent: OwnableComponent::Event, + GenerationRequested: GenerationRequested, + GenerationCompleted: GenerationCompleted, + GenerationFailed: GenerationFailed, + TestGeneration: TestGeneration, + } + + #[derive(Drop, starknet::Event)] + struct GenerationRequested { + #[key] + id: u64, + requester: ContractAddress, + timestamp: u64, + is_test: bool, + } + + #[derive(Drop, starknet::Event)] + struct GenerationCompleted { + #[key] + id: u64, + n1: u8, + n2: u8, + n3: u8, + n4: u8, + n5: u8, + timestamp: u64, + is_test: bool, + } + + #[derive(Drop, starknet::Event)] + struct GenerationFailed { + #[key] + id: u64, + code: felt252, + timestamp: u64, + } + + #[derive(Drop, starknet::Event)] + struct TestGeneration { + #[key] + id: u64, + n1: u8, + n2: u8, + n3: u8, + n4: u8, + n5: u8, + timestamp: u64, + } + + #[storage] + struct Storage { + generation_counter: u64, + completed_counter: u64, + failed_counter: u64, + // status: 1 pending, 2 completed, 3 failed + generation_status: Map, + generation_is_test: Map, + // timestamps + requested_at: Map, + fulfilled_at: Map, + // store 5 numbers by (id, index) + numbers_by_generation: Map<(u64, u8), u8>, + // optional correlation with oracle request id + request_id_by_generation: Map, + generation_by_request_id: Map, + // config + vrf_coordinator: ContractAddress, + dev_mode: bool, + #[substorage(v0)] + ownable: OwnableComponent::Storage, + } + + #[constructor] + fn constructor( + ref self: ContractState, + owner: ContractAddress, + vrf_coordinator: ContractAddress, + dev_mode: bool, + ) { + self.ownable.initializer(owner); + self.vrf_coordinator.write(vrf_coordinator); + self.dev_mode.write(dev_mode); + self.generation_counter.write(0_u64); + self.completed_counter.write(0_u64); + self.failed_counter.write(0_u64); + } + + #[abi(embed_v0)] + impl RandomnessImpl of IRandomnessLottery { + fn request_randomness_prod( + ref self: ContractState, seed: u64, callback_fee_limit: u128, publish_delay: u64, + ) -> u64 { + // anyone can request; adjust to onlyOwner if needed + let next_id = self.generation_counter.read() + 1_u64; + self.generation_counter.write(next_id); + + self.generation_status.write(next_id, STATUS_PENDING); + self.generation_is_test.write(next_id, false); + self.requested_at.write(next_id, get_block_timestamp()); + + // Optional: correlate with a VRF request id (0 if unknown at this point) + self.request_id_by_generation.write(next_id, 0_u64); + + self + .emit( + GenerationRequested { + id: next_id, + requester: get_caller_address(), + timestamp: get_block_timestamp(), + is_test: false, + }, + ); + + // Consumo sincrónico de aleatorio usando Cartridge VRF. + // El caller debe prefijar la multicall con `request_random(caller, source)`. + // Aquí consumimos con el MISMO `Source`. + let vrf_addr = self.vrf_coordinator.read(); + let vrf = IVrfProviderDispatcher { contract_address: vrf_addr }; + let rand_felt: felt252 = vrf.consume_random(Source::Salt(seed.into())); + + // Derivar 5 números en [1,49] a partir del random consumido + let base_seed: u64 = felt_to_u64(rand_felt); + let mut nums = derive_five_unique_numbers(base_seed); + + // persistir números + let n1 = *nums.at(0); + let n2 = *nums.at(1); + let n3 = *nums.at(2); + let n4 = *nums.at(3); + let n5 = *nums.at(4); + + self.numbers_by_generation.write((next_id, 0_u8), n1); + self.numbers_by_generation.write((next_id, 1_u8), n2); + self.numbers_by_generation.write((next_id, 2_u8), n3); + self.numbers_by_generation.write((next_id, 3_u8), n4); + self.numbers_by_generation.write((next_id, 4_u8), n5); + + self.generation_status.write(next_id, STATUS_COMPLETED); + self.fulfilled_at.write(next_id, get_block_timestamp()); + self.completed_counter.write(self.completed_counter.read() + 1_u64); + + self + .emit( + GenerationCompleted { + id: next_id, + n1: n1, + n2: n2, + n3: n3, + n4: n4, + n5: n5, + timestamp: get_block_timestamp(), + is_test: false, + }, + ); + + next_id + } + + fn devnet_generate(ref self: ContractState, seed: u64) -> u64 { + assert(self.dev_mode.read(), 'DEV_DISABLED'); + + let next_id = self.generation_counter.read() + 1_u64; + self.generation_counter.write(next_id); + self.generation_status.write(next_id, STATUS_PENDING); + self.generation_is_test.write(next_id, true); + self.requested_at.write(next_id, get_block_timestamp()); + + let mut nums = derive_five_unique_numbers(seed); + // persist numbers + let n1 = *nums.at(0); + let n2 = *nums.at(1); + let n3 = *nums.at(2); + let n4 = *nums.at(3); + let n5 = *nums.at(4); + + self.numbers_by_generation.write((next_id, 0_u8), n1); + self.numbers_by_generation.write((next_id, 1_u8), n2); + self.numbers_by_generation.write((next_id, 2_u8), n3); + self.numbers_by_generation.write((next_id, 3_u8), n4); + self.numbers_by_generation.write((next_id, 4_u8), n5); + + self.generation_status.write(next_id, STATUS_COMPLETED); + self.fulfilled_at.write(next_id, get_block_timestamp()); + self.completed_counter.write(self.completed_counter.read() + 1_u64); + + self + .emit( + TestGeneration { + id: next_id, + n1: n1, + n2: n2, + n3: n3, + n4: n4, + n5: n5, + timestamp: get_block_timestamp(), + }, + ); + + next_id + } + + fn get_generation_numbers(self: @ContractState, id: u64) -> Array { + let status = self.generation_status.read(id); + assert(status == STATUS_COMPLETED, 'NOT_COMPLETED'); + + let mut arr: Array = array![]; + arr.append(self.numbers_by_generation.read((id, 0_u8))); + arr.append(self.numbers_by_generation.read((id, 1_u8))); + arr.append(self.numbers_by_generation.read((id, 2_u8))); + arr.append(self.numbers_by_generation.read((id, 3_u8))); + arr.append(self.numbers_by_generation.read((id, 4_u8))); + arr + } + + fn get_generation_status(self: @ContractState, id: u64) -> u8 { + self.generation_status.read(id) + } + + fn get_generation_timestamps(self: @ContractState, id: u64) -> (u64, u64) { + let req = self.requested_at.read(id); + let ful = self.fulfilled_at.read(id); + (req, ful) + } + + fn get_latest_id(self: @ContractState) -> u64 { + self.generation_counter.read() + } + } + + // This callback is intended to be called by the VRF coordinator (Cartridge) + // Adjust the signature if your VRF exposes a different callback interface. + // Common form inspired by existing VRF oracles: + // receive_random_words(requester_address, request_id, random_words, calldata) + #[external(v0)] + fn receive_random_words( + ref self: ContractState, + requester_address: ContractAddress, + request_id: u64, + random_words: Span, + _calldata: Array, + ) { + // only VRF coordinator can call + assert(get_caller_address() == self.vrf_coordinator.read(), 'ONLY_COORDINATOR'); + + // Map the request to a generation id if previously recorded, else create one ad-hoc. + let maybe_id = self.generation_by_request_id.read(request_id); + let mut id = maybe_id; + if id == 0_u64 { + // no mapping was set; create a new generation id to store this result + id = self.generation_counter.read() + 1_u64; + self.generation_counter.write(id); + self.generation_status.write(id, STATUS_PENDING); + self.generation_is_test.write(id, false); + self.requested_at.write(id, get_block_timestamp()); + self.request_id_by_generation.write(id, request_id); + self.generation_by_request_id.write(request_id, id); + self + .emit( + GenerationRequested { + id: id, + requester: requester_address, + timestamp: get_block_timestamp(), + is_test: false, + }, + ); + } + + // Defensive checks + assert(self.generation_status.read(id) == STATUS_PENDING, 'BAD_STATUS'); + + // Derive 5 unique numbers from the random words provided + let base_seed: u64 = derive_seed_from_words(random_words); + let mut nums = derive_five_unique_numbers(base_seed); + + // persist numbers + let n1 = *nums.at(0); + let n2 = *nums.at(1); + let n3 = *nums.at(2); + let n4 = *nums.at(3); + let n5 = *nums.at(4); + + self.numbers_by_generation.write((id, 0_u8), n1); + self.numbers_by_generation.write((id, 1_u8), n2); + self.numbers_by_generation.write((id, 2_u8), n3); + self.numbers_by_generation.write((id, 3_u8), n4); + self.numbers_by_generation.write((id, 4_u8), n5); + + self.generation_status.write(id, STATUS_COMPLETED); + self.fulfilled_at.write(id, get_block_timestamp()); + self.completed_counter.write(self.completed_counter.read() + 1_u64); + + self + .emit( + GenerationCompleted { + id: id, + n1: n1, + n2: n2, + n3: n3, + n4: n4, + n5: n5, + timestamp: get_block_timestamp(), + is_test: false, + }, + ); + } + + #[external(v0)] + fn mark_generation_failed(ref self: ContractState, id: u64, code: felt252) { + self.ownable.assert_only_owner(); + let status = self.generation_status.read(id); + assert(status == STATUS_PENDING, 'BAD_STATUS'); + self.generation_status.write(id, STATUS_FAILED); + self.fulfilled_at.write(id, get_block_timestamp()); + self.failed_counter.write(self.failed_counter.read() + 1_u64); + self.emit(GenerationFailed { id: id, code: code, timestamp: get_block_timestamp() }); + } + + // Admin helpers + #[external(v0)] + fn set_vrf_coordinator(ref self: ContractState, addr: ContractAddress) { + self.ownable.assert_only_owner(); + self.vrf_coordinator.write(addr); + } + + // ===== Helpers ===== + fn felt_to_u64(value: felt252) -> u64 { + let maybe_u128: Option = value.try_into(); + match maybe_u128 { + Option::Some(v_u128) => { + let mod64_divisor: u128 = 18446744073709551616_u128; // 2^64 + let mod64: u128 = v_u128 % mod64_divisor; + let out: u64 = mod64.try_into().unwrap(); + out + }, + Option::None => { 0_u64 }, + } + } + fn derive_seed_from_words(words: Span) -> u64 { + if words.len() == 0_usize { + return get_block_timestamp(); + } + let w0: felt252 = *words.at(0); + let maybe_u128: Option = w0.try_into(); + match maybe_u128 { + Option::Some(v_u128) => { + // 2^64 (usar literal directa; compila en u128) + let mod64_divisor: u128 = 18446744073709551616_u128; + let mod64: u128 = v_u128 % mod64_divisor; + let seed_u64: u64 = mod64.try_into().unwrap(); + seed_u64 + }, + Option::None => { get_block_timestamp() }, + } + } + + fn derive_five_unique_numbers(seed: u64) -> Array { + let mut out: Array = array![]; + let mut state_u128: u128 = seed.into(); + // LCG parameters over 2^64 domain + let a: u128 = 6364136223846793005_u128; // multiplier + let c: u128 = 1442695040888963407_u128; // increment + let modulus: u128 = 18446744073709551616_u128; // 2^64 + + while out.len() < 5_usize { + state_u128 = (state_u128 * a + c) % modulus; + let state: u64 = state_u128.try_into().unwrap(); + // candidate in [1,49] + let candidate: u8 = (((state % 49_u64) + 1_u64) % 256_u64).try_into().unwrap(); + if !contains_u8(@out, candidate) { + out.append(candidate); + } + } + out + } + + fn contains_u8(arr: @Array, value: u8) -> bool { + let mut i: usize = 0_usize; + let mut found: bool = false; + while i < arr.len() { + if *arr.at(i) == value { + found = true; + break; + } + i = i + 1_usize; + } + found + } +} + diff --git a/packages/snfoundry/contracts/src/lib.cairo b/packages/snfoundry/contracts/src/lib.cairo index fa5b5dc..39543b4 100644 --- a/packages/snfoundry/contracts/src/lib.cairo +++ b/packages/snfoundry/contracts/src/lib.cairo @@ -1,2 +1,3 @@ +pub mod Randomness; pub mod YourContract; diff --git a/packages/snfoundry/scripts-ts/deploy.ts b/packages/snfoundry/scripts-ts/deploy.ts index 2aacbbe..846b0d6 100644 --- a/packages/snfoundry/scripts-ts/deploy.ts +++ b/packages/snfoundry/scripts-ts/deploy.ts @@ -40,12 +40,34 @@ import { green } from "./helpers/colorize-log"; * * * @returns {Promise} - */ const deployScript = async (): Promise => { + await deployContract( + { + contract: "YourContract", + contractName: "YourContractExportName", + constructorArgs: { + owner: deployer.address, + }, + options: { + maxFee: BigInt(1000000000000) + } + } + ); + }; + +*/ + +const deployScript = async (): Promise => { + // Dirección del VRF provider de Cartridge en Sepolia testnet + const VRF_PROVIDER_ADDRESS = + "0x051fea4450da9d6aee758bdeba88b2f665bcbf549d2c61421aa724e9ac0ced8f"; + await deployContract({ - contract: "YourContract", + contract: "Randomness", constructorArgs: { owner: deployer.address, + vrf_coordinator: VRF_PROVIDER_ADDRESS, + dev_mode: true, }, }); }; diff --git a/packages/snfoundry/scripts-ts/helpers/parse-deployments.ts b/packages/snfoundry/scripts-ts/helpers/parse-deployments.ts index aa2490c..b754782 100644 --- a/packages/snfoundry/scripts-ts/helpers/parse-deployments.ts +++ b/packages/snfoundry/scripts-ts/helpers/parse-deployments.ts @@ -38,7 +38,7 @@ const getContractDataFromDeployments = (): Record< try { const abiFilePath = path.join( __dirname, - `../../contracts/target/dev/contracts_${contractData.contract}.contract_class.json` + `../../contracts/target/dev/starklotto_adapter_vrf_${contractData.contract}.contract_class.json` ); const abiContent: CompiledSierra = JSON.parse( fs.readFileSync(abiFilePath, "utf8")