> 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/api-de-contexto.md).

# API de contexto

## Visão geral

Esta seção mostrará o código dos providers que usaremos, como para abas, carteira e escrow.&#x20;

## Gerenciamento de Estado Global das Abas

O gerenciamento de estado global das abas envolve manter e sincronizar o estado dos componentes de aba em toda a aplicação para garantir consistência e eficiência.

```typescript
"use client";

import { createContext, useContext, useState, ReactNode } from "react";

type Tabs = "deploy" | "escrow" | "helper";

interface TabsContextType {
  activeTab: Tabs;
  setActiveTab: (tab: Tabs) => void;
}

const TabsContext = createContext<TabsContextType | undefined>(undefined);

export function useTabsContext() {
  const context = useContext(TabsContext);
  if (!context) {
    throw new Error("useTabsContext must be used within TabsProvider");
  }
  return context;
}

export function TabsProvider({ children }: { children: ReactNode }) {
  const [activeTab, setActiveTab] = useState<Tabs>("deploy");

  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      {children}
    </TabsContext.Provider>
  );
}

```

## Gerenciamento de Estado Global do Escrow

O gerenciamento de estado global do escrow envolve lidar com o estado relacionado às funcionalidades de escrow dentro de uma aplicação. Isso garante que todos os componentes que interagem com operações de escrow mantenham um estado sincronizado.

```typescript
"use client";

import { Escrow } from "@/@types/escrows/escrow.entity";
import { createContext, useContext, useState, ReactNode } from "react";

/**
 *
 * Contexto do Escrow
 *
 */
interface EscrowContextProps {
  escrow: Escrow | null;
  setEscrow: (escrow: Escrow) => void;
  resetEscrow: () => void;
}

const EscrowContext = createContext<EscrowContextProps | undefined>(undefined);

/**
 * Provider do Escrow
 *
 * @Nota:
 * - Estamos usando useContext para fornecer o escrow único em todo o projeto. Mas no seu caso, você
 *   pode usar Redux ou Zustand para armazenar o escrow.
 *
 */
export const EscrowProvider = ({ children }: { children: ReactNode }) => {
  const [escrow, setEscrowState] = useState<Escrow | null>(null);

  /**
   * Definir Escrow
   *
   * @param newEscrow - Novo escrow
   */
  const setEscrow = (newEscrow: Escrow) => {
    setEscrowState(newEscrow);
  };

  /**
   * Resetar Escrow
   */
  const resetEscrow = () => {
    setEscrowState(null);
  };

  return (
    <EscrowContext.Provider value={{ escrow, setEscrow, resetEscrow }}>
      {children}
    </EscrowContext.Provider>
  );
};

export const useEscrowContext = () => {
  const context = useContext(EscrowContext);
  if (!context) {
    throw new Error("useEscrowContext must be used within EscrowProvider");
  }
  return context;
};

```

## Gerenciamento de Estado Global da Carteira

O gerenciamento de estado global da carteira garante o tratamento consistente dos estados relacionados à carteira em toda a aplicação.

```typescript
"use client";

import {
  createContext,
  useContext,
  useState,
  useEffect,
  ReactNode,
} from "react";

type WalletContextType = {
  walletAddress: string | null;
  walletName: string | null;
  setWalletInfo: (address: string, name: string) => void;
  clearWalletInfo: () => void;
};

const WalletContext = createContext<WalletContextType | undefined>(undefined);

export const WalletProvider = ({ children }: { children: ReactNode }) => {
  const [walletAddress, setWalletAddress] = useState<string | null>(null);
  const [walletName, setWalletName] = useState<string | null>(null);

  // Carregar ou definir informações da carteira a partir do localStorage
  useEffect(() => {
    const storedAddress = localStorage.getItem("walletAddress");
    const storedName = localStorage.getItem("walletName");

    if (storedAddress) setWalletAddress(storedAddress);
    if (storedName) setWalletName(storedName);
  }, []);

  /**
   * Definir informações da carteira
   *
   * @param address - Endereço da carteira
   * @param name - Nome da carteira
   */
  const setWalletInfo = (address: string, name: string) => {
    setWalletAddress(address);
    setWalletName(name);
    localStorage.setItem("walletAddress", address);
    localStorage.setItem("walletName", name);
  };

  /**
   * Limpar informações da carteira
   */
  const clearWalletInfo = () => {
    setWalletAddress(null);
    setWalletName(null);
    localStorage.removeItem("walletAddress");
    localStorage.removeItem("walletName");
  };

  return (
    <WalletContext.Provider
      value={{ walletAddress, walletName, setWalletInfo, clearWalletInfo }}
    >
      {children}
    </WalletContext.Provider>
  );
};

export const useWalletContext = () => {
  const context = useContext(WalletContext);
  if (!context) {
    throw new Error("useWalletContext must be used within WalletProvider");
  }
  return context;
};

```

## Provider Global

Construímos um provider global para gerenciar os providers.

```typescript
import { EscrowProvider } from "./escrow.provider";
import { WalletProvider } from "./wallet.provider";
import { TabsProvider } from "./tabs.provider";

export const GlobalProvider = ({ children }: { children: React.ReactNode }) => {
  return (
    <WalletProvider>
      <TabsProvider>
        <EscrowProvider>{children}</EscrowProvider>
      </TabsProvider>
    </WalletProvider>
  );
};

```


---

# 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, and the optional `goal` query parameter:

```
GET https://docs.trustlesswork.com/trustless-work/v1-pt/dapps-oss/escrow-lab/api-de-contexto.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
