> For the complete documentation index, see [llms.txt](https://docs.trustlesswork.com/trustless-work/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.trustlesswork.com/trustless-work/v1-pt/dapps-oss/escrow-lab/formularios/obter-saldos-de-multiplos-escrows.md).

# Obter saldos de múltiplos escrows

## 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({
  signer: z.string().min(1, "Endereço do signatário é obrigatório"),
  endereços: z
    .array(
      z.object({
        valor: z.string().min(1, "Endereço é obrigatório"),
      })
    )
    .min(1, "Pelo menos um endereço é 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 { useWalletContext } from "@/providers/wallet.provider";
import { useState } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { formSchema } from "../schemas/get-multiple-escrow-balances-form.schema";
import { toast } from "sonner";
import { escrowService } from "../services/escrow.service";
import { GetBalanceParams } from "@/@types/escrows/escrow-payload.entity";
import { EscrowRequestResponse } from "@/@types/escrows/escrow-response.entity";

type FormData = z.infer<typeof formSchema>;

export const useGetMultipleEscrowBalancesForm = () => {
  const { walletAddress } = useWalletContext();
  const [loading, setLoading] = useState(false);
  const [response, setResponse] = useState<EscrowRequestResponse | null>(null);

  const form = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      signer: walletAddress || "",
      addresses: [{ value: "" }],
    },
  });

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "addresses",
  });

  const onSubmit = async (payload: FormData) => {
    setLoading(true);
    setResponse(null);

    // Transform the payload to the correct format
    const transformedData: GetBalanceParams = {
      addresses: payload.addresses.map((a) => a.value),
      signer: payload.signer,
    };

    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 EscrowRequestResponse
       */
      const balances = (await escrowService.execute({
        payload: transformedData,
        endpoint: "/helper/get-multiple-escrow-balance",
        method: "get",
        requiresSignature: false,
        returnEscrowDataIsRequired: false,
      })) as EscrowRequestResponse;

      /**
       * @Respostas:
       * balances !== null
       * - Saldos de escrow recebidos com sucesso
       * - Definir a resposta
       * - Mostrar um toast de sucesso
       *
       * balances === null
       * - Mostrar um toast de erro
       */
      if (balances) {
        setResponse(balances);
        toast.info("Saldos de Escrow Recebidos");
      }
    } catch (err) {
      toast.error(
        err instanceof Error ? err.message : "Ocorreu um erro desconhecido"
      );
    } finally {
      setLoading(false);
    }
  };

  return { form, loading, response, fields, append, remove, 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
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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-saldos-de-multiplos-escrows.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.
