# Obter escrow

## Esquema

Isso valida um formulário de escrow usando Zod, incluindo endereços de carteira.

```typescript
import { z } from "zod";

export const formSchema = z.object({
  contractId: z.string().min(1, "ID do contrato é obrigatório"),
  signer: z.string().min(1, "Endereço do Signer é obrigatório"),
});

```

## Hook Personalizado

Isso contém toda a lógica do formulário, incluindo validação de esquema, função onSubmit e outros estados e funcionalidades.

```typescript
import { formSchema } from "../schemas/get-escrow-form.schema";
import { useWalletContext } from "@/providers/wallet.provider";
import { useEscrowContext } from "@/providers/escrow.provider";
import { useState } from "react";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { GetEscrowPayload } from "@/@types/escrows/escrow-payload.entity";
import { escrowService } from "../services/escrow.service";
import { toast } from "sonner";
import { Escrow } from "@/@types/escrows/escrow.entity";

export const useGetEscrowForm = () => {
  const { walletAddress } = useWalletContext();
  const { escrow, setEscrow } = useEscrowContext();
  const [loading, setLoading] = useState(false);
  const [response, setResponse] = useState<Escrow | null>(null);
  const [error, setError] = useState<string | null>(null);

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      contractId: escrow?.contractId || "",
      signer: walletAddress || "Conecte sua carteira para obter seu endereço",
    },
  });

  const onSubmit = async (payload: GetEscrowPayload) => {
    setLoading(true);
    setError(null);
    setResponse(null);
    try {
      /**
       * Chamada à API usando o serviço de escrow
       * @Nota:
       * - Precisamos especificar o endpoint e o método
       * - Precisamos especificar que returnEscrowDataIsRequired é false
       * - O resultado será um Escrow
       */
      const escrow = (await escrowService.execute({
        payload,
        endpoint: "/escrow/get-escrow-by-contract-id",
        method: "get",
        requiresSignature: false,
      })) as Escrow;

      /**
       * @Respostas:
       * escrow !== null
       * - Escrow recebido com sucesso
       * - Definir o escrow no contexto
       * - Mostrar um toast de sucesso
       *
       * escrow === null
       * - Mostrar um toast de erro
       */
      if (escrow) {
        setEscrow({ ...escrow, contractId: payload.contractId });
        setResponse(escrow);
        toast.info("Escrow Recebido");
      }
    } catch (err) {
      toast.error(
        err instanceof Error ? err.message : "Ocorreu um erro desconhecido"
      );
    } finally {
      setLoading(false);
    }
  };

  return { form, loading, response, error, onSubmit };
};

```

## Formulário

Este formulário é construído com react hook form. Usamos o hook personalizado e o esquema Zod mencionados anteriormente.

```typescript
"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
} from "@/components/ui/form";
import { useGetEscrowForm } from "../../hooks/get-escrow-form.hook";
import { ResponseDisplay } from "@/components/utils/response-display";

export function GetEscrowForm() {
  const { form, loading, response, onSubmit } = useGetEscrowForm();

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <FormField
          control={form.control}
          name="contractId"
          render={({ field }) => (
            <FormItem>
              <FormLabel>ID do Contrato / Escrow</FormLabel>
              <FormControl>
                <Input placeholder="CAZ6UQX7..." {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="signer"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Endereço do Assinante</FormLabel>
              <FormControl>
                <Input disabled placeholder="GSIGN...XYZ" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <Button type="submit" className="w-full" disabled={loading}>
          {loading ? "Obtendo Escrow..." : "Obter Escrow"}
        </Button>
      </form>

      <ResponseDisplay response={response} />
    </Form>
  );
}

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.trustlesswork.com/trustless-work/v1-pt/dapps-oss/escrow-lab/formularios/obter-escrow.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
