> ## Documentation Index
> Fetch the complete documentation index at: https://docs.groundtech.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Integrate PRIME on Tempo

> Deposit into your PRIME gVault, read customer balances and redeem shares on Tempo.

Before you start, [set up your gVault](https://docs.groundtech.co/v3/docs/gtokens/discover-yield-sources.md) and [allowlist the customer wallet](https://docs.groundtech.co/v3/docs/gtokens/manage-gtoken-access.md).

## 1. Connect to your PRIME gVault

Use your PRIME gVault's `contractAddress` from setup. Set `primeAssetId` to the underlying PRIME investment UUID returned as `assetId` by discovery. Connect the customer's wallet to Tempo.

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { ethers } from 'ethers';

async function connectPrimeGVault(signer, gVaults, primeAssetId) {
  const gVault = gVaults.find(vault =>
    vault.assetId === primeAssetId
  );
  if (!gVault) {
    throw new Error('No PRIME gVault is available');
  }

  const owner = await signer.getAddress();
  const vault = new ethers.Contract(gVault.contractAddress, [
    'function asset() view returns (address)',
    'function decimals() view returns (uint8)',
    'function balanceOf(address) view returns (uint256)',
    'function previewRedeem(uint256) view returns (uint256)',
    'function deposit(uint256,address,uint256) returns (uint256)',
    'function redeem(uint256,address,address,uint256) returns (uint256)',
  ], signer);
  const assetAddress = await vault.asset();
  if (assetAddress.toLowerCase() !== gVault.asset.contractAddress.toLowerCase()) {
    throw new Error('Funding asset does not match the gVault configuration');
  }

  const asset = new ethers.Contract(assetAddress, [
    'function decimals() view returns (uint8)',
    'function balanceOf(address) view returns (uint256)',
    'function approve(address,uint256) returns (bool)',
  ], signer);

  return { vault, asset, owner };
}

const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send('eth_requestAccounts', []);
const client = await connectPrimeGVault(provider.getSigner(), gVaults, primeAssetId);
```

## 2. Fund your sandbox wallet

For sandbox, get gTESTUSDC from Ground's [sandbox faucet](https://docs.groundtech.co/v3/api-reference/request-sandbox-tempo-usdc.md)
and gas fee tokens from the [Tempo faucet](https://docs.tempo.xyz/quickstart/faucet).
For production, continue to [Deposit assets](#3-deposit-assets) with the funding asset and gas fee tokens already in the customer's wallet.

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { randomUUID } from 'node:crypto';

const faucetUrl = 'https://sandbox.groundtech.co/v3/sandbox/faucets/tempo-usdc';
const headers = { Authorization: `Bearer ${process.env.GROUND_API_KEY}` };
const customerAddress = process.env.CUSTOMER_WALLET_ADDRESS;
const idempotencyKey = randomUUID();

const response = await fetch(faucetUrl, {
  method: 'POST',
  headers: {
    ...headers,
    'Content-Type': 'application/json',
    'Idempotency-Key': idempotencyKey,
  },
  body: JSON.stringify({ address: customerAddress, amount: '5' }),
});
if (!response.ok) throw new Error(await response.text());
const request = await response.json();
```

Save `request.id`. On your backend, poll until the transfer is `confirmed` before depositing:

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
async function waitForFaucet(id) {
  for (let attempt = 0; attempt < 30; attempt++) {
    const response = await fetch(`${faucetUrl}/${id}`, { headers });
    if (!response.ok) throw new Error(await response.text());
    const funding = await response.json();
    if (funding.status === 'confirmed') return funding;
    if (funding.status === 'failed') {
      throw new Error(`Faucet request ${id} failed`);
    }
    await new Promise(resolve => setTimeout(resolve, 2000));
  }
  throw new Error(`Faucet request ${id} is still pending`);
}

const funding = await waitForFaucet(request.id);
```

If polling times out, check the same request ID again. If the transfer fails,
contact Ground with the request ID before requesting another transfer.

## 3. Deposit assets

Back in your application, use the customer's wallet to approve the asset, simulate the deposit, then call `deposit`. This example accepts up to 0.5% fewer shares than the estimate. Choose a tolerance appropriate for your application.

`assetAmount` is a decimal string: `"1"` deposits one funding token.

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
async function depositPrime({ vault, asset, owner }, assetAmount) {
  const assets = ethers.utils.parseUnits(assetAmount, await asset.decimals());
  if (assets.lte(0)) throw new Error('Deposit amount must be positive');

  const approval = await asset.approve(vault.address, assets);
  await approval.wait();

  const expectedShares = await vault.callStatic.deposit(assets, owner, 1);
  const minShares = expectedShares.mul(9950).div(10000);
  if (minShares.isZero()) throw new Error('Deposit amount is too small');

  const transaction = await vault.deposit(assets, owner, minShares);
  const receipt = await transaction.wait();
  return {
    transactionHash: receipt.transactionHash,
    shareBalance: await vault.balanceOf(owner),
  };
}

const deposit = await depositPrime(client, '1');
```

When the deposit confirms, the customer receives shares. If simulation fails, check wallet access, the funding balance and the requested amount before submitting.

## 4. Read the customer's balance

Read the customer's shares and their estimated value in the funding asset:

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
async function readPrimePosition({ vault, asset, owner }) {
  const shares = await vault.balanceOf(owner);
  const estimatedAssets = await vault.previewRedeem(shares);
  return {
    shares: ethers.utils.formatUnits(shares, await vault.decimals()),
    estimatedAssetValue: ethers.utils.formatUnits(
      estimatedAssets, await asset.decimals(),
    ),
  };
}

const position = await readPrimePosition(client);
```

`previewRedeem` estimates the current asset value; the amount received can change before redemption.

## 5. Redeem shares

The customer signs a redemption to exchange shares for assets. PRIME redemptions settle in the transaction when liquidity is available. This example redeems the balance read above with a 0.5% tolerance.

`shareAmount` is a decimal string in share units. Here, `owner` is the customer's wallet and `receiver` is the address that receives the assets. Both use the customer's address.

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
async function redeemPrime({ vault, asset, owner }, shareAmount) {
  const shares = ethers.utils.parseUnits(shareAmount, await vault.decimals());
  if (shares.lte(0)) throw new Error('Share amount must be positive');

  const receiver = owner;
  const expectedAssets = await vault.callStatic.redeem(shares, receiver, owner, 1);
  const minAssets = expectedAssets.mul(9950).div(10000);
  if (minAssets.isZero()) throw new Error('Redemption amount is too small');

  const transaction = await vault.redeem(shares, receiver, owner, minAssets);
  const receipt = await transaction.wait();
  return {
    transactionHash: receipt.transactionHash,
    shareBalance: await vault.balanceOf(owner),
    fundingAssetBalance: await asset.balanceOf(owner),
  };
}

const redemption = await redeemPrime(client, position.shares);
```

If redemption reverts, the customer keeps their shares. Simulate again before retrying. If a transaction is still pending, check its status before sending another.

See [Deposit and redeem onchain](https://docs.groundtech.co/v3/docs/gtokens/deposit-and-redeem.md) for the contract method reference and fee-share redemptions.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.