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

# Turnkey

> Discover, enter, track and exit yields with Turnkey policy-controlled keys signing the transactions Yield.xyz builds.

This guide builds a server-side flow where you discover a yield, enter it, track the position and exit, with every transaction signed by a Turnkey key. Yield.xyz builds ready-to-sign transactions and never signs or holds funds; Turnkey signs them under policies that restrict the key to the exact contracts and functions the flow needs.

## Resources

* [Turnkey quickstart](https://docs.turnkey.com/getting-started/quickstart)
* [`@turnkey/ethers`](https://www.npmjs.com/package/@turnkey/ethers), the Turnkey ethers signer
* [Working example](https://github.com/tkhq/sdk/tree/main/examples/with-yield-xyz) in the Turnkey SDK repo
* [Enter and exit flows](https://docs.yield.xyz/guides/earn/enter-exit-flows.md) and [EVM signing](https://docs.yield.xyz/guides/transaction-signing/evm.md)

## Prerequisites

* A Yield.xyz API key. See [Onboarding](https://docs.yield.xyz/documentation/get-started/onboarding.md).
* A Turnkey organization set up with the quickstart:
  * **Organization ID:** the grouping for your users, wallets and policies.
  * **Root quorum user:** a root user with an API key pair.
  * **Non-root user:** a second user with its own API key, outside the root quorum. This user signs yield transactions.
  * **Wallet:** an HD wallet with at least one Ethereum account, funded with ETH and USDC on Base for this example.

After you create the non-root user, remove it from the root quorum, from the Turnkey dashboard or the API, so its key can only act within the policies below.

## Restrict the signing key with policies

The non-root user should only be able to approve USDC and deposit into or withdraw from the vault you offer. Create the policies with the root user. Each one matches the target contract (`eth.tx.to`) and the function selector, the first four bytes of `eth.tx.data`: `0x095ea7b3` for `approve`, `0x6e553f65` for ERC-4626 `deposit` and `0xba087652` for ERC-4626 `redeem`.

```typescript theme={null}
import { Turnkey } from "@turnkey/sdk-server";

const turnkey = new Turnkey({
  apiBaseUrl: "https://api.turnkey.com",
  apiPrivateKey: process.env.TURNKEY_API_PRIVATE_KEY!,
  apiPublicKey: process.env.TURNKEY_API_PUBLIC_KEY!,
  defaultOrganizationId: process.env.TURNKEY_ORGANIZATION_ID!,
}).apiClient();

// The non-root user that signs yield transactions
const userId = process.env.NONROOT_USER_ID!;

const policies = [
  {
    policyName: "Allow approve on USDC",
    condition: `eth.tx.to == '${process.env.USDC_ADDRESS}' && eth.tx.data[0..10] == '0x095ea7b3'`,
  },
  {
    policyName: "Allow deposit on the vault",
    condition: `eth.tx.to == '${process.env.VAULT_ADDRESS}' && eth.tx.data[0..10] == '0x6e553f65'`,
  },
  {
    policyName: "Allow redeem on the vault",
    condition: `eth.tx.to == '${process.env.VAULT_ADDRESS}' && eth.tx.data[0..10] == '0xba087652'`,
  },
];

for (const p of policies) {
  const { policyId } = await turnkey.createPolicy({
    ...p,
    effect: "EFFECT_ALLOW",
    consensus: `approvers.any(user, user.id == '${userId}')`,
    notes: "",
  });
  console.log(`Created ${p.policyName}: ${policyId}`);
}
```

> [!TIP]
>
> You don't need to look up addresses or selectors by hand. Build the enter and exit actions once, then read `to` and the first four bytes of `data` from each `unsignedTransaction` and add one policy per pair. Do the same for every yield you offer: RWA issuers, for example, use their own contracts and functions such as `subscribe` or `depositInstant`, not the ERC-4626 selectors above.

## How Yield.xyz fits

Yield.xyz gives you one API across 4,000+ yields on 85+ networks:

* **Discover:** `GET /v1/yields` returns yields with their metadata.
* **Act:** `POST /v1/actions/enter`, `/exit` and `/manage` return an ordered list of unsigned transactions.
* **Track:** `POST /v1/yields/{yieldId}/balances` and `POST /v1/yields/balances` return lifecycle-aware balances.

This guide uses EVM networks. Non-EVM networks follow the same flow with a different signer; see [Transaction signing](https://docs.yield.xyz/guides/transaction-signing/index.md).

## Discover a yield

Discovery is a plain read and Turnkey doesn't change it. Run it on your server so your API key stays private.

```typescript theme={null}
const res = await fetch(
  "https://api.yield.xyz/v1/yields?network=base&token=USDC&limit=10",
  { headers: { "x-api-key": process.env.YIELD_API_KEY! } },
);
const { items } = await res.json();

const selected = items[0];
const yieldId = selected.id;
const rate = selected.rewardRate.total;                       // current estimated rate
const enterFields = selected.mechanics.arguments.enter.fields; // what enter needs
const kycRequired = selected.mechanics.requirements?.kycRequired ?? false;
```

Every field on a yield is described in [Yield metadata](https://docs.yield.xyz/documentation/earn/core-concepts/yield-metadata.md).

## Find yields to offer

Rather than hardcoding yield IDs, which change as yields are added and retired, query the catalog for what you want to offer:

```bash theme={null}
# Stablecoin and DeFi yields on Base
curl "https://api.yield.xyz/v1/yields?network=base&token=USDC&types=lending,vault" \
  -H "x-api-key: $YIELD_API_KEY"

# Native staking
curl "https://api.yield.xyz/v1/yields?type=staking&limit=100" \
  -H "x-api-key: $YIELD_API_KEY"

# Tokenized real-world assets
curl "https://api.yield.xyz/v1/yields?type=real_world_asset&networks=ethereum,base" \
  -H "x-api-key: $YIELD_API_KEY"
```

Add `prime=true` to return only yields that meet the [Prime](https://docs.yield.xyz/documentation/earn/core-concepts/yield-metadata.md) quality bar. For staking, default users to [preferred validators](https://docs.yield.xyz/documentation/earn/staking/validators/preferred-validators.md). For DeFi, wrap yields in an [OAV](https://docs.yield.xyz/documentation/earn/oavs/single-strategy.md) to charge fees and auto-compound incentives (see [Monetization](#monetization)).

## Enter a yield

Build the enter action, then sign and broadcast each transaction with the non-root Turnkey user, in order.

```typescript theme={null}
import { ethers } from "ethers";
import { TurnkeySigner } from "@turnkey/ethers";
import { Turnkey } from "@turnkey/sdk-server";

const turnkey = new Turnkey({
  apiBaseUrl: "https://api.turnkey.com",
  apiPublicKey: process.env.NONROOT_API_PUBLIC_KEY!,
  apiPrivateKey: process.env.NONROOT_API_PRIVATE_KEY!,
  defaultOrganizationId: process.env.TURNKEY_ORGANIZATION_ID!,
});

const signer = new TurnkeySigner({
  client: turnkey.apiClient(),
  organizationId: process.env.TURNKEY_ORGANIZATION_ID!,
  signWith: process.env.SIGN_WITH!, // the wallet account address
}).connect(new ethers.JsonRpcProvider(process.env.RPC_URL!));

const address = process.env.SIGN_WITH!;

async function yieldApi(path: string, body: unknown, method = "POST") {
  const res = await fetch(`https://api.yield.xyz${path}`, {
    method,
    headers: { "content-type": "application/json", "x-api-key": process.env.YIELD_API_KEY! },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw Object.assign(new Error(`yield.xyz ${res.status}`), { status: res.status, body: await res.json() });
  return res.json();
}

const TERMINAL = ["CONFIRMED", "FAILED", "SKIPPED"];

async function signAndTrack(action: any) {
  const txs = [...action.transactions].sort((a, b) => a.stepIndex - b.stepIndex);
  for (const tx of txs) {
    if (TERMINAL.includes(tx.status)) continue; // e.g. an approval already covered
    const parsed = JSON.parse(tx.unsignedTransaction);
    const sent = await signer.sendTransaction(parsed);
    await sent.wait();
    await yieldApi(`/v1/transactions/${tx.id}/submit-hash`, { hash: sent.hash }, "PUT");
  }
}

const action = await yieldApi("/v1/actions/enter", {
  yieldId,
  address,
  arguments: { amount: "0.5" }, // token units, as defined by mechanics.arguments.enter
});
await signAndTrack(action);
```

For a vault deposit, the first transaction approves the vault to spend USDC and the second deposits. Yield.xyz works out those steps, so you never encode the calls or look up ABIs yourself. Build the `arguments` from `mechanics.arguments.enter.fields` rather than hardcoding `{ amount }`, so the same code works for yields that also need a `validatorAddress` or another field; see [Enter and exit flows](https://docs.yield.xyz/guides/earn/enter-exit-flows.md).

## KYC-gated RWA yields

Tokenized real-world assets, such as US Treasuries, money market funds and private credit, use the same enter and exit flow, so no new signing code is needed. Some issuers require the wallet to be allowlisted first, shown by `mechanics.requirements.kycRequired: true` on the yield.

Check the wallet before you show a deposit button:

```typescript theme={null}
const kyc = await fetch(
  `https://api.yield.xyz/v1/yields/${yieldId}/kyc/status?address=${address}`,
  { headers: { "x-api-key": process.env.YIELD_API_KEY! } },
).then((r) => r.json());
// kyc.kycStatus: not_required | not_started | pending | approved | rejected
// kyc.authorizeUrl: the issuer's KYC portal, when the issuer provides one
```

Send the user to `authorizeUrl` when the status is `not_started` or `rejected`, and enter once it is `approved`. If you call enter for a wallet that is not cleared, the API returns `412` with `RwaKycError`, and the message includes the issuer's KYC URL.

```typescript theme={null}
try {
  await signAndTrack(await yieldApi("/v1/actions/enter", { yieldId, address, arguments: { amount: "100000" } }));
} catch (e: any) {
  if (e.status === 412) {
    // Not allowlisted yet: fetch kyc/status and hand the user to authorizeUrl
  } else throw e;
}
```

RWA enter and exit transactions call the issuer's own contracts, so add a matching Turnkey policy for each `to` and selector they use. Issuer minimums and eligibility are in [RWA KYC](https://docs.yield.xyz/documentation/earn/rwas/kyc.md) and on each issuer's page under [RWAs](https://docs.yield.xyz/documentation/earn/rwas/index.md).

## Read the position balance

Balances are lifecycle-aware: each one has a `type` that says whether funds are `active`, `entering`, `exiting`, `withdrawable`, `claimable` or `locked`.

```typescript theme={null}
const { balances } = await yieldApi(`/v1/yields/${yieldId}/balances`, { address });
for (const b of balances) {
  console.log(b.type, b.amount, b.token.symbol, b.pendingActions?.map((p: any) => p.type));
}
```

For many yields or wallets at once, use `POST /v1/yields/balances` with `{ "queries": [{ "address", "network" }] }`. See [Tracking balances](https://docs.yield.xyz/guides/earn/tracking-balances.md).

## Handle pending actions

A balance can carry `pendingActions`, such as `CLAIM_REWARDS` or `CLAIM_UNSTAKED`. Pass one back to `POST /v1/actions/manage` unchanged:

```typescript theme={null}
const pending = balances.find((b: any) => b.pendingActions?.length)?.pendingActions[0];
if (pending) {
  const manage = await yieldApi("/v1/actions/manage", {
    yieldId,
    address,
    action: pending.type,
    passthrough: pending.passthrough,
  });
  await signAndTrack(manage);
}
```

## Exit a yield

Exiting is the same pattern as entering:

```typescript theme={null}
const exit = await yieldApi("/v1/actions/exit", {
  yieldId,
  address,
  arguments: { amount: "0.1" }, // see mechanics.arguments.exit
});
await signAndTrack(exit);
```

Some exits need more than one transaction, for example withdraw and unwrap; `signAndTrack` sends them in order.

Not every exit settles at once. Staking unbonds wait out the network's cooldown, and many RWA redemptions settle on a NAV strike or over several days. While that happens the position shows as an `exiting` balance. When it settles it becomes `withdrawable` with a `CLAIM_UNSTAKED` pending action, which you complete through `POST /v1/actions/manage` as above.

## Track transaction status

After each broadcast, report the hash with `PUT /v1/transactions/{transactionId}/submit-hash`, then poll `GET /v1/transactions/{transactionId}` (or `GET /v1/actions/{actionId}`) until it reaches a terminal status. See [Monitoring and alerting](https://docs.yield.xyz/guides/earn/monitoring-alerting.md).

## Integration tips

* Send transactions in `stepIndex` order and skip any already at a terminal status.
* Never change `unsignedTransaction` before signing; use its `chainId`.
* Build arguments from `mechanics.arguments.*` for the right fields and units.
* Scope Turnkey policies to the exact `to` and selector pairs your yields use, and add new ones when you add a yield.
* Keep your Yield.xyz API key on the server.

## Monetization

How you earn depends on the yield type. Each yield's `mechanics.possibleFeeTakingMechanisms` says which fees you can configure on it.

* **Staking:** deposit fees, deducted atomically in the same transaction, and a share of validator revenue through Yield.xyz's validator agreements. See [Preferred validators](https://docs.yield.xyz/documentation/earn/staking/validators/preferred-validators.md).
* **DeFi:** revenue share from some protocols and curators, and user-facing deposit, performance and management fees through [OAVs](https://docs.yield.xyz/documentation/earn/oavs/single-strategy.md).
* **RWAs:** issuer fees are set by the issuer and passed through. Where an RWA is wrapped in an OAV, you can add your own fees on top.

OAVs also improve the user experience: incentive tokens are sold into the deposit asset and reinvested automatically, wrapping and swapping are handled for the user, and users only ever see their deposit token. See [Earn monetization](https://docs.yield.xyz/documentation/earn/monetization.md) for fee configuration, and [Plans](https://docs.yield.xyz/documentation/plans-limits/plans-tiers.md) for commercial terms.

## Next steps

> [card] [Enter and exit flows](https://docs.yield.xyz/guides/earn/enter-exit-flows.md)
>
> The full request, sign and poll loop.

> [card] [Yield metadata](https://docs.yield.xyz/documentation/earn/core-concepts/yield-metadata.md)
>
> Every field returned on a yield.

> [card] [Shield](https://docs.yield.xyz/documentation/security/shield.md)
>
> Verify each transaction before Turnkey signs it.

> [card] [Embedded wallets](https://docs.yield.xyz/guides/integrations/index.md)
>
> The same flow with other wallet providers.


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