# Implementation

#### 1. Import dependencies in your project

```tsx
import { ArgentTMA, SessionAccountInterface } from '@argent/tma-wallet';
```

#### 2. Initialize the ArgentTMA object

Initialize the `ArgentTMA` object with your app configuration:

```tsx
const argentTMA = ArgentTMA.init({
  environment: "sepolia", // "sepolia" | "mainnet" (Whitelisting required)
  appName: "My TG Mini Test Dapp", // Your Telegram app name
  appTelegramUrl: "<https://t.me/my_telegram_bot/app_name>", // Your Telegram app URL
  sessionParams: {
    allowedMethods: [
      // List of contracts/methods allowed to be called by the session key
      {
        contract:
          "0x036133c88c1954413150db74c26243e2af77170a4032934b275708d84ec5452f", // contract address
        selector: "increment", //function selector
      }
    ],
    validityDays: 90 // session validity (in days) - default: 90
  },
});
```

#### 3. Request a connection

If the user is not connected, call the `requestConnection()` method to open the wallet and ask the user to approve the connection. At the same time, you can ask user for token approvals:

```tsx
const handleConnectButton = async () => {
  await argentTMA.requestConnection({
        callbackData: 'custom_callback',
        approvalRequests: [
          {
            tokenAddress: '0x049D36570D4e46f48e99674bd3fcc84644DdD6b96F7C741B1562B82f9e004dC7',
            amount: BigInt(1000000000000000000).toString(),
            spender: 'spender_address',
          }
        ],
      });
};

```

The wallet will redirect back to your app and the account will be available from the `connect()` method.

#### 4. Check connection status

You can check if the user is connected at any time using the `isConnected()` method:

```tsx
const isConnected = argentTMA.isConnected();
```

#### 5. Connect to the wallet

Call the `connect()` method when your app loads to check if the user is already connected. It is also used to fetch the `account` object. It is an extended `starknet.js` account object.

For instance, you could wrap this in a `useEffect` hook.

```tsx
useEffect(() => {
    // Call connect() as soon as the app is loaded
    argentTMA
      .connect()
      .then((res) => {
        if (!res) {
          // Not connected
          setIsConnected(false);
          return;
        }
        
        const { account, callbackData } = res;

        if (account.getSessionStatus() !== "VALID") {
          // Session has expired or scope (allowed methods) has changed
          // A new connection request should be triggered

          // The account object is still available to get access to user's address
          // but transactions can't be executed
          const { account } = res;

          setAccount(account);
          setIsConnected(false);
          return;
        }

        // The session account is returned and can be used to submit transactions
        setAccount(account);
        setIsConnected(true);
        // Custom data passed to the requestConnection() method is available here
        console.log("callback data:", callbackData);
      })
      .catch((err) => {
        console.error("Failed to connect", err);
      });
  }, []);
```

#### 6. Interact with Starknet using the account

You can interact with your contracts using starknet.js. For instance, you could do this:

```tsx
const { transaction_hash } = await account.execute(myCall, {
      version: 3,
      maxFee: 10 ** 15,
      feeDataAvailabilityMode: RPC.EDataAvailabilityMode.L1,
      resourceBounds: {
        l1_gas: {
          max_amount: num.toHex(maxQtyGasAuthorized),
          max_price_per_unit: num.toHex(maxPriceAuthorizeForOneGas),
        },
        l2_gas: {
          max_amount: num.toHex(0),
          max_price_per_unit: num.toHex(0),
        },
      },
    });
```

#### 7. Check account session status

```tsx
const sessionStatus = account.getSessionStatus();
// "VALID" | "EXPIRED" | "INVALID_SCOPE" | "INVALID_SIGNATURE"
```

#### 8. Request approval

It is possible to ask to user to sign new approval transactions with `requestApprovals()`.

```typescript
async function handleApproval() {
    try {
      const res = await argentTMA.requestApprovals(
        [
          {
            tokenAddress: '0x049D36570D4e46f48e99674bd3fcc84644DdD6b96F7C741B1562B82f9e004dC7',
            amount: BigInt(1000000000000000000).toString(),
            spender: 'spender_address',
          }
        ],
      );
    } catch (error) {
      console.error('Approval failed:', error);
    }
  }
```

#### 9. Clear session

Calling `clearSession` removes the session object from local storage. It is mostly used for debugging. The session would still be valid on-chain.

We could imagine doing something like this:

```tsx
const handleClearSessionButton = async () => {
    await argentTMA.clearSession();
    setAccount(undefined);
  };
```

***

List of useful ressources:

* [npm package](https://www.npmjs.com/package/@argent/tma-wallet)
* [Tamagotchi coding tutorial](https://www.argent.xyz/blog/argent-telegram-tamagotchi)
* [Building a Telegram Game on Starknet](https://hackmd.io/@manoah22/Sk_eRyi1Jx#Building-a-Telegram-Game-on-Starknet-with-Argents-Wallet-SDK-A-Step-by-Step-Guide)


---

# 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.ready.co/telegram-wallet-deprecated/implementation.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.
